repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/backend/CloudSetupFragment.kt | 1 | 15054 | package com.battlelancer.seriesguide.backend
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.backend.settings.HexagonSettings
import com.battlelancer.seriesguide.databinding.FragmentCloudSetupBinding
import com.battlelancer.seriesguide.sync.SgSyncAdapter
import com.battlelancer.seriesguide.sync.SyncProgress
import com.battlelancer.seriesguide.traktapi.ConnectTraktActivity
import com.battlelancer.seriesguide.ui.SeriesGuidePreferences
import com.battlelancer.seriesguide.util.Errors
import com.battlelancer.seriesguide.util.Utils
import com.battlelancer.seriesguide.util.safeShow
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.ErrorCodes
import com.firebase.ui.auth.IdpResponse
import com.google.android.gms.tasks.Task
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
/**
* Manages signing in and out with Cloud and account removal.
* Tries to silent sign-in when started. Enables Cloud on sign-in.
* If Cloud is still enabled, but the account requires validation
* enables to retry sign-in or to sign out (actually just disable Cloud).
*/
class CloudSetupFragment : Fragment() {
private var binding: FragmentCloudSetupBinding? = null
private var snackbar: Snackbar? = null
private var signInAccount: FirebaseUser? = null
private lateinit var hexagonTools: HexagonTools
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
hexagonTools = SgApp.getServicesComponent(requireContext()).hexagonTools()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return FragmentCloudSetupBinding.inflate(inflater, container, false).also {
binding = it
}.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding!!.apply {
buttonCloudSignIn.setOnClickListener {
// restrict access to supporters
if (Utils.hasAccessToX(activity)) {
startHexagonSetup()
} else {
Utils.advertiseSubscription(activity)
}
}
buttonCloudSignOut.setOnClickListener { signOut() }
textViewCloudWarnings.setOnClickListener {
// link to trakt account activity which has details about disabled features
startActivity(Intent(context, ConnectTraktActivity::class.java))
}
buttonCloudRemoveAccount.setOnClickListener {
if (RemoveCloudAccountDialogFragment().safeShow(
parentFragmentManager,
"remove-cloud-account"
)) {
setProgressVisible(true)
}
}
updateViews()
setProgressVisible(true)
syncStatusCloud.visibility = View.GONE
}
}
override fun onStart() {
super.onStart()
trySilentSignIn()
}
override fun onResume() {
super.onResume()
EventBus.getDefault().register(this)
}
override fun onPause() {
super.onPause()
EventBus.getDefault().unregister(this)
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(@Suppress("UNUSED_PARAMETER") event: RemoveCloudAccountDialogFragment.CanceledEvent) {
setProgressVisible(false)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(event: RemoveCloudAccountDialogFragment.AccountRemovedEvent) {
event.handle(requireContext())
setProgressVisible(false)
updateViews()
}
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
fun onEvent(event: SyncProgress.SyncEvent) {
binding?.syncStatusCloud?.setProgress(event)
}
private fun trySilentSignIn() {
val firebaseUser = FirebaseAuth.getInstance().currentUser
if (firebaseUser != null) {
changeAccount(firebaseUser, null)
return
}
// check if the user is still signed in
val signInTask = AuthUI.getInstance()
.silentSignIn(requireContext(), hexagonTools.firebaseSignInProviders)
if (signInTask.isSuccessful) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Timber.d("Got cached sign-in")
handleSilentSignInResult(signInTask)
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
Timber.d("Trying async sign-in")
signInTask.addOnCompleteListener { task ->
if (isAdded) {
handleSilentSignInResult(task)
}
}
}
}
/**
* @param task A completed sign-in task.
*/
private fun handleSilentSignInResult(task: Task<AuthResult>) {
val account = if (task.isSuccessful) {
task.result?.user
} else {
null
}
// Note: Do not show error message if silent sign-in fails, just update UI.
changeAccount(account, null)
}
/**
* If the Firebase account is not null, saves it and auto-starts setup if Cloud is not
* enabled or the account needs validation.
* On sign-in failure with error message (so was not canceled) sets should validate account flag.
*/
private fun changeAccount(account: FirebaseUser?, errorIfNull: String?) {
val signedIn = account != null
if (signedIn) {
Timber.i("Signed in to Cloud.")
signInAccount = account
} else {
signInAccount = null
errorIfNull?.let {
HexagonSettings.shouldValidateAccount(requireContext(), true)
showSnackbar(getString(R.string.hexagon_signin_fail_format, it))
}
}
setProgressVisible(false)
updateViews()
if (signedIn && Utils.hasAccessToX(requireContext())) {
if (!HexagonSettings.isEnabled(requireContext())
|| HexagonSettings.shouldValidateAccount(requireContext())) {
Timber.i("Auto-start Cloud setup.")
startHexagonSetup()
}
}
}
private val signInWithFirebase =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
changeAccount(FirebaseAuth.getInstance().currentUser, null)
} else {
val response = IdpResponse.fromResultIntent(result.data)
if (response == null) {
// user chose not to sign in or add account, show no error message
changeAccount(null, null)
} else {
val errorMessage: String?
val ex = response.error
if (ex != null) {
when (ex.errorCode) {
ErrorCodes.NO_NETWORK -> {
errorMessage = getString(R.string.offline)
}
ErrorCodes.PLAY_SERVICES_UPDATE_CANCELLED -> {
// user cancelled, show no error message
errorMessage = null
}
else -> {
if (ex.errorCode == ErrorCodes.DEVELOPER_ERROR
&& !hexagonTools.isGoogleSignInAvailable) {
// Note: If trying to sign-in with email already used with
// Google Sign-In on other device, fails to fall back to
// Google Sign-In because Play Services is not available.
errorMessage = getString(R.string.hexagon_signin_google_only)
} else {
errorMessage = ex.message
Errors.logAndReportHexagonAuthError(
HexagonAuthError.build(ACTION_SIGN_IN, ex)
)
}
}
}
} else {
errorMessage = "Unknown error"
Errors.logAndReportHexagonAuthError(
HexagonAuthError(ACTION_SIGN_IN, errorMessage)
)
}
changeAccount(null, errorMessage)
}
}
}
private fun signIn() {
// Create and launch sign-in intent
val intent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(hexagonTools.firebaseSignInProviders)
.setIsSmartLockEnabled(hexagonTools.isGoogleSignInAvailable)
.setTheme(SeriesGuidePreferences.THEME)
.build()
signInWithFirebase.launch(intent)
}
private fun signOut() {
if (HexagonSettings.shouldValidateAccount(requireContext())) {
// Account needs to be repaired, so can't sign out, just disable Cloud
hexagonTools.removeAccountAndSetDisabled()
updateViews()
} else {
setProgressVisible(true)
AuthUI.getInstance().signOut(requireContext()).addOnCompleteListener {
Timber.i("Signed out.")
signInAccount = null
hexagonTools.removeAccountAndSetDisabled()
if ([email protected]) {
setProgressVisible(false)
updateViews()
}
}
}
}
private fun updateViews() {
if (HexagonSettings.isEnabled(requireContext())) {
// hexagon enabled...
binding?.textViewCloudUser?.text = HexagonSettings.getAccountName(requireContext())
if (HexagonSettings.shouldValidateAccount(requireContext())) {
// ...but account needs to be repaired
binding?.textViewCloudDescription?.setText(R.string.hexagon_signed_out)
setButtonsVisible(
signInVisible = true,
signOutVisible = true,
removeVisible = false
)
} else {
// ...and account is fine
binding?.textViewCloudDescription?.setText(R.string.hexagon_description)
setButtonsVisible(
signInVisible = false,
signOutVisible = true,
removeVisible = true
)
}
} else {
// did try to setup, but failed?
if (!HexagonSettings.hasCompletedSetup(requireContext())) {
// show error message
binding?.textViewCloudDescription?.setText(R.string.hexagon_setup_incomplete)
} else {
binding?.textViewCloudDescription?.setText(R.string.hexagon_description)
}
binding?.textViewCloudUser?.text = null
setButtonsVisible(
signInVisible = true,
signOutVisible = false,
removeVisible = false
)
}
}
private fun setButtonsVisible(
signInVisible: Boolean,
signOutVisible: Boolean,
removeVisible: Boolean
) {
binding?.apply {
buttonCloudSignIn.isGone = !signInVisible
buttonCloudSignOut.isGone = !signOutVisible
buttonCloudRemoveAccount.isGone = !removeVisible
}
}
/**
* Disables buttons and shows a progress bar.
*/
private fun setProgressVisible(isVisible: Boolean) {
binding?.apply {
progressBarCloudAccount.visibility = if (isVisible) View.VISIBLE else View.GONE
buttonCloudSignIn.isEnabled = !isVisible
buttonCloudSignOut.isEnabled = !isVisible
buttonCloudRemoveAccount.isEnabled = !isVisible
}
}
private fun showSnackbar(message: CharSequence) {
dismissSnackbar()
snackbar = Snackbar.make(requireView(), message, Snackbar.LENGTH_INDEFINITE).also {
it.show()
}
}
private fun dismissSnackbar() {
snackbar?.dismiss()
}
private fun startHexagonSetup() {
dismissSnackbar()
setProgressVisible(true)
val signInAccountOrNull = signInAccount
if (signInAccountOrNull == null) {
signIn()
} else {
Timber.i("Setting up Hexagon...")
// set setup incomplete flag
HexagonSettings.setSetupIncomplete(requireContext())
// validate account data
if (signInAccountOrNull.email.isNullOrEmpty()) {
Timber.d("Setting up Hexagon...FAILURE_AUTH")
// show setup incomplete message + error toast
view?.let {
Snackbar.make(it, R.string.hexagon_setup_fail_auth, Snackbar.LENGTH_LONG)
.show()
}
} else if (hexagonTools.setAccountAndEnabled(signInAccountOrNull)) {
// schedule full sync
Timber.d("Setting up Hexagon...SUCCESS_SYNC_REQUIRED")
SgSyncAdapter.requestSyncFullImmediate(requireContext(), false)
HexagonSettings.setSetupCompleted(requireContext())
} else {
// Do not set completed, will show setup incomplete message.
Timber.d("Setting up Hexagon...FAILURE")
}
setProgressVisible(false)
updateViews()
}
}
companion object {
private const val ACTION_SIGN_IN = "sign-in"
}
}
| apache-2.0 | 2a8f58227d8b83815c719e573ce7464c | 36.729323 | 112 | 0.588481 | 5.506218 | false | false | false | false |
jayrave/falkon | falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/query/lenient/QueryBuilderExtn.kt | 1 | 782 | package com.jayrave.falkon.dao.query.lenient
import com.jayrave.falkon.mapper.ReadOnlyColumnOfTable
import java.sql.SQLException
/**
* A convenience function to select multiple columns in one go
*
* @param [columns] to be selected
* @param [aliaser] used to compute the alias to be used for the selected columns
*
* @throws [SQLException] if [columns] is empty
*/
fun <Z : AdderOrEnder<Z>> AdderOrEnder<Z>.select(
columns: Iterable<ReadOnlyColumnOfTable<*, *>>,
aliaser: ((ReadOnlyColumnOfTable<*, *>) -> String)? = null): Z {
var result: Z? = null
columns.forEach { column ->
result = select(column, aliaser?.invoke(column))
}
if (result == null) {
throw SQLException("Columns can't be empty")
}
return result!!
} | apache-2.0 | 3fc03ad1335f937c07aeb406295a7c56 | 26.964286 | 81 | 0.668798 | 3.852217 | false | false | false | false |
duftler/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/metrics/MetricsTagHelper.kt | 1 | 2059 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.metrics
import com.netflix.spectator.api.BasicTag
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware
import com.netflix.spinnaker.orca.pipeline.model.Stage
class MetricsTagHelper : CloudProviderAware {
companion object {
private val helper = MetricsTagHelper()
fun commonTags(stage: Stage, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, status: ExecutionStatus): Iterable<BasicTag> =
arrayListOf(
BasicTag("status", status.toString()),
BasicTag("executionType", stage.execution.type.name.capitalize()),
BasicTag("isComplete", status.isComplete.toString()),
BasicTag("cloudProvider", helper.getCloudProvider(stage).valueOrNa())
)
fun detailedTaskTags(stage: Stage, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, status: ExecutionStatus): Iterable<BasicTag> =
arrayListOf(
BasicTag("taskType", taskModel.implementingClass),
BasicTag("account", helper.getCredentials(stage).valueOrNa()),
// sorting regions to reduce the metrics cardinality
BasicTag("region", helper.getRegions(stage).let {
if (it.isEmpty()) { "n_a" } else { it.sorted().joinToString(",") }
}))
private fun String?.valueOrNa(): String {
return if (this == null || isBlank()) {
"n_a"
} else {
this
}
}
}
}
| apache-2.0 | 3c20bc2c41d3181f5f83fe7de6be7fe6 | 37.12963 | 144 | 0.705197 | 4.245361 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/data/netease/result/MvDetailResultBean.kt | 1 | 2262 | package tech.summerly.quiet.data.netease.result
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/9/8
* desc :
*/
class MvDetailResultBean(
@SerializedName("data")
@Expose
val data: Data? = null,
@SerializedName("code")
@Expose
val code: Int
) {
data class Brs(
@SerializedName("1080")
@Expose
val _1080: String? = null,
@SerializedName("720")
@Expose
val _720: String? = null,
@SerializedName("480")
@Expose
val _480: String? = null,
@SerializedName("240")
@Expose
val _240: String? = null
)
data class Data(
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("title")
@Expose
val name: String? = null,
@SerializedName("artistId")
@Expose
val artistId: Long? = null,
@SerializedName("artistName")
@Expose
val artistName: String? = null,
@SerializedName("cover")
@Expose
val cover: String? = null,
@SerializedName("playCount")
@Expose
val playCount: Long? = null,
@SerializedName("subCount")
@Expose
val subCount: Long? = null,
@SerializedName("shareCount")
@Expose
val shareCount: Long? = null,
@SerializedName("likeCount")
@Expose
val likeCount: Long? = null,
@SerializedName("commentCount")
@Expose
val commentCount: Long? = null,
@SerializedName("duration")
@Expose
val duration: Long,
@SerializedName("publishTime")
@Expose
val publishTime: String? = null,
@SerializedName("brs")
@Expose
val brs: Brs? = null,
@SerializedName("commentThreadId")
@Expose
val commentThreadId: String? = null
)
} | gpl-2.0 | 627896cf2362f8ac316a4bffe5d7ebe4 | 22.091837 | 49 | 0.493369 | 4.854077 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/customselector/ui/adapter/ImageAdapterTest.kt | 2 | 7443 | package fr.free.nrw.commons.customselector.ui.adapter
import android.content.ContentResolver
import android.content.Context
import android.content.SharedPreferences
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.widget.GridLayout
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.R
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.customselector.listeners.ImageSelectListener
import fr.free.nrw.commons.customselector.model.Image
import fr.free.nrw.commons.customselector.ui.selector.CustomSelectorActivity
import fr.free.nrw.commons.customselector.ui.selector.ImageLoader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.jupiter.api.Assertions
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.lang.reflect.Field
import java.util.*
import kotlin.collections.ArrayList
/**
* Custom Selector image adapter test.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@ExperimentalCoroutinesApi
class ImageAdapterTest {
@Mock
private lateinit var imageLoader: ImageLoader
@Mock
private lateinit var imageSelectListener: ImageSelectListener
@Mock
private lateinit var context: Context
@Mock
private lateinit var mockContentResolver: ContentResolver
@Mock
private lateinit var sharedPreferences: SharedPreferences
private lateinit var activity: CustomSelectorActivity
private lateinit var imageAdapter: ImageAdapter
private lateinit var images : ArrayList<Image>
private lateinit var holder: ImageAdapter.ImageViewHolder
private lateinit var selectedImageField: Field
private var uri: Uri = Mockito.mock(Uri::class.java)
private lateinit var image: Image
private val testDispatcher = TestCoroutineDispatcher()
/**
* Set up variables.
*/
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
Dispatchers.setMain(testDispatcher)
activity = Robolectric.buildActivity(CustomSelectorActivity::class.java).get()
imageAdapter = ImageAdapter(activity, imageSelectListener, imageLoader)
image = Image(1, "image", uri, "abc/abc", 1, "bucket1")
images = ArrayList()
val inflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val listItemView: View = inflater.inflate(R.layout.item_custom_selector_image, null, false)
holder = ImageAdapter.ImageViewHolder(listItemView)
selectedImageField = imageAdapter.javaClass.getDeclaredField("selectedImages")
selectedImageField.isAccessible = true
}
@After
fun tearDown() {
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
/**
* Test on create view holder.
*/
@Test
fun onCreateViewHolder() {
imageAdapter.createViewHolder(GridLayout(activity), 0)
}
/**
* Test on bind view holder.
*/
@Test
fun onBindViewHolder() {
whenever(context.contentResolver).thenReturn(mockContentResolver)
whenever(mockContentResolver.getType(uri)).thenReturn("jpg")
Whitebox.setInternalState(imageAdapter, "context", context)
// Parameters.
images.add(image)
imageAdapter.init(images, images, TreeMap())
whenever(context.getSharedPreferences("custom_selector", 0))
.thenReturn(sharedPreferences)
// Test conditions.
imageAdapter.onBindViewHolder(holder, 0)
selectedImageField.set(imageAdapter, images)
imageAdapter.onBindViewHolder(holder, 0)
}
/**
* Test processThumbnailForActionedImage
*/
@Test
fun processThumbnailForActionedImage() = runBlocking {
Whitebox.setInternalState(imageAdapter, "allImages", listOf(image))
whenever(imageLoader.nextActionableImage(listOf(image), Dispatchers.IO, Dispatchers.Default,
0)).thenReturn(0)
imageAdapter.processThumbnailForActionedImage(holder, 0)
}
/**
* Test processThumbnailForActionedImage
*/
@Test
fun `processThumbnailForActionedImage when reached end of the folder`() = runBlocking {
whenever(imageLoader.nextActionableImage(ArrayList(), Dispatchers.IO, Dispatchers.Default,
0)).thenReturn(-1)
imageAdapter.processThumbnailForActionedImage(holder, 0)
}
/**
* Test init.
*/
@Test
fun init() {
imageAdapter.init(images, images, TreeMap())
}
/**
* Test private function select or remove image.
*/
@Test
fun selectOrRemoveImage() {
// Access function
val func = imageAdapter.javaClass.getDeclaredMethod("selectOrRemoveImage", ImageAdapter.ImageViewHolder::class.java, Int::class.java)
func.isAccessible = true
// Parameters
images.addAll(listOf(image, image))
imageAdapter.init(images, images, TreeMap())
// Test conditions
holder.itemUploaded()
func.invoke(imageAdapter, holder, 0)
holder.itemNotUploaded()
holder.itemNotForUpload()
func.invoke(imageAdapter, holder, 0)
holder.itemNotForUpload()
func.invoke(imageAdapter, holder, 0)
selectedImageField.set(imageAdapter, images)
func.invoke(imageAdapter, holder, 1)
}
/**
* Test private function onThumbnailClicked.
*/
@Test
fun onThumbnailClicked() {
images.add(image)
Whitebox.setInternalState(imageAdapter, "images", images)
// Access function
val func = imageAdapter.javaClass.getDeclaredMethod(
"onThumbnailClicked",
Int::class.java,
ImageAdapter.ImageViewHolder::class.java
)
func.isAccessible = true
func.invoke(imageAdapter, 0, holder)
}
/**
* Test get item count.
*/
@Test
fun getItemCount() {
Assertions.assertEquals(0, imageAdapter.itemCount)
}
/**
* Test setSelectedImages.
*/
@Test
fun setSelectedImages() {
images.add(image)
imageAdapter.setSelectedImages(images)
}
/**
* Test refresh.
*/
@Test
fun refresh() {
imageAdapter.refresh(listOf(image), listOf(image))
}
/**
* Test getSectionName.
*/
@Test
fun getSectionName() {
images.add(image)
Whitebox.setInternalState(imageAdapter, "images", images)
Assertions.assertEquals("", imageAdapter.getSectionName(0))
}
/**
* Test cleanUp.
*/
@Test
fun cleanUp() {
imageAdapter.cleanUp()
}
/**
* Test getImageId
*/
@Test
fun getImageIdAt() {
imageAdapter.init(listOf(image), listOf(image), TreeMap())
Assertions.assertEquals(1, imageAdapter.getImageIdAt(0))
}
} | apache-2.0 | b6b7c3e3a147edeecd4035808072b2f2 | 29.260163 | 141 | 0.694612 | 4.672316 | false | true | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/LocalKeyStoreManager.kt | 1 | 2230 | package com.fsck.k9
import com.fsck.k9.mail.MailServerDirection
import com.fsck.k9.mail.ssl.LocalKeyStore
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
class LocalKeyStoreManager(
private val localKeyStore: LocalKeyStore
) {
/**
* Add a new certificate for the incoming or outgoing server to the local key store.
*/
@Throws(CertificateException::class)
fun addCertificate(account: Account, direction: MailServerDirection, certificate: X509Certificate) {
val serverSettings = if (direction === MailServerDirection.INCOMING) {
account.incomingServerSettings
} else {
account.outgoingServerSettings
}
localKeyStore.addCertificate(serverSettings.host!!, serverSettings.port, certificate)
}
/**
* Examine the existing settings for an account. If the old host/port is different from the
* new host/port, then try and delete any (possibly non-existent) certificate stored for the
* old host/port.
*/
fun deleteCertificate(account: Account, newHost: String, newPort: Int, direction: MailServerDirection) {
val serverSettings = if (direction === MailServerDirection.INCOMING) {
account.incomingServerSettings
} else {
account.outgoingServerSettings
}
val oldHost = serverSettings.host!!
val oldPort = serverSettings.port
if (oldPort == -1) {
// This occurs when a new account is created
return
}
if (newHost != oldHost || newPort != oldPort) {
localKeyStore.deleteCertificate(oldHost, oldPort)
}
}
/**
* Examine the settings for the account and attempt to delete (possibly non-existent)
* certificates for the incoming and outgoing servers.
*/
fun deleteCertificates(account: Account) {
account.incomingServerSettings.let { serverSettings ->
localKeyStore.deleteCertificate(serverSettings.host!!, serverSettings.port)
}
account.outgoingServerSettings.let { serverSettings ->
localKeyStore.deleteCertificate(serverSettings.host!!, serverSettings.port)
}
}
}
| apache-2.0 | 3b0ae4f04dffd7a707ed94302dcb8386 | 36.79661 | 108 | 0.67713 | 4.775161 | false | false | false | false |
androidx/constraintlayout | projects/ComposeConstraintLayout/macrobenchmark-app/src/main/java/com/example/macrobenchmark/newmessage/NewMessageState.kt | 2 | 1565 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark.newmessage
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@Suppress("NOTHING_TO_INLINE")
@Composable
internal inline fun rememberNewMessageState(
key: Any = Unit,
initialLayoutState: NewMessageLayout
): NewMessageState {
return remember(key) { NewMessageState(initialLayoutState) }
}
internal class NewMessageState(initialLayoutState: NewMessageLayout) {
private var _currentState = mutableStateOf(initialLayoutState)
val currentState: NewMessageLayout
get() = _currentState.value
fun setToFull() {
_currentState.value = NewMessageLayout.Full
}
fun setToMini() {
_currentState.value = NewMessageLayout.Mini
}
fun setToFab() {
_currentState.value = NewMessageLayout.Fab
}
}
internal enum class NewMessageLayout {
Full,
Mini,
Fab
} | apache-2.0 | dae6c3166476902cfbb8c8f8d2aaab82 | 27.472727 | 75 | 0.736102 | 4.299451 | false | false | false | false |
android/user-interface-samples | CanonicalLayouts/supporting-panel-compose/app/src/main/java/com/example/supportingpanelcompose/ui/theme/Color.kt | 1 | 916 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.supportingpanelcompose.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | apache-2.0 | 16c30e04e5800b5c0531f14de5a39aa3 | 32.962963 | 75 | 0.7631 | 3.620553 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/converters/Cards.kt | 1 | 1138 | package org.luxons.sevenwonders.engine.converters
import org.luxons.sevenwonders.engine.Player
import org.luxons.sevenwonders.engine.cards.Card
import org.luxons.sevenwonders.engine.moves.Move
import org.luxons.sevenwonders.model.cards.HandCard
import org.luxons.sevenwonders.model.cards.TableCard
internal fun Card.toTableCard(lastMove: Move? = null): TableCard = TableCard(
name = name,
color = color,
requirements = requirements.toApiRequirements(),
chainParent = chainParent,
chainChildren = chainChildren,
image = image,
back = back,
playedDuringLastMove = lastMove != null && this.name == lastMove.card.name,
)
internal fun List<Card>.toHandCards(player: Player, forceSpecialFree: Boolean) =
map { it.toHandCard(player, forceSpecialFree) }
private fun Card.toHandCard(player: Player, forceSpecialFree: Boolean): HandCard = HandCard(
name = name,
color = color,
requirements = requirements.toApiRequirements(),
chainParent = chainParent,
chainChildren = chainChildren,
image = image,
back = back,
playability = computePlayabilityBy(player, forceSpecialFree),
)
| mit | bd9bbdcc1fe04b10ba44f6b71fd1e9dc | 34.5625 | 92 | 0.750439 | 3.924138 | false | false | false | false |
InnoFang/DesignPatterns | src/io/innofang/singleton/example/kotlin/ThreadSafeDoubleCheckSingleton.kt | 1 | 746 | package io.innofang.singleton.example.kotlin
/**
* Created by Inno Fang on 2017/8/12.
*/
class ThreadSafeDoubleCheckSingleton {
companion object {
// implement 1
val instance1 by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
ThreadSafeDoubleCheckSingleton()
}
// implement 2
@Volatile private var instance2: ThreadSafeDoubleCheckSingleton? = null
fun get(): ThreadSafeDoubleCheckSingleton {
if (null == instance2) {
synchronized(this) {
if (null == instance2) {
instance2 = ThreadSafeDoubleCheckSingleton()
}
}
}
return instance2!!
}
}
} | gpl-3.0 | eb0c49f2ffaadb3bd2c7ca92b16af5c4 | 26.666667 | 79 | 0.552279 | 5.29078 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/SVNLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/input/metrics/AbsoluteCoupledChurn.kt | 1 | 1070 | package de.maibornwolff.codecharta.importer.svnlogparser.input.metrics
import de.maibornwolff.codecharta.importer.svnlogparser.input.Commit
import de.maibornwolff.codecharta.importer.svnlogparser.input.Modification
class AbsoluteCoupledChurn : Metric {
private var totalChurn: Long = 0
private var ownChurn: Long = 0
override fun description(): String {
return "Absolute Coupled Churn: Total number of lines changed in all other files when this file was commited."
}
override fun metricName(): String {
return "abs_coupled_churn"
}
override fun value(): Number {
return totalChurn - ownChurn
}
override fun registerCommit(commit: Commit) {
val commitsTotalChurn = commit.modifications
.map { it.additions + it.deletions }
.sum()
if (commitsTotalChurn > 0) {
totalChurn += commitsTotalChurn
}
}
override fun registerModification(modification: Modification) {
ownChurn += modification.additions + modification.deletions
}
}
| bsd-3-clause | acb06af8168553346cefd9a7625e68d9 | 29.571429 | 118 | 0.688785 | 4.385246 | false | false | false | false |
jtc42/unicornpi-android | app/src/main/java/com/joeltcollins/unicornpi/ItemOneFragment.kt | 1 | 12144 | /*
* Copyright (c) 2017. Truiton (http://www.truiton.com/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Mohit Gupt (https://github.com/mohitgupt)
*
*/
package com.joeltcollins.unicornpi
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import org.json.JSONException
import org.json.JSONObject
import org.json.JSONTokener
import kotlinx.coroutines.*
import kotlinx.android.synthetic.main.fragment_item_one.*
class ItemOneFragment : Fragment() {
// While creating view
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Get current view
return inflater.inflate(R.layout.fragment_item_one, container, false)
}
// Once view has been inflated/created
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Grab resources from XML
val fadeStatusActive: String = getString(R.string.fade_status_active)
val fadeStatusInactive: String = getString(R.string.fade_status_inactive)
val statusInactive: Int = ContextCompat.getColor(context!!, R.color.label_inactive)
// BRIGHTNESS SEEK LISTENER & FUNCTIONS
brightness_seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
var progress = 0
override fun onProgressChanged(seekBar: SeekBar, progresValue: Int, fromUser: Boolean) {
progress = progresValue
brightness_text.text = "$progress"
if (fromUser) { // Blocks API call if UI is just updating (caused fades to stop on app load)
// OLD
// val params = mapOf("val" to progress.toString())
// retreiveAsync("brightness/set", params, false)
//NEW
val params = mapOf("global_brightness_val" to progress.toString())
retreiveAsync("state", params, false, method="POST")
}
if (fade_status.text.toString() == fadeStatusActive) {
fade_status.text = fadeStatusInactive
fade_status.setTextColor(statusInactive)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {
val params = mapOf("global_brightness_val" to progress.toString())
retreiveAsync("state", params, false, method="POST")
}
})
// FADE START BUTTON LISTENER & FUNCTIONS
fade_start_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Fade started")
val minutes = Integer.parseInt(fade_time!!.text.toString())
val target = fade_target_seekbar!!.progress / 100.toFloat()
val params = mapOf(
"special_fade_minutes" to minutes.toString(),
"special_fade_target" to target.toString(),
"special_fade_status" to "1"
)
retreiveAsync("state", params, false, method = "POST")
}
})
// FADE START BUTTON LISTENER & FUNCTIONS
fade_stop_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Fade stopped")
val params = mapOf(
"special_fade_status" to "0"
)
retreiveAsync("state", params, false, method = "POST")
}
})
// ALARM TIME BUTTON LISTENER & FUNCTIONS
alarm_time_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
// Start timepicker fragment
// onTimeSet, and UI updating, is handled by AlarmTimeFragment
val newFragment = AlarmTimeFragment()
newFragment.show(activity.fragmentManager, "TimePicker")
}
})
// ALARM START BUTTON LISTENER & FUNCTIONS
alarm_start_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Alarm set")
val lead = alarm_lead.text.toString()
val tail = alarm_tail.text.toString()
val time = alarm_time_text.text.toString()
val params = mapOf(
"special_alarm_lead" to lead,
"special_alarm_tail" to tail,
"special_alarm_time" to time,
"special_alarm_status" to "1"
)
retreiveAsync("state", params, false, method = "POST")
}
})
// ALARM START BUTTON LISTENER & FUNCTIONS
alarm_stop_button.setOnClickListener(object : View.OnClickListener {
//Get main activity
val activity: MainActivity = getActivity() as MainActivity
override fun onClick(view: View) {
activity.showSnack("Alarm unset")
val params = mapOf("special_alarm_status" to "0")
retreiveAsync("state", params, false, method = "POST")
}
})
// GET API RESPONSE FOR UI STARTUP
// Happens here because post-execute uses UI elements
retreiveAsync("state", mapOf(), true, redraw_all = true, method = "GET")
}
// Get and process HTTP response in a coroutine
private fun retreiveAsync(
api_arg: String,
params: Map<String, String>,
show_progress: Boolean,
redraw_all: Boolean = false,
method: String = "GET"){
val activity: MainActivity = activity as MainActivity
// Launch a new coroutine that executes in the Android UI thread
GlobalScope.launch(Dispatchers.Main){
// Start loader
if (show_progress) {activity.toggleLoader(true)}
// Suspend while data is obtained
val response = withContext(Dispatchers.Default) {
activity.suspendedGetFromURL(activity.apiBase+api_arg, params, method=method)
}
// Call function to handle response string, only if response not null
if (response != null) {
// If fragment layout is not null (ie. fragment still in view), handle response
if (frag_layout != null) {handleResponse(response, redraw_all=redraw_all)}
// Else log that handling has been aborted
else {Log.i("INFO", "Response processing aborted")}
// Stop loader
if (show_progress) {activity.toggleLoader(false)}
}
}
}
//HANDLE JSON RESPONSE
private fun handleResponse(responseObject: JSONObject, redraw_all: Boolean = false) {
var updateBrightnessSlider = false
//Grab resources from XML
val alarmStatusActive: String = getString(R.string.alarm_status_active)
val alarmStatusInactive: String = getString(R.string.alarm_status_inactive)
val fadeStatusActive: String = getString(R.string.fade_status_active)
val fadeStatusInactive: String = getString(R.string.fade_status_inactive)
val statusActive: Int = ContextCompat.getColor(context!!, R.color.label_active)
val statusInactive: Int = ContextCompat.getColor(context!!, R.color.label_inactive)
try {
// If global status is returned, route music have been status/all, so brightness slider should be updated
if (redraw_all) {
updateBrightnessSlider = true
}
if (responseObject.has("global_brightness_val")) {
val responseBrightnessVal = responseObject.getInt("global_brightness_val")
if (updateBrightnessSlider) {
brightness_seekbar.progress = responseBrightnessVal
}
}
if (responseObject.has("special_alarm_time")) {
val alarmTime = responseObject.getString("special_alarm_time")
val parts = alarmTime.split(":".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
val currentHours = Integer.parseInt(parts[0])
val currentMins = Integer.parseInt(parts[1])
val formattedTime = String.format("%02d", currentHours) + ":" + String.format("%02d", currentMins)
alarm_time_text.text = formattedTime
}
if (responseObject.has("special_alarm_lead")) {
val responseAlarmLead = responseObject.getInt("special_alarm_lead")
alarm_lead!!.setText(responseAlarmLead.toString())
}
if (responseObject.has("special_alarm_tail")) {
val responseAlarmTail = responseObject.getInt("special_alarm_tail")
alarm_tail!!.setText(responseAlarmTail.toString())
}
if (responseObject.has("special_alarm_status")) {
val responseAlarmStatus = responseObject.getBoolean("special_alarm_status")
if (responseAlarmStatus) {
alarm_status.text = alarmStatusActive
alarm_status.setTextColor(statusActive)
} else {
alarm_status.text = alarmStatusInactive
alarm_status.setTextColor(statusInactive)
}
}
if (responseObject.has("special_fade_minutes")) {
val responseFadeMinutes = responseObject.getInt("special_fade_minutes")
fade_time!!.setText(responseFadeMinutes.toString())
}
if (responseObject.has("special_fade_target")) {
val responseFadeTarget = responseObject.getString("special_fade_target")
val fadePercent = Math.round(java.lang.Float.parseFloat(responseFadeTarget) * 100)
fade_target_seekbar!!.progress = fadePercent
}
if (responseObject.has("special_fade_status")) {
val responseAlarmStatus = responseObject.getBoolean("special_fade_status")
if (responseAlarmStatus) {
fade_status.text = fadeStatusActive
fade_status.setTextColor(statusActive)
} else {
fade_status.text = fadeStatusInactive
fade_status.setTextColor(statusInactive)
}
}
} catch (e: JSONException) {e.printStackTrace()}
}
companion object {
fun newInstance(): ItemOneFragment {
val fragmentHome = ItemOneFragment()
val args = Bundle()
fragmentHome.arguments = args
return fragmentHome
}
}
}
| apache-2.0 | b4656d9c917fc199c3485a376d6f202d | 38.809836 | 117 | 0.59323 | 4.957942 | false | false | false | false |
sampsonjoliver/Firestarter | app/src/main/java/com/sampsonjoliver/firestarter/views/channel/create/CreateChannelActivity.kt | 1 | 14409 | package com.sampsonjoliver.firestarter.views.channel.create
import android.app.Activity
import android.app.DatePickerDialog
import android.app.ProgressDialog
import android.app.TimePickerDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AlertDialog
import android.text.format.DateUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.google.android.gms.common.GooglePlayServicesNotAvailableException
import com.google.android.gms.common.GooglePlayServicesRepairableException
import com.google.android.gms.location.places.ui.PlacePicker
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageMetadata
import com.sampsonjoliver.firestarter.FirebaseActivity
import com.sampsonjoliver.firestarter.R
import com.sampsonjoliver.firestarter.models.Session
import com.sampsonjoliver.firestarter.service.FirebaseService
import com.sampsonjoliver.firestarter.service.References
import com.sampsonjoliver.firestarter.service.SessionManager
import com.sampsonjoliver.firestarter.utils.*
import com.sampsonjoliver.firestarter.utils.IntentUtils.dispatchPickPhotoIntent
import com.sampsonjoliver.firestarter.utils.IntentUtils.dispatchTakePictureIntent
import com.sampsonjoliver.firestarter.views.dialogs.DatePickerDialogFragment
import com.sampsonjoliver.firestarter.views.dialogs.FormDialog
import com.sampsonjoliver.firestarter.views.dialogs.TimePickerDialogFragment
import kotlinx.android.synthetic.main.activity_create_channel.*
import java.io.ByteArrayOutputStream
import java.util.*
class CreateChannelActivity : FirebaseActivity() {
companion object {
val BUNDLE_TAG_TAG = "BUNDLE_TAG_TAG"
}
val calendarHolder = Calendar.getInstance()
var currentPhotoPath: String? = null
var photoUploadPending: Boolean = false
val session = Session().apply {
startDate = Date().time
username = SessionManager.getUsername()
userId = SessionManager.getUid()
}
var startDateSet = false
var endDateSet = false
val progressDialog by lazy { ProgressDialog(this) }
fun setStartTime(timeInMillis: Long) {
val currentDuration = session.durationMs
startDate.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_DATE)
startTime.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_TIME)
if (!endDateSet) {
setEndTime(timeInMillis + currentDuration)
endDateSet = false
} else {
session.durationMs = timeInMillis - session.endDate
}
session.startDate = timeInMillis
startDateSet = true
}
fun setEndTime(timeInMillis: Long) {
endDate.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_DATE)
endTime.text = DateUtils.formatDateTime(this, timeInMillis, DateUtils.FORMAT_SHOW_TIME)
session.durationMs = timeInMillis - session.startDate
endDateSet = true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_channel)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
setStartTime(Date().time)
setEndTime(session.startDate + 1000 * 60 * 60 * 2)
endDateSet = false
startDate.setOnClickListener {
calendarHolder.time = session.startDateAsDate
DatePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.YEAR),
calendarHolder.get(Calendar.MONTH),
calendarHolder.get(Calendar.DAY_OF_MONTH))
.apply { listener = DatePickerDialog.OnDateSetListener { datePicker, year, month, day ->
calendarHolder.time = session.startDateAsDate
calendarHolder.set(Calendar.YEAR, year)
calendarHolder.set(Calendar.MONTH, month)
calendarHolder.set(Calendar.DAY_OF_MONTH, day)
setStartTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, DatePickerDialogFragment.TAG)
}
startTime.setOnClickListener {
calendarHolder.time = session.startDateAsDate
TimePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.HOUR),
calendarHolder.get(Calendar.MINUTE))
.apply { listener = TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
calendarHolder.time = session.startDateAsDate
calendarHolder.set(Calendar.HOUR_OF_DAY, hour)
calendarHolder.set(Calendar.MINUTE, minute)
setStartTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, TimePickerDialogFragment.TAG)
}
endDate.setOnClickListener {
calendarHolder.time = session.endDateAsDate
DatePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.YEAR),
calendarHolder.get(Calendar.MONTH),
calendarHolder.get(Calendar.DAY_OF_MONTH),
session.startDateAsDate)
.apply { listener = DatePickerDialog.OnDateSetListener { datePicker, year, month, day ->
calendarHolder.time = session.endDateAsDate
calendarHolder.set(Calendar.YEAR, year)
calendarHolder.set(Calendar.MONTH, month)
calendarHolder.set(Calendar.DAY_OF_MONTH, day)
setEndTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, DatePickerDialogFragment.TAG)
endDateSet = true
}
endTime.setOnClickListener {
calendarHolder.time = session.endDateAsDate
TimePickerDialogFragment.newInstance(
calendarHolder.get(Calendar.HOUR),
calendarHolder.get(Calendar.MINUTE))
.apply { listener = TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
calendarHolder.time = session.endDateAsDate
calendarHolder.set(Calendar.HOUR_OF_DAY, hour)
calendarHolder.set(Calendar.MINUTE, minute)
setEndTime(calendarHolder.timeInMillis)
} }
.show(supportFragmentManager, TimePickerDialogFragment.TAG)
}
location.setOnClickListener {
// Construct an intent for the place picker
try {
val intent = PlacePicker.IntentBuilder().build(this)
startActivityForResult(intent, IntentUtils.REQUEST_PLACE_PICKER)
} catch (e: GooglePlayServicesRepairableException) {
// ...
} catch (e: GooglePlayServicesNotAvailableException) {
// ...
}
}
addTag.setOnClickListener {
progressDialog.setMessage(getString(R.string.loading))
progressDialog.show()
FirebaseService.getReference(References.tags).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError?) {
progressDialog.dismiss()
}
override fun onDataChange(p0: DataSnapshot?) {
progressDialog.dismiss()
val tags = p0?.children?.map { it.key }?.toTypedArray()
val selectedTags = tags?.map { Pair(it, session.tags[it] ?: false) }.orEmpty().toMap(mutableMapOf())
val checkedIndexes = selectedTags.values.toBooleanArray()
AlertDialog.Builder(this@CreateChannelActivity)
.setMultiChoiceItems(tags, checkedIndexes, { dialogInterface, i, b ->
selectedTags.set(tags?.get(i).orEmpty(), b)
})
.setPositiveButton(getString(R.string.save), { dialogInterface, i ->
session.tags = selectedTags
tagList.text = session.tags.entries.filter { it.value == true }.map { it.key }.joinToString()
})
.setNegativeButton(getString(R.string.cancel), null)
.show()
}
})
}
banner.setOnClickListener {
AlertDialog.Builder(this@CreateChannelActivity)
.setItems(arrayOf(getString(R.string.take_photo), getString(R.string.upload_photo)), { dialogInterface, index ->
if (index == 0) {
// Take photo
currentPhotoPath = dispatchTakePictureIntent(this)
} else if (index == 1) {
// Upload photo
dispatchPickPhotoIntent(this)
}
}).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
IntentUtils.REQUEST_PLACE_PICKER -> {
resultCode.whenEqual(Activity.RESULT_OK) {
// The user has selected a place. Extract the name and address.
val place = PlacePicker.getPlace(this, data)
val name = place.name
val address = place.address
session.address = address.toString()
session.setLocation(place.latLng)
location.text = address
}
}
IntentUtils.REQUEST_IMAGE_PICKER -> {
photoUploadPending = false
currentPhotoPath = null
resultCode.whenEqual(Activity.RESULT_OK) {
data?.data?.run {
photoUploadPending = true
currentPhotoPath = this.toString()
}
}
banner.setImageURI(currentPhotoPath ?: "")
}
IntentUtils.REQUEST_IMAGE_CAPTURE -> {
photoUploadPending = false
resultCode.whenEqual(Activity.RESULT_OK) {
Uri.parse(currentPhotoPath)?.run {
photoUploadPending = true
}
}
banner.setImageURI(currentPhotoPath)
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_create_channel, menu)
return super.onCreateOptionsMenu(menu)
}
fun saveChannel() {
val progressDialog = ProgressDialog(this@CreateChannelActivity)
progressDialog.setMessage(getString(R.string.creating_channel))
progressDialog.show()
if (photoUploadPending) {
Uri.parse(currentPhotoPath)?.run {
progressDialog.setMessage(getString(R.string.uploading_image, 0f))
val thumb = BitmapUtils.decodeSampledBitmap(currentPhotoPath!!, 820, 312)
val bos = ByteArrayOutputStream()
thumb.compress(Bitmap.CompressFormat.PNG, 100, bos)
val thumbData = bos.toByteArray()
FirebaseStorage.getInstance().getReference("${References.Images}/banners/${this.lastPathSegment}")
.putBytes(thumbData, StorageMetadata.Builder()
.setContentType("image/jpg")
.setCustomMetadata("uid", SessionManager.getUid())
.build()
).addOnFailureListener {
Log.d(TAG, "Upload Failed: " + it.message)
progressDialog.dismiss()
}.addOnProgressListener {
Log.d(TAG, "Upload Progress: ${it.bytesTransferred} / ${it.totalByteCount}")
progressDialog.setMessage(getString(R.string.uploading_image, (it.bytesTransferred.toFloat() / it.totalByteCount.toFloat()) * 100f))
}.addOnSuccessListener { photoIt ->
progressDialog.setMessage(getString(R.string.creating_channel))
session.bannerUrl = photoIt.downloadUrl.toString()
FirebaseService.createSession(session,
{ finish() },
{ Snackbar.make(toolbar, R.string.create_session_save_error, Snackbar.LENGTH_LONG).show() }
)
}
}
} else {
FirebaseService.createSession(session,
{ finish() },
{ Snackbar.make(toolbar, R.string.create_session_save_error, Snackbar.LENGTH_LONG).show() }
)
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu_save -> {
if (validate()) {
saveChannel()
}
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
fun validate(): Boolean {
session.topic = topic.text.toString()
session.description = description.text.toString()
return session.topic.isNullOrBlank().not() &&
session.address.isNullOrBlank().not() &&
session.username.isNullOrBlank().not() &&
session.startDate > 0 &&
session.durationMs > 0
}
} | apache-2.0 | 9ef8f8fed39bcba8d2f22d35564a21c6 | 42.534743 | 160 | 0.596572 | 5.589216 | false | false | false | false |
nisrulz/android-examples | UsingTimberLogger/app/src/main/java/github/nisrulz/example/usingtimberlogger/ReleaseTree.kt | 1 | 647 | package github.nisrulz.example.usingtimberlogger
import android.util.Log
import timber.log.Timber
class ReleaseTree : Timber.Tree() {
override fun isLoggable(tag: String?, priority: Int): Boolean {
// Only log WARN, ERROR, WTF
return !(priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO)
}
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (isLoggable(tag, priority)) {
// Report all caught exceptions to crashlytics
if (priority == Log.ERROR && t != null) {
// Crashlytics.log(t)
}
}
}
} | apache-2.0 | 0ea36f9c808c52ea74ab4d23f8821d2a | 29.857143 | 90 | 0.601236 | 4.201299 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/crafting/FurnaceCraftingProcess.kt | 2 | 1774 | package com.cout970.magneticraft.misc.crafting
import com.cout970.magneticraft.api.internal.ApiUtils
import com.cout970.magneticraft.misc.fromCelsiusToKelvin
import com.cout970.magneticraft.systems.tilemodules.ModuleInventory
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.FurnaceRecipes
/**
* Created by cout970 on 2017/07/01.
*/
class FurnaceCraftingProcess(
val invModule: ModuleInventory,
val inputSlot: Int,
val outputSlot: Int
) : ICraftingProcess, IHeatCraftingProcess {
private var cacheKey: ItemStack = ItemStack.EMPTY
private var cacheValue: ItemStack = ItemStack.EMPTY
private fun getInput() = invModule.inventory.extractItem(inputSlot, 1, true)
private fun getOutput(input: ItemStack): ItemStack {
if (ApiUtils.equalsIgnoreSize(cacheKey, input)) return cacheValue
val recipe = FurnaceRecipes.instance().getSmeltingResult(input)
cacheKey = input
cacheValue = recipe
return recipe
}
override fun craft() {
val input = invModule.inventory.extractItem(inputSlot, 1, false)
val output = FurnaceRecipes.instance().getSmeltingResult(input).copy()
invModule.inventory.insertItem(outputSlot, output, false)
}
override fun canCraft(): Boolean {
val input = getInput()
// check non empty and size >= 1
if (input.isEmpty) return false
//check recipe
val output = getOutput(input)
if (output.isEmpty) return false
//check inventory space
val insert = invModule.inventory.insertItem(outputSlot, output, true)
return insert.isEmpty
}
override fun duration(): Float = 100f
override fun minTemperature(): Float = 60.fromCelsiusToKelvin().toFloat()
} | gpl-2.0 | 9adb9709f16eeaa57d83f58addac46dd | 31.272727 | 80 | 0.710823 | 4.42394 | false | false | false | false |
f-droid/fdroidclient | libs/index/src/commonMain/kotlin/org/fdroid/index/IndexConverter.kt | 1 | 3486 | package org.fdroid.index
import org.fdroid.index.v1.IndexV1
import org.fdroid.index.v1.Localized
import org.fdroid.index.v2.AntiFeatureV2
import org.fdroid.index.v2.CategoryV2
import org.fdroid.index.v2.IndexV2
import org.fdroid.index.v2.LocalizedTextV2
import org.fdroid.index.v2.PackageV2
import org.fdroid.index.v2.ReleaseChannelV2
public const val RELEASE_CHANNEL_BETA: String = "Beta"
internal const val DEFAULT_LOCALE = "en-US"
public class IndexConverter(
private val defaultLocale: String = DEFAULT_LOCALE,
) {
public fun toIndexV2(v1: IndexV1): IndexV2 {
val antiFeatures = HashMap<String, AntiFeatureV2>()
val categories = HashMap<String, CategoryV2>()
val packagesV2 = HashMap<String, PackageV2>(v1.apps.size)
v1.apps.forEach { app ->
val versions = v1.packages[app.packageName]
val preferredSigner = versions?.get(0)?.signer
val appAntiFeatures: Map<String, LocalizedTextV2> =
app.antiFeatures.associateWith { emptyMap() }
val whatsNew: LocalizedTextV2? = app.localized?.mapValuesNotNull { it.value.whatsNew }
var isFirstVersion = true
val packageV2 = PackageV2(
metadata = app.toMetadataV2(preferredSigner, defaultLocale),
versions = versions?.associate {
val versionCode = it.versionCode ?: 0
val suggestedVersionCode = app.suggestedVersionCode?.toLongOrNull() ?: 0
val versionReleaseChannels = if (versionCode > suggestedVersionCode)
listOf(RELEASE_CHANNEL_BETA) else emptyList()
val wn = if (isFirstVersion) whatsNew else null
isFirstVersion = false
it.hash to it.toPackageVersionV2(versionReleaseChannels, appAntiFeatures, wn)
} ?: emptyMap(),
)
appAntiFeatures.mapInto(antiFeatures)
app.categories.mapInto(categories)
packagesV2[app.packageName] = packageV2
}
return IndexV2(
repo = v1.repo.toRepoV2(
locale = defaultLocale,
antiFeatures = antiFeatures,
categories = categories,
releaseChannels = getV1ReleaseChannels(),
),
packages = packagesV2,
)
}
}
internal fun <T> Collection<String>.mapInto(map: HashMap<String, T>, valueGetter: (String) -> T) {
forEach { key ->
if (!map.containsKey(key)) map[key] = valueGetter(key)
}
}
internal fun List<String>.mapInto(map: HashMap<String, CategoryV2>) {
mapInto(map) { key ->
CategoryV2(name = mapOf(DEFAULT_LOCALE to key))
}
}
internal fun Map<String, LocalizedTextV2>.mapInto(map: HashMap<String, AntiFeatureV2>) {
keys.mapInto(map) { key ->
AntiFeatureV2(name = mapOf(DEFAULT_LOCALE to key))
}
}
public fun getV1ReleaseChannels(): Map<String, ReleaseChannelV2> = mapOf(
RELEASE_CHANNEL_BETA to ReleaseChannelV2(
name = mapOf(DEFAULT_LOCALE to RELEASE_CHANNEL_BETA),
description = emptyMap(),
)
)
internal fun <T> Map<String, Localized>.mapValuesNotNull(
transform: (Map.Entry<String, Localized>) -> T?,
): Map<String, T>? {
val map = LinkedHashMap<String, T>(size)
for (element in this) {
val value = transform(element)
if (value != null) map[element.key] = value
}
return map.takeIf { map.isNotEmpty() }
}
| gpl-3.0 | 4c4d9f2803d9e903d95dd9fd07b6dc7c | 36.483871 | 98 | 0.634825 | 3.993127 | false | false | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/browser/webview/factory/WebViewClientFactory.kt | 1 | 7944 | /*
* Copyright (c) 2020 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.webview.factory
import android.annotation.TargetApi
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.webkit.SslErrorHandler
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.FragmentActivity
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.dialog.ConfirmDialogFragment
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.BrowserHeaderViewModel
import jp.toastkid.yobidashi.browser.FaviconApplier
import jp.toastkid.yobidashi.browser.LoadingViewModel
import jp.toastkid.yobidashi.browser.block.AdRemover
import jp.toastkid.yobidashi.browser.history.ViewHistoryInsertion
import jp.toastkid.yobidashi.browser.tls.TlsErrorMessageGenerator
import jp.toastkid.yobidashi.browser.webview.GlobalWebViewPool
import jp.toastkid.yobidashi.browser.webview.usecase.RedirectionUseCase
import jp.toastkid.rss.suggestion.RssAddingSuggestion
import jp.toastkid.yobidashi.tab.History
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
class WebViewClientFactory(
private val contentViewModel: ContentViewModel?,
private val adRemover: AdRemover,
private val faviconApplier: FaviconApplier,
private val preferenceApplier: PreferenceApplier,
private val browserHeaderViewModel: BrowserHeaderViewModel? = null,
private val rssAddingSuggestion: RssAddingSuggestion? = null,
private val loadingViewModel: LoadingViewModel? = null,
private val currentView: () -> WebView? = { null }
) {
/**
* Add onPageFinished and onPageStarted.
*/
operator fun invoke(): WebViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
browserHeaderViewModel?.updateProgress(0)
browserHeaderViewModel?.nextUrl(url)
rssAddingSuggestion?.invoke(view, url)
browserHeaderViewModel?.setBackButtonEnability(view.canGoBack())
}
override fun onPageFinished(view: WebView, url: String?) {
super.onPageFinished(view, url)
val title = view.title ?: ""
val urlStr = url ?: ""
val tabId = GlobalWebViewPool.getTabId(view)
if (tabId?.isNotBlank() == true) {
CoroutineScope(Dispatchers.Main).launch {
loadingViewModel?.finished(tabId, History.make(title, urlStr))
}
}
browserHeaderViewModel?.updateProgress(100)
browserHeaderViewModel?.stopProgress(true)
try {
if (view == currentView()) {
browserHeaderViewModel?.nextTitle(title)
browserHeaderViewModel?.nextUrl(urlStr)
}
} catch (e: Exception) {
Timber.e(e)
}
if (preferenceApplier.saveViewHistory
&& title.isNotEmpty()
&& urlStr.isNotEmpty()
) {
ViewHistoryInsertion
.make(
view.context,
title,
urlStr,
faviconApplier.makePath(urlStr)
)
.invoke()
}
}
override fun onReceivedError(
view: WebView, request: WebResourceRequest, error: WebResourceError) {
super.onReceivedError(view, request, error)
browserHeaderViewModel?.updateProgress(100)
browserHeaderViewModel?.stopProgress(true)
}
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
super.onReceivedSslError(view, handler, error)
handler?.cancel()
val context = view?.context ?: return
if (context !is FragmentActivity || context.isFinishing) {
return
}
ConfirmDialogFragment.show(
context.supportFragmentManager,
context.getString(R.string.title_ssl_connection_error),
TlsErrorMessageGenerator().invoke(context, error),
"tls_error"
)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
if (preferenceApplier.adRemove) {
adRemover(request.url.toString())
} else {
super.shouldInterceptRequest(view, request)
}
@Suppress("OverridingDeprecatedMember")
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? =
if (preferenceApplier.adRemove) {
adRemover(url)
} else {
@Suppress("DEPRECATION")
super.shouldInterceptRequest(view, url)
}
@Suppress("DEPRECATION")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean =
shouldOverrideUrlLoading(view, request?.url?.toString())
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean =
url?.let {
val context: Context? = view?.context
val uri: Uri = Uri.parse(url)
if (RedirectionUseCase.isTarget(uri)) {
RedirectionUseCase().invoke(view, uri)
return@let false
}
when (uri.scheme) {
"market", "intent" -> {
try {
context?.startActivity(Intent.parseUri(url, Intent.URI_INTENT_SCHEME))
true
} catch (e: ActivityNotFoundException) {
Timber.w(e)
context?.let {
contentViewModel?.snackShort(context.getString(R.string.message_cannot_launch_app))
}
true
}
}
"tel" -> {
context?.startActivity(Intent(Intent.ACTION_DIAL, uri))
view?.reload()
true
}
"mailto" -> {
context?.startActivity(Intent(Intent.ACTION_SENDTO, uri))
view?.reload()
true
}
else -> {
super.shouldOverrideUrlLoading(view, url)
}
}
} ?: super.shouldOverrideUrlLoading(view, url)
}
} | epl-1.0 | ea9eb365673d9201df42a474e1b80e7c | 38.527363 | 119 | 0.585599 | 5.555245 | false | false | false | false |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/RequestPermissionActivity.kt | 2 | 3004 | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leakcanary.internal
import android.annotation.TargetApi
import android.app.Activity
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.os.Bundle
import android.os.Build
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import com.squareup.leakcanary.core.R
@TargetApi(Build.VERSION_CODES.M) //
internal class RequestPermissionActivity : Activity() {
private val targetPermission: String
get() = intent.getStringExtra(TARGET_PERMISSION_EXTRA)!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
if (hasTargetPermission()) {
finish()
return
}
val permissions = arrayOf(targetPermission)
requestPermissions(permissions, 42)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (!hasTargetPermission()) {
Toast.makeText(application, R.string.leak_canary_permission_not_granted, LENGTH_LONG)
.show()
}
finish()
}
override fun finish() {
// Reset the animation to avoid flickering.
overridePendingTransition(0, 0)
super.finish()
}
private fun hasTargetPermission(): Boolean {
return checkSelfPermission(targetPermission) == PERMISSION_GRANTED
}
companion object {
private const val TARGET_PERMISSION_EXTRA = "targetPermission"
fun createIntent(context: Context, permission: String): Intent {
return Intent(context, RequestPermissionActivity::class.java).apply {
flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TOP
putExtra(TARGET_PERMISSION_EXTRA, permission)
}
}
fun createPendingIntent(context: Context, permission: String): PendingIntent {
val intent = createIntent(context, permission)
val flags = if (Build.VERSION.SDK_INT >= 23) {
FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE
} else {
FLAG_UPDATE_CURRENT
}
return PendingIntent.getActivity(context, 1, intent, flags)
}
}
}
| apache-2.0 | 2dd1091f71b716e8b33c385a3f2dddce | 30.621053 | 91 | 0.728029 | 4.398243 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2020/Day22.kt | 1 | 2882 | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import java.util.*
/**
* --- Day 22: Crab Combat ---
* https://adventofcode.com/2020/day/22
*/
class Day22 : Solver {
override fun solve(lines: List<String>): Result {
val playersA = parse(lines)
// Make copy for Part B where we have to start over.
val playersB = playersA.map { LinkedList(it) }
// The game is going while none of them ran out of cards.
while (playersA[0].isNotEmpty() && playersA[1].isNotEmpty()) {
val top = Pair(playersA[0].removeAt(0), playersA[1].removeAt(0))
if (top.first > top.second) {
playersA[0].add(top.first)
playersA[0].add(top.second)
} else {
playersA[1].add(top.second)
playersA[1].add(top.first)
}
}
val winnerA = if (playersA.isNotEmpty()) 0 else 1
val resultA = playersA[winnerA].reversed().withIndex().map { (it.index + 1) * it.value }.sum()
// Part 2
val winnerB = recursiveCombat(playersB, 1)
val resultB = playersB[winnerB].reversed().withIndex().map { (it.index + 1) * it.value }.sum()
return Result("$resultA", "$resultB")
}
private fun recursiveCombat(players: List<LinkedList<Long>>, gameNo: Int): Int {
val history = Array(2) { mutableSetOf<Int>() }
var roundNo = 1
var roundWinner = -42
while (players[0].isNotEmpty() && players[1].isNotEmpty()) {
// Player 0 wins when history repeats.
if (players[0].hashCode() in history[0] || players[1].hashCode() in history[1]) return 0
history[0].add(players[0].hashCode())
history[1].add(players[1].hashCode())
// Top cards.
val top = Pair(players[0].pop(), players[1].pop())
roundWinner = if (players[0].size >= top.first && players[1].size >= top.second) {
// Play sub-game, recursive combat! Create copies so that our list is not changed.
val subListA = LinkedList(players[0].subList(0, top.first.toInt()))
val subListB = LinkedList(players[1].subList(0, top.second.toInt()))
recursiveCombat(listOf(subListA, subListB), gameNo + 1)
} else if (top.first > top.second) 0 else 1
// Add cards to the round winners deck in the right order (winner's first).
players[roundWinner].add(if (roundWinner == 0) top.first else top.second)
players[roundWinner].add(if (roundWinner == 0) top.second else top.first)
roundNo++
}
return roundWinner
}
private fun parse(lines: List<String>): List<LinkedList<Long>> {
val players = mutableListOf<LinkedList<Long>>(LinkedList(), LinkedList())
var activePlayerParsing = 0
for (line in lines) {
if (line.startsWith("Player 1:") || line.isBlank()) continue
if (line.startsWith("Player 2:")) activePlayerParsing = 1
else players[activePlayerParsing].add(line.toLong())
}
return players
}
} | apache-2.0 | b0aa172be4f46dc5b27fe545f8889307 | 37.44 | 98 | 0.640527 | 3.562423 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/ui/adapter/CompanyListAdapter.kt | 1 | 2619 | package info.papdt.express.helper.ui.adapter
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.util.ArrayList
import de.hdodenhof.circleimageview.CircleImageView
import info.papdt.express.helper.R
import info.papdt.express.helper.api.Kuaidi100PackageApi
import info.papdt.express.helper.ui.common.SimpleRecyclerViewAdapter
class CompanyListAdapter(
recyclerView: RecyclerView,
private var list: ArrayList<Kuaidi100PackageApi.CompanyInfo.Company>?
) : SimpleRecyclerViewAdapter(recyclerView) {
fun setList(list: ArrayList<Kuaidi100PackageApi.CompanyInfo.Company>) {
this.list = list
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleRecyclerViewAdapter.ClickableViewHolder {
bindContext(parent.context)
return ItemHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_list_company, parent, false))
}
override fun onBindViewHolder(holder: SimpleRecyclerViewAdapter.ClickableViewHolder, position: Int) {
super.onBindViewHolder(holder, position)
val item = getItem(position)
if (holder is ItemHolder) {
holder.titleText.text = item.name
holder.otherText.text = if (item.phone != null) item.phone else item.website
holder.otherText.visibility = if (holder.otherText.text != null) View.VISIBLE else View.INVISIBLE
/** Set up the logo */
holder.firstCharText.text = item.name.substring(0, 1)
item.getPalette().let {
holder.logoView.setImageDrawable(
ColorDrawable(it.getPackageIconBackground(context!!)))
holder.firstCharText.setTextColor(
it.getPackageIconForeground(context!!))
}
}
}
override fun getItemCount(): Int = list?.size ?: 0
fun getItem(pos: Int): Kuaidi100PackageApi.CompanyInfo.Company = list!![pos]
inner class ItemHolder(itemView: View) : SimpleRecyclerViewAdapter.ClickableViewHolder(itemView) {
internal var titleText: AppCompatTextView = itemView.findViewById(R.id.tv_title)
internal var otherText: AppCompatTextView = itemView.findViewById(R.id.tv_other)
internal var logoView: CircleImageView = itemView.findViewById(R.id.iv_logo)
internal var firstCharText: TextView = itemView.findViewById(R.id.tv_first_char)
}
}
| gpl-3.0 | cded81c3bf31e1251967062d9f5c40fa | 39.921875 | 118 | 0.722413 | 4.515517 | false | false | false | false |
googleapis/gax-kotlin | examples-android/app/src/main/java/com/google/api/kgax/examples/grpc/LanguageRetryActivity.kt | 1 | 2969 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kgax.examples.grpc
import android.os.Bundle
import android.support.test.espresso.idling.CountingIdlingResource
import android.util.Log
import com.google.api.kgax.Retry
import com.google.api.kgax.RetryContext
import com.google.api.kgax.grpc.StubFactory
import com.google.cloud.language.v1.AnalyzeEntitiesRequest
import com.google.cloud.language.v1.Document
import com.google.cloud.language.v1.LanguageServiceGrpc
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
/**
* Kotlin example showcasing client side retries using KGax with gRPC and the
* Google Natural Language API.
*/
class LanguageRetryActivity : AbstractExampleActivity<LanguageServiceGrpc.LanguageServiceFutureStub>(
CountingIdlingResource("LanguageRetry")
) {
lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override val factory = StubFactory(
LanguageServiceGrpc.LanguageServiceFutureStub::class,
"language.googleapis.com", 443
)
override val stub by lazy {
applicationContext.resources.openRawResource(R.raw.sa).use {
factory.fromServiceAccount(
it,
listOf("https://www.googleapis.com/auth/cloud-platform")
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
// call the api
launch(Dispatchers.Main) {
val response = stub.prepare {
withRetry(RetryForever)
}.execute { it ->
it.analyzeEntities(
AnalyzeEntitiesRequest.newBuilder().apply {
document = Document.newBuilder().apply {
content = "Hi there Joe"
type = Document.Type.PLAIN_TEXT
}.build()
}.build()
)
}
updateUIWithExampleResult(response.toString())
}
}
}
object RetryForever : Retry {
override fun retryAfter(error: Throwable, context: RetryContext): Long? {
Log.i("Retry", "Will attempt retry #${context.numberOfAttempts}")
// retry after a 500 ms delay
return 500
}
}
| apache-2.0 | be0bc07f1ae76721673445ceb88f1f79 | 31.988889 | 101 | 0.666891 | 4.653605 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/movie/get/MovieGetProductionCompany.kt | 1 | 806 | package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.get
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder("id", "logo_path", "name", "origin_country")
class MovieGetProductionCompany {
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: Int? = null
@get:JsonProperty("logo_path")
@set:JsonProperty("logo_path")
@JsonProperty("logo_path")
var logoPath: String? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("origin_country")
@set:JsonProperty("origin_country")
@JsonProperty("origin_country")
var originCountry: String? = null
} | apache-2.0 | 4e20e7652443512d8bee32ef825fe7cd | 27.821429 | 65 | 0.699752 | 3.838095 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/samples/html/InspectHtmlTextSample.kt | 1 | 1742 | package io.noties.markwon.app.samples.html
import android.text.style.URLSpan
import io.noties.markwon.Markwon
import io.noties.markwon.MarkwonVisitor
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample
import io.noties.markwon.html.HtmlPlugin
import io.noties.markwon.html.HtmlTag
import io.noties.markwon.html.MarkwonHtmlRenderer
import io.noties.markwon.html.TagHandler
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.sample.annotations.MarkwonSampleInfo
import io.noties.markwon.sample.annotations.Tag
@MarkwonSampleInfo(
id = "20210201140501",
title = "Inspect text",
description = "Inspect text content of a `HTML` node",
artifacts = [MarkwonArtifact.HTML],
tags = [Tag.html]
)
class InspectHtmlTextSample : MarkwonTextViewSample() {
override fun render() {
val md = """
<p>lorem ipsum</p>
<div class="custom-youtube-player">https://www.youtube.com/watch?v=abcdefgh</div>
""".trimIndent()
val markwon = Markwon.builder(context)
.usePlugin(HtmlPlugin.create {
it.addHandler(DivHandler())
})
.build()
markwon.setMarkdown(textView, md)
}
class DivHandler : TagHandler() {
override fun handle(visitor: MarkwonVisitor, renderer: MarkwonHtmlRenderer, tag: HtmlTag) {
val attr = tag.attributes()["class"] ?: return
if (attr.contains(CUSTOM_CLASS)) {
val text = visitor.builder().substring(tag.start(), tag.end())
visitor.builder().setSpan(
URLSpan(text),
tag.start(),
tag.end()
)
}
}
override fun supportedTags(): Collection<String> = setOf("div")
companion object {
const val CUSTOM_CLASS = "custom-youtube-player"
}
}
} | apache-2.0 | cbeb99d9c3a52c5658be7e112de2f8fa | 29.578947 | 95 | 0.697474 | 3.950113 | false | false | false | false |
rei-m/android_hyakuninisshu | state/src/main/java/me/rei_m/hyakuninisshu/state/exam/action/FetchAllExamResultAction.kt | 1 | 1277 | /*
* Copyright (c) 2020. Rei Matsushita
*
* 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 me.rei_m.hyakuninisshu.state.exam.action
import me.rei_m.hyakuninisshu.state.core.Action
import me.rei_m.hyakuninisshu.state.exam.model.ExamResult
/**
* 力試しの結果をすべて取得するアクション.
*/
sealed class FetchAllExamResultAction(override val error: Throwable? = null) : Action {
class Success(
val examResultList: List<ExamResult>
) : FetchAllExamResultAction() {
override fun toString() = "$name(examResultList=$examResultList)"
}
class Failure(error: Throwable) : FetchAllExamResultAction(error) {
override fun toString() = "$name(error=$error)"
}
override val name = "FetchAllExamResultAction"
}
| apache-2.0 | 72eb8ed3e39bd39f3e5045204741c683 | 34.4 | 112 | 0.732042 | 3.933333 | false | false | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/alarm/AlarmItem.kt | 1 | 1619 | /*
* Copyright 2016, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates.alarm
import com.github.duplicates.DaysOfWeek
import com.github.duplicates.DuplicateItem
import com.github.duplicates.DuplicateItemType
/**
* Duplicate alarm item.
*
* @author moshe.w
*/
class AlarmItem : DuplicateItem(DuplicateItemType.ALARM) {
var activate: Int = 0
var alarmTime: Int = 0
var alertTime: Long = 0
var createTime: Long = 0
var isDailyBriefing: Boolean = false
var name: String? = null
var notificationType: Int = 0
var repeat: DaysOfWeek? = null
var isSnoozeActivate: Boolean = false
var snoozeDoneCount: Int = 0
var snoozeDuration: Int = 0
var snoozeRepeat: Int = 0
var soundTone: Int = 0
var soundType: Int = 0
var soundUri: String? = null
var isSubdueActivate: Boolean = false
var subdueDuration: Int = 0
var subdueTone: Int = 0
var subdueUri: Int = 0
var volume: Int = 0
override fun contains(s: CharSequence): Boolean {
return name?.contains(s, true) ?: false
}
}
| apache-2.0 | a64204816f36c6e600ee13a13277305e | 29.54717 | 75 | 0.702285 | 3.987685 | false | false | false | false |
dennism1997/BeachVolleyballWeather | app/src/main/java/com/moumou/beachvolleyballweather/SharedPreferencesHandler.kt | 1 | 1447 | package com.moumou.beachvolleyballweather
import android.content.Context
import android.support.v7.app.AlertDialog
import android.support.v7.preference.PreferenceManager
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import com.moumou.beachvolleyballweather.weather.WeatherLocation
object SharedPreferencesHandler {
val KEY_WEATHER_LOCATIONS = "WEATHERLOCATIONS"
fun storeLocations(c : Context, l : ArrayList<WeatherLocation>) {
val sharedPref = PreferenceManager.getDefaultSharedPreferences(c)
val editor = sharedPref.edit()
editor.putString(KEY_WEATHER_LOCATIONS, Gson().toJson(l))
editor.apply()
}
fun getLocations(c : Context) : ArrayList<WeatherLocation> {
val sharedPref = PreferenceManager.getDefaultSharedPreferences(c)
val s = sharedPref.getString(KEY_WEATHER_LOCATIONS, "")
val type = object : TypeToken<ArrayList<WeatherLocation>>() {}.type
if (s != "") {
try {
return Gson().fromJson<ArrayList<WeatherLocation>>(s, type)
} catch (e : JsonSyntaxException) {
AlertDialog.Builder(c).setMessage(c.getString(R.string.storage_parsing_error)).setPositiveButton(
R.string.ok) { dialog, _ ->
dialog.dismiss()
}.show()
}
}
return ArrayList()
}
} | mit | 1a3ad69e8cbd836b59599c34ee58f2a0 | 35.2 | 113 | 0.666206 | 4.579114 | false | false | false | false |
SchoolPower/SchoolPower-Android | app/src/main/java/com/carbonylgroup/schoolpower/data/Subject.kt | 1 | 6721 | /**
* Copyright (C) 2019 SchoolPower Studio
*/
package com.carbonylgroup.schoolpower.data
import com.carbonylgroup.schoolpower.utils.Utils
import org.json.JSONObject
import java.io.Serializable
import java.util.*
/*
Sample:
{
"assignments": [
(AssignmentItem)...
],
"expression": "1(A-E)",
"startDate": "2017-08-31T16:00:00.000Z",
"endDate": "2018-01-21T16:00:00.000Z",
"finalGrades": {
"X1": {
"percent": "0.0",
"letter": "--",
"comment": null,
"eval": "--",
"startDate": 1515945600,
"endDate": 1515945600
},
"T2": {
"percent": "92.0",
"letter": "A",
"comment": "Some comments",
"eval": "M",
"startDate": 1510502400,
"endDate": 1510502400
},
"T1": {
"percent": "90.0",
"letter": "A",
"comment": "Some comments",
"eval": "M",
"startDate": 1504195200,
"endDate": 1504195200
},
"S1": {
"percent": "91.0",
"letter": "A",
"comment": null,
"eval": "M",
"startDate": 1504195200,
"endDate": 1504195200
}
},
"name": "Course Name",
"roomName": "100",
"teacher": {
"firstName": "John",
"lastName": "Doe",
"email": null,
"schoolPhone": null
}
}
*/
class Subject(json: JSONObject, utils: Utils) : Serializable {
val name: String = json.getString("name")
val teacherName: String = json.getJSONObject("teacher").let { obj -> obj.getString("firstName") + " " + obj.getString("lastName") }
val teacherEmail: String = json.getJSONObject("teacher").optString("email")
val blockLetter: String // init in code
val roomNumber: String = json.getString("roomName")
val assignments: ArrayList<AssignmentItem> = arrayListOf()
val grades: HashMap<String, Grade> = hashMapOf()
val startDate: Long
val endDate: Long
var margin = 0
private fun getAdjustedExpression(utils: Utils, blockLetterRaw: String): String {
// Smart block display
if (!utils.getPreferences().getBoolean("list_preference_even_odd_filter", false)
|| blockLetterRaw == "")
return blockLetterRaw
val blockStartIndex = blockLetterRaw.indexOf('(')
val currentWeekIsEven =
utils.getPreferences().getBoolean("list_preference_is_even_week", false)
val blocksToDisplay = arrayListOf<String>()
var oddEvenWeekFeatureEnabled = false
// e.g. 1(A-J), 2(B-C,F,H)
for (block in blockLetterRaw.substring(blockStartIndex + 1, blockLetterRaw.length - 1)
.split(",")) {
// A, B, C, D, E
val odd = block.indexOf('A') != -1
|| block.indexOf('B') != -1
|| block.indexOf('C') != -1
|| block.indexOf('D') != -1
|| block.indexOf('E') != -1
// F, G, H, I, J
val even = block.indexOf('F') != -1
|| block.indexOf('G') != -1
|| block.indexOf('H') != -1
|| block.indexOf('I') != -1
|| block.indexOf('J') != -1
if (even) oddEvenWeekFeatureEnabled = true
if ((even && currentWeekIsEven) || (odd && !currentWeekIsEven))
blocksToDisplay.add(block)
}
if (oddEvenWeekFeatureEnabled) {
return blockLetterRaw.substring(0, blockStartIndex + 1) +
blocksToDisplay.joinToString(",") + ")"
} else {
return blockLetterRaw
}
}
init {
if (!json.isNull("assignments")) {
val jsonAssignments = json.getJSONArray("assignments")
(0 until jsonAssignments.length()).mapTo(assignments) { AssignmentItem(jsonAssignments.getJSONObject(it)) }
}
val categoriesWeights = CategoryWeightData(utils)
if (!json.isNull("finalGrades")) {
val finalGrades = json.getJSONObject("finalGrades")
for (key in finalGrades.keys()) {
val grade = finalGrades.getJSONObject(key)
grades[key] = Grade(grade.getString("percent").toDouble().toInt().toString(),
grade.getString("letter"), grade.getString("comment"), grade.getString("eval"),
CalculatedGrade(this, key, categoriesWeights))
}
}
startDate = Utils.convertDateToTimestamp(json.getString("startDate"))
endDate = Utils.convertDateToTimestamp(json.getString("endDate"))
val blockLetterRaw = json.getString("expression")
blockLetter = try {
getAdjustedExpression(utils, blockLetterRaw)
} catch (e: Exception) {
blockLetterRaw
}
}
// Call it when weights of categories have been changed.
fun recalculateGrades(weights: CategoryWeightData) {
for ((name, grade) in grades) {
grade.calculatedGrade = CalculatedGrade(this, name, weights)
}
}
// Compare `oldSubject` with this one and mark changed assignments
fun markNewAssignments(oldSubject: Subject, utils: Utils) {
// Mark new or changed assignments
val newAssignmentListCollection = assignments
val oldAssignmentListCollection = oldSubject.assignments
for (item in newAssignmentListCollection) {
// if no item in oldAssignmentListCollection has the same title, score and date as those of the new one, then the assignment should be marked.
val found = oldAssignmentListCollection.any {
it.title == item.title && it.score == item.score && it.date == item.date && !it.isNew
}
if (!found) {
item.isNew = true
margin = 0
val oldPercent = utils.getLatestTermGrade(oldSubject)?.getGrade() ?: continue
val newPercent = utils.getLatestTermGrade(this)?.getGrade() ?: continue
if (oldPercent != newPercent)
margin = newPercent - oldPercent
}
}
}
fun getShortName() = Utils.getShortName(name)
fun getLatestTermName(utils: Utils): String? =
utils.getLatestTermName(this.grades)
fun getLatestTermGrade(utils: Utils) = utils.getLatestTermGrade(this)
} | gpl-3.0 | 2ee67976f022ff930050f5c318872c73 | 34.946524 | 154 | 0.536825 | 4.510738 | false | false | false | false |
SpryServers/sprycloud-android | src/main/java/com/nextcloud/client/logger/ui/LogsEmailSender.kt | 2 | 3734 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.logger.ui
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.core.content.FileProvider
import com.nextcloud.client.core.AsyncRunner
import com.nextcloud.client.core.Cancellable
import com.nextcloud.client.core.Clock
import com.nextcloud.client.logger.LogEntry
import com.owncloud.android.R
import java.io.File
import java.io.FileWriter
import java.util.TimeZone
class LogsEmailSender(private val context: Context, private val clock: Clock, private val runner: AsyncRunner) {
private companion object {
const val LOGS_MIME_TYPE = "text/plain"
}
private class Task(
private val context: Context,
private val logs: List<LogEntry>,
private val file: File,
private val tz: TimeZone
) : Function0<Uri?> {
override fun invoke(): Uri? {
file.parentFile.mkdirs()
val fo = FileWriter(file, false)
logs.forEach {
fo.write(it.toString(tz))
fo.write("\n")
}
fo.close()
return FileProvider.getUriForFile(context, context.getString(R.string.file_provider_authority), file)
}
}
private var task: Cancellable? = null
fun send(logs: List<LogEntry>) {
if (task == null) {
val outFile = File(context.cacheDir, "attachments/logs.txt")
task = runner.post(Task(context, logs, outFile, clock.tz), onResult = { task = null; send(it) })
}
}
fun stop() {
if (task != null) {
task?.cancel()
task = null
}
}
private fun send(uri: Uri?) {
task = null
val intent = Intent(Intent.ACTION_SEND_MULTIPLE)
intent.putExtra(Intent.EXTRA_EMAIL, context.getString(R.string.mail_logger))
val subject = context.getString(R.string.log_send_mail_subject).format(context.getString(R.string.app_name))
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, getPhoneInfo())
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.type = LOGS_MIME_TYPE
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayListOf(uri))
try {
context.startActivity(intent)
} catch (ex: ActivityNotFoundException) {
Toast.makeText(context, R.string.log_send_no_mail_app, Toast.LENGTH_SHORT).show()
}
}
private fun getPhoneInfo(): String {
return "Model: " + Build.MODEL + "\n" +
"Brand: " + Build.BRAND + "\n" +
"Product: " + Build.PRODUCT + "\n" +
"Device: " + Build.DEVICE + "\n" +
"Version-Codename: " + Build.VERSION.CODENAME + "\n" +
"Version-Release: " + Build.VERSION.RELEASE
}
}
| gpl-2.0 | e89499125d452dffae596e27f5ba8c97 | 33.897196 | 116 | 0.655329 | 4.080874 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/partition/PartitionTypes.kt | 2 | 336 | package me.jahnen.libaums.core.partition
/**
* Created by magnusja on 28/02/17.
*/
object PartitionTypes {
const val UNKNOWN = -1
const val FAT12 = 0
const val FAT16 = 1
const val FAT32 = 2
const val LINUX_EXT = 3
const val APPLE_HFS_HFS_PLUS = 4
const val ISO9660 = 5
const val NTFS_EXFAT = 6
}
| apache-2.0 | 8fa19f2ef7f72dabd8efaa11bc26d848 | 15.8 | 40 | 0.633929 | 3.054545 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/fixme_show/ShowFixme.kt | 1 | 1645 | package de.westnordost.streetcomplete.quests.fixme_show
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
class ShowFixme() : OsmFilterQuestType<List<String>>() {
override val elementFilter =
"nodes, ways, relations with fixme and fixme!=continue and highway!=proposed and railway!=proposed" +
" and !fixme:requires_aerial_image " +
" and !fixme:use_better_tagging_scheme " +
" and !fixme:3d_tagging "
override val commitMessage = "Handle fixme tag"
override val icon = R.drawable.ic_quest_power
override val isSplitWayEnabled = true
override fun getTitle(tags: Map<String, String>) = R.string.quest_show_fixme
override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> {
val name = tags["fixme"]
return if (name != null) arrayOf(name) else arrayOf()
}
override fun createForm() = ShowFixmeForm()
override fun applyAnswerTo(answer: List<String>, changes: StringMapChangesBuilder) {
val value = answer.first()
if ("fixme:solved" == value) {
//TODO: handle it without magic values
changes.delete("fixme")
} else {
changes.add(value, "yes")
}
}
override val wikiLink = "Key:fixme"
override val questTypeAchievements: List<QuestTypeAchievement>
get() = listOf()
}
| gpl-3.0 | b5e2e306e33f45c1a296c156f31383e3 | 36.386364 | 117 | 0.678419 | 4.422043 | false | false | false | false |
stealthcode/RxJava | language-adaptors/rxjava-kotlin/src/test/kotlin/rx/lang/kotlin/BasicKotlinTests.kt | 2 | 11680 | /**
* Copyright 2013 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 rx.lang.kotlin
import rx.Observable
import org.junit.Test
import rx.subscriptions.Subscriptions
import org.mockito.Mockito.*
import org.mockito.Matchers.*
import rx.Observer
import org.junit.Assert.*
import rx.Notification
import rx.Subscription
import kotlin.concurrent.thread
import rx.Observable.OnSubscribeFunc
import rx.lang.kotlin.BasicKotlinTests.AsyncObservable
import rx.Observable.OnSubscribe
import rx.Subscriber
/**
* This class use plain Kotlin without extensions from the language adaptor
*/
public class BasicKotlinTests : KotlinTests() {
[Test]
public fun testCreate() {
Observable.create(object:OnSubscribe<String> {
override fun call(subscriber: Subscriber<in String>?) {
subscriber!!.onNext("Hello")
subscriber.onCompleted()
}
})!!.subscribe { result ->
a!!.received(result)
}
verify(a, times(1))!!.received("Hello")
}
[Test]
public fun testFilter() {
Observable.from(listOf(1, 2, 3))!!.filter { it!! >= 2 }!!.subscribe(received())
verify(a, times(0))!!.received(1);
verify(a, times(1))!!.received(2);
verify(a, times(1))!!.received(3);
}
[Test]
public fun testLast() {
assertEquals("three", Observable.from(listOf("one", "two", "three"))!!.toBlockingObservable()!!.last())
}
[Test]
public fun testLastWithPredicate() {
assertEquals("two", Observable.from(listOf("one", "two", "three"))!!.toBlockingObservable()!!.last { x -> x!!.length == 3 })
}
[Test]
public fun testMap1() {
Observable.from(1)!!.map { v -> "hello_$v" }!!.subscribe(received())
verify(a, times(1))!!.received("hello_1")
}
[Test]
public fun testMap2() {
Observable.from(listOf(1, 2, 3))!!.map { v -> "hello_$v" }!!.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
verify(a, times(1))!!.received("hello_2")
verify(a, times(1))!!.received("hello_3")
}
[Test]
public fun testMaterialize() {
Observable.from(listOf(1, 2, 3))!!.materialize()!!.subscribe((received()))
verify(a, times(4))!!.received(any(javaClass<Notification<Int>>()))
verify(a, times(0))!!.error(any(javaClass<Exception>()))
}
[Test]
public fun testMergeDelayError() {
Observable.mergeDelayError(
Observable.from(listOf(1, 2, 3)),
Observable.merge(
Observable.from(6),
Observable.error(NullPointerException()),
Observable.from(7)
),
Observable.from(listOf(4, 5))
)!!.subscribe(received(), { e -> a!!.error(e) })
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(1))!!.received(3)
verify(a, times(1))!!.received(4)
verify(a, times(1))!!.received(5)
verify(a, times(1))!!.received(6)
verify(a, times(0))!!.received(7)
verify(a, times(1))!!.error(any(javaClass<NullPointerException>()))
}
[Test]
public fun testMerge() {
Observable.merge(
Observable.from(listOf(1, 2, 3)),
Observable.merge(
Observable.from(6),
Observable.error(NullPointerException()),
Observable.from(7)
),
Observable.from(listOf(4, 5))
)!!.subscribe(received(), { e -> a!!.error(e) })
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(1))!!.received(3)
verify(a, times(0))!!.received(4)
verify(a, times(0))!!.received(5)
verify(a, times(1))!!.received(6)
verify(a, times(0))!!.received(7)
verify(a, times(1))!!.error(any(javaClass<NullPointerException>()))
}
[Test]
public fun testScriptWithMaterialize() {
TestFactory().observable.materialize()!!.subscribe((received()))
verify(a, times(2))!!.received(any(javaClass<Notification<Int>>()))
}
[Test]
public fun testScriptWithMerge() {
val factory = TestFactory()
Observable.merge(factory.observable, factory.observable)!!.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
verify(a, times(1))!!.received("hello_2")
}
[Test]
public fun testFromWithIterable() {
val list = listOf(1, 2, 3, 4, 5)
assertEquals(5, Observable.from(list)!!.count()!!.toBlockingObservable()!!.single())
}
[Test]
public fun testFromWithObjects() {
val list = listOf(1, 2, 3, 4, 5)
assertEquals(2, Observable.from(listOf(list, 6))!!.count()!!.toBlockingObservable()!!.single())
}
[Test]
public fun testStartWith() {
val list = listOf(10, 11, 12, 13, 14)
val startList = listOf(1, 2, 3, 4, 5)
assertEquals(6, Observable.from(list)!!.startWith(0)!!.count()!!.toBlockingObservable()!!.single())
assertEquals(10, Observable.from(list)!!.startWith(startList)!!.count()!!.toBlockingObservable()!!.single())
}
[Test]
public fun testScriptWithOnNext() {
TestFactory().observable.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
}
[Test]
public fun testSkipTake() {
Observable.from(listOf(1, 2, 3))!!.skip(1)!!.take(1)!!.subscribe(received())
verify(a, times(0))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testSkip() {
Observable.from(listOf(1, 2, 3))!!.skip(2)!!.subscribe(received())
verify(a, times(0))!!.received(1)
verify(a, times(0))!!.received(2)
verify(a, times(1))!!.received(3)
}
[Test]
public fun testTake() {
Observable.from(listOf(1, 2, 3))!!.take(2)!!.subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testTakeLast() {
TestFactory().observable.takeLast(1)!!.subscribe((received()))
verify(a, times(1))!!.received("hello_1")
}
[Test]
public fun testTakeWhile() {
Observable.from(listOf(1, 2, 3))!!.takeWhile { x -> x!! < 3 }!!.subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testTakeWhileWithIndex() {
Observable.from(listOf(1, 2, 3))!!.takeWhileWithIndex { x, i -> i!! < 2 }!!.subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(0))!!.received(3)
}
[Test]
public fun testToSortedList() {
TestFactory().numbers.toSortedList()!!.subscribe(received())
verify(a, times(1))!!.received(listOf(1, 2, 3, 4, 5))
}
[Test]
public fun testForEach() {
Observable.create(AsyncObservable())!!.toBlockingObservable()!!.forEach(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
verify(a, times(1))!!.received(3)
}
[Test(expected = javaClass<RuntimeException>())]
public fun testForEachWithError() {
Observable.create(AsyncObservable())!!.toBlockingObservable()!!.forEach { throw RuntimeException("err") }
fail("we expect an exception to be thrown")
}
[Test]
public fun testLastOrDefault() {
assertEquals("two", Observable.from(listOf("one", "two"))!!.toBlockingObservable()!!.lastOrDefault("default") { x -> x!!.length == 3 })
assertEquals("default", Observable.from(listOf("one", "two"))!!.toBlockingObservable()!!.lastOrDefault("default") { x -> x!!.length > 3 })
}
[Test(expected = javaClass<IllegalArgumentException>())]
public fun testSingle() {
assertEquals("one", Observable.from("one")!!.toBlockingObservable()!!.single { x -> x!!.length == 3 })
Observable.from(listOf("one", "two"))!!.toBlockingObservable()!!.single { x -> x!!.length == 3 }
fail()
}
[Test]
public fun testDefer() {
Observable.defer { Observable.from(listOf(1, 2)) }!!.subscribe(received())
verify(a, times(1))!!.received(1)
verify(a, times(1))!!.received(2)
}
[Test]
public fun testAll() {
Observable.from(listOf(1, 2, 3))!!.all { x -> x!! > 0 }!!.subscribe(received())
verify(a, times(1))!!.received(true)
}
[Test]
public fun testZip() {
val o1 = Observable.from(listOf(1, 2, 3))!!
val o2 = Observable.from(listOf(4, 5, 6))!!
val o3 = Observable.from(listOf(7, 8, 9))!!
val values = Observable.zip(o1, o2, o3) { a, b, c -> listOf(a, b, c) }!!.toList()!!.toBlockingObservable()!!.single()!!
assertEquals(listOf(1, 4, 7), values[0])
assertEquals(listOf(2, 5, 8), values[1])
assertEquals(listOf(3, 6, 9), values[2])
}
[Test]
public fun testZipWithIterable() {
val o1 = Observable.from(listOf(1, 2, 3))!!
val o2 = Observable.from(listOf(4, 5, 6))!!
val o3 = Observable.from(listOf(7, 8, 9))!!
val values = Observable.zip(listOf(o1, o2, o3)) { args -> listOf(*args) }!!.toList()!!.toBlockingObservable()!!.single()!!
assertEquals(listOf(1, 4, 7), values[0])
assertEquals(listOf(2, 5, 8), values[1])
assertEquals(listOf(3, 6, 9), values[2])
}
[Test]
public fun testGroupBy() {
var count = 0
Observable.from(listOf("one", "two", "three", "four", "five", "six"))!!
.groupBy { s -> s!!.length }!!
.flatMap { groupObervable ->
groupObervable!!.map { s ->
"Value: $s Group ${groupObervable.getKey()}"
}
}!!.toBlockingObservable()!!.forEach { s ->
println(s)
count++
}
assertEquals(6, count)
}
public class TestFactory() {
var counter = 1
val numbers: Observable<Int>
get(){
return Observable.from(listOf(1, 3, 2, 5, 4))!!
}
val onSubscribe: TestOnSubscribe
get(){
return TestOnSubscribe(counter++)
}
val observable: Observable<String>
get(){
return Observable.create(onSubscribe)!!
}
}
class AsyncObservable : OnSubscribe<Int> {
override fun call(op: Subscriber<in Int>?) {
thread {
Thread.sleep(50)
op!!.onNext(1)
op.onNext(2)
op.onNext(3)
op.onCompleted()
}
}
}
class TestOnSubscribe(val count: Int) : OnSubscribe<String> {
override fun call(op: Subscriber<in String>?) {
op!!.onNext("hello_$count")
op.onCompleted()
}
}
} | apache-2.0 | a3ff9d8cf8948696da4348464c7bed11 | 32.184659 | 146 | 0.56661 | 4.004114 | false | true | false | false |
yifeidesu/Bitty | app/src/main/java/com/robyn/bitty/utils/tweetUtils/playerUtils.kt | 1 | 2767 | package com.robyn.bitty.utils.tweetUtils
import android.content.Context
import android.net.Uri
import android.view.View
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.SimpleExoPlayerView
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import com.twitter.sdk.android.core.models.Tweet
/**
* Methods to play a video contained in a Tweet
*
* todo: replace by glide!?
*
* Created by yifei on 12/4/2017.
*/
/**
* Create a [SimpleExoPlayer], set [uri] as data source to it, and return it.
*/
fun getPlayer(context: Context, uri: Uri): SimpleExoPlayer {
// Create the player with all default params
val bandwidthMeter = DefaultBandwidthMeter()
val trackSelector = DefaultTrackSelector(bandwidthMeter)
val player = ExoPlayerFactory.newSimpleInstance(context, trackSelector)
// Get data source from uri
val dataSourceFactory = DefaultDataSourceFactory(context,
Util.getUserAgent(context, "videodemoapp"), bandwidthMeter)
val extractorsFactory = DefaultExtractorsFactory()
val videoSource = ExtractorMediaSource(uri,
dataSourceFactory, extractorsFactory, null, null)
// Set the data source to the player
player.prepare(videoSource)
return player
}
/**
* This method decides if the [tweet] has video url.
* If it does, it has a player to player the video on the url
*
* Currently works only for some types, mp4, gif ...
*/
fun playVideo(tweet: Tweet, context: Context, playerView: SimpleExoPlayerView) {
with(getVideoUrl(tweet)) {
if (this!=null) {
playerView.player = getPlayer(context, this)
playerView.visibility = View.VISIBLE
}else{
playerView.visibility = View.GONE
}
}
}
/**
* Returns the [tweet]'s 1st video url, if it has any.
*/
fun getVideoUrl(tweet: Tweet): Uri? {
var uri: Uri? = null
// rewrite logic
tweet.extendedEntities?.apply {
if (!this.media.isEmpty()) {
with(tweet.extendedEntities.media.get(0).videoInfo) {
this?.apply {
if (!this.variants.isEmpty()) {
this.variants[0].url.apply {
uri = Uri.parse(this)
}
}
}
}
}
}
return uri
} | apache-2.0 | de5ab57a96556847dcd32b343da0f143 | 27.833333 | 80 | 0.678713 | 4.316693 | false | false | false | false |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/ui/timeline/holders/StatusViewHolder.kt | 1 | 2739 | package com.andreapivetta.blu.ui.timeline.holders
import android.support.annotation.CallSuper
import android.view.View
import android.widget.TextView
import com.andreapivetta.blu.R
import com.andreapivetta.blu.common.utils.Utils
import com.andreapivetta.blu.common.utils.loadAvatar
import com.andreapivetta.blu.common.utils.visible
import com.andreapivetta.blu.data.model.Tweet
import com.andreapivetta.blu.ui.timeline.InteractionListener
import kotlinx.android.synthetic.main.tweet_basic.view.*
open class StatusViewHolder(container: View, listener: InteractionListener) :
BaseViewHolder(container, listener) {
protected var retweetTextView: TextView = container.retweetTextView
@CallSuper
override fun setup(tweet: Tweet) {
val currentTweet: Tweet
if (tweet.retweet) {
currentTweet = tweet.getRetweetedTweet()
retweetTextView.visible()
retweetTextView.text = container.context.getString(
R.string.retweeted_by, tweet.user.screenName)
} else {
currentTweet = tweet
retweetTextView.visible(false)
}
val currentUser = currentTweet.user
userNameTextView.text = currentUser.name
userScreenNameTextView.text = "@${currentUser.screenName}"
timeTextView.text = " • ${Utils.formatDate(currentTweet.timeStamp)}"
userProfilePicImageView.loadAvatar(currentUser.biggerProfileImageURL)
if (currentTweet.favorited)
favouriteImageButton.setImageResource(R.drawable.ic_favorite_red)
else
favouriteImageButton.setImageResource(R.drawable.ic_favorite)
if (currentTweet.retweeted)
retweetImageButton.setImageResource(R.drawable.ic_repeat_green)
else
retweetImageButton.setImageResource(R.drawable.ic_repeat)
favouritesStatsTextView.text = "${tweet.favoriteCount}"
retweetsStatsTextView.text = "${tweet.retweetCount}"
statusTextView.text = currentTweet.getTextWithoutMediaURLs()
userProfilePicImageView.setOnClickListener { listener.showUser(currentUser) }
favouriteImageButton.setOnClickListener {
if (currentTweet.favorited)
listener.unfavorite(currentTweet)
else
listener.favorite(currentTweet)
}
retweetImageButton.setOnClickListener {
if (currentTweet.retweeted)
listener.unretweet(currentTweet)
else
listener.retweet(currentTweet)
}
respondImageButton.setOnClickListener { listener.reply(currentTweet, currentUser) }
container.setOnClickListener { listener.openTweet(currentTweet) }
}
}
| apache-2.0 | b7bc3ab5d89cbe8405feb3915b03625a | 35.986486 | 91 | 0.700037 | 4.922662 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | test/nl/hannahsten/texifyidea/completion/LatexCompletionTest.kt | 1 | 4864 | package nl.hannahsten.texifyidea.completion
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import nl.hannahsten.texifyidea.file.LatexFileType
import org.junit.Test
class LatexCompletionTest : BasePlatformTestCase() {
@Throws(Exception::class)
override fun setUp() {
super.setUp()
}
@Test
fun testCompleteLatexReferences() {
// given
myFixture.configureByText(LatexFileType, """\ap<caret>""")
// when
val result = myFixture.complete(CompletionType.BASIC)
// then
assertTrue("LaTeX autocompletion should be available", result.any { it.lookupString.startsWith("appendix") })
}
@Test
fun testCompleteCustomCommandReferences() {
// given
myFixture.configureByText(
LatexFileType,
"""
\newcommand{\hi}{hi}
\h<caret>
""".trimIndent()
)
// when
val result = myFixture.complete(CompletionType.BASIC)
// then
assertTrue("LaTeX autocompletion of custom commands should be available", result.any { it.lookupString == "hi" })
}
fun testCompleteCustomColorDefinitions() {
myFixture.configureByText(
LatexFileType,
"""
\colorlet{fadedred}{red!70!}
\color{r<caret>}
""".trimIndent()
)
val result = myFixture.complete(CompletionType.BASIC)
assertTrue("fadedred should be available", result.any { it.lookupString == "fadedred" })
}
fun testCompletionInCustomArgument() {
myFixture.configureByText(
LatexFileType,
"""
\newcommand{\hello}[1]{hello #1}
\hello{\te<caret>}
""".trimIndent()
)
val result = myFixture.complete(CompletionType.BASIC)
assertTrue(result.any { it.lookupString.startsWith("textbf") })
}
// fun testCustomCommandAliasCompletion() {
// myFixture.configureByText(LatexFileType, """
// \begin{thebibliography}{9}
// \bibitem{testkey}
// Reference.
// \end{thebibliography}
//
// \newcommand{\mycite}[1]{\cite{#1}}
//
// \mycite{<caret>}
// """.trimIndent())
// CommandManager.updateAliases(setOf("\\cite"), project)
// val result = myFixture.complete(CompletionType.BASIC)
//
// assertTrue(result.any { it.lookupString == "testkey" })
// }
// Test doesn't work
// fun testTwoLevelCustomCommandAliasCompletion() {
// myFixture.configureByText(LatexFileType, """
// \begin{thebibliography}{9}
// \bibitem{testkey}
// Reference.
// \end{thebibliography}
//
// \newcommand{\mycite}[1]{\cite{#1}}
// <caret>
// """.trimIndent())
//
// // For n-level autocompletion, the autocompletion needs to run n times (but only runs when the number of indexed
// // newcommands changes)
// CommandManager.updateAliases(setOf("\\cite"), project)
// CommandManager.updateAliases(setOf("\\cite"), project)
//
// myFixture.complete(CompletionType.BASIC)
// myFixture.type("""\newcommand{\myothercite}[1]{\mycite{#1}}""")
// myFixture.type("""\myother""")
// myFixture.complete(CompletionType.BASIC)
// val result = myFixture.complete(CompletionType.BASIC, 2)
//
// assertTrue(result.any { it.lookupString == "testkey" })
// }
fun testCustomLabelAliasCompletion() {
myFixture.configureByText(
LatexFileType,
"""
\newcommand{\mylabel}[1]{\label{#1}}
\mylabel{label1}
\label{label2}
~\ref{la<caret>}
""".trimIndent()
)
val result = myFixture.complete(CompletionType.BASIC)
assertTrue(result.any { it.lookupString == "label1" })
}
// Test only works when no other tests are run
// fun testCustomLabelPositionAliasCompletion() {
// myFixture.configureByText(LatexFileType, """
// \newcommand{\mylabel}[2]{\section{#1}\label{sec:#2}}
//
// \mylabel{section1}{label1}
// \label{label2}
//
// ~\ref{<caret>}
// """.trimIndent())
//
// CommandManager.updateAliases(Magic.Command.labelDefinition, project)
// val result = myFixture.complete(CompletionType.BASIC)
//
// assertEquals(2, result.size)
// assertTrue(result.any { it.lookupString == "label1" })
// assertFalse(result.any { it.lookupString == "section1" })
// assertFalse(result.any { it.lookupString == "sec:#2" })
// }
} | mit | 7c9c9b7452eacc0f93598789cb5cae00 | 30.797386 | 123 | 0.574219 | 4.462385 | false | true | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/people/SyncPersonBackdrop.kt | 1 | 2347 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.actions.people
import android.content.ContentValues
import android.content.Context
import com.uwetrottmann.tmdb2.entities.TaggedImagesResultsPage
import com.uwetrottmann.tmdb2.services.PeopleService
import net.simonvt.cathode.actions.TmdbCallAction
import net.simonvt.cathode.actions.people.SyncPersonBackdrop.Params
import net.simonvt.cathode.images.ImageType
import net.simonvt.cathode.images.ImageUri
import net.simonvt.cathode.provider.DatabaseContract.PersonColumns
import net.simonvt.cathode.provider.ProviderSchematic.People
import net.simonvt.cathode.provider.helper.PersonDatabaseHelper
import net.simonvt.cathode.provider.update
import retrofit2.Call
import javax.inject.Inject
class SyncPersonBackdrop @Inject constructor(
private val context: Context,
private val personHelper: PersonDatabaseHelper,
private val peopleService: PeopleService
) : TmdbCallAction<Params, TaggedImagesResultsPage>() {
override fun key(params: Params): String = "SyncPersonBackdrop&tmdbId=${params.tmdbId}"
override fun getCall(params: Params): Call<TaggedImagesResultsPage> =
peopleService.taggedImages(params.tmdbId, 1, "en")
override suspend fun handleResponse(params: Params, response: TaggedImagesResultsPage) {
val personId = personHelper.getIdFromTmdb(params.tmdbId)
val values = ContentValues()
if (response.results!!.size > 0) {
val taggedImage = response.results!![0]
val path = ImageUri.create(ImageType.STILL, taggedImage.file_path)
values.put(PersonColumns.SCREENSHOT, path)
} else {
values.putNull(PersonColumns.SCREENSHOT)
}
context.contentResolver.update(People.withId(personId), values)
}
data class Params(val tmdbId: Int)
}
| apache-2.0 | b2524d7f71c73b5dfe53ecd9a69f3e8d | 36.854839 | 90 | 0.782701 | 4.168739 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/entitymapper/EpisodeMapper.kt | 1 | 5151 | /*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.entitymapper
import android.database.Cursor
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.common.database.getBoolean
import net.simonvt.cathode.common.database.getFloat
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.common.database.getStringOrNull
import net.simonvt.cathode.entity.Episode
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.util.DataHelper
object EpisodeMapper : MappedCursorLiveData.CursorMapper<Episode> {
override fun map(cursor: Cursor): Episode? {
return if (cursor.moveToFirst()) mapEpisode(cursor) else null
}
fun mapEpisode(cursor: Cursor): Episode {
val id = cursor.getLong(EpisodeColumns.ID)
val showId = cursor.getLong(EpisodeColumns.SHOW_ID)
val seasonId = cursor.getLong(EpisodeColumns.SEASON_ID)
val season = cursor.getInt(EpisodeColumns.SEASON)
val episode = cursor.getInt(EpisodeColumns.EPISODE)
val numberAbs = cursor.getInt(EpisodeColumns.NUMBER_ABS)
val title = cursor.getStringOrNull(EpisodeColumns.TITLE)
val overview = cursor.getStringOrNull(EpisodeColumns.OVERVIEW)
val traktId = cursor.getLong(EpisodeColumns.TRAKT_ID)
val imdbId = cursor.getStringOrNull(EpisodeColumns.IMDB_ID)
val tvdbId = cursor.getInt(EpisodeColumns.TVDB_ID)
val tmdbId = cursor.getInt(EpisodeColumns.TMDB_ID)
val tvrageId = cursor.getLong(EpisodeColumns.TVRAGE_ID)
var firstAired = cursor.getLong(EpisodeColumns.FIRST_AIRED)
if (firstAired != 0L) {
firstAired = DataHelper.getFirstAired(firstAired)
}
val updatedAt = cursor.getLong(EpisodeColumns.UPDATED_AT)
val userRating = cursor.getInt(EpisodeColumns.USER_RATING)
val ratedAt = cursor.getLong(EpisodeColumns.RATED_AT)
val rating = cursor.getFloat(EpisodeColumns.RATING)
val votes = cursor.getInt(EpisodeColumns.VOTES)
val plays = cursor.getInt(EpisodeColumns.PLAYS)
val watched = cursor.getBoolean(EpisodeColumns.WATCHED)
val watchedAt = cursor.getLong(EpisodeColumns.LAST_WATCHED_AT)
val inCollection = cursor.getBoolean(EpisodeColumns.IN_COLLECTION)
val collectedAt = cursor.getLong(EpisodeColumns.COLLECTED_AT)
val inWatchlist = cursor.getBoolean(EpisodeColumns.IN_WATCHLIST)
val watchlistedAt = cursor.getLong(EpisodeColumns.LISTED_AT)
val watching = cursor.getBoolean(EpisodeColumns.WATCHING)
val checkedIn = cursor.getBoolean(EpisodeColumns.CHECKED_IN)
val checkinStartedAt = cursor.getLong(EpisodeColumns.STARTED_AT)
val checkinExpiresAt = cursor.getLong(EpisodeColumns.EXPIRES_AT)
val lastCommentSync = cursor.getLong(EpisodeColumns.LAST_COMMENT_SYNC)
val notificationDismissed = cursor.getBoolean(EpisodeColumns.NOTIFICATION_DISMISSED)
val showTitle = cursor.getStringOrNull(EpisodeColumns.SHOW_TITLE)
return Episode(
id,
showId,
seasonId,
season,
episode,
numberAbs,
title,
overview,
traktId,
imdbId,
tvdbId,
tmdbId,
tvrageId,
firstAired,
updatedAt,
userRating,
ratedAt,
rating,
votes,
plays,
watched,
watchedAt,
inCollection,
collectedAt,
inWatchlist,
watchlistedAt,
watching,
checkedIn,
checkinStartedAt,
checkinExpiresAt,
lastCommentSync,
notificationDismissed,
showTitle
)
}
@JvmField
val projection = arrayOf(
EpisodeColumns.ID,
EpisodeColumns.SHOW_ID,
EpisodeColumns.SEASON_ID,
EpisodeColumns.SEASON,
EpisodeColumns.EPISODE,
EpisodeColumns.NUMBER_ABS,
EpisodeColumns.TITLE,
EpisodeColumns.OVERVIEW,
EpisodeColumns.TRAKT_ID,
EpisodeColumns.TVDB_ID,
EpisodeColumns.TMDB_ID,
EpisodeColumns.TVRAGE_ID,
EpisodeColumns.FIRST_AIRED,
EpisodeColumns.UPDATED_AT,
EpisodeColumns.USER_RATING,
EpisodeColumns.RATED_AT,
EpisodeColumns.RATING,
EpisodeColumns.VOTES,
EpisodeColumns.PLAYS,
EpisodeColumns.WATCHED,
EpisodeColumns.LAST_WATCHED_AT,
EpisodeColumns.IN_COLLECTION,
EpisodeColumns.COLLECTED_AT,
EpisodeColumns.IN_WATCHLIST,
EpisodeColumns.LISTED_AT,
EpisodeColumns.WATCHING,
EpisodeColumns.CHECKED_IN,
EpisodeColumns.STARTED_AT,
EpisodeColumns.EXPIRES_AT,
EpisodeColumns.LAST_COMMENT_SYNC,
EpisodeColumns.NOTIFICATION_DISMISSED,
EpisodeColumns.SHOW_TITLE
)
}
| apache-2.0 | 773aa2e8ac8b3dbe8626540b2a92e4cd | 34.280822 | 88 | 0.742574 | 4.436693 | false | false | false | false |
Flank/simple-flank | src/test/kotlin/SigningValidationTest.kt | 1 | 2720 | import java.io.File
import org.junit.Test
import strikt.api.expectThat
import strikt.assertions.contains
class SigningValidationTest : GradleTest() {
@Test
fun warnIfDefaultSigning() {
projectFromResources("app")
val build = gradleRunner("flankRunDebug").forwardOutput().build()
expectThat(build.output) { contains("Warning: The debug keystore should be set") }
}
@Test
fun failIfDefaultSigningAndHermeticTests() {
projectFromResources("app")
File(testProjectDir.root, "build.gradle.kts")
.appendText(
"""
simpleFlank {
hermeticTests.set(true)
}
""".trimIndent())
gradleRunner("flankRunDebug").forwardOutput().buildAndFail()
}
@Test
fun failIfNoSigningAndHermeticTests() {
projectFromResources("app")
File(testProjectDir.root, "build.gradle.kts")
.appendText(
"""
android {
testBuildType = "beta"
buildTypes {
create("beta")
}
}
simpleFlank {
hermeticTests.set(true)
}
""".trimIndent())
gradleRunner("flankRunDebug").forwardOutput().buildAndFail()
}
@Test
fun workFineIfCustomSigning() {
projectFromResources("app")
File(testProjectDir.root, "build.gradle.kts")
.appendText(
"""
android {
signingConfigs {
named("debug") {
storeFile = File(projectDir, "someKeystore")
keyAlias = "debugKey"
keyPassword = "debugKeystore"
storePassword = "debugKeystore"
}
}
buildTypes {
getByName("debug") {
signingConfig = signingConfigs.getByName("debug")
}
}
}
simpleFlank {
hermeticTests.set(true)
}
""".trimIndent())
val build = gradleRunner("flankRunDebug").forwardOutput().build()
expectThat(build.output) { not { contains("The debug keystore should be set") } }
}
@Test
fun workFineNotOnlyWithDebugSigningConfig() {
projectFromResources("app")
File(testProjectDir.root, "build.gradle.kts")
.appendText(
"""
android {
signingConfigs {
create("mySigning") {
storeFile = File(projectDir, "someKeystore")
keyAlias = "debugKey"
keyPassword = "debugKeystore"
storePassword = "debugKeystore"
}
}
buildTypes {
getByName("debug") {
signingConfig = signingConfigs.getByName("mySigning")
}
}
}
simpleFlank {
hermeticTests.set(true)
}
""".trimIndent())
gradleRunner("flankRunDebug").forwardOutput().build()
}
}
| apache-2.0 | d71a1476e7dd8904e4699c4a4456270f | 23.727273 | 86 | 0.582353 | 4.602369 | false | true | false | false |
NextFaze/dev-fun | devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/processing/KElements.kt | 1 | 3741 | package com.nextfaze.devfun.compiler.processing
import com.nextfaze.devfun.compiler.get
import com.nextfaze.devfun.compiler.isClassPublic
import com.nextfaze.devfun.compiler.toKClassBlock
import com.nextfaze.devfun.compiler.toTypeName
import com.squareup.kotlinpoet.CodeBlock
import kotlinx.metadata.ClassName
import kotlinx.metadata.Flag
import kotlinx.metadata.Flags
import kotlinx.metadata.KmClassVisitor
import kotlinx.metadata.jvm.KotlinClassHeader
import kotlinx.metadata.jvm.KotlinClassMetadata
import javax.inject.Inject
import javax.inject.Singleton
import javax.lang.model.element.Name
import javax.lang.model.element.TypeElement
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.TypeMirror
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
@Singleton
internal class KElements @Inject constructor(
private val elements: Elements,
private val types: Types
) {
private val typeElementMap = mutableMapOf<Name, ClassElement>()
private val metaDataElement: DeclaredType = types.getDeclaredType(elements.getTypeElement("kotlin.Metadata"))
operator fun get(typeElement: TypeElement) =
with(typeElement) { typeElementMap.getOrPut(qualifiedName) { ClassElement(this) } }
inner class ClassElement(val element: TypeElement) : TypeElement by element {
private val metaDataAnnotation by lazy {
element.annotationMirrors.firstOrNull { types.isSameType(it.annotationType, metaDataElement) }
}
val isInterface = element.kind.isInterface
private val isClass = element.kind.isClass
val simpleName = element.simpleName.toString()
override fun toString() = element.toString()
val isPublic by lazy { element.isClassPublic }
val type: TypeMirror by lazy { element.asType() }
val typeName by lazy { type.toTypeName() }
val typeBlock: CodeBlock by lazy { CodeBlock.of("%T", typeName) }
val klassBlock: CodeBlock by lazy { type.toKClassBlock(elements = elements) }
val isKtFile by lazy { isClass && metaDataAnnotation?.get<Int>("k") == KotlinClassHeader.FILE_FACADE_KIND }
private val header: KotlinClassHeader? by lazy {
val annotation = metaDataAnnotation ?: return@lazy null
KotlinClassHeader(
kind = annotation["k"],
metadataVersion = annotation["mv"],
bytecodeVersion = annotation["bv"],
data1 = annotation["d1"],
data2 = annotation["d2"],
extraString = annotation["xs"],
packageName = annotation["pn"],
extraInt = annotation["xi"]
)
}
private val metadata by lazy { header?.let { KotlinClassMetadata.read(it) } }
val isKObject by lazy {
var flag = false
val metadata = metadata
if (isClass && !isKtFile && metadata is KotlinClassMetadata.Class) {
metadata.accept(object : KmClassVisitor() {
override fun visit(flags: Flags, name: ClassName) {
flag = Flag.Class.IS_OBJECT(flags)
}
})
}
return@lazy flag
}
val isCompanionObject by lazy {
var flag = false
val metadata = metadata
if (isClass && !isKtFile && metadata is KotlinClassMetadata.Class) {
metadata.accept(object : KmClassVisitor() {
override fun visit(flags: Flags, name: ClassName) {
flag = Flag.Class.IS_COMPANION_OBJECT(flags)
}
})
}
return@lazy flag
}
}
}
| apache-2.0 | 8e860987c692f9024e6d976f50b677ee | 37.96875 | 115 | 0.645549 | 4.890196 | false | false | false | false |
JurajBegovac/RxKotlinTraits | rxkotlin-traits/src/main/kotlin/com/jurajbegovac/rxkotlin/traits/shared_sequence/SharedSequence+Operators.kt | 1 | 5556 | package com.jurajbegovac.rxkotlin.traits.shared_sequence
import com.jurajbegovac.rxkotlin.traits.observable.debug
/** Created by juraj begovac on 13/06/2017. */
fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.debug(
id: String,
logger: (String) -> Unit): SharedSequence<SharingStrategy, Element> =
SharedSequence(source.debug(id, logger), sharingStrategy)
fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.map(
errorValue: Result? = null,
func: (Element) -> Result): SharedSequence<SharingStrategy, Result> {
val errorStream = if (errorValue != null) sharingStrategy.just(errorValue) else sharingStrategy.empty()
return flatMap(errorStream,
{ element ->
try {
val result = func(element)
sharingStrategy.just(result)
} catch (e: Throwable) {
reportError(e)
errorStream
}
})
}
fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.filter(
errorValue: Boolean = false,
predicate: (Element) -> Boolean): SharedSequence<SharingStrategy, Element> {
val source = this.source
.filter {
try {
predicate(it)
} catch (e: Throwable) {
reportError(e)
errorValue
}
}
return SharedSequence(source, this.sharingStrategy)
}
fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.flatMap(
errorValue: SharedSequence<SharingStrategy, Result> = this.sharingStrategy.empty(),
func: (Element) -> SharedSequence<SharingStrategy, Result>): SharedSequence<SharingStrategy, Result> {
val source = this.source
.flatMap {
try {
func(it).source
} catch (e: Throwable) {
reportError(e)
errorValue.source
}
}
return SharedSequence(source, this.sharingStrategy)
}
fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.switchMap(
errorValue: SharedSequence<SharingStrategy, Result> = this.sharingStrategy.empty(),
func: (Element) -> SharedSequence<SharingStrategy, Result>): SharedSequence<SharingStrategy, Result> {
val source = this.source
.switchMap {
try {
func(it).source
} catch (e: Throwable) {
reportError(e)
errorValue.source
}
}
return SharedSequence(source, this.sharingStrategy)
}
fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.flatMapIterable(
errorValue: Iterable<Result> = emptyList<Result>(),
func: (Element) -> Iterable<Result>): SharedSequence<SharingStrategy, Result> {
val source = this.source
.flatMapIterable {
try {
func(it)
} catch (e: Throwable) {
reportError(e)
errorValue
}
}
return SharedSequence(source, this.sharingStrategy)
}
fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.distinctUntilChanged(): SharedSequence<SharingStrategy, Element> =
SharedSequence(this.source.distinctUntilChanged(), this.sharingStrategy)
fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.distinctUntilChanged(
errorValue: Boolean = false,
comparator: (Element, Element) -> Boolean): SharedSequence<SharingStrategy, Element> {
val source = this.source
.distinctUntilChanged { e1, e2 ->
try {
comparator(e1, e2)
} catch (e: Throwable) {
reportError(e)
errorValue
}
}
return SharedSequence(source, this.sharingStrategy)
}
fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.distinctUntilChanged(
errorValue: Boolean = false,
keySelector: (Element) -> Result): SharedSequence<SharingStrategy, Element> {
val source = this.source
.distinctUntilChanged { e ->
try {
keySelector(e)
} catch (e: Throwable) {
reportError(e)
errorValue
}
}
return SharedSequence(source, this.sharingStrategy)
}
fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.startWith(
item: Element): SharedSequence<SharingStrategy, Element> =
SharedSequence(this.source.startWith(item), this.sharingStrategy)
fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.scan(
errorValue: Result,
initialValue: Result,
accumulator: (Result, Element) -> Result): SharedSequence<SharingStrategy, Result> {
val source = this.source
.scan(initialValue) { r, t ->
try {
accumulator(r, t)
} catch (e: Throwable) {
reportError(e)
errorValue
}
}
return SharedSequence(source, this.sharingStrategy)
}
fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.doOnNext(
onNext: (Element) -> Unit): SharedSequence<SharingStrategy, Element> {
val source = this.source
.doOnNext {
try {
onNext(it)
} catch (e: Throwable) {
reportError(e)
}
}
return SharedSequence(source, this.sharingStrategy)
}
| mit | c029587e9320f2b5e0eb78577b40992d | 35.313725 | 164 | 0.668826 | 4.502431 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/timer_recordings/TimerRecordingListFragment.kt | 1 | 11042 | package org.tvheadend.tvhclient.ui.features.dvr.timer_recordings
import android.os.Bundle
import android.view.*
import android.widget.Filter
import androidx.appcompat.widget.PopupMenu
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import org.tvheadend.data.entity.TimerRecording
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.RecyclerviewFragmentBinding
import org.tvheadend.tvhclient.ui.base.BaseFragment
import org.tvheadend.tvhclient.ui.common.*
import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface
import org.tvheadend.tvhclient.ui.common.interfaces.SearchRequestInterface
import org.tvheadend.tvhclient.util.extensions.gone
import org.tvheadend.tvhclient.util.extensions.visible
import org.tvheadend.tvhclient.util.extensions.visibleOrGone
import timber.log.Timber
import java.util.concurrent.CopyOnWriteArrayList
class TimerRecordingListFragment : BaseFragment(), RecyclerViewClickInterface, SearchRequestInterface, Filter.FilterListener {
private lateinit var binding: RecyclerviewFragmentBinding
private lateinit var timerRecordingViewModel: TimerRecordingViewModel
private lateinit var recyclerViewAdapter: TimerRecordingRecyclerViewAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = RecyclerviewFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
timerRecordingViewModel = ViewModelProvider(requireActivity())[TimerRecordingViewModel::class.java]
arguments?.let {
timerRecordingViewModel.selectedListPosition = it.getInt("listPosition")
}
recyclerViewAdapter = TimerRecordingRecyclerViewAdapter(isDualPane, this, htspVersion)
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
binding.recyclerView.adapter = recyclerViewAdapter
binding.recyclerView.gone()
binding.searchProgress.visibleOrGone(baseViewModel.isSearchActive)
timerRecordingViewModel.recordings.observe(viewLifecycleOwner, { recordings ->
if (recordings != null) {
recyclerViewAdapter.addItems(recordings)
observeSearchQuery()
}
binding.recyclerView.visible()
showStatusInToolbar()
activity?.invalidateOptionsMenu()
if (isDualPane && recyclerViewAdapter.itemCount > 0) {
showRecordingDetails(timerRecordingViewModel.selectedListPosition)
}
})
}
private fun observeSearchQuery() {
Timber.d("Observing search query")
baseViewModel.searchQueryLiveData.observe(viewLifecycleOwner, { query ->
if (query.isNotEmpty()) {
Timber.d("View model returned search query '$query'")
onSearchRequested(query)
} else {
Timber.d("View model returned empty search query")
onSearchResultsCleared()
}
})
}
private fun showStatusInToolbar() {
context?.let {
if (!baseViewModel.isSearchActive) {
toolbarInterface.setTitle(getString(R.string.timer_recordings))
toolbarInterface.setSubtitle(it.resources.getQuantityString(R.plurals.items, recyclerViewAdapter.itemCount, recyclerViewAdapter.itemCount))
} else {
toolbarInterface.setTitle(getString(R.string.search_results))
toolbarInterface.setSubtitle(it.resources.getQuantityString(R.plurals.timer_recordings, recyclerViewAdapter.itemCount, recyclerViewAdapter.itemCount))
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val ctx = context ?: return super.onOptionsItemSelected(item)
return when (item.itemId) {
R.id.menu_add_recording -> return addNewTimerRecording(requireActivity())
R.id.menu_remove_all_recordings -> showConfirmationToRemoveAllTimerRecordings(ctx, CopyOnWriteArrayList(recyclerViewAdapter.items))
else -> super.onOptionsItemSelected(item)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.recording_list_options_menu, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
// Enable the remove all recordings menu if there are at least 2 recordings available
if (sharedPreferences.getBoolean("delete_all_recordings_menu_enabled", resources.getBoolean(R.bool.pref_default_delete_all_recordings_menu_enabled))
&& recyclerViewAdapter.itemCount > 1
&& isConnectionToServerAvailable) {
menu.findItem(R.id.menu_remove_all_recordings)?.isVisible = true
}
menu.findItem(R.id.menu_add_recording)?.isVisible = isConnectionToServerAvailable
menu.findItem(R.id.menu_search)?.isVisible = recyclerViewAdapter.itemCount > 0
menu.findItem(R.id.media_route_menu_item)?.isVisible = false
}
private fun showRecordingDetails(position: Int) {
timerRecordingViewModel.selectedListPosition = position
recyclerViewAdapter.setPosition(position)
val recording = recyclerViewAdapter.getItem(position)
if (recording == null || !isVisible) {
return
}
val fm = activity?.supportFragmentManager
if (!isDualPane) {
val fragment = TimerRecordingDetailsFragment.newInstance(recording.id)
fm?.beginTransaction()?.also {
it.replace(R.id.main, fragment)
it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
it.addToBackStack(null)
it.commit()
}
} else {
var fragment = activity?.supportFragmentManager?.findFragmentById(R.id.details)
if (fragment !is TimerRecordingDetailsFragment) {
fragment = TimerRecordingDetailsFragment.newInstance(recording.id)
// Check the lifecycle state to avoid committing the transaction
// after the onSaveInstance method was already called which would
// trigger an illegal state exception.
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
fm?.beginTransaction()?.also {
it.replace(R.id.details, fragment)
it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
it.commit()
}
}
} else if (timerRecordingViewModel.currentIdLiveData.value != recording.id) {
timerRecordingViewModel.currentIdLiveData.value = recording.id
}
}
}
private fun showPopupMenu(view: View, position: Int) {
val ctx = context ?: return
val timerRecording = recyclerViewAdapter.getItem(position) ?: return
val popupMenu = PopupMenu(ctx, view)
popupMenu.menuInflater.inflate(R.menu.timer_recordings_popup_menu, popupMenu.menu)
popupMenu.menuInflater.inflate(R.menu.external_search_options_menu, popupMenu.menu)
preparePopupOrToolbarSearchMenu(popupMenu.menu, timerRecording.title, isConnectionToServerAvailable)
popupMenu.menu.findItem(R.id.menu_disable_recording)?.isVisible = htspVersion >= 19 && timerRecording.isEnabled
popupMenu.menu.findItem(R.id.menu_enable_recording)?.isVisible = htspVersion >= 19 && !timerRecording.isEnabled
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.menu_edit_recording -> return@setOnMenuItemClickListener editSelectedTimerRecording(requireActivity(), timerRecording.id)
R.id.menu_remove_recording -> return@setOnMenuItemClickListener showConfirmationToRemoveSelectedTimerRecording(ctx, timerRecording, null)
R.id.menu_disable_recording -> return@setOnMenuItemClickListener enableTimerRecording(timerRecording, false)
R.id.menu_enable_recording -> return@setOnMenuItemClickListener enableTimerRecording(timerRecording, true)
R.id.menu_search_imdb -> return@setOnMenuItemClickListener searchTitleOnImdbWebsite(ctx, timerRecording.title)
R.id.menu_search_fileaffinity -> return@setOnMenuItemClickListener searchTitleOnFileAffinityWebsite(ctx, timerRecording.title)
R.id.menu_search_youtube -> return@setOnMenuItemClickListener searchTitleOnYoutube(ctx, timerRecording.title)
R.id.menu_search_google -> return@setOnMenuItemClickListener searchTitleOnGoogle(ctx, timerRecording.title)
R.id.menu_search_epg -> return@setOnMenuItemClickListener searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, timerRecording.title)
else -> return@setOnMenuItemClickListener false
}
}
popupMenu.show()
}
private fun enableTimerRecording(timerRecording: TimerRecording, enabled: Boolean): Boolean {
val intent = timerRecordingViewModel.getIntentData(requireContext(), timerRecording)
intent.action = "updateTimerecEntry"
intent.putExtra("id", timerRecording.id)
intent.putExtra("enabled", if (enabled) 1 else 0)
activity?.startService(intent)
return true
}
override fun onClick(view: View, position: Int) {
showRecordingDetails(position)
}
override fun onLongClick(view: View, position: Int): Boolean {
showPopupMenu(view, position)
return true
}
override fun onFilterComplete(i: Int) {
binding.searchProgress.gone()
showStatusInToolbar()
// Preselect the first result item in the details screen
if (isDualPane) {
when {
recyclerViewAdapter.itemCount > timerRecordingViewModel.selectedListPosition -> {
showRecordingDetails(timerRecordingViewModel.selectedListPosition)
}
recyclerViewAdapter.itemCount <= timerRecordingViewModel.selectedListPosition -> {
showRecordingDetails(0)
}
recyclerViewAdapter.itemCount == 0 -> {
removeDetailsFragment()
}
}
}
}
override fun onSearchRequested(query: String) {
recyclerViewAdapter.filter.filter(query, this)
}
override fun onSearchResultsCleared() {
recyclerViewAdapter.filter.filter("", this)
}
override fun getQueryHint(): String {
return getString(R.string.search_timer_recordings)
}
}
| gpl-3.0 | a917f9d6734029ae5af8913115b0fd21 | 45.987234 | 166 | 0.689006 | 5.45284 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/epg/EpgViewPagerFragment.kt | 1 | 9084 | package org.tvheadend.tvhclient.ui.features.epg
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintSet
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.EpgViewpagerFragmentBinding
import org.tvheadend.tvhclient.util.extensions.visibleOrGone
import timber.log.Timber
import java.util.*
class EpgViewPagerFragment : Fragment(), EpgScrollInterface {
private lateinit var epgViewModel: EpgViewModel
private lateinit var recyclerViewAdapter: EpgVerticalRecyclerViewAdapter
/**
* Defines if the current time indication (vertical line) shall be shown.
* The indication shall only be shown for the first fragment.
*/
private val showTimeIndication: Boolean
get() {
return fragmentId == 0
}
private var updateViewHandler = Handler(Looper.getMainLooper())
private var updateViewTask: Runnable? = null
private var updateTimeIndicationHandler = Handler(Looper.getMainLooper())
private var updateTimeIndicationTask: Runnable? = null
private lateinit var constraintSet: ConstraintSet
private lateinit var binding: EpgViewpagerFragmentBinding
private var recyclerViewLinearLayoutManager: LinearLayoutManager? = null
private var enableScrolling = false
private var fragmentId = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = DataBindingUtil.inflate(inflater, R.layout.epg_viewpager_fragment, container, false)
return binding.root
}
override fun onDestroy() {
super.onDestroy()
if (showTimeIndication) {
updateViewTask?.let {
updateViewHandler.removeCallbacks(it)
}
updateTimeIndicationTask?.let {
updateTimeIndicationHandler.removeCallbacks(it)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Timber.d("Initializing")
epgViewModel = ViewModelProvider(requireActivity())[EpgViewModel::class.java]
// Required to show the vertical current time indication
constraintSet = ConstraintSet()
constraintSet.clone(binding.constraintLayout)
// Get the id that defines the position of the fragment in the viewpager
fragmentId = arguments?.getInt("fragmentId") ?: 0
binding.startTime = epgViewModel.getStartTime(fragmentId)
binding.endTime = epgViewModel.getEndTime(fragmentId)
recyclerViewAdapter = EpgVerticalRecyclerViewAdapter(requireActivity(), epgViewModel, fragmentId, viewLifecycleOwner)
recyclerViewLinearLayoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
binding.viewpagerRecyclerView.layoutManager = recyclerViewLinearLayoutManager
binding.viewpagerRecyclerView.setHasFixedSize(true)
binding.viewpagerRecyclerView.adapter = recyclerViewAdapter
binding.viewpagerRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState != SCROLL_STATE_IDLE) {
enableScrolling = true
} else if (enableScrolling) {
enableScrolling = false
activity?.let {
val fragment = it.supportFragmentManager.findFragmentById(R.id.main)
if (fragment is EpgScrollInterface) {
(fragment as EpgScrollInterface).onScrollStateChanged()
}
}
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (enableScrolling) {
activity?.let {
val position = recyclerViewLinearLayoutManager?.findFirstVisibleItemPosition() ?: -1
val childView = recyclerViewLinearLayoutManager?.getChildAt(0)
val offset = if (childView == null) 0 else childView.top - recyclerView.paddingTop
val fragment = it.supportFragmentManager.findFragmentById(R.id.main)
if (fragment is EpgScrollInterface && position >= 0) {
(fragment as EpgScrollInterface).onScroll(position, offset)
}
}
}
}
})
// In case the channels and hours and days to show have changed invalidate
// the adapter so that the UI can be updated with the new data
Timber.d("Observing trigger to reload epg data")
epgViewModel.viewAndEpgDataIsInvalid.observe(viewLifecycleOwner, { reload ->
Timber.d("Trigger to reload epg data has changed to $reload")
if (reload) {
recyclerViewAdapter.loadProgramData()
}
})
binding.currentTime.visibleOrGone(showTimeIndication)
if (showTimeIndication) {
// Create the handler and the timer task that will update the
// entire view every 30 minutes if the first screen is visible.
// This prevents the time indication from moving to far to the right
updateViewTask = object : Runnable {
override fun run() {
recyclerViewAdapter.notifyDataSetChanged()
updateViewHandler.postDelayed(this, 1200000)
}
}
// Create the handler and the timer task that will update the current
// time indication every minute.
updateTimeIndicationTask = object : Runnable {
override fun run() {
setCurrentTimeIndication()
updateTimeIndicationHandler.postDelayed(this, 60000)
}
}
updateViewTask?.let {
updateViewHandler.postDelayed(it, 60000)
}
updateTimeIndicationTask?.let {
updateTimeIndicationHandler.post(it)
}
}
// The program data needs to be loaded when the fragment is created
recyclerViewAdapter.loadProgramData()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
recyclerViewLinearLayoutManager?.let {
outState.putParcelable("layout", it.onSaveInstanceState())
}
}
/**
* Shows a vertical line in the program guide to indicate the current time.
* It is only visible in the first screen. This method is called every minute.
*/
private fun setCurrentTimeIndication() {
// Get the difference between the current time and the given start time. Calculate
// from this value in minutes the width in pixels. This will be horizontal offset
// for the time indication. If channel icons are shown then we need to add a
// the icon width to the offset.
val currentTime = Calendar.getInstance().timeInMillis
val durationTime = (currentTime - epgViewModel.getStartTime(fragmentId)) / 1000 / 60
val offset = (durationTime * epgViewModel.pixelsPerMinute).toInt()
Timber.d("Fragment id: $fragmentId, current time: $currentTime, start time: ${epgViewModel.getStartTime(fragmentId)}, offset: $offset, durationTime: $durationTime, pixelsPerMinute: ${epgViewModel.pixelsPerMinute}")
// Set the left constraint of the time indication so it shows the actual time
binding.currentTime.let {
constraintSet.connect(it.id, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, offset)
constraintSet.connect(it.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, offset)
constraintSet.applyTo(binding.constraintLayout)
}
}
override fun onScroll(position: Int, offset: Int) {
recyclerViewLinearLayoutManager?.scrollToPositionWithOffset(position, offset)
}
override fun onScrollStateChanged() {
// NOP
}
companion object {
fun newInstance(fragmentId: Int): EpgViewPagerFragment {
val fragment = EpgViewPagerFragment()
val bundle = Bundle()
bundle.putInt("fragmentId", fragmentId)
fragment.arguments = bundle
return fragment
}
}
}
| gpl-3.0 | dd2460bb5682c8873e70f8aa2247841c | 43.312195 | 222 | 0.660722 | 5.624768 | false | false | false | false |
SeunAdelekan/Kanary | src/main/com/iyanuadelekan/kanary/app/Extensions.kt | 1 | 887 | package com.iyanuadelekan.kanary.app
import com.fasterxml.jackson.databind.ObjectMapper
import com.iyanuadelekan.kanary.exceptions.InvalidResponseEntityException
import javax.servlet.http.HttpServletResponse
/**
* @author Iyanu Adelekan on 24/11/2018.
*/
fun HttpServletResponse.withStatus(statusCode: Int): HttpServletResponse {
status = statusCode
return this
}
@Throws(InvalidResponseEntityException::class)
fun <T : Any> HttpServletResponse.send(data: T) {
val isValidResponseEntity =
data.javaClass.getAnnotation(ResponseEntity::class.java) != null
if (isValidResponseEntity) {
val mapper = ObjectMapper()
val json = mapper.writeValueAsString(data)
contentType = "application/json"
writer.print(json)
println(json) // TODO remove this line.
return
}
throw InvalidResponseEntityException()
} | apache-2.0 | 174a36840b313ac6dc3d4f0b9a501d42 | 27.645161 | 76 | 0.730552 | 4.595855 | false | false | false | false |
kotlin-graphics/uno-sdk | vk/src/main/kotlin/uno/vk/glfw vk.kt | 1 | 1166 | package uno.vk
import kool.adr
import kool.mInt
import org.lwjgl.glfw.GLFWVulkan
import org.lwjgl.system.MemoryUtil.*
import uno.glfw.GlfwWindow
import uno.glfw.glfw
import uno.glfw.stak
import vkk.VK_CHECK_RESULT
import vkk.entities.VkSurfaceKHR
import vkk.identifiers.Instance
// --- [ glfwVulkanSupported ] ---
val glfw.vulkanSupported: Boolean
get() = GLFWVulkan.glfwVulkanSupported()
// --- [ glfwGetRequiredInstanceExtensions ] ---
val glfw.requiredInstanceExtensions: ArrayList<String>
get() = stak {
val pCount = it.mInt()
val ppNames = GLFWVulkan.nglfwGetRequiredInstanceExtensions(pCount.adr)
val count = pCount[0]
if (count == 0) arrayListOf()
else {
val pNames = memPointerBuffer(ppNames, count)
val res = ArrayList<String>(count)
for (i in 0 until count)
res += memASCII(pNames[i])
res
}
}
// --- [ glfwCreateWindowSurface ] ---
infix fun Instance.createSurface(window: GlfwWindow): VkSurfaceKHR =
VkSurfaceKHR(stak.longAdr { VK_CHECK_RESULT(GLFWVulkan.nglfwCreateWindowSurface(adr, window.handle.value, NULL, it)) }) | mit | 796c0fa3e4ced2593f211862e8afb618 | 31.416667 | 127 | 0.680961 | 3.886667 | false | false | false | false |
olonho/carkot | kotstd/kt/ByteArray.kt | 1 | 3003 | package kotlin
external fun malloc_array(size: Int): Int
external fun kotlinclib_byte_array_get_ix(dataRawPtr: Int, index: Int): Byte
external fun kotlinclib_byte_array_set_ix(dataRawPtr: Int, index: Int, value: Byte)
external fun kotlinclib_byte_size(): Int
class ByteArray(var size: Int) {
val dataRawPtr: Int
/** Returns the number of elements in the array. */
//size: Int
init {
this.dataRawPtr = malloc_array(kotlinclib_byte_size() * this.size)
var index = 0
while (index < this.size) {
set(index, 0)
index = index + 1
}
}
/** Returns the array element at the given [index]. This method can be called using the index operator. */
operator fun get(index: Int): Byte {
return kotlinclib_byte_array_get_ix(this.dataRawPtr, index)
}
/** Sets the element at the given [index] to the given [value]. This method can be called using the index operator. */
operator fun set(index: Int, value: Byte) {
kotlinclib_byte_array_set_ix(this.dataRawPtr, index, value)
}
fun clone(): ByteArray {
val newInstance = ByteArray(this.size)
var index = 0
while (index < this.size) {
val value = this.get(index)
newInstance.set(index, value)
index = index + 1
}
return newInstance
}
}
fun ByteArray.print() {
var index = 0
print('[')
while (index < size) {
print(get(index))
index++
if (index < size) {
print(';')
print(' ')
}
}
print(']')
}
fun ByteArray.println() {
this.print()
//println()
}
fun ByteArray.copyOf(newSize: Int): ByteArray {
val newInstance = ByteArray(newSize)
var index = 0
val end = if (newSize > this.size) this.size else newSize
while (index < end) {
val value = this.get(index)
newInstance.set(index, value)
index = index + 1
}
while (index < newSize) {
newInstance.set(index, 0)
index = index + 1
}
return newInstance
}
fun ByteArray.copyOfRange(fromIndex: Int, toIndex: Int): ByteArray {
val newInstance = ByteArray(toIndex - fromIndex)
var index = fromIndex
while (index < toIndex) {
val value = this.get(index)
newInstance.set(index - fromIndex, value)
index = index + 1
}
return newInstance
}
operator fun ByteArray.plus(element: Byte): ByteArray {
val index = size
val result = this.copyOf(index + 1)
result[index] = element
return result
}
operator fun ByteArray.plus(elements: ByteArray): ByteArray {
val thisSize = size
val arraySize = elements.size
val resultSize = thisSize + arraySize
val newInstance = this.copyOf(resultSize)
var index = thisSize
while (index < resultSize) {
val value = elements.get(index - thisSize)
newInstance.set(index, value)
index = index + 1
}
return newInstance
} | mit | 8349385aa91d16054ecb5cd60058e681 | 23.826446 | 122 | 0.606061 | 3.951316 | false | false | false | false |
d9n/intellij-rust | debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt | 1 | 1946 | package org.rust.debugger.lang
import com.intellij.psi.PsiElement
import com.intellij.xdebugger.XSourcePosition
import com.jetbrains.cidr.execution.debugger.CidrDebugProcess
import com.jetbrains.cidr.execution.debugger.backend.LLValue
import com.jetbrains.cidr.execution.debugger.evaluation.CidrDebuggerTypesHelper
import com.jetbrains.cidr.execution.debugger.evaluation.CidrMemberValue
import org.rust.lang.core.psi.RsCodeFragmentFactory
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.ext.RsCompositeElement
import org.rust.lang.core.psi.ext.getNextNonCommentSibling
import org.rust.lang.core.psi.ext.parentOfType
class RsDebuggerTypesHelper(process: CidrDebugProcess) : CidrDebuggerTypesHelper(process) {
override fun computeSourcePosition(value: CidrMemberValue): XSourcePosition? = null
override fun isImplicitContextVariable(position: XSourcePosition, `var`: LLValue): Boolean? = false
override fun resolveProperty(value: CidrMemberValue, dynamicTypeName: String?): XSourcePosition? = null
override fun resolveToDeclaration(position: XSourcePosition, `var`: LLValue): PsiElement? {
if (!isRust(position)) return delegate?.resolveToDeclaration(position, `var`)
val context = getContextElement(position)
return resolveToDeclaration(context, `var`.name)
}
private val delegate: CidrDebuggerTypesHelper? =
RsDebuggerLanguageSupportFactory.DELEGATE?.createTypesHelper(process)
private fun isRust(position: XSourcePosition): Boolean =
getContextElement(position).containingFile is RsFile
}
private fun resolveToDeclaration(ctx: PsiElement?, name: String): PsiElement? {
val composite = ctx?.getNextNonCommentSibling()?.parentOfType<RsCompositeElement>(strict = false)
?: return null
val path = RsCodeFragmentFactory(composite.project).createLocalVariable(name, composite)
?: return null
return path.reference.resolve()
}
| mit | b73dd58609d37d0de439251335f46747 | 44.255814 | 107 | 0.791881 | 4.611374 | false | false | false | false |
goodwinnk/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/RepositoryBrowser.kt | 1 | 7752 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.intellij.ide.impl.ContentManagerWatcher
import com.intellij.ide.util.treeView.AbstractTreeBuilder
import com.intellij.ide.util.treeView.AbstractTreeStructure
import com.intellij.ide.util.treeView.NodeDescriptor
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.ex.FileSystemTreeImpl
import com.intellij.openapi.fileChooser.ex.RootFileElement
import com.intellij.openapi.fileChooser.impl.FileTreeBuilder
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.RemoteFilePath
import com.intellij.openapi.vcs.actions.VcsContextFactory
import com.intellij.openapi.vcs.changes.ByteBackedContentRevision
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ContentRevision
import com.intellij.openapi.vcs.changes.CurrentContentRevision
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.vfs.AbstractVcsVirtualFile
import com.intellij.openapi.vcs.vfs.VcsVirtualFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.content.ContentFactory
import com.intellij.util.PlatformIcons
import java.awt.BorderLayout
import java.io.File
import java.util.*
import javax.swing.Icon
import javax.swing.JPanel
import javax.swing.JTree
import javax.swing.tree.DefaultTreeModel
const val TOOLWINDOW_ID = "Repositories"
fun showRepositoryBrowser(project: Project, root: AbstractVcsVirtualFile, localRoot: VirtualFile, title: String) {
val toolWindowManager = ToolWindowManager.getInstance(project)
val repoToolWindow = toolWindowManager.getToolWindow(TOOLWINDOW_ID)
?: registerRepositoriesToolWindow(toolWindowManager)
for (content in repoToolWindow.contentManager.contents) {
val component = content.component as? RepositoryBrowserPanel ?: continue
if (component.root == root) {
repoToolWindow.contentManager.setSelectedContent(content)
return
}
}
val contentPanel = RepositoryBrowserPanel(project, root, localRoot)
val content = ContentFactory.SERVICE.getInstance().createContent(contentPanel, title, true)
repoToolWindow.contentManager.addContent(content)
repoToolWindow.contentManager.setSelectedContent(content, true)
repoToolWindow.activate(null)
}
private fun registerRepositoriesToolWindow(toolWindowManager: ToolWindowManager): ToolWindow {
val toolWindow = toolWindowManager.registerToolWindow(TOOLWINDOW_ID, true, ToolWindowAnchor.LEFT)
ContentManagerWatcher(toolWindow, toolWindow.contentManager)
return toolWindow
}
val REPOSITORY_BROWSER_DATA_KEY = DataKey.create<RepositoryBrowserPanel>("com.intellij.openapi.vcs.impl.RepositoryBrowserPanel")
class RepositoryBrowserPanel(
val project: Project,
val root: AbstractVcsVirtualFile,
val localRoot: VirtualFile
) : JPanel(BorderLayout()), DataProvider {
private val fileSystemTree: FileSystemTreeImpl
init {
val fileChooserDescriptor = object : FileChooserDescriptor(true, false, false, false, false, true) {
override fun getRoots(): List<VirtualFile> = listOf(root)
override fun getIcon(file: VirtualFile): Icon? {
if (file.isDirectory) {
return PlatformIcons.FOLDER_ICON
}
return FileTypeManager.getInstance().getFileTypeByFileName(file.name).icon
}
}
fileSystemTree = object : FileSystemTreeImpl(project, fileChooserDescriptor) {
override fun createTreeBuilder(tree: JTree?,
treeModel: DefaultTreeModel?,
treeStructure: AbstractTreeStructure?,
comparator: Comparator<NodeDescriptor<Any>>?,
descriptor: FileChooserDescriptor?,
onInitialized: Runnable?): AbstractTreeBuilder {
return object : FileTreeBuilder(tree, treeModel, treeStructure, comparator, descriptor, onInitialized) {
override fun isAutoExpandNode(nodeDescriptor: NodeDescriptor<*>): Boolean {
return nodeDescriptor.element is RootFileElement
}
}
}
}
fileSystemTree.addOkAction {
val files = fileSystemTree.selectedFiles
for (file in files) {
FileEditorManager.getInstance(project).openFile(file, true)
}
}
val actionGroup = DefaultActionGroup()
actionGroup.add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE))
actionGroup.add(ActionManager.getInstance().getAction("Vcs.ShowDiffWithLocal"))
fileSystemTree.registerMouseListener(actionGroup)
val scrollPane = ScrollPaneFactory.createScrollPane(fileSystemTree.tree)
add(scrollPane, BorderLayout.CENTER)
}
override fun getData(dataId: String): Any? {
return when {
CommonDataKeys.VIRTUAL_FILE_ARRAY.`is`(dataId) -> fileSystemTree.selectedFiles
CommonDataKeys.NAVIGATABLE_ARRAY.`is`(dataId) ->
fileSystemTree.selectedFiles
.filter { !it.isDirectory }
.map { OpenFileDescriptor(project, it) }
.toTypedArray()
REPOSITORY_BROWSER_DATA_KEY.`is`(dataId) -> this
else -> null
}
}
fun hasSelectedFiles() = fileSystemTree.selectedFiles.any { it is VcsVirtualFile }
fun getSelectionAsChanges(): List<Change> {
return fileSystemTree.selectedFiles
.filterIsInstance<VcsVirtualFile>()
.map { createChangeVsLocal(it) }
}
private fun createChangeVsLocal(file: VcsVirtualFile): Change {
val repoRevision = VcsVirtualFileContentRevision(file)
val localPath = File(localRoot.path, file.path)
val localRevision = CurrentContentRevision(VcsContextFactory.SERVICE.getInstance().createFilePathOn(localPath))
return Change(repoRevision, localRevision)
}
}
class DiffRepoWithLocalAction : AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
return e.getData(REPOSITORY_BROWSER_DATA_KEY) != null
}
override fun update(e: AnActionEvent) {
val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return
e.presentation.isEnabled = repoBrowser.hasSelectedFiles()
}
override fun actionPerformed(e: AnActionEvent) {
val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return
val changes = repoBrowser.getSelectionAsChanges()
ShowDiffAction.showDiffForChange(repoBrowser.project, changes)
}
}
class VcsVirtualFileContentRevision(private val vcsVirtualFile: VcsVirtualFile) : ContentRevision, ByteBackedContentRevision {
override fun getContent(): String? {
return contentAsBytes?.let { LoadTextUtil.getTextByBinaryPresentation(it, vcsVirtualFile).toString() }
}
override fun getContentAsBytes(): ByteArray? {
return vcsVirtualFile.fileRevision?.loadContent()
}
override fun getFile(): FilePath {
return RemoteFilePath(vcsVirtualFile.path, vcsVirtualFile.isDirectory)
}
override fun getRevisionNumber(): VcsRevisionNumber {
return vcsVirtualFile.fileRevision?.revisionNumber ?: VcsRevisionNumber.NULL
}
} | apache-2.0 | ce3542c5ee6a92f72e3fb6165b55fcf0 | 40.682796 | 140 | 0.763029 | 4.93758 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/animation/RxAbstractPathAnimator.kt | 1 | 4579 | /*
* Copyright (C) 2015 tyrantgit
*
* 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.tamsiree.rxui.animation
import android.content.res.TypedArray
import android.graphics.Path
import android.view.View
import android.view.ViewGroup
import com.tamsiree.rxui.R
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* @author tamsiree
*/
abstract class RxAbstractPathAnimator(protected val mConfig: Config) {
private val mRandom: Random = Random()
fun randomRotation(): Float {
return mRandom.nextFloat() * 28.6f - 14.3f
}
fun createPath(counter: AtomicInteger, view: View, factor: Int): Path {
var factor = factor
val r = mRandom
var x = r.nextInt(mConfig.xRand)
var x2 = r.nextInt(mConfig.xRand)
val y = view.height - mConfig.initY
var y2: Int = counter.toInt() * 15 + mConfig.animLength * factor + r.nextInt(mConfig.animLengthRand)
factor = y2 / mConfig.bezierFactor
x += mConfig.xPointFactor
x2 += mConfig.xPointFactor
val y3 = y - y2
y2 = y - y2 / 2
val p = Path()
p.moveTo(mConfig.initX.toFloat(), y.toFloat())
p.cubicTo(mConfig.initX.toFloat(), y - factor.toFloat(), x.toFloat(), y2 + factor.toFloat(), x.toFloat(), y2.toFloat())
p.moveTo(x.toFloat(), y2.toFloat())
p.cubicTo(x.toFloat(), y2 - factor.toFloat(), x2.toFloat(), y3 + factor.toFloat(), x2.toFloat(), y3.toFloat())
return p
}
abstract fun start(child: View, parent: ViewGroup?)
class Config {
var initX = 0
var initY = 0
var xRand = 0
var animLengthRand = 0
var bezierFactor = 0
var xPointFactor = 0
var animLength = 0
@JvmField
var heartWidth = 0
@JvmField
var heartHeight = 0
@JvmField
var animDuration = 0
companion object {
@JvmStatic
fun fromTypeArray(typedArray: TypedArray): Config {
val config = Config()
val res = typedArray.resources
config.initX = typedArray.getDimension(R.styleable.RxHeartLayout_initX,
res.getDimensionPixelOffset(R.dimen.heart_anim_init_x).toFloat()).toInt()
config.initY = typedArray.getDimension(R.styleable.RxHeartLayout_initY,
res.getDimensionPixelOffset(R.dimen.heart_anim_init_y).toFloat()).toInt()
config.xRand = typedArray.getDimension(R.styleable.RxHeartLayout_xRand,
res.getDimensionPixelOffset(R.dimen.heart_anim_bezier_x_rand).toFloat()).toInt()
config.animLength = typedArray.getDimension(R.styleable.RxHeartLayout_animLength,
res.getDimensionPixelOffset(R.dimen.heart_anim_length).toFloat()).toInt()
config.animLengthRand = typedArray.getDimension(R.styleable.RxHeartLayout_animLengthRand,
res.getDimensionPixelOffset(R.dimen.heart_anim_length_rand).toFloat()).toInt()
config.bezierFactor = typedArray.getInteger(R.styleable.RxHeartLayout_bezierFactor,
res.getInteger(R.integer.heart_anim_bezier_factor))
config.xPointFactor = typedArray.getDimension(R.styleable.RxHeartLayout_xPointFactor,
res.getDimensionPixelOffset(R.dimen.heart_anim_x_point_factor).toFloat()).toInt()
config.heartWidth = typedArray.getDimension(R.styleable.RxHeartLayout_heart_width,
res.getDimensionPixelOffset(R.dimen.heart_size_width).toFloat()).toInt()
config.heartHeight = typedArray.getDimension(R.styleable.RxHeartLayout_heart_height,
res.getDimensionPixelOffset(R.dimen.heart_size_height).toFloat()).toInt()
config.animDuration = typedArray.getInteger(R.styleable.RxHeartLayout_anim_duration,
res.getInteger(R.integer.anim_duration))
return config
}
}
}
} | apache-2.0 | d49f34929933c9ef4645a1b7c2f1af6e | 43.038462 | 127 | 0.640533 | 4.259535 | false | true | false | false |
tbrooks8/quasar | quasar-kotlin/src/test/kotlin/co/paralleluniverse/kotlin/actors/PingPong.kt | 1 | 3443 | /*
* Quasar: lightweight threads and actors for the JVM.
* Copyright (c) 2015, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package actors
import co.paralleluniverse.actors.*
import co.paralleluniverse.actors.behaviors.BehaviorActor
import co.paralleluniverse.actors.behaviors.ProxyServerActor
import co.paralleluniverse.actors.behaviors.Supervisor
import co.paralleluniverse.actors.behaviors.Supervisor.*
import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode
import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode.*
import co.paralleluniverse.actors.behaviors.SupervisorActor
import co.paralleluniverse.actors.behaviors.SupervisorActor.*
import co.paralleluniverse.actors.behaviors.SupervisorActor.RestartStrategy.*
import co.paralleluniverse.fibers.Suspendable
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.*
import co.paralleluniverse.kotlin.Actor
import co.paralleluniverse.kotlin.Actor.Companion.Timeout
import co.paralleluniverse.kotlin.*
/**
* @author circlespainter
* @author pron
*/
// This example is meant to be a translation of the canonical
// Erlang [ping-pong example](http://www.erlang.org/doc/getting_started/conc_prog.html#id67347).
data class Msg(val txt: String, val from: ActorRef<Any?>)
class Ping(val n: Int) : Actor() {
@Suspendable override fun doRun() {
val pong: ActorRef<Any> = ActorRegistry.getActor("pong")
for(i in 1..n) {
pong.send(Msg("ping", self())) // Fiber-blocking
receive { // Fiber-blocking, always consume the message
when (it) {
"pong" -> println("Ping received pong")
else -> null // Discard
}
}
}
pong.send("finished") // Fiber-blocking
println("Ping exiting")
}
}
class Pong() : Actor() {
@Suspendable override fun doRun() {
while (true) {
// snippet Kotlin Actors example
receive(1000, TimeUnit.MILLISECONDS) { // Fiber-blocking
when (it) {
is Msg -> {
if (it.txt == "ping")
it.from.send("pong") // Fiber-blocking
}
"finished" -> {
println("Pong received 'finished', exiting")
return // Non-local return, exit actor
}
is Timeout -> {
println("Pong timeout in 'receive', exiting")
return // Non-local return, exit actor
}
else -> defer()
}
}
// end of snippet
}
}
}
public class KotlinPingPongActorTest {
@Test public fun testActors() {
val pong = spawn(register("pong", Pong()))
val ping = spawn(Ping(3))
LocalActor.join(pong)
LocalActor.join(ping)
}
}
| gpl-3.0 | 2efd4aaa902379b1be23a48dab1f9bb3 | 35.62766 | 97 | 0.599477 | 4.627688 | false | false | false | false |
SchibstedSpain/Leku | leku/src/main/java/com/schibstedspain/leku/locale/DefaultCountryLocaleRect.kt | 1 | 5194 | package com.schibstedspain.leku.locale
import com.google.android.gms.maps.model.LatLng
import java.util.Locale
@SuppressWarnings("MagicNumber")
internal object DefaultCountryLocaleRect {
private val US_LOWER_LEFT = LatLng(16.132785, -168.372760)
private val US_UPPER_RIGHT = LatLng(72.344643, -47.598995)
private val UK_LOWER_LEFT = LatLng(49.495463, -8.392245)
private val UK_UPPER_RIGHT = LatLng(59.409006, 2.652597)
private val FRANCE_LOWER_LEFT = LatLng(42.278589, -5.631326)
private val FRANCE_UPPER_RIGHT = LatLng(51.419246, 9.419559)
private val ITALY_LOWER_LEFT = LatLng(36.072602, 6.344287)
private val ITALY_UPPER_RIGHT = LatLng(47.255500, 19.209133)
private val GERMANY_LOWER_LEFT = LatLng(47.103880, 5.556203)
private val GERMANY_UPPER_RIGHT = LatLng(55.204320, 15.453816)
private val GERMAN_LOWER_LEFT = LatLng(45.875834, 6.235783) // DACH Region
private val GERMAN_UPPER_RIGHT = LatLng(55.130976, 16.922589) // DACH Region
private val UAE_LOWER_LEFT = LatLng(22.523123, 51.513718) // United Arab Emirates
private val UAE_UPPER_RIGHT = LatLng(26.188523, 56.568692) // United Arab Emirates
private const val UAE_COUNTRY_CODE = "ar_ae"
private val INDIA_LOWER_LEFT = LatLng(5.445640, 67.487799)
private val INDIA_UPPER_RIGHT = LatLng(37.691225, 90.413055)
private const val INDIA_COUNTRY_CODE = "en_in"
private val SPAIN_LOWER_LEFT = LatLng(26.525467, -18.910366)
private val SPAIN_UPPER_RIGHT = LatLng(43.906271, 5.394197)
private const val SPAIN_COUNTRY_CODE = "es_es"
private val PAKISTAN_LOWER_LEFT = LatLng(22.895428, 60.201233)
private val PAKISTAN_UPPER_RIGHT = LatLng(37.228272, 76.918031)
private const val PAKISTAN_COUNTRY_CODE = "en_pk"
private val VIETNAM_LOWER_LEFT = LatLng(6.997486, 101.612789)
private val VIETNAM_UPPER_RIGHT = LatLng(24.151926, 110.665524)
private const val VIETNAM_COUNTRY_CODE = "vi_VN"
private val HK_LOWER_LEFT = LatLng(22.153611, 113.835000) // Hong Kong
private val HK_UPPER_RIGHT = LatLng(22.563333, 114.441389) // Hong Kong
private const val HK_COUNTRY_CODE = "zh_HK"
private val BRAZIL_LOWER_LEFT = LatLng(-34.990322, -75.004705) // Brazil
private val BRAZIL_UPPER_RIGHT = LatLng(10.236344, -30.084353) // Brazil
private const val BRAZIL_COUNTRY_CODE = "pt_BR"
private val IRELAND_LOWER_LEFT = LatLng(51.304344, -10.763079)
private val IRELAND_UPPER_RIGHT = LatLng(55.367338, -6.294837)
private const val IRELAND_COUNTRY_CODE = "en_IE"
val defaultLowerLeft: LatLng?
get() = getLowerLeftFromZone(Locale.getDefault())
val defaultUpperRight: LatLng?
get() = getUpperRightFromZone(Locale.getDefault())
fun getLowerLeftFromZone(locale: Locale): LatLng? {
return when {
Locale.US == locale -> US_LOWER_LEFT
Locale.UK == locale -> UK_LOWER_LEFT
Locale.FRANCE == locale -> FRANCE_LOWER_LEFT
Locale.ITALY == locale -> ITALY_LOWER_LEFT
Locale.GERMANY == locale -> GERMANY_LOWER_LEFT
Locale.GERMAN == locale -> GERMAN_LOWER_LEFT
locale.toString().equals(UAE_COUNTRY_CODE, ignoreCase = true) -> UAE_LOWER_LEFT
locale.toString().equals(INDIA_COUNTRY_CODE, ignoreCase = true) -> INDIA_LOWER_LEFT
locale.toString().equals(SPAIN_COUNTRY_CODE, ignoreCase = true) -> SPAIN_LOWER_LEFT
locale.toString().equals(PAKISTAN_COUNTRY_CODE, ignoreCase = true) -> PAKISTAN_LOWER_LEFT
locale.toString().equals(VIETNAM_COUNTRY_CODE, ignoreCase = true) -> VIETNAM_LOWER_LEFT
locale.toString().equals(HK_COUNTRY_CODE, ignoreCase = true) -> HK_LOWER_LEFT
locale.toString().equals(BRAZIL_COUNTRY_CODE, ignoreCase = true) -> BRAZIL_LOWER_LEFT
locale.toString().equals(IRELAND_COUNTRY_CODE, ignoreCase = true) -> IRELAND_LOWER_LEFT
else -> null
}
}
fun getUpperRightFromZone(locale: Locale): LatLng? {
return when {
Locale.US == locale -> US_UPPER_RIGHT
Locale.UK == locale -> UK_UPPER_RIGHT
Locale.FRANCE == locale -> FRANCE_UPPER_RIGHT
Locale.ITALY == locale -> ITALY_UPPER_RIGHT
Locale.GERMANY == locale -> GERMANY_UPPER_RIGHT
Locale.GERMAN == locale -> GERMAN_UPPER_RIGHT
locale.toString().equals(UAE_COUNTRY_CODE, ignoreCase = true) -> UAE_UPPER_RIGHT
locale.toString().equals(INDIA_COUNTRY_CODE, ignoreCase = true) -> INDIA_UPPER_RIGHT
locale.toString().equals(SPAIN_COUNTRY_CODE, ignoreCase = true) -> SPAIN_UPPER_RIGHT
locale.toString().equals(PAKISTAN_COUNTRY_CODE, ignoreCase = true) -> PAKISTAN_UPPER_RIGHT
locale.toString().equals(VIETNAM_COUNTRY_CODE, ignoreCase = true) -> VIETNAM_UPPER_RIGHT
locale.toString().equals(HK_COUNTRY_CODE, ignoreCase = true) -> HK_UPPER_RIGHT
locale.toString().equals(BRAZIL_COUNTRY_CODE, ignoreCase = true) -> BRAZIL_UPPER_RIGHT
locale.toString().equals(IRELAND_COUNTRY_CODE, ignoreCase = true) -> IRELAND_UPPER_RIGHT
else -> null
}
}
}
| apache-2.0 | 31ea4abc8d7ff39ca6b70dff3ea34668 | 49.427184 | 102 | 0.671352 | 3.323097 | false | false | false | false |
stripe/stripe-android | link/src/test/java/com/stripe/android/link/ui/inline/InlineSignupViewModelTest.kt | 1 | 13210 | package com.stripe.android.link.ui.inline
import com.google.common.truth.Truth.assertThat
import com.stripe.android.core.Logger
import com.stripe.android.core.exception.APIConnectionException
import com.stripe.android.core.model.CountryCode
import com.stripe.android.link.LinkPaymentLauncher
import com.stripe.android.link.account.LinkAccountManager
import com.stripe.android.link.analytics.LinkEventsReporter
import com.stripe.android.link.model.LinkAccount
import com.stripe.android.link.ui.signup.SignUpState
import com.stripe.android.link.ui.signup.SignUpViewModel
import com.stripe.android.model.ConsumerSession
import com.stripe.android.model.PaymentIntent
import com.stripe.android.ui.core.elements.PhoneNumberController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.robolectric.RobolectricTestRunner
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
class InlineSignupViewModelTest {
private val linkAccountManager = mock<LinkAccountManager>()
private val linkEventsReporter = mock<LinkEventsReporter>()
@BeforeTest
fun setUp() {
Dispatchers.setMain(UnconfinedTestDispatcher())
}
@AfterTest
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `When email is provided it should not trigger lookup and should collect phone number`() =
runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel(prefilledEmail = CUSTOMER_EMAIL)
viewModel.toggleExpanded()
assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName)
verify(linkAccountManager, times(0)).lookupConsumer(any(), any())
}
@Test
fun `When email and phone are provided it should prefill all values`() =
runTest(UnconfinedTestDispatcher()) {
val viewModel = InlineSignupViewModel(
config = LinkPaymentLauncher.Configuration(
stripeIntent = mockStripeIntent(),
merchantName = MERCHANT_NAME,
customerEmail = CUSTOMER_EMAIL,
customerPhone = CUSTOMER_PHONE,
customerName = CUSTOMER_NAME,
customerBillingCountryCode = CUSTOMER_BILLING_COUNTRY_CODE,
shippingValues = null,
),
linkAccountManager = linkAccountManager,
linkEventsReporter = linkEventsReporter,
logger = Logger.noop()
)
viewModel.toggleExpanded()
assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName)
assertThat(viewModel.phoneController.initialPhoneNumber).isEqualTo(CUSTOMER_PHONE)
verify(linkAccountManager, times(0)).lookupConsumer(any(), any())
}
@Test
fun `When email lookup call fails then useLink is false`() =
runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel()
viewModel.toggleExpanded()
viewModel.emailController.onRawValueChange("[email protected]")
whenever(linkAccountManager.lookupConsumer(any(), any()))
.thenReturn(Result.failure(APIConnectionException()))
// Advance past lookup debounce delay
advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100)
assertThat(viewModel.viewState.value.useLink).isEqualTo(false)
whenever(linkAccountManager.lookupConsumer(any(), any()))
.thenReturn(Result.success(mock()))
viewModel.emailController.onRawValueChange("[email protected]")
// Advance past lookup debounce delay
advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100)
assertThat(viewModel.viewState.value.useLink).isEqualTo(true)
}
@Test
fun `When entered existing account then it emits user input`() =
runTest(UnconfinedTestDispatcher()) {
val email = "[email protected]"
val viewModel = createViewModel()
viewModel.toggleExpanded()
viewModel.emailController.onRawValueChange(email)
val linkAccount = LinkAccount(
mockConsumerSessionWithVerificationSession(
ConsumerSession.VerificationSession.SessionType.Sms,
ConsumerSession.VerificationSession.SessionState.Started
)
)
whenever(linkAccountManager.lookupConsumer(any(), any()))
.thenReturn(Result.success(linkAccount))
// Advance past lookup debounce delay
advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100)
assertThat(viewModel.viewState.value.userInput).isEqualTo(UserInput.SignIn(email))
}
@Test
fun `When entered non-existing account then it collects phone number`() =
runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel()
viewModel.toggleExpanded()
viewModel.emailController.onRawValueChange("[email protected]")
whenever(linkAccountManager.lookupConsumer(any(), any()))
.thenReturn(Result.success(null))
// Advance past lookup debounce delay
advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100)
assertThat(viewModel.viewState.value.userInput).isNull()
assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName)
}
@Test
fun `When user input becomes invalid then it emits null user input`() =
runTest(UnconfinedTestDispatcher()) {
val email = "[email protected]"
val viewModel = createViewModel()
viewModel.toggleExpanded()
viewModel.emailController.onRawValueChange(email)
assertThat(viewModel.viewState.value.userInput).isNull()
whenever(linkAccountManager.lookupConsumer(any(), any()))
.thenReturn(Result.success(null))
// Advance past lookup debounce delay
advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100)
assertThat(viewModel.viewState.value.userInput).isNull()
val phone = "1234567890"
viewModel.phoneController.onRawValueChange(phone)
assertThat(viewModel.viewState.value.userInput)
.isEqualTo(UserInput.SignUp(email, "+1$phone", "US", name = null))
viewModel.phoneController.onRawValueChange("")
assertThat(viewModel.viewState.value.userInput).isNull()
}
@Test
fun `When user checks box then analytics event is sent`() =
runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel()
viewModel.toggleExpanded()
verify(linkEventsReporter).onInlineSignupCheckboxChecked()
}
@Test
fun `When signup starts then analytics event is sent`() =
runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel()
viewModel.toggleExpanded()
viewModel.emailController.onRawValueChange("[email protected]")
whenever(linkAccountManager.lookupConsumer(any(), any()))
.thenReturn(Result.success(null))
// Advance past lookup debounce delay
advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100)
assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName)
verify(linkEventsReporter).onSignupStarted(true)
}
@Test
fun `User input is valid without name for US users`() = runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel(countryCode = CountryCode.US)
viewModel.toggleExpanded()
viewModel.emailController.onRawValueChange("[email protected]")
viewModel.phoneController.onRawValueChange("1234567890")
assertThat(viewModel.viewState.value.userInput).isEqualTo(
UserInput.SignUp(
email = "[email protected]",
phone = "+11234567890",
country = CountryCode.US.value,
name = null
)
)
}
@Test
fun `User input is only valid with name for non-US users`() =
runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel(countryCode = CountryCode.CA)
viewModel.toggleExpanded()
viewModel.emailController.onRawValueChange("[email protected]")
viewModel.phoneController.selectCanadianPhoneNumber()
viewModel.phoneController.onRawValueChange("1234567890")
assertThat(viewModel.viewState.value.userInput).isNull()
viewModel.nameController.onRawValueChange("Someone from Canada")
assertThat(viewModel.viewState.value.userInput).isEqualTo(
UserInput.SignUp(
email = "[email protected]",
phone = "+11234567890",
country = CountryCode.CA.value,
name = "Someone from Canada"
)
)
}
@Test
fun `Prefilled values are handled correctly`() = runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel(
countryCode = CountryCode.GB,
prefilledEmail = CUSTOMER_EMAIL,
prefilledName = CUSTOMER_NAME,
prefilledPhone = "+44$CUSTOMER_PHONE"
)
viewModel.toggleExpanded()
val expectedInput = UserInput.SignUp(
email = CUSTOMER_EMAIL,
phone = "+44$CUSTOMER_PHONE",
country = CountryCode.GB.value,
name = CUSTOMER_NAME
)
assertThat(viewModel.viewState.value.userInput).isEqualTo(expectedInput)
}
@Test
fun `E-mail is required for user input to be valid`() = runTest(UnconfinedTestDispatcher()) {
val viewModel = createViewModel(
countryCode = CountryCode.GB,
prefilledName = CUSTOMER_NAME,
prefilledPhone = "+44$CUSTOMER_PHONE"
)
viewModel.toggleExpanded()
assertThat(viewModel.viewState.value.userInput).isNull()
viewModel.emailController.onRawValueChange("[email protected]")
assertThat(viewModel.viewState.value.userInput).isNotNull()
}
private fun createViewModel(
countryCode: CountryCode = CountryCode.US,
prefilledEmail: String? = null,
prefilledName: String? = null,
prefilledPhone: String? = null
) = InlineSignupViewModel(
config = LinkPaymentLauncher.Configuration(
stripeIntent = mockStripeIntent(countryCode),
merchantName = MERCHANT_NAME,
customerEmail = prefilledEmail,
customerName = prefilledName,
customerPhone = prefilledPhone,
customerBillingCountryCode = null,
shippingValues = null,
),
linkAccountManager = linkAccountManager,
linkEventsReporter = linkEventsReporter,
logger = Logger.noop()
)
private fun mockConsumerSessionWithVerificationSession(
type: ConsumerSession.VerificationSession.SessionType,
state: ConsumerSession.VerificationSession.SessionState
): ConsumerSession {
val verificationSession = mock<ConsumerSession.VerificationSession>()
whenever(verificationSession.type).thenReturn(type)
whenever(verificationSession.state).thenReturn(state)
val verificationSessions = listOf(verificationSession)
val consumerSession = mock<ConsumerSession>()
whenever(consumerSession.verificationSessions).thenReturn(verificationSessions)
whenever(consumerSession.clientSecret).thenReturn("secret")
whenever(consumerSession.emailAddress).thenReturn("email")
return consumerSession
}
private fun mockStripeIntent(
countryCode: CountryCode = CountryCode.US
): PaymentIntent = mock {
on { this.countryCode } doReturn countryCode.value
}
private fun PhoneNumberController.selectCanadianPhoneNumber() {
val canada = countryDropdownController.displayItems.indexOfFirst {
it.contains("Canada")
}
onSelectedCountryIndex(canada)
}
private companion object {
const val MERCHANT_NAME = "merchantName"
const val CUSTOMER_EMAIL = "[email protected]"
const val CUSTOMER_PHONE = "1234567890"
const val CUSTOMER_NAME = "Customer"
const val CUSTOMER_BILLING_COUNTRY_CODE = "US"
}
}
| mit | 874780ae02f0b812d7a7a1a5f894a2e6 | 37.852941 | 105 | 0.66654 | 5.252485 | false | true | false | false |
andimage/PCBridge | src/main/kotlin/com/projectcitybuild/repositories/PlayerConfigRepository.kt | 1 | 2223 | package com.projectcitybuild.repositories
import com.projectcitybuild.core.infrastructure.database.DataSource
import com.projectcitybuild.entities.PlayerConfig
import com.projectcitybuild.modules.playercache.PlayerConfigCache
import java.time.LocalDateTime
import java.util.UUID
import javax.inject.Inject
class PlayerConfigRepository @Inject constructor(
private val cache: PlayerConfigCache,
private val dataSource: DataSource
) {
fun get(uuid: UUID): PlayerConfig? {
val cachedPlayer = cache.get(uuid)
if (cachedPlayer != null) {
return cachedPlayer
}
val row = dataSource.database().getFirstRow(
"SELECT * FROM players WHERE `uuid`=(?) LIMIT 1",
uuid.toString()
)
if (row != null) {
val deserializedPlayer = PlayerConfig(
id = row.get("id"),
uuid = UUID.fromString(row.get("uuid")),
isMuted = row.get("is_muted"),
isAllowingTPs = row.get("is_allowing_tp"),
firstSeen = row.get("first_seen"),
)
cache.put(uuid, deserializedPlayer)
return deserializedPlayer
}
return null
}
fun add(uuid: UUID, isMuted: Boolean, isAllowingTPs: Boolean, firstSeen: LocalDateTime): PlayerConfig {
val lastInsertedId = dataSource.database().executeInsert(
"INSERT INTO players VALUES (NULL, ?, ?, ?, ?)",
uuid.toString(),
isMuted,
isAllowingTPs,
firstSeen,
)
val playerConfig = PlayerConfig(
id = lastInsertedId,
uuid,
isMuted,
isAllowingTPs,
firstSeen,
)
cache.put(uuid, playerConfig)
return playerConfig
}
fun save(player: PlayerConfig) {
cache.put(player.uuid, player)
dataSource.database().executeUpdate(
"UPDATE players SET `uuid` = ?, `is_muted` = ?, `is_allowing_tp` = ?, `first_seen` = ? WHERE `id`= ?",
player.uuid.toString(),
player.isMuted,
player.isAllowingTPs,
player.firstSeen,
player.id,
)
}
}
| mit | 8998c560f15e65e945142f8bc9115eb7 | 30.309859 | 114 | 0.579847 | 4.518293 | false | true | false | false |
AndroidX/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/ColorLightTokens.kt | 3 | 2144 | /*
* 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.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
internal object ColorLightTokens {
val Background = PaletteTokens.Neutral99
val Error = PaletteTokens.Error40
val ErrorContainer = PaletteTokens.Error90
val InverseOnSurface = PaletteTokens.Neutral95
val InversePrimary = PaletteTokens.Primary80
val InverseSurface = PaletteTokens.Neutral20
val OnBackground = PaletteTokens.Neutral10
val OnError = PaletteTokens.Error100
val OnErrorContainer = PaletteTokens.Error10
val OnPrimary = PaletteTokens.Primary100
val OnPrimaryContainer = PaletteTokens.Primary10
val OnSecondary = PaletteTokens.Secondary100
val OnSecondaryContainer = PaletteTokens.Secondary10
val OnSurface = PaletteTokens.Neutral10
val OnSurfaceVariant = PaletteTokens.NeutralVariant30
val OnTertiary = PaletteTokens.Tertiary100
val OnTertiaryContainer = PaletteTokens.Tertiary10
val Outline = PaletteTokens.NeutralVariant50
val OutlineVariant = PaletteTokens.NeutralVariant80
val Primary = PaletteTokens.Primary40
val PrimaryContainer = PaletteTokens.Primary90
val Scrim = PaletteTokens.Neutral0
val Secondary = PaletteTokens.Secondary40
val SecondaryContainer = PaletteTokens.Secondary90
val Surface = PaletteTokens.Neutral99
val SurfaceTint = Primary
val SurfaceVariant = PaletteTokens.NeutralVariant90
val Tertiary = PaletteTokens.Tertiary40
val TertiaryContainer = PaletteTokens.Tertiary90
} | apache-2.0 | f3873c5c780af9fc5e9653f930af8220 | 41.058824 | 75 | 0.775653 | 4.552017 | false | false | false | false |
AndroidX/androidx | tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/LazySemantics.kt | 3 | 7482 | /*
* 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.tv.foundation.lazy.grid
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.CollectionInfo
import androidx.compose.ui.semantics.ScrollAxisRange
import androidx.compose.ui.semantics.collectionInfo
import androidx.compose.ui.semantics.horizontalScrollAxisRange
import androidx.compose.ui.semantics.indexForKey
import androidx.compose.ui.semantics.scrollBy
import androidx.compose.ui.semantics.scrollToIndex
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.verticalScrollAxisRange
import androidx.tv.foundation.lazy.layout.LazyLayoutSemanticState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun rememberLazyGridSemanticState(
state: TvLazyGridState,
itemProvider: LazyLayoutItemProvider,
reverseScrolling: Boolean
): LazyLayoutSemanticState =
remember(state, itemProvider, reverseScrolling) {
object : LazyLayoutSemanticState {
override fun scrollAxisRange(): ScrollAxisRange =
ScrollAxisRange(
value = {
// This is a simple way of representing the current position without
// needing any lazy items to be measured. It's good enough so far, because
// screen-readers care mostly about whether scroll position changed or not
// rather than the actual offset in pixels.
state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / 100_000f
},
maxValue = {
if (state.canScrollForward) {
// If we can scroll further, we don't know the end yet,
// but it's upper bounded by #items + 1
itemProvider.itemCount + 1f
} else {
// If we can't scroll further, the current value is the max
state.firstVisibleItemIndex +
state.firstVisibleItemScrollOffset / 100_000f
}
},
reverseScrolling = reverseScrolling
)
override suspend fun animateScrollBy(delta: Float) {
state.animateScrollBy(delta)
}
override suspend fun scrollToItem(index: Int) {
state.scrollToItem(index)
}
// TODO(popam): check if this is correct - it would be nice to provide correct columns
override fun collectionInfo(): CollectionInfo =
CollectionInfo(rowCount = -1, columnCount = -1)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Suppress("ComposableModifierFactory", "ModifierInspectorInfo")
@Composable
internal fun Modifier.lazyGridSemantics(
itemProvider: LazyGridItemProvider,
state: TvLazyGridState,
coroutineScope: CoroutineScope,
isVertical: Boolean,
reverseScrolling: Boolean,
userScrollEnabled: Boolean
) = this.then(
remember(
itemProvider,
state,
isVertical,
reverseScrolling,
userScrollEnabled
) {
val indexForKeyMapping: (Any) -> Int = { needle ->
val key = itemProvider::getKey
var result = -1
for (index in 0 until itemProvider.itemCount) {
if (key(index) == needle) {
result = index
break
}
}
result
}
val accessibilityScrollState = ScrollAxisRange(
value = {
// This is a simple way of representing the current position without
// needing any lazy items to be measured. It's good enough so far, because
// screen-readers care mostly about whether scroll position changed or not
// rather than the actual offset in pixels.
state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / 100_000f
},
maxValue = {
if (state.canScrollForward) {
// If we can scroll further, we don't know the end yet,
// but it's upper bounded by #items + 1
itemProvider.itemCount + 1f
} else {
// If we can't scroll further, the current value is the max
state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / 100_000f
}
},
reverseScrolling = reverseScrolling
)
val scrollByAction: ((x: Float, y: Float) -> Boolean)? = if (userScrollEnabled) {
{ x, y ->
val delta = if (isVertical) {
y
} else {
x
}
coroutineScope.launch {
(state as ScrollableState).animateScrollBy(delta)
}
// TODO(aelias): is it important to return false if we know in advance we cannot scroll?
true
}
} else {
null
}
val scrollToIndexAction: ((Int) -> Boolean)? = if (userScrollEnabled) {
{ index ->
require(index >= 0 && index < state.layoutInfo.totalItemsCount) {
"Can't scroll to index $index, it is out of " +
"bounds [0, ${state.layoutInfo.totalItemsCount})"
}
coroutineScope.launch {
state.scrollToItem(index)
}
true
}
} else {
null
}
// TODO(popam): check if this is correct - it would be nice to provide correct columns here
val collectionInfo = CollectionInfo(rowCount = -1, columnCount = -1)
Modifier.semantics {
indexForKey(indexForKeyMapping)
if (isVertical) {
verticalScrollAxisRange = accessibilityScrollState
} else {
horizontalScrollAxisRange = accessibilityScrollState
}
if (scrollByAction != null) {
scrollBy(action = scrollByAction)
}
if (scrollToIndexAction != null) {
scrollToIndex(action = scrollToIndexAction)
}
this.collectionInfo = collectionInfo
}
}
)
| apache-2.0 | dbfe188d9047fed3684bed72ba6eb0ed | 38.172775 | 104 | 0.593291 | 5.485337 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/formatter/RsAutoIndentMacrosTest.kt | 3 | 9684 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter
import org.rust.ide.typing.RsTypingTestBase
class RsAutoIndentMacrosTest : RsTypingTestBase() {
fun `test macro call argument one line braces`() = doTestByText("""
foo! {/*caret*/}
""", """
foo! {
/*caret*/
}
""")
fun `test macro call argument one line parens`() = doTestByText("""
foo! (/*caret*/);
""", """
foo! (
/*caret*/
);
""")
fun `test macro call argument one line brackets`() = doTestByText("""
foo! [/*caret*/];
""", """
foo! [
/*caret*/
];
""")
fun `test macro call argument two lines`() = doTestByText("""
foo! {/*caret*/
}
""", """
foo! {
/*caret*/
}
""")
fun `test macro call argument one line with extra token`() = doTestByText("""
foo! {/*caret*/foo}
""", """
foo! {
/*caret*/foo}
""")
fun `test macro call argument tt one line braces`() = doTestByText("""
foo! {
{/*caret*/}
}
""", """
foo! {
{
/*caret*/
}
}
""")
fun `test macro call argument tt one line parens`() = doTestByText("""
foo! {
(/*caret*/)
}
""", """
foo! {
(
/*caret*/
)
}
""")
fun `test macro call argument tt one line brackets`() = doTestByText("""
foo! {
[/*caret*/]
}
""", """
foo! {
[
/*caret*/
]
}
""")
fun `test macro call argument tt one line with extra token`() = doTestByText("""
foo! {
{/*caret*/foo}
}
""", """
foo! {
{
/*caret*/foo}
}
""")
fun `test macro definition body one line braces`() = doTestByText("""
macro_rules! foo {/*caret*/}
""", """
macro_rules! foo {
/*caret*/
}
""")
fun `test macro definition body one line parens`() = doTestByText("""
macro_rules! foo (/*caret*/);
""", """
macro_rules! foo (
/*caret*/
);
""")
fun `test macro definition body one line brackets`() = doTestByText("""
macro_rules! foo [/*caret*/];
""", """
macro_rules! foo [
/*caret*/
];
""")
fun `test macro definition body two lines`() = doTestByText("""
macro_rules! foo {/*caret*/
}
""", """
macro_rules! foo {
/*caret*/
}
""")
fun `test macro definition body one line with extra tokens`() = doTestByText("""
macro_rules! foo {/*caret*/() => {}}
""", """
macro_rules! foo {
/*caret*/() => {}}
""")
fun `test macro definition case pattern one line parens`() = doTestByText("""
macro_rules! foo {
(/*caret*/) => {}
}
""", """
macro_rules! foo {
(
/*caret*/
) => {}
}
""")
fun `test macro definition case pattern one line braces`() = doTestByText("""
macro_rules! foo {
{/*caret*/} => {}
}
""", """
macro_rules! foo {
{
/*caret*/
} => {}
}
""")
fun `test macro definition case pattern one line brackets`() = doTestByText("""
macro_rules! foo {
[/*caret*/] => {}
}
""", """
macro_rules! foo {
[
/*caret*/
] => {}
}
""")
fun `test macro definition case pattern one line with extra token`() = doTestByText("""
macro_rules! foo {
(/*caret*/foo) => {}
}
""", """
macro_rules! foo {
(
/*caret*/foo) => {}
}
""")
fun `test macro definition case body one line braces`() = doTestByText("""
macro_rules! foo {
() => {/*caret*/}
}
""", """
macro_rules! foo {
() => {
/*caret*/
}
}
""")
fun `test macro definition case body one line parens`() = doTestByText("""
macro_rules! foo {
() => (/*caret*/)
}
""", """
macro_rules! foo {
() => (
/*caret*/
)
}
""")
fun `test macro definition case body one line brackets`() = doTestByText("""
macro_rules! foo {
() => [/*caret*/]
}
""", """
macro_rules! foo {
() => [
/*caret*/
]
}
""")
fun `test macro definition case body one line with extra token`() = doTestByText("""
macro_rules! foo {
() => {/*caret*/foo}
}
""", """
macro_rules! foo {
() => {
/*caret*/foo}
}
""")
fun `test macro definition case body tt one line braces`() = doTestByText("""
macro_rules! foo {
() => {
{/*caret*/}
}
}
""", """
macro_rules! foo {
() => {
{
/*caret*/
}
}
}
""")
fun `test macro definition case body tt one line parens`() = doTestByText("""
macro_rules! foo {
() => {
(/*caret*/)
}
}
""", """
macro_rules! foo {
() => {
(
/*caret*/
)
}
}
""")
fun `test macro definition case body tt one line brackets`() = doTestByText("""
macro_rules! foo {
() => {
[/*caret*/]
}
}
""", """
macro_rules! foo {
() => {
[
/*caret*/
]
}
}
""")
fun `test macro definition case body tt one line with extra token`() = doTestByText("""
macro_rules! foo {
() => {
{/*caret*/foo}
}
}
""", """
macro_rules! foo {
() => {
{
/*caret*/foo}
}
}
""")
fun `test macro definition case body tt 2 one line braces`() = doTestByText("""
macro_rules! foo {
() => {
{
{/*caret*/}
}
}
}
""", """
macro_rules! foo {
() => {
{
{
/*caret*/
}
}
}
}
""")
fun `test macro definition case body tt 2 one line parens`() = doTestByText("""
macro_rules! foo {
() => {
{
(/*caret*/)
}
}
}
""", """
macro_rules! foo {
() => {
{
(
/*caret*/
)
}
}
}
""")
fun `test macro definition case body tt 2 one line brackets`() = doTestByText("""
macro_rules! foo {
() => {
{
[/*caret*/]
}
}
}
""", """
macro_rules! foo {
() => {
{
[
/*caret*/
]
}
}
}
""")
fun `test macro definition case body tt 2 one line with extra token`() = doTestByText("""
macro_rules! foo {
() => {
{
{/*caret*/foo}
}
}
}
""", """
macro_rules! foo {
() => {
{
{
/*caret*/foo}
}
}
}
""")
fun `test macro definition case pattern between tokens 1`() = doTestByText("""
macro_rules! foo {
(
foo/*caret*/
bar
) => {}
}
""", """
macro_rules! foo {
(
foo
/*caret*/
bar
) => {}
}
""")
fun `test macro definition case pattern between tokens 2`() = doTestByText("""
macro_rules! foo {
(
foo/*caret*/bar
baz
) => {}
}
""", """
macro_rules! foo {
(
foo
/*caret*/bar
baz
) => {}
}
""")
fun `test macro definition case body between tokens 1`() = doTestByText("""
macro_rules! foo {
() => {
foo/*caret*/
bar
}
}
""", """
macro_rules! foo {
() => {
foo
/*caret*/
bar
}
}
""")
fun `test macro definition case body between tokens 2`() = doTestByText("""
macro_rules! foo {
() => {
foo/*caret*/bar
baz
}
}
""", """
macro_rules! foo {
() => {
foo
/*caret*/bar
baz
}
}
""")
}
| mit | bd05cf735d40eeca260b6c55c7c19d70 | 20.959184 | 93 | 0.333333 | 5.070157 | false | true | false | false |
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/settings/SettingsModule.kt | 1 | 1972 | /*
* Copyright (C) 2017 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.settings
import android.app.Activity
import com.memoizrlabs.Scope
import com.memoizrlabs.Shank
import com.memoizrlabs.ShankModule
import com.memoizrlabs.shankkotlin.provideSingletonFor
import com.memoizrlabs.shankkotlin.registerFactory
import com.mvcoding.expensius.feature.currency.provideCurrenciesSource
import com.mvcoding.expensius.model.ReportSettings
import com.mvcoding.expensius.provideAppUserSource
import com.mvcoding.expensius.provideRxSchedulers
import memoizrlabs.com.shankandroid.withThisScope
class SettingsModule : ShankModule {
override fun registerFactories() {
settingsPresenter()
reportSettingsSource()
}
private fun settingsPresenter() = registerFactory(SettingsPresenter::class) { ->
SettingsPresenter(provideAppUserSource(), provideAppUserSource(), provideCurrenciesSource(), provideRxSchedulers())
}
private fun reportSettingsSource() = registerFactory(ReportSettingsSource::class) { ->
val appUserSource = provideAppUserSource()
ReportSettingsSource { appUserSource.data().map { ReportSettings(it.settings.reportPeriod, it.settings.reportGroup, it.settings.mainCurrency) } }
}
}
fun Activity.provideSettingsPresenter() = withThisScope.provideSingletonFor<SettingsPresenter>()
fun provideReportSettingsSource(scope: Scope) = Shank.with(scope).provideSingletonFor<ReportSettingsSource>() | gpl-3.0 | 6a99650872a4de032433d421d55b8ca8 | 41.891304 | 153 | 0.791582 | 4.554273 | false | false | false | false |
google/dokka | runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AbstractDokkaGradleTest.kt | 2 | 4472 | package org.jetbrains.dokka.gradle
import com.intellij.rt.execution.junit.FileComparisonFailure
import org.gradle.testkit.runner.GradleRunner
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
val testDataFolder = Paths.get("testData")
val pluginClasspathData = Paths.get("build", "createClasspathManifest", "dokka-plugin-classpath.txt")
val androidPluginClasspathData = pluginClasspathData.resolveSibling("android-dokka-plugin-classpath.txt")
val dokkaFatJarPathData = pluginClasspathData.resolveSibling("fatjar.txt")
val androidLocalProperties = testDataFolder.resolve("android.local.properties").let { if (Files.exists(it)) it else null }
abstract class AbstractDokkaGradleTest {
@get:Rule val testProjectDir = TemporaryFolder()
open val pluginClasspath: List<File> = pluginClasspathData.toFile().readLines().map { File(it) }
fun checkOutputStructure(expected: String, actualSubpath: String) {
val expectedPath = testDataFolder.resolve(expected)
val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize()
assertEqualsIgnoringSeparators(expectedPath.toFile(), buildString {
actualPath.toFile().writeStructure(this, File(actualPath.toFile(), "."))
})
}
fun checkNoErrorClasses(actualSubpath: String, extension: String = "html", errorClassMarker: String = "ERROR CLASS") {
val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize()
var checked = 0
Files.walk(actualPath).filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".$extension") }.forEach {
val text = it.toFile().readText()
val noErrorClasses = text.replace(errorClassMarker, "?!")
if (noErrorClasses != text) {
throw FileComparisonFailure("", noErrorClasses, text, null)
}
checked++
}
println("$checked files checked for error classes")
}
fun checkNoUnresolvedLinks(actualSubpath: String, extension: String = "html", marker: Regex = "[\"']#[\"']".toRegex()) {
val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize()
var checked = 0
Files.walk(actualPath).filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".$extension") }.forEach {
val text = it.toFile().readText()
val noErrorClasses = text.replace(marker, "?!")
if (noErrorClasses != text) {
throw FileComparisonFailure("", noErrorClasses, text, null)
}
checked++
}
println("$checked files checked for unresolved links")
}
fun checkExternalLink(actualSubpath: String, linkBody: String, fullLink: String, extension: String = "html") {
val match = "!!match!!"
val notMatch = "!!not-match!!"
val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize()
var checked = 0
var totalEntries = 0
Files.walk(actualPath).filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".$extension") }.forEach {
val text = it.toFile().readText()
val textWithoutMatches = text.replace(fullLink, match)
val textWithoutNonMatches = textWithoutMatches.replace(linkBody, notMatch)
if (textWithoutNonMatches != textWithoutMatches) {
val expected = textWithoutNonMatches.replace(notMatch, fullLink).replace(match, fullLink)
val actual = textWithoutMatches.replace(match, fullLink)
throw FileComparisonFailure("", expected, actual, null)
}
if (text != textWithoutMatches)
totalEntries++
checked++
}
println("$checked files checked for valid external links '$linkBody', found $totalEntries links")
}
fun configure(gradleVersion: String = "3.5", kotlinVersion: String = "1.1.2", arguments: Array<String>): GradleRunner {
val fatjar = dokkaFatJarPathData.toFile().readText()
return GradleRunner.create().withProjectDir(testProjectDir.root)
.withArguments("-Pdokka_fatjar=$fatjar", "-Ptest_kotlin_version=$kotlinVersion", *arguments)
.withPluginClasspath(pluginClasspath)
.withGradleVersion(gradleVersion)
.withDebug(true)
}
} | apache-2.0 | 5a0d538a8e68a0c092c93c067d529d43 | 40.416667 | 125 | 0.666369 | 4.672936 | false | true | false | false |
raxden/square | sample/src/main/java/com/raxdenstudios/square/sample/commons/InjectFragmentActivity.kt | 2 | 2081 | package com.raxdenstudios.square.sample.commons
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.raxdenstudios.square.interceptor.Interceptor
import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.AutoInflateLayoutInterceptor
import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.HasAutoInflateLayoutInterceptor
import com.raxdenstudios.square.interceptor.commons.injectfragment.HasInjectFragmentInterceptor
import com.raxdenstudios.square.interceptor.commons.injectfragment.InjectFragmentInterceptor
import kotlinx.android.synthetic.main.inject_fragment_activity.*
class InjectFragmentActivity : AppCompatActivity(),
HasAutoInflateLayoutInterceptor,
HasInjectFragmentInterceptor<InjectedFragment> {
private lateinit var mAutoInflateLayoutInterceptor: AutoInflateLayoutInterceptor
private lateinit var mInjectFragmentInterceptor: InjectFragmentInterceptor
var mContentView: View? = null
var mInjectedFragment: InjectedFragment? = null
// ======== HasInflateLayoutInterceptor ========================================================
override fun onContentViewCreated(view: View) {
mContentView = view
}
// ======== HasInjectFragmentInterceptor =======================================================
override fun onLoadFragmentContainer(): View =
container_view
override fun onCreateFragment(): InjectedFragment =
InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment 1") })
override fun onFragmentLoaded(fragment: InjectedFragment) {
mInjectedFragment = fragment
}
// =============================================================================================
override fun onInterceptorCreated(interceptor: Interceptor) {
when(interceptor) {
is AutoInflateLayoutInterceptor -> mAutoInflateLayoutInterceptor = interceptor
is InjectFragmentInterceptor -> mInjectFragmentInterceptor = interceptor
}
}
} | apache-2.0 | ac789f74b5bea15b0d9bb9bc54fabd26 | 41.489796 | 101 | 0.700625 | 6.031884 | false | false | false | false |
teobaranga/T-Tasks | t-tasks/src/main/java/com/teo/ttasks/ui/activities/edit_task/EditTaskActivity.kt | 1 | 10919 | package com.teo.ttasks.ui.activities.edit_task
import android.app.DatePickerDialog
import android.app.Dialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.format.DateFormat
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.DatePicker
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import com.teo.ttasks.R
import com.teo.ttasks.data.TaskListsAdapter
import com.teo.ttasks.data.model.Task
import com.teo.ttasks.data.model.TaskList
import com.teo.ttasks.databinding.ActivityEditTaskBinding
import com.teo.ttasks.util.DateUtils
import com.teo.ttasks.util.toastShort
import org.koin.androidx.scope.lifecycleScope
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
import org.threeten.bp.ZoneId
import java.util.*
class EditTaskActivity : AppCompatActivity(), EditTaskView {
class DatePickerFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Use the current date as the default date in the picker
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
// Create a new instance of DatePickerDialog and return it
return DatePickerDialog(requireContext(), activity as EditTaskActivity, year, month, day)
}
}
private val editTaskPresenter: EditTaskPresenter by lifecycleScope.inject()
private lateinit var editTaskBinding: ActivityEditTaskBinding
private lateinit var taskListsAdapter: TaskListsAdapter
private lateinit var taskListId: String
private var datePickerFragment: DatePickerFragment? = null
/**
* Flag indicating that the reminder time has been clicked.
* Used to differentiate between the reminder time and the due time.
*/
private var reminderTimeClicked: Boolean = false
/** Listener invoked when the reminder time has been selected */
private val reminderTimeSetListener: TimePickerDialog.OnTimeSetListener =
TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
val localTime = LocalTime.of(hourOfDay, minute)
val formattedTime = localTime.format(DateUtils.formatterTime)
if (reminderTimeClicked) {
editTaskBinding.reminder.text = formattedTime
editTaskPresenter.setReminderTime(localTime)
reminderTimeClicked = false
} else {
// editTaskBinding.dueDate.text = DateUtils.formatDate(this, time)
editTaskBinding.dueTime.text = formattedTime
editTaskPresenter.setDueTime(localTime)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
editTaskBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit_task)
editTaskBinding.view = this
editTaskPresenter.bindView(this)
val taskId = intent.getStringExtra(EXTRA_TASK_ID)?.trim()
taskListId = checkNotNull(intent.getStringExtra(EXTRA_TASK_LIST_ID)?.trim())
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
taskListsAdapter = TaskListsAdapter(this).apply {
setDropDownViewResource(R.layout.spinner_item_task_list_edit_dropdown)
editTaskBinding.taskLists.adapter = this
}
if (taskId.isNullOrBlank()) {
// Update the toolbar title
supportActionBar!!.setTitle(R.string.title_activity_new_task)
// Show the keyboard
editTaskBinding.taskTitle.requestFocus()
}
// Load the available task lists and the task, if available
editTaskPresenter.loadTask(taskListId, taskId)
}
override fun onDestroy() {
editTaskPresenter.unbindView(this)
super.onDestroy()
}
override fun onTaskLoaded(task: Task) {
editTaskBinding.task = task
}
override fun onTaskListsLoaded(taskLists: List<TaskList>) {
with(taskListsAdapter) {
clear()
addAll(taskLists)
}
if (taskLists.isNotEmpty()) {
editTaskBinding.taskLists.setSelection(
taskLists
.indexOfFirst { taskList -> taskList.id == taskListId }
.coerceAtLeast(0))
}
}
override fun onTaskLoadError() {
toastShort(R.string.error_task_loading)
finish()
}
override fun onTaskSaved() {
onBackPressed()
}
override fun onTaskSaveError() {
// TODO: 2016-07-24 implement
}
/**
* Reset the due time
*
* @return true if the due time was reset, false otherwise
*/
override fun onDueTimeLongClicked(v: View): Boolean {
// TODO: 2016-05-18 return false if the due time is already reset
editTaskBinding.dueTime.setText(R.string.due_time_all_day)
return true
}
override fun onTitleChanged(title: CharSequence, start: Int, before: Int, count: Int) {
editTaskPresenter.setTaskTitle(title.toString())
// Clear the error
editTaskBinding.taskTitle.error = null
}
override fun onNotesChanged(notes: CharSequence, start: Int, before: Int, count: Int) {
editTaskPresenter.setTaskNotes(notes.toString())
}
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
val dateTime = LocalDateTime.of(year, monthOfYear + 1, dayOfMonth, 0, 0)
.atZone(ZoneId.systemDefault())
editTaskPresenter.dueDate = dateTime
// Display the date after being processed by the presenter
editTaskBinding.dueDate.text = dateTime.format(DateUtils.formatterDate)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_edit_task, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.done -> {
if (editTaskBinding.taskTitle.length() == 0) {
editTaskBinding.taskTitle.error = getString(R.string.error_no_title)
editTaskBinding.taskTitle.requestFocus()
return true
}
editTaskPresenter.finishTask()
return true
}
}
return super.onOptionsItemSelected(item)
}
@Suppress("UNUSED_PARAMETER")
fun onDueDateClicked(v: View) {
hideKeyboard()
if (editTaskPresenter.hasDueDate()) {
val dialog = AlertDialog.Builder(this)
.setView(R.layout.dialog_remove_change)
.show()
dialog.findViewById<LinearLayout>(R.id.remove)!!.setOnClickListener {
// Reset the due date & reminder
editTaskPresenter.removeDueDate()
editTaskPresenter.removeReminder()
editTaskBinding.dueDate.text = null
editTaskBinding.reminder.text = null
dialog.dismiss()
}
dialog.findViewById<LinearLayout>(R.id.change)!!.setOnClickListener {
datePickerFragment = (datePickerFragment ?: DatePickerFragment()).apply {
show(supportFragmentManager, "datePicker")
}
dialog.dismiss()
}
} else {
datePickerFragment = (datePickerFragment ?: DatePickerFragment()).apply {
show(supportFragmentManager, "datePicker")
}
}
}
@Suppress("UNUSED_PARAMETER")
fun onDueTimeClicked(v: View) {
hideKeyboard()
showReminderTimePickerDialog()
}
@Suppress("UNUSED_PARAMETER")
fun onReminderClicked(v: View) {
hideKeyboard()
if (!editTaskPresenter.hasDueDate()) {
toastShort("You need to set a due date before adding a reminder")
return
}
if (editTaskPresenter.hasReminder()) {
val dialog = AlertDialog.Builder(this)
.setView(R.layout.dialog_remove_change)
.show()
dialog.findViewById<LinearLayout>(R.id.remove)!!.setOnClickListener {
editTaskPresenter.removeReminder()
editTaskBinding.reminder.text = null
dialog.dismiss()
}
dialog.findViewById<LinearLayout>(R.id.change)!!.setOnClickListener {
reminderTimeClicked = true
showReminderTimePickerDialog()
dialog.dismiss()
}
} else {
reminderTimeClicked = true
showReminderTimePickerDialog()
}
}
/**
* Show the picker for the task reminder time
*/
private fun showReminderTimePickerDialog() {
// Use the current time as the default values for the picker
val c = Calendar.getInstance()
val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
// Create a new instance of TimePickerDialog and return it
TimePickerDialog(
this,
reminderTimeSetListener,
hour,
minute,
DateFormat.is24HourFormat(this)
).show()
}
private fun hideKeyboard() {
currentFocus?.windowToken?.let {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(it, 0)
}
}
companion object {
private const val EXTRA_TASK_ID = "taskId"
private const val EXTRA_TASK_LIST_ID = "taskListId"
fun startEdit(context: Context, taskId: String, taskListId: String, bundle: Bundle?) {
context.startActivity(getTaskCreateIntent(context, taskListId).apply {
putExtra(EXTRA_TASK_ID, taskId)
}, bundle)
}
fun startCreate(context: Context, taskListId: String, bundle: Bundle?) {
context.startActivity(getTaskCreateIntent(context, taskListId), bundle)
}
/**
* Used when starting this activity from the widget
*/
fun getTaskCreateIntent(context: Context, taskListId: String): Intent {
return Intent(context, EditTaskActivity::class.java).apply {
putExtra(EXTRA_TASK_LIST_ID, taskListId)
}
}
}
}
| apache-2.0 | 78d9af55330c90f5091429990ed2e67f | 33.121875 | 105 | 0.635131 | 4.958674 | false | false | false | false |
saki4510t/libcommon | common/src/main/java/com/serenegiant/widget/GLView.kt | 1 | 9541 | package com.serenegiant.widget
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://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.
*/
import android.content.Context
import android.opengl.GLES20
import android.opengl.Matrix
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.Choreographer
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import androidx.annotation.AnyThread
import androidx.annotation.CallSuper
import androidx.annotation.Size
import androidx.annotation.WorkerThread
import com.serenegiant.gl.GLContext
import com.serenegiant.gl.GLManager
import com.serenegiant.gl.ISurface
/**
* SurfaceViewのSurfaceへOpenGL|ESで描画するためのヘルパークラス
* SurfaceViewを継承
*/
open class GLView @JvmOverloads constructor(
context: Context?, attrs: AttributeSet? = null, defStyle: Int = 0)
: SurfaceView(context, attrs, defStyle), IGLTransformView {
/**
* GLスレッド上での処理
*/
interface GLRenderer {
/**
* Surfaceが生成された時
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
fun onSurfaceCreated()
/**
* Surfaceのサイズが変更された
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
fun onSurfaceChanged(format: Int, width: Int, height: Int)
/**
* トランスフォームマトリックスを適用
*/
@WorkerThread
fun applyTransformMatrix(@Size(min=16) transform: FloatArray)
/**
* 描画イベント
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
fun drawFrame()
/**
* Surfaceが破棄された
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
fun onSurfaceDestroyed()
}
private val mGLManager: GLManager
private val mGLContext: GLContext
private val mGLHandler: Handler
@Volatile
private var mHasSurface: Boolean = false
/**
* SurfaceViewのSurfaceへOpenGL|ESで描画するためのISurfaceインスタンス
*/
private var mTarget: ISurface? = null
private val mMatrix: FloatArray = FloatArray(16)
private var mMatrixChanged = false
private var mGLRenderer: GLRenderer? = null
init {
if (DEBUG) Log.v(TAG, "コンストラクタ:")
mGLManager = GLManager()
mGLContext = mGLManager.glContext
mGLHandler = mGLManager.glHandler
Matrix.setIdentityM(mMatrix, 0)
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
if (DEBUG) Log.v(TAG, "surfaceCreated:")
if ((width > 0) && (height > 0)) {
mHasSurface = true
mMatrixChanged = true
queueEvent { onSurfaceCreated() }
}
}
override fun surfaceChanged
(holder: SurfaceHolder, format: Int,
width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "surfaceChanged:(${width}x${height})")
queueEvent { onSurfaceChanged(format, width, height) }
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
if (DEBUG) Log.v(TAG, "surfaceDestroyed:")
mHasSurface = false
queueEvent { onSurfaceDestroyed() }
}
})
}
override fun onDetachedFromWindow() {
mGLManager.release()
super.onDetachedFromWindow()
}
/**
* OpenGL|ES3.xが使用可能かどうかを取得
*/
@AnyThread
fun isGLES3() : Boolean {
return mGLContext.isGLES3
}
@AnyThread
fun isOES3Supported() : Boolean {
return mGLContext.isOES3Supported
}
/**
* 内部使用のGLManagerインスタンスを取得
*/
@AnyThread
fun getGLManager() : GLManager {
return mGLManager
}
/**
* 内部使用のGLContextを取得
*/
@AnyThread
fun getGLContext() : GLContext {
return mGLContext
}
/**
* GLRendererをセット
*/
@AnyThread
fun setRenderer(renderer: GLRenderer?) {
queueEvent {
mGLRenderer = renderer
}
}
/**
* Viewportを設定
* @param x
* @param y
* @param width
* @param height
*/
@AnyThread
fun setViewport(x: Int, y: Int, width: Int, height: Int) {
queueEvent {
if (mTarget != null) {
mTarget!!.setViewPort(x, y, width, height)
}
}
}
/**
* EGL/GLコンテキストを保持しているワーカースレッド上で実行要求する
*/
@AnyThread
fun queueEvent(task: Runnable) {
mGLHandler.post(task)
}
/**
* EGL/GLコンテキストを保持しているワーカースレッド上で実行要求する
*/
@AnyThread
fun queueEvent(task: Runnable, delayMs: Long) {
if (delayMs > 0) {
mGLHandler.postDelayed(task, delayMs)
} else {
mGLHandler.post(task)
}
}
/**
* EGL/GLコンテキストを保持しているワーカースレッド上で実行待ちしていれば実行待ちを解除する
*/
@AnyThread
fun removeEvent(task: Runnable) {
mGLHandler.removeCallbacks(task)
}
//--------------------------------------------------------------------------------
/**
* IGLTransformViewの実装
*/
@AnyThread
override fun setTransform(@Size(min=16) transform: FloatArray?) {
synchronized(mMatrix) {
if (transform != null) {
System.arraycopy(transform, 0, mMatrix, 0, 16)
} else {
Matrix.setIdentityM(mMatrix, 0)
}
mMatrixChanged = true
}
}
/**
* IGLTransformViewの実装
*/
@AnyThread
override fun getTransform(@Size(min=16) transform: FloatArray?): FloatArray {
var result = transform
if (result == null) {
result = FloatArray(16)
}
synchronized(mMatrix) {
System.arraycopy(mMatrix, 0, result, 0, 16)
}
return result
}
/**
* IGLTransformViewの実装
*/
@AnyThread
override fun getView(): View {
return this
}
//--------------------------------------------------------------------------------
/**
* デフォルトのレンダリングコンテキストへ切り返る
* Surfaceが有効であればそのサーフェースへの描画コンテキスト
* Surfaceが無効であればEGL/GLコンテキスト保持用のオフスクリーンへの描画コンテキストになる
*/
@WorkerThread
protected fun makeDefault() {
if (mTarget != null) {
mTarget!!.makeCurrent()
} else {
mGLContext.makeDefault()
}
}
/**
* Choreographerを使ったvsync同期用描画のFrameCallback実装
*/
private var mChoreographerCallback
= object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
if (mHasSurface) {
mGLManager.postFrameCallbackDelayed(this, 0)
makeDefault()
synchronized(mMatrix) {
if (mMatrixChanged) {
applyTransformMatrix(mMatrix)
mMatrixChanged = false
}
}
drawFrame()
mTarget?.swap()
}
}
}
/**
* Surfaceが生成された時
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
@CallSuper
protected fun onSurfaceCreated() {
if (DEBUG) Log.v(TAG, "onSurfaceCreated:")
mTarget = mGLContext.egl.createFromSurface(holder.surface)
// 画面全体へ描画するためにビューポートを設定する
mTarget?.setViewPort(0, 0, width, height)
mGLManager.postFrameCallbackDelayed(mChoreographerCallback, 0)
mGLRenderer?.onSurfaceCreated()
}
/**
* Surfaceのサイズが変更された
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
@CallSuper
protected fun onSurfaceChanged(
format: Int, width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "onSurfaceChanged:(${width}x${height})")
// 画面全体へ描画するためにビューポートを設定する
mTarget?.setViewPort(0, 0, width, height)
mGLRenderer?.onSurfaceChanged(format, width, height)
}
/**
* 描画イベント
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
protected fun drawFrame() {
if (mHasSurface) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
mGLRenderer?.drawFrame()
}
}
/**
* Surfaceが破棄された
* EGL/GLコンテキストを保持しているワーカースレッド上で実行される
*/
@WorkerThread
@CallSuper
protected fun onSurfaceDestroyed() {
if (DEBUG) Log.v(TAG, "onSurfaceDestroyed:")
if (mGLManager.isValid) {
mGLManager.removeFrameCallback(mChoreographerCallback)
mGLHandler.removeCallbacksAndMessages(null)
}
mGLRenderer?.onSurfaceDestroyed()
if (mTarget != null) {
mTarget!!.release()
mTarget = null
}
}
/**
* トランスフォームマトリックスを適用
*/
@WorkerThread
@CallSuper
protected fun applyTransformMatrix(@Size(min=16) transform: FloatArray) {
if (DEBUG) Log.v(TAG, "applyTransformMatrix:")
mGLRenderer?.applyTransformMatrix(transform)
}
companion object {
private const val DEBUG = false // TODO set false on release
private val TAG = GLView::class.java.simpleName
}
} | apache-2.0 | a20ea153cea19bb52f3c8a26ae4cdce6 | 21.221622 | 82 | 0.69286 | 3.118741 | false | false | false | false |
bogerchan/National-Geography | app/src/main/java/me/boger/geographic/biz/common/FavoriteNGDataSupplier.kt | 1 | 3940 | package me.boger.geographic.biz.common
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import com.google.gson.reflect.TypeToken
import me.boger.geographic.R
import me.boger.geographic.core.NGRumtime
import me.boger.geographic.biz.detailpage.DetailPageData
import me.boger.geographic.biz.detailpage.DetailPagePictureData
import me.boger.geographic.biz.selectpage.SelectPageAlbumData
import me.boger.geographic.core.NGBroadcastManager
import me.boger.geographic.core.NGConstants
import me.boger.geographic.util.Timber
import java.util.*
/**
* Created by BogerChan on 2017/7/10.
*/
class FavoriteNGDataSupplier(ctx: Context) {
companion object {
val KEY_FAVORITE_NG_DETAIL_DATA = "fav_ng_detail_data"
}
private var mDetailPageData: DetailPageData = DetailPageData("0", ArrayList<DetailPagePictureData>(0))
private var mSP = ctx.getSharedPreferences(ctx.packageName, Context.MODE_PRIVATE)
init {
val jsonDetailPageData = mSP.getString(KEY_FAVORITE_NG_DETAIL_DATA, null)
if (!TextUtils.isEmpty(jsonDetailPageData)) {
val list = NGRumtime.gson.fromJson<MutableList<DetailPagePictureData>>(
jsonDetailPageData,
object : TypeToken<MutableList<DetailPagePictureData>>() {}.type)
mDetailPageData.counttotal = list.size.toString()
mDetailPageData.picture = list
}
}
fun addDetailPageDataToFavorite(data: DetailPagePictureData): Boolean {
try {
if (mDetailPageData.picture.contains(data)) {
return true
}
mDetailPageData.picture.add(data)
mSP.edit()
.putString(KEY_FAVORITE_NG_DETAIL_DATA, NGRumtime.gson.toJson(mDetailPageData.picture))
.apply()
} catch (e: Exception) {
Timber.e(e)
mDetailPageData.picture.remove(data)
return false
}
NGBroadcastManager.sendLocalBroadcast(Intent(NGConstants.ACTION_FAVORITE_DATA_CHANGED))
return true
}
fun removeDetailPageDataToFavorite(data: DetailPagePictureData): Boolean {
try {
if (!mDetailPageData.picture.contains(data)) {
return true
}
mDetailPageData.picture.remove(data)
mSP.edit()
.putString(KEY_FAVORITE_NG_DETAIL_DATA, NGRumtime.gson.toJson(mDetailPageData.picture))
.apply()
} catch (e: Exception) {
Timber.e(e)
mDetailPageData.picture.add(data)
return false
}
NGBroadcastManager.sendLocalBroadcast(Intent(NGConstants.ACTION_FAVORITE_DATA_CHANGED))
return true
}
fun getDetailPageData(): DetailPageData {
mDetailPageData.picture.forEach {
it.clearLocale()
}
return mDetailPageData.copy(picture = mDetailPageData.picture.toMutableList())
}
private fun getLastCoverUrl(): String {
return if (mDetailPageData.picture.size > 0)
mDetailPageData.picture.last().url else ""
}
private fun getImageCount() = mDetailPageData.picture.size
fun syncFavoriteState(data: DetailPageData) {
val favoriteIdSet = mutableSetOf<String>()
mDetailPageData.picture.forEach {
favoriteIdSet.add(it.id)
}
data.picture.forEach {
it.favorite = favoriteIdSet.contains(it.id)
}
}
fun getFavoriteAlbumData(): SelectPageAlbumData {
return SelectPageAlbumData(
"unset",
String.format(Locale.getDefault(),
NGRumtime.application.getString(R.string.text_favorite_item_title),
getImageCount()),
getLastCoverUrl(), "unset", "unset", "unset", "unset", "unset", "unset",
"unset", "unset", "unset")
}
} | apache-2.0 | 729390eecb55da81c6d521e594b41853 | 34.827273 | 107 | 0.640609 | 4.287269 | false | false | false | false |
czyzby/ktx | math/src/main/kotlin/ktx/math/ranges.kt | 2 | 6361 | package ktx.math
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.math.MathUtils
/**
* Creates a range defined with the given inclusive [tolerance] above and below this center value.
*/
infix fun Int.amid(tolerance: Int) = (this - tolerance)..(this + tolerance)
/**
* Returns a random element from this range using the specified source of randomness.
*
* This overload allows passing a [java.util.Random] instance so, for instance, [MathUtils.random] may be used. Results
* are undefined for an empty range, and there is no error checking.
*/
fun IntRange.random(random: java.util.Random) = random.nextInt(1 + last - first) + first
/**
* Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [multiplier].
*/
operator fun IntRange.times(multiplier: Int) = (first * multiplier)..(last * multiplier)
/**
* Creates a range by scaling the [range]'s [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* this multiplier.
*/
operator fun Int.times(range: IntRange) = (this * range.first)..(this * range.last)
/**
* Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [divisor].
*/
operator fun IntRange.div(divisor: Int) = (first / divisor)..(last / divisor)
/**
* Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [addend].
*/
operator fun IntRange.plus(addend: Int) = (first + addend)..(last + addend)
/**
* Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [subtrahend].
*/
operator fun IntRange.minus(subtrahend: Int) = (start - subtrahend)..(endInclusive - subtrahend)
/**
* Creates a range defined with the given [tolerance] above and below this center value.
*/
infix fun Float.amid(tolerance: Float) = (this - tolerance)..(this + tolerance)
/**
* Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [multiplier].
*/
operator fun ClosedRange<Float>.times(multiplier: Float) = (start * multiplier)..(endInclusive * multiplier)
/**
* Creates a range by scaling the [range]'s [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* this multiplier.
*/
operator fun Float.times(range: ClosedRange<Float>) = (this * range.start)..(this * range.endInclusive)
/**
* Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [denominator].
*/
operator fun ClosedRange<Float>.div(denominator: Float) = (start / denominator)..(endInclusive / denominator)
/**
* Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [addend].
*/
operator fun ClosedRange<Float>.plus(addend: Float) = (start + addend)..(endInclusive + addend)
/**
* Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by
* the [subtrahend].
*/
operator fun ClosedRange<Float>.minus(subtrahend: Float) = (start - subtrahend)..(endInclusive - subtrahend)
/**
* Returns a pseudo-random, uniformly distributed [Float] value from [MathUtils.random]'s sequence, bounded by
* this range.
*
* Results are undefined for an empty range, and there is no error checking. Note that
* [endInclusive][ClosedRange.endInclusive] is treated as exclusive as it is not practical to keep it inclusive.
*/
fun ClosedRange<Float>.random() = MathUtils.random.nextFloat() * (endInclusive - start) + start
/**
* Returns a pseudo-random, standard Gaussian distributed [Float] value from [MathUtils.random]'s sequence. The
* distribution is centered to this range's center and is scaled so this range is six standard deviations wide.
*
* Results are undefined for an empty range, and there is no error checking.
*
* @param clamped If true (the default), values outside the range are clamped to the range.
*/
fun ClosedRange<Float>.randomGaussian(clamped: Boolean = true) =
((MathUtils.random.nextGaussian() / 6.0 + 0.5).toFloat() * (endInclusive - start) + start).let {
if (clamped)
it.coerceIn(this)
else
it
}
/**
* Returns a triangularly distributed random number in this range, with the *mode* centered in this range, giving a
* symmetric distribution.
*
* This function uses [MathUtils.randomTriangular]. Note that [endInclusive][ClosedRange.endInclusive] is treated as
* exclusive as it is not practical to keep it inclusive. Results are undefined for an empty range, and there is no
* error checking.
*/
fun ClosedRange<Float>.randomTriangular() = MathUtils.randomTriangular(start, endInclusive)
/**
* Returns a triangularly distributed random number in this range, where values around the *mode* are more likely.
* [normalizedMode] must be a value in the range 0.0..1.0 and represents the fractional position of the mode across the
* range.
*
* This function uses `MathUtils.randomTriangular(min, max, mode)`. Note that [endInclusive][ClosedRange.endInclusive]
* is treated as exclusive as it is not practical to keep it inclusive. Results are undefined for an empty range, and
* there is no error checking.
*/
fun ClosedRange<Float>.randomTriangular(normalizedMode: Float): Float =
MathUtils.randomTriangular(
start, endInclusive,
normalizedMode * (endInclusive - start) + start
)
/**
* Linearly interpolate between the start and end of this range.
*
* @param progress The position to interpolate, where 0 corresponds with [ClosedRange.start] and 1 corresponds with
* [ClosedRange.endInclusive].
* @return The interpolated value.
*/
fun ClosedRange<Float>.lerp(progress: Float): Float =
progress * (endInclusive - start) + start
/**
* Interpolate between the start and end of this range.
*
* @param progress The position to interpolate, where 0 corresponds with [ClosedRange.start] and 1 corresponds with
* [ClosedRange.endInclusive].
* @param interpolation The function to interpolate with.
* @return The interpolated value.
*/
fun ClosedRange<Float>.interpolate(progress: Float, interpolation: Interpolation): Float =
interpolation.apply(progress) * (endInclusive - start) + start
| cc0-1.0 | 26ca444ffdbc83503be4bf06ec69fe5b | 40.575163 | 119 | 0.737305 | 4.109173 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/osmquest/OsmQuest.kt | 1 | 2627 | package de.westnordost.streetcomplete.data.osm.osmquest
import java.util.Date
import de.westnordost.streetcomplete.data.quest.Quest
import de.westnordost.streetcomplete.data.quest.QuestStatus
import de.westnordost.streetcomplete.data.osm.changes.StringMapChanges
import de.westnordost.streetcomplete.data.quest.QuestType
import de.westnordost.osmapi.map.data.Element
import de.westnordost.osmapi.map.data.LatLon
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometry
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.data.osm.upload.HasElementTagChanges
import de.westnordost.streetcomplete.data.osm.upload.UploadableInChangeset
import de.westnordost.streetcomplete.util.measuredLength
import de.westnordost.streetcomplete.util.pointOnPolylineFromEnd
import de.westnordost.streetcomplete.util.pointOnPolylineFromStart
/** Represents one task for the user to complete/correct the data based on one OSM element */
data class OsmQuest(
override var id: Long?,
override val osmElementQuestType: OsmElementQuestType<*>, // underlying OSM data
override val elementType: Element.Type,
override val elementId: Long,
override var status: QuestStatus,
override var changes: StringMapChanges?,
var changesSource: String?,
override var lastUpdate: Date,
override val geometry: ElementGeometry
) : Quest, UploadableInChangeset, HasElementTagChanges {
constructor(type: OsmElementQuestType<*>, elementType: Element.Type, elementId: Long, geometry: ElementGeometry)
: this(null, type, elementType, elementId, QuestStatus.NEW, null, null, Date(), geometry)
override val center: LatLon get() = geometry.center
override val type: QuestType<*> get() = osmElementQuestType
override val position: LatLon get() = center
override val markerLocations: Collection<LatLon> get() {
if (osmElementQuestType.hasMarkersAtEnds && geometry is ElementPolylinesGeometry) {
val polyline = geometry.polylines[0]
val length = polyline.measuredLength()
if (length > 15 * 4) {
return listOf(
polyline.pointOnPolylineFromStart(15.0)!!,
polyline.pointOnPolylineFromEnd(15.0)!!
)
}
}
return listOf(center)
}
override fun isApplicableTo(element: Element) = osmElementQuestType.isApplicableTo(element)
/* --------------------------- UploadableInChangeset --------------------------- */
override val source: String get() = changesSource!!
}
| gpl-3.0 | 79086db7623146fa1a9341a23134fa66 | 44.293103 | 116 | 0.734678 | 4.820183 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem1968.kt | 1 | 658 | package leetcode
/**
* https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/
*/
class Problem1968 {
fun rearrangeArray(nums: IntArray): IntArray {
nums.sort()
val mid = nums.size / 2
val answer = IntArray(nums.size)
var i = 0
var j = 0
while (i <= mid && j < nums.size) {
answer[j] = nums[i]
i++
j += 2
}
i = if (nums.size % 2 == 0) mid else mid + 1
j = 1
while (i < nums.size && j < nums.size) {
answer[j] = nums[i]
i++
j += 2
}
return answer
}
}
| mit | 1689e15cad6088cb9fa6f164eb79e777 | 23.37037 | 87 | 0.462006 | 3.556757 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/main/java/uk/co/reecedunn/intellij/plugin/xquery/codeInspection/xqst/XQST0047.kt | 1 | 3258 | /*
* Copyright (C) 2017-2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.codeInspection.xqst
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.PsiFile
import com.intellij.util.SmartList
import uk.co.reecedunn.intellij.plugin.core.codeInspection.Inspection
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.intellij.resources.XQueryPluginBundle
import uk.co.reecedunn.intellij.plugin.xdm.types.element
import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceDeclaration
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModuleImport
import uk.co.reecedunn.intellij.plugin.xquery.model.XQueryPrologResolver
class XQST0047 : Inspection("xqst/XQST0047.md", XQST0047::class.java.classLoader) {
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
if (file !is XQueryModule) return null
val descriptors = SmartList<ProblemDescriptor>()
file.children().forEach { module ->
val uris = HashMap<String, XpmNamespaceDeclaration>()
val prolog = (module as? XQueryPrologResolver)?.prolog?.firstOrNull()
prolog?.children()?.filterIsInstance<XQueryModuleImport>()?.forEach(fun(child) {
val ns = child as? XpmNamespaceDeclaration
val uri = ns?.namespaceUri?.data
// NOTE: A ModuleImport without a namespace prefix can import
// additional definitions into the namespace.
if (ns == null || uri == null || ns.namespacePrefix?.data.isNullOrBlank())
return
val duplicate: XpmNamespaceDeclaration? = uris[uri]
if (duplicate != null) {
val description =
XQueryPluginBundle.message("inspection.XQST0047.duplicate-namespace-uri.message", uri)
descriptors.add(
manager.createProblemDescriptor(
ns.namespaceUri?.element!!,
description,
null as LocalQuickFix?,
ProblemHighlightType.GENERIC_ERROR,
isOnTheFly
)
)
}
uris[uri] = ns
})
}
return descriptors.toTypedArray()
}
} | apache-2.0 | f209970dcf8f298d240bdd486f3f0b24 | 44.901408 | 119 | 0.668815 | 4.877246 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/max_speed/AddMaxSpeed.kt | 1 | 2600 | package de.westnordost.streetcomplete.quests.max_speed
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.OsmTaggings
import de.westnordost.streetcomplete.data.osm.Countries
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddMaxSpeed(o: OverpassMapDataDao) : SimpleOverpassQuestType<MaxSpeedAnswer>(o) {
override val tagFilters = """
ways with highway ~ motorway|trunk|primary|secondary|tertiary|unclassified|residential
and !maxspeed and !maxspeed:forward and !maxspeed:backward
and !source:maxspeed and !zone:maxspeed and !maxspeed:type and !zone:traffic
and surface !~ ${OsmTaggings.ANYTHING_UNPAVED.joinToString("|")}
and motor_vehicle !~ private|no
and vehicle !~ private|no
and (access !~ private|no or (foot and foot !~ private|no))
and area != yes
"""
override val commitMessage = "Add speed limits"
override val icon = R.drawable.ic_quest_max_speed
override val hasMarkersAtEnds = true
// see #813: US has different rules for each different state which need to be respected
override val enabledForCountries = Countries.allExcept("US")
override val defaultDisabledMessage = R.string.default_disabled_msg_maxspeed
override fun getTitle(tags: Map<String, String>) =
if (tags.containsKey("name"))
R.string.quest_maxspeed_name_title2
else
R.string.quest_maxspeed_title_short2
override fun createForm() = AddMaxSpeedForm()
override fun applyAnswerTo(answer: MaxSpeedAnswer, changes: StringMapChangesBuilder) {
when(answer) {
is MaxSpeedSign -> {
changes.add("maxspeed", answer.value)
changes.add("maxspeed:type", "sign")
}
is MaxSpeedZone -> {
changes.add("maxspeed", answer.value)
changes.add("maxspeed:type", answer.countryCode + ":" + answer.roadType)
}
is AdvisorySpeedSign -> {
changes.add("maxspeed:advisory", answer.value)
changes.add("maxspeed:type:advisory", "sign")
}
is IsLivingStreet -> {
changes.modify("highway", "living_street")
}
is ImplicitMaxSpeed -> {
changes.add("maxspeed:type", answer.countryCode + ":" + answer.roadType)
}
}
}
}
| gpl-3.0 | 1bb835129f8d977c5fed03642bd70ac5 | 42.333333 | 94 | 0.658077 | 4.467354 | false | false | false | false |
HabitRPG/habitica-android | shared/src/commonMain/kotlin/com/habitrpg/shared/habitica/models/responses/MaintenanceResponse.kt | 1 | 264 | package com.habitrpg.shared.habitica.models.responses
class MaintenanceResponse {
var activeMaintenance: Boolean? = null
var minBuild: Int? = null
var title: String? = null
var imageUrl: String? = null
var description: String? = null
} | gpl-3.0 | 42a7925f6b4770f95d35ab2a69f0cabd | 27.555556 | 53 | 0.693182 | 4.125 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/plugin/PluginEmptySequenceTypePsiImpl.kt | 1 | 2065 | /*
* Copyright (C) 2019, 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.psi.impl.plugin
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.util.elementType
import uk.co.reecedunn.intellij.plugin.intellij.lang.*
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType
import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginEmptySequenceType
import xqt.platform.intellij.xpath.XPathTokenProvider
private val XQUERY10_REC_EMPTY: List<Version> = listOf(
XQuerySpec.REC_1_0_20070123,
EXistDB.VERSION_4_0
)
private val XQUERY10_WD_EMPTY: List<Version> = listOf(
XQuerySpec.WD_1_0_20030502,
XQuerySpec.MARKLOGIC_0_9,
until(EXistDB.VERSION_4_0)
)
class PluginEmptySequenceTypePsiImpl(node: ASTNode) :
ASTWrapperPsiElement(node), PluginEmptySequenceType, VersionConformance {
// region XdmSequenceType
override val typeName: String = "empty-sequence()"
override val itemType: XdmItemType?
get() = null
override val lowerBound: Int = 0
override val upperBound: Int = 0
// endregion
// region VersionConformance
override val requiresConformance: List<Version>
get() = when (conformanceElement.elementType) {
XPathTokenProvider.KEmpty -> XQUERY10_WD_EMPTY
else -> XQUERY10_REC_EMPTY
}
override val conformanceElement: PsiElement
get() = firstChild
// endregion
}
| apache-2.0 | e3b8efd649afdb1152210fcdb189fd7b | 31.265625 | 79 | 0.738499 | 4.041096 | false | false | false | false |
elect86/jAssimp | src/test/kotlin/assimp/md5/boarMan.kt | 2 | 4070 | package assimp.md5
import assimp.*
import glm_.mat4x4.Mat4
import glm_.vec3.Vec3
import io.kotest.matchers.shouldBe
object boarMan {
operator fun invoke(fileName: String) {
Importer().testURLs(getResource(fileName)) {
flags shouldBe 0
with(rootNode) {
name shouldBe "<MD5_Root>"
transformation shouldBe Mat4(
1f, 0f, 0f, 0f,
0f, 0f, -1f, 0f,
0f, 1f, 0f, 0f,
0f, 0f, 0f, 1f)
parent shouldBe null
numChildren shouldBe 2
with(children[0]) {
name shouldBe "<MD5_Mesh>"
transformation shouldBe Mat4()
(parent === rootNode) shouldBe true
numChildren shouldBe 0
numMeshes shouldBe 1
meshes[0] shouldBe 0
}
with(children[1]) {
name shouldBe "<MD5_Hierarchy>"
transformation shouldBe Mat4()
(parent === rootNode) shouldBe true
numChildren shouldBe 1
with(children[0]) {
name shouldBe "Bone"
transformation shouldBe Mat4(
1.00000000f, -0.000000000f, 0.000000000f, 0.000000000f,
0.000000000f, -5.96046448e-07f, 1.00000000f, 0.000000000f,
-0.000000000f, -1.00000000f, -5.96046448e-07f, 0.000000000f,
0.000000000f, 0.000000000f, 0.000000000f, 1.00000000f
)
(parent === rootNode.children[1]) shouldBe true
numChildren shouldBe 0
numMeshes shouldBe 0
}
numMeshes shouldBe 0
}
numMeshes shouldBe 0
}
with(meshes[0]) {
primitiveTypes shouldBe 4
numVertices shouldBe 8436
numFaces shouldBe 2812
vertices[0] shouldBe Vec3(2.81622696f, 0.415550232f, 24.7310295f)
vertices[4217] shouldBe Vec3(7.40894270f, 2.25090504f, 23.1958885f)
vertices[8435] shouldBe Vec3(1.2144182f, -3.79157066f, 25.3626385f)
textureCoords[0][0][0] shouldBe 0.704056978f
textureCoords[0][0][1] shouldBe 0.896108985f
textureCoords[0][4217][0] shouldBe 1.852235f
textureCoords[0][4217][1] shouldBe 0.437269986f
textureCoords[0][8435][0] shouldBe 0.303604007f
textureCoords[0][8435][1] shouldBe 1.94788897f
faces.asSequence().filterIndexed { i, _ -> i in 0..7 }.forEachIndexed { i, f ->
val idx = i * 3
f shouldBe mutableListOf(idx + 1, idx + 2, idx)
}
faces[1407] shouldBe mutableListOf(4708, 4707, 4706)
faces[2811] shouldBe mutableListOf(8435, 8434, 8433)
numBones shouldBe 1
with(bones[0]) {
name shouldBe "Bone"
numWeights shouldBe 8436
weights.forEachIndexed { i, w -> w.vertexId shouldBe i; w.weight shouldBe 1f }
offsetMatrix shouldBe Mat4(
1.00000000f, -0.000000000f, 0.000000000f, -0.000000000f,
-0.000000000f, -5.96046448e-07f, -1.00000000f, 0.000000000f,
0.000000000f, 1.00000000f, -5.96046448e-07f, -0.000000000f,
-0.000000000f, 0.000000000f, -0.000000000f, 1.00000000f)
}
materialIndex shouldBe 0
name.isEmpty() shouldBe true
}
numMaterials shouldBe 1
with(materials[0]) {
textures[0].file shouldBe ""
}
}
}
} | mit | 023a12134f3677e3eace4f2354ec0f61 | 36.694444 | 98 | 0.480098 | 4.522222 | false | false | false | false |
matija94/show-me-the-code | java/Android-projects/Keddit/app/src/main/java/com/example/matija/keddit/MainActivity.kt | 1 | 1690 | package com.example.matija.keddit
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
if (savedInstanceState == null) {
changeFragment(NewsFragment())
}
}
fun changeFragment(f: Fragment, cleanStack: Boolean = false) {
val ft = supportFragmentManager.beginTransaction()
if(cleanStack) {
clearBackStack()
}
ft.setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out, R.anim.abc_popup_enter, R.anim.abc_popup_exit)
ft.replace(R.id.activity_base_content, f)
ft.addToBackStack(null)
ft.commit()
}
fun clearBackStack() {
val manager = supportFragmentManager
if (manager.backStackEntryCount > 0) {
val first = manager.getBackStackEntryAt(0)
manager.popBackStack(first.id, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
}
/**
* Finish activity when reaching the last fragment.
*/
override fun onBackPressed() {
val fragmentManager = supportFragmentManager
if (fragmentManager.backStackEntryCount > 1) {
fragmentManager.popBackStack()
} else {
finish()
}
}
}
| mit | 8546c0291b2797898eb352fb63f6813f | 28.649123 | 118 | 0.660947 | 4.435696 | false | false | false | false |
MarkNKamau/JustJava-Android | app/src/main/java/com/marknkamau/justjava/data/db/DbRepositoryImpl.kt | 1 | 1699 | package com.marknkamau.justjava.data.db
import com.marknkamau.justjava.data.models.AppProduct
import com.marknkamau.justjava.data.models.CartItem
import com.marknkamau.justjava.data.models.CartOptionEntity
import com.marknkamau.justjava.data.models.CartProductEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class DbRepositoryImpl(private val cartDao: CartDao) : DbRepository {
override suspend fun saveItemToCart(product: AppProduct, quantity: Int) = withContext(Dispatchers.IO) {
val cartProductId = cartDao.addItem(
CartProductEntity(
0,
product.id,
product.name,
product.price,
product.calculateTotal(quantity),
quantity
)
)
product.choices?.forEach { choice ->
choice.options.filter { it.isChecked }.forEach { option ->
val optionEntity = CartOptionEntity(
0,
choice.id.toLong(),
choice.name,
option.id.toLong(),
option.name,
option.price,
cartProductId
)
cartDao.addItem(optionEntity)
}
}
Unit
}
override suspend fun getCartItems(): List<CartItem> = withContext(Dispatchers.IO) {
cartDao.getAllWithOptions()
}
override suspend fun deleteItemFromCart(item: CartItem) = withContext(Dispatchers.IO) {
cartDao.deleteItem(item.cartItem)
}
override suspend fun clearCart() = withContext(Dispatchers.IO) {
cartDao.deleteAll()
}
}
| apache-2.0 | 9fbab8a31f774752a94d35118fd224c5 | 31.673077 | 107 | 0.600942 | 4.924638 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectObjectBox/app/src/main/java/me/liuqingwen/android/projectobjectbox/ContactListFragment.kt | 1 | 13214 | package me.liuqingwen.android.projectobjectbox
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.constraint.ConstraintLayout.LayoutParams.PARENT_ID
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.ListPreloader
import com.bumptech.glide.RequestBuilder
import es.dmoral.toasty.Toasty
import io.objectbox.Box
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import org.jetbrains.anko.*
import org.jetbrains.anko.constraint.layout.ConstraintSetBuilder.Side.*
import org.jetbrains.anko.constraint.layout.applyConstraintSet
import org.jetbrains.anko.constraint.layout.constraintLayout
import org.jetbrains.anko.constraint.layout.matchConstraint
import org.jetbrains.anko.design.snackbar
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.support.v4.*
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Qingwen on 2018-3-2, project: ProjectObjectBox.
*
* @Author: Qingwen
* @DateTime: 2018-3-2
* @Package: me.liuqingwen.android.projectobjectbox.view in project: ProjectObjectBox
*
* Notice: If you are using this class or file, check it and do some modification.
*/
@SuppressLint("CheckResult")
class ContactListFragment: BasicFragment(), AnkoLogger
{
interface IFragmentInteractionListener:IJobHolder
{
fun onContactSelect(contact: Contact)
}
companion object
{
fun newInstance() = ContactListFragment()
}
private var fragmentInteractionListener: IFragmentInteractionListener? = null
private lateinit var contactBox: Box<Contact>
private lateinit var layoutSwipeRefreshLayout: SwipeRefreshLayout
private lateinit var recyclerView: RecyclerView
private val contactList by lazy(LazyThreadSafetyMode.NONE) { mutableListOf<Contact>() }
private val adapter by lazy(LazyThreadSafetyMode.NONE) {ContactListAdapter(this.contactList,super.getGlideRequest {
this.placeholder(R.mipmap.ic_launcher_round)
this.error(R.mipmap.ic_launcher_round)
this.circleCrop() }, { this.updateData(it) }, { this.selectContact(it) }, { this.popUpMenuFor(it) })
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = UI {
layoutSwipeRefreshLayout = swipeRefreshLayout {
onRefresh {
launch(contextJob + UI) {
loadData()
isRefreshing = false
}
}
recyclerView = recyclerView {
adapter = [email protected]
layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
addItemDecoration(DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL))
}
}
}.view
fun updateOrInsert(id: Long)
{
val contact = this.contactBox.get(id)
if (id > 0)
{
val index = this.contactList.withIndex().find { it.value.id == id }?.index
if (index != null)
{
this.contactList[index] = contact
this.adapter.notifyItemChanged(index)
}
else
{
this.contactList.add(contact)
this.adapter.notifyItemInserted(this.contactList.size - 1)
}
}
}
private suspend fun loadData()
{
val listCount = this.contactList.size.toLong()
val dataCount = this.contactBox.count()
if (dataCount == listCount && this.contactBox.all.containsAll(this.contactList))
{
this.toast("")
if (dataCount <= 0) Toasty.warning(this.ctx,"Contact list is empty!", Toast.LENGTH_SHORT, true).show() else Toasty.info(this.ctx,"Already the newest list.", Toast.LENGTH_SHORT, true).show()
}
else
{
this.contactList.clear()
this.contactList += this.contactBox.all
if (listCount >= 0)
{
this.adapter.notifyDataSetChanged()
}
Toasty.success(this.ctx, "Contact list refreshed!", Toast.LENGTH_SHORT, true).show()
}
//Simulate the http or io processing
delay(1000)
}
private suspend fun updateData(contact: Contact)
{
this.contactBox.put(contact)
//Simulate the http or io processing
delay(500)
Toasty.success(this.ctx, "Contact saved successfully!", Toast.LENGTH_SHORT, true).show()
}
private suspend fun saveData(contact: Contact, position: Int)
{
this.updateData(contact)
this.contactList.add(position, contact)
this.adapter.notifyItemInserted(position)
}
private fun selectContact(contact: Contact)
{
this.fragmentInteractionListener?.onContactSelect(contact)
}
private fun popUpMenuFor(contact: Contact)
{
val position = contactList.indexOf(contact)
selector("[ ${contact.name} ]", listOf("Contact Information", "Copy As New", "Delete Contact")){_, selection ->
when(selection)
{
0 -> {
this.selectContact(contact)
}
1 -> {
val newContact = contact.copy(id = 0)
this.contactBox.put(newContact)
this.contactList.add(newContact)
this.adapter.notifyItemInserted(this.contactList.size - 1)
}
2 -> {
alert("Are your sure DELETE [ ${contact.name} ] from your contact list? The action cannot be restored!", "Warning") {
positiveButton("Cancel"){}
negativeButton("Delete"){
[email protected](contact.id)
[email protected](position)
[email protected](position)
val view = [email protected]
snackbar(view, "Mis-operation?", "Undo"){
launch(view.contextJob + UI) {
[email protected](contact, position)
}
}
}
}.show()
}
else -> Unit
}
}
}
override fun onAttach(context: Context?)
{
super.onAttach(context)
val app = context!!.applicationContext as MyApplication
this.contactBox = app.objectBoxStore.boxFor(Contact::class.java)
this.fragmentInteractionListener = context as? IFragmentInteractionListener
//I can load data before view created, because I just load the data without refresh the list!
launch(context.contextJob + UI) {
[email protected]()
}
}
override fun onDestroy()
{
super.onDestroy()
this.fragmentInteractionListener?.job?.cancel()
}
}
/**
* Here is the bug after the list scroll, the frist click will not be responsed!
* And the issue is opened here: [https://issuetracker.google.com/issues/66996774?pli=1]
*/
class ContactViewHolder(itemView: View):RecyclerView.ViewHolder(itemView)
{
fun bind(contact: Contact, requestBuilder: RequestBuilder<Drawable>?, actionCheck: (suspend (Contact) -> Unit)?, actionClick: ((Contact) -> Unit)?, actionLongClick: ((Contact) -> Unit)?)
{
val (_, name, _, birthday, address, imageUrl, isStar, _) = contact
this.itemView.find<TextView>(ID_LABEL_NAME).text = name
this.itemView.find<TextView>(
ID_LABEL_BIRTHDAY).text = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(birthday)
this.itemView.find<TextView>(ID_LABEL_ADDRESS).text = address
val checkboxStar = this.itemView.find<CheckBox>(
ID_CHECKBOX_STAR)
checkboxStar.isChecked = isStar
checkboxStar.setOnCheckedChangeListener { checkBox, isChecked ->
contact.isStarContact = isChecked
checkBox.isEnabled = false
launch(UI) {
actionCheck?.invoke(contact)
checkBox.isEnabled = true
}
}
val imageHead = this.itemView.find<ImageView>(
ID_IMAGE_HEAD)
requestBuilder?.load(imageUrl)?.into(imageHead)
actionClick?.run { [email protected] { this.invoke(contact) } }
actionLongClick?.run { [email protected] { this.invoke(contact); true } }
}
}
class ContactListAdapter(private val contactList: List<Contact>, private val requestBuilder: RequestBuilder<Drawable>? = null, val onItemCheckListener: (suspend (Contact) -> Unit)? = null, val onItemClickListener: ((Contact) -> Unit)? = null, val onItemLongClickListener: ((Contact) -> Unit)? = null):
RecyclerView.Adapter<ContactViewHolder>(), ListPreloader.PreloadModelProvider<Contact>
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ContactViewHolder(
ContactListUI().createView(
AnkoContext.create(parent.context, parent)))
override fun getItemCount() = this.contactList.size
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) = holder.bind(this.contactList[position], this.requestBuilder, this.onItemCheckListener, this.onItemClickListener, this.onItemLongClickListener)
override fun getPreloadItems(position: Int) = this.contactList.slice(position until position + 1)
override fun getPreloadRequestBuilder(item: Contact) = this.requestBuilder
}
private var ID_IMAGE_HEAD = 0x01
private var ID_LABEL_NAME = 0x02
private var ID_LABEL_BIRTHDAY = 0x03
private var ID_LABEL_ADDRESS = 0x04
private var ID_CHECKBOX_STAR = 0x05
class ContactListUI : AnkoComponent<ViewGroup>
{
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
constraintLayout {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
imageView {
id = ID_IMAGE_HEAD
}.lparams(width = matchConstraint, height = dip(80))
textView {
id = ID_LABEL_NAME
typeface = Typeface.DEFAULT_BOLD
}.lparams(width = wrapContent, height = wrapContent)
textView {
id = ID_LABEL_BIRTHDAY
textSize = 12.0f
}.lparams(width = wrapContent, height = wrapContent)
textView {
id = ID_LABEL_ADDRESS
textSize = 12.0f
}.lparams(width = matchConstraint, height = matchConstraint)
checkBox {
id = ID_CHECKBOX_STAR
}.lparams(width = wrapContent, height = wrapContent)
applyConstraintSet {
setDimensionRatio(ID_IMAGE_HEAD, "w,1:1")
connect(
START of ID_IMAGE_HEAD to START of PARENT_ID margin dip(8),
TOP of ID_IMAGE_HEAD to TOP of PARENT_ID margin dip(4),
BOTTOM of ID_IMAGE_HEAD to BOTTOM of PARENT_ID margin dip(4),
START of ID_LABEL_NAME to END of ID_IMAGE_HEAD margin dip(8),
TOP of ID_LABEL_NAME to TOP of PARENT_ID margin dip(4),
START of ID_LABEL_BIRTHDAY to START of ID_LABEL_NAME,
TOP of ID_LABEL_BIRTHDAY to BOTTOM of ID_LABEL_NAME margin dip(8),
START of ID_LABEL_ADDRESS to START of ID_LABEL_NAME,
END of ID_LABEL_ADDRESS to START of ID_CHECKBOX_STAR margin dip(8),
TOP of ID_LABEL_ADDRESS to BOTTOM of ID_LABEL_BIRTHDAY margin dip(4),
BOTTOM of ID_LABEL_ADDRESS to BOTTOM of PARENT_ID,
END of ID_CHECKBOX_STAR to END of PARENT_ID margin dip(8),
TOP of ID_CHECKBOX_STAR to TOP of PARENT_ID margin dip(8),
BOTTOM of ID_CHECKBOX_STAR to BOTTOM of PARENT_ID margin dip(8)
)
}
}
}
} | mit | 22e21a7d544310b34c0599ce95a86ad6 | 40.040373 | 301 | 0.619646 | 4.803344 | false | false | false | false |
Rin-Da/UCSY-News | app/src/main/java/io/github/rin_da/ucsynews/presentation/home/view/NavHeaderView.kt | 1 | 1667 | package io.github.rin_da.ucsynews.presentation.home.view
import android.content.Context
import android.view.Gravity
import android.view.View
import com.pawegio.kandroid.dp
import io.github.rin_da.ucsynews.R
import io.github.rin_da.ucsynews.presentation.base.ui.appCompatImageView
import io.github.rin_da.ucsynews.presentation.base.ui.setDemiBold
import org.jetbrains.anko.*
/**
* Created by user on 12/15/16.
*/
class NavHeaderView : AnkoComponent<Context> {
override fun createView(ui: AnkoContext<Context>): View {
with(ui) {
verticalLayout(theme = R.style.ThemeOverlay_AppCompat_Dark) {
backgroundColor = R.color.colorPrimary
gravity = Gravity.CENTER
lparams(width = matchParent, height = dimen(R.dimen.nav_header_height))
appCompatImageView {
imageResource = R.drawable.ic_sad
}.lparams(width = dimen(R.dimen.home_profile_image_dimens), height = dimen(R.dimen.home_profile_image_dimens)) {
}
textView {
textSize = sp(8).toFloat()
setDemiBold()
gravity = Gravity.CENTER_HORIZONTAL
text = "Sovalnokovia Marcida"
}.lparams(width = dp(200), height = wrapContent) {
gravity = Gravity.CENTER
topMargin = dimen(R.dimen.activity_vertical_margin)
bottomPadding = dimen(R.dimen.activity_vertical_margin)
leftPadding = dimen(R.dimen.activity_horizontal_margin)
}
}
}
return ui.view
}
}
| mit | ff69c16afc8ebf70b20e9af29d228d05 | 36.044444 | 128 | 0.60108 | 4.363874 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/helper/SearchHelperKt.kt | 1 | 7935 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.common.Direction
import com.maddyhome.idea.vim.helper.SearchHelper.findPositionOfFirstCharacter
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
private data class State(val position: Int, val trigger: Char, val inQuote: Boolean?, val lastOpenSingleQuotePos: Int)
// bounds are considered inside corresponding quotes
fun checkInString(chars: CharSequence, currentPos: Int, str: Boolean): Boolean {
val begin = findPositionOfFirstCharacter(chars, currentPos, setOf('\n'), false, Direction.BACKWARDS)?.second ?: 0
val changes = quoteChanges(chars, begin)
// TODO: here we need to keep only the latest element in beforePos (if any) and
// don't need atAndAfterPos to be eagerly collected
var (beforePos, atAndAfterPos) = changes.partition { it.position < currentPos }
var (atPos, afterPos) = atAndAfterPos.partition { it.position == currentPos }
assert(atPos.size <= 1) { "Multiple characters at position $currentPos in string $chars" }
if (atPos.isNotEmpty()) {
val atPosChange = atPos[0]
if (afterPos.isEmpty()) {
// it is situation when cursor is on closing quote, so we must consider that we are inside quotes pair
afterPos = afterPos.toMutableList()
afterPos.add(atPosChange)
} else {
// it is situation when cursor is on opening quote, so we must consider that we are inside quotes pair
beforePos = beforePos.toMutableList()
beforePos.add(atPosChange)
}
}
val lastBeforePos = beforePos.lastOrNull()
// if opening quote was found before pos (inQuote=true), it doesn't mean pos is in string, we need
// to find closing quote to be sure
var posInQuote = lastBeforePos?.inQuote?.let { if (it) null else it }
val lastOpenSingleQuotePosBeforeCurrentPos = lastBeforePos?.lastOpenSingleQuotePos ?: -1
var posInChar = if (lastOpenSingleQuotePosBeforeCurrentPos == -1) false else null
var inQuote: Boolean? = null
for ((_, trigger, inQuoteAfter, lastOpenSingleQuotePosAfter) in afterPos) {
inQuote = inQuoteAfter
if (posInQuote != null && posInChar != null) break
if (posInQuote == null && inQuoteAfter != null) {
// if we found double quote
if (trigger == '"') {
// then previously it has opposite value
posInQuote = !inQuoteAfter
// if we found single quote
} else if (trigger == '\'') {
// then we found closing single quote
posInQuote = inQuoteAfter
}
}
if (posInChar == null && lastOpenSingleQuotePosAfter != lastOpenSingleQuotePosBeforeCurrentPos) {
// if we found double quote and we reset position of last single quote
if (trigger == '"' && lastOpenSingleQuotePosAfter == -1) {
// then it means previously there supposed to be open single quote
posInChar = false
// if we found single quote
} else if (trigger == '\'') {
// if we reset position of last single quote
// it means we found closing single quote
// else it means we found opening single quote
posInChar = lastOpenSingleQuotePosAfter == -1
}
}
}
return if (str) posInQuote != null && posInQuote && (inQuote == null || !inQuote) else posInChar != null && posInChar
}
// yields changes of inQuote and lastOpenSingleQuotePos during while iterating over chars
// rules are that:
// - escaped quotes are skipped
// - single quoted group may enclose only one character, maybe escaped,
// - so distance between opening and closing single quotes cannot be more than 3
// - bounds are considered inside corresponding quotes
private fun quoteChanges(chars: CharSequence, begin: Int) = sequence {
// position of last found unpaired single quote
var lastOpenSingleQuotePos = -1
// whether we are in double quotes
// true - definitely yes
// false - definitely no
// null - maybe yes, in case we found such combination: '"
// in that situation it may be double quote inside single quotes, so we cannot threat it as double quote pair open/close
var inQuote: Boolean? = false
val charsToSearch = setOf('\'', '"', '\n')
var found = findPositionOfFirstCharacter(chars, begin, charsToSearch, false, Direction.FORWARDS)
while (found != null && found.first != '\n') {
val i = found.second
val c = found.first
when (c) {
'"' -> {
// if [maybe] in quote, then we know we found closing quote, so now we surely are not in quote
if (inQuote == null || inQuote) {
// we just found closing double quote
inQuote = false
// reset last found single quote, as it was in string literal
lastOpenSingleQuotePos = -1
// if we previously found unclosed single quote
} else if (lastOpenSingleQuotePos >= 0) {
// ...but we are too far from it
if (i - lastOpenSingleQuotePos > 2) {
// then it definitely was not opening single quote
lastOpenSingleQuotePos = -1
// and we found opening double quote
inQuote = true
} else {
// else we don't know if we inside double or single quotes or not
inQuote = null
}
// we were not in double nor in single quote, so now we are in double quote
} else {
inQuote = true
}
}
'\'' -> {
// if we previously found unclosed single quote
if (lastOpenSingleQuotePos >= 0) {
// ...but we are too far from it
if (i - lastOpenSingleQuotePos > 3) {
// ... forget about it and threat current one as unclosed
lastOpenSingleQuotePos = i
} else {
// else we found closing single quote
lastOpenSingleQuotePos = -1
// and if we didn't know whether we are in double quote or not
if (inQuote == null) {
// then now we are definitely not in
inQuote = false
}
}
} else {
// we found opening single quote
lastOpenSingleQuotePos = i
}
}
}
yield(State(i, c, inQuote, lastOpenSingleQuotePos))
found =
findPositionOfFirstCharacter(chars, i + Direction.FORWARDS.toInt(), charsToSearch, false, Direction.FORWARDS)
}
}
/**
* Check ignorecase and smartcase options to see if a case insensitive search should be performed with the given pattern.
*
* When ignorecase is not set, this will always return false - perform a case sensitive search.
*
* Otherwise, check smartcase. When set, the search will be case insensitive if the pattern contains only lowercase
* characters, and case sensitive (returns false) if the pattern contains any lowercase characters.
*
* The smartcase option can be ignored, e.g. when searching for the whole word under the cursor. This always performs a
* case insensitive search, so `\<Work\>` will match `Work` and `work`. But when choosing the same pattern from search
* history, the smartcase option is applied, and `\<Work\>` will only match `Work`.
*/
fun shouldIgnoreCase(pattern: String, ignoreSmartCaseOption: Boolean): Boolean {
val sc = VimPlugin.getOptionService().isSet(OptionScope.GLOBAL, OptionConstants.smartcaseName) &&
!ignoreSmartCaseOption
return VimPlugin.getOptionService().isSet(OptionScope.GLOBAL, OptionConstants.ignorecaseName) && !(sc && containsUpperCase(pattern))
}
private fun containsUpperCase(pattern: String): Boolean {
for (i in pattern.indices) {
if (Character.isUpperCase(pattern[i]) && (i == 0 || pattern[i - 1] != '\\')) {
return true
}
}
return false
}
| mit | 1fe32603de4e4c455c1aa7c2851e7c60 | 42.125 | 134 | 0.670321 | 4.252412 | false | false | false | false |
andrewoma/kommon | src/main/kotlin/com/github/andrewoma/kommon/collection/CircularBuffer.kt | 1 | 4264 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* 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.github.andrewoma.kommon.collection
import java.util.*
internal class CircularBuffer<T>(size: Int) : List<T> {
private var elements: Array<Any?> // TODO ... fix bound of Array
private var start = 0
private var end = 0
private var full = false
private var maxElements = 0
init {
require(size >= 0) { "The size must be greater than 0" }
elements = arrayOfNulls(size)
maxElements = elements.size
}
override val size: Int
get() = when {
end < start -> maxElements - start + end
end == start -> if (full) maxElements else 0
else -> end - start
}
override fun isEmpty() = size == 0
fun add(element: T) {
if (size == maxElements) {
remove()
}
elements[end++] = element
if (end >= maxElements) {
end = 0
}
if (end == start) {
full = true
}
}
fun remove(): T {
if (isEmpty()) throw NoSuchElementException()
val element = elements[start]
elements[start++] = null
if (start >= maxElements) {
start = 0
}
full = false
@Suppress("UNCHECKED_CAST")
return element as T
}
private fun increment(index: Int) = (index + 1).let { if (it >= maxElements) 0 else it }
override fun iterator(): Iterator<T> {
return object : Iterator<T> {
private var index = start
private var lastReturnedIndex = -1
private var isFirst = full
override fun hasNext() = isFirst || (index != end)
override fun next(): T {
if (!hasNext()) {
throw NoSuchElementException()
}
isFirst = false
lastReturnedIndex = index
index = increment(index)
@Suppress("UNCHECKED_CAST")
return elements[lastReturnedIndex] as T
}
}
}
override fun contains(element: T): Boolean {
throw UnsupportedOperationException()
}
override fun containsAll(elements: Collection<T>): Boolean {
throw UnsupportedOperationException()
}
override fun get(index: Int): T {
if (index >= size) throw IndexOutOfBoundsException("")
val pos = (start + index).let { if (it >= maxElements) it - maxElements else it }
@Suppress("UNCHECKED_CAST")
return elements[pos] as T
}
override fun indexOf(element: T): Int {
throw UnsupportedOperationException()
}
override fun lastIndexOf(element: T): Int {
throw UnsupportedOperationException()
}
override fun listIterator(): ListIterator<T> {
throw UnsupportedOperationException()
}
override fun listIterator(index: Int): ListIterator<T> {
throw UnsupportedOperationException()
}
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
throw UnsupportedOperationException()
}
override fun toString(): String {
return this.joinToString(", ", "[", "]")
}
}
| mit | c35d3609eac19b0e5f192586b676e3c1 | 29.676259 | 92 | 0.609522 | 4.828992 | false | false | false | false |
mdaniel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/MacDistributionBuilder.kt | 1 | 22513 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.createTask
import com.intellij.diagnostic.telemetry.use
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.util.SystemProperties
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData
import org.jetbrains.intellij.build.impl.productInfo.checkInArchive
import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.copyFile
import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders
import org.jetbrains.intellij.build.io.writeNewFile
import org.jetbrains.intellij.build.tasks.NoDuplicateZipArchiveOutputStream
import org.jetbrains.intellij.build.tasks.dir
import org.jetbrains.intellij.build.tasks.entry
import org.jetbrains.intellij.build.tasks.executableFileUnixMode
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermission
import java.time.LocalDate
import java.util.concurrent.ForkJoinTask
import java.util.function.BiConsumer
import java.util.zip.Deflater
import kotlin.io.path.nameWithoutExtension
class MacDistributionBuilder(override val context: BuildContext,
private val customizer: MacDistributionCustomizer,
private val ideaProperties: Path?) : OsSpecificDistributionBuilder {
private val targetIcnsFileName: String = "${context.productProperties.baseFileName}.icns"
override val targetOs: OsFamily
get() = OsFamily.MACOS
private fun getDocTypes(): String {
val associations = mutableListOf<String>()
if (customizer.associateIpr) {
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>ipr</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${targetIcnsFileName}</string>
<key>CFBundleTypeName</key>
<string>${context.applicationInfo.productName} Project File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
for (fileAssociation in customizer.fileAssociations) {
val iconPath = fileAssociation.iconPath
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>${fileAssociation.extension}</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${if (iconPath.isEmpty()) targetIcnsFileName else File(iconPath).name}</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
return associations.joinToString(separator = "\n ") + customizer.additionalDocTypes
}
override fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
doCopyExtraFiles(macDistDir = targetPath, arch = arch, copyDistFiles = true)
}
private fun doCopyExtraFiles(macDistDir: Path, arch: JvmArchitecture?, copyDistFiles: Boolean) {
@Suppress("SpellCheckingInspection")
val platformProperties = mutableListOf(
"\n#---------------------------------------------------------------------",
"# macOS-specific system properties",
"#---------------------------------------------------------------------",
"com.apple.mrj.application.live-resize=false",
"apple.laf.useScreenMenuBar=true",
"jbScreenMenuBar.enabled=true",
"apple.awt.fileDialogForDirectories=true",
"apple.awt.graphics.UseQuartz=true",
"apple.awt.fullscreencapturealldisplays=false"
)
customizer.getCustomIdeaProperties(context.applicationInfo).forEach(BiConsumer { k, v -> platformProperties.add("$k=$v") })
layoutMacApp(ideaProperties!!, platformProperties, getDocTypes(), macDistDir, context)
unpackPty4jNative(context, macDistDir, "darwin")
generateBuildTxt(context, macDistDir.resolve("Resources"))
if (copyDistFiles) {
copyDistFiles(context, macDistDir)
}
customizer.copyAdditionalFiles(context, macDistDir.toString())
if (arch != null) {
customizer.copyAdditionalFiles(context, macDistDir, arch)
}
generateUnixScripts(context, emptyList(), macDistDir.resolve("bin"), OsFamily.MACOS)
}
override fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
doCopyExtraFiles(macDistDir = osAndArchSpecificDistPath, arch = arch, copyDistFiles = false)
context.executeStep(spanBuilder("build macOS artifacts").setAttribute("arch", arch.name), BuildOptions.MAC_ARTIFACTS_STEP) {
val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)
val publishSit = context.publishSitArchive
val publishZipOnly = !publishSit && context.options.buildStepsToSkip.contains(BuildOptions.MAC_DMG_STEP)
val binariesToSign = customizer.getBinariesToSign(context, arch)
if (!binariesToSign.isEmpty()) {
context.executeStep(spanBuilder("sign binaries for macOS distribution")
.setAttribute("arch", arch.name), BuildOptions.MAC_SIGN_STEP) {
context.signFiles(binariesToSign.map(osAndArchSpecificDistPath::resolve), mapOf(
"mac_codesign_options" to "runtime",
"mac_codesign_force" to "true",
"mac_codesign_deep" to "true",
))
}
}
val macZip = (if (publishZipOnly) context.paths.artifactDir else context.paths.tempDir)
.resolve("$baseName.mac.${arch.name}.zip")
val macZipWithoutRuntime = macZip.resolveSibling(macZip.nameWithoutExtension + "-no-jdk.zip")
val zipRoot = getMacZipRoot(customizer, context)
val runtimeDist = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.MACOS, arch)
val directories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, runtimeDist)
val extraFiles = context.getDistFiles()
val compressionLevel = if (publishSit || publishZipOnly) Deflater.DEFAULT_COMPRESSION else Deflater.BEST_SPEED
val errorsConsumer = context.messages::warning
if (context.options.buildMacArtifactsWithRuntime) {
buildMacZip(
targetFile = macZip,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context,
javaExecutablePath = "../jbr/Contents/Home/bin/java"),
directories = directories,
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(true),
compressionLevel = compressionLevel,
errorsConsumer = errorsConsumer
)
}
if (context.options.buildMacArtifactsWithoutRuntime) {
buildMacZip(
targetFile = macZipWithoutRuntime,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context, javaExecutablePath = null),
directories = directories - runtimeDist,
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(false),
compressionLevel = compressionLevel,
errorsConsumer = errorsConsumer
)
}
if (publishZipOnly) {
Span.current().addEvent("skip DMG and SIT artifacts producing")
context.notifyArtifactBuilt(macZip)
if (context.options.buildMacArtifactsWithoutRuntime) {
context.notifyArtifactBuilt(macZipWithoutRuntime)
}
}
else {
buildAndSignDmgFromZip(macZip, macZipWithoutRuntime, arch, context.builtinModule).invoke()
}
}
}
fun buildAndSignDmgFromZip(macZip: Path, macZipWithoutRuntime: Path?, arch: JvmArchitecture, builtinModule: BuiltinModulesFileData?): ForkJoinTask<*> {
return createBuildForArchTask(builtinModule, arch, macZip, macZipWithoutRuntime, customizer, context)
}
private fun layoutMacApp(ideaPropertiesFile: Path,
platformProperties: List<String>,
docTypes: String?,
macDistDir: Path,
context: BuildContext) {
val macCustomizer = customizer
copyDirWithFileFilter(context.paths.communityHomeDir.communityRoot.resolve("bin/mac"), macDistDir.resolve("bin"), customizer.binFilesFilter)
copyDir(context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/Contents"), macDistDir)
val executable = context.productProperties.baseFileName
Files.move(macDistDir.resolve("MacOS/executable"), macDistDir.resolve("MacOS/$executable"))
//noinspection SpellCheckingInspection
val icnsPath = Path.of((if (context.applicationInfo.isEAP) customizer.icnsPathForEAP else null) ?: customizer.icnsPath)
val resourcesDistDir = macDistDir.resolve("Resources")
copyFile(icnsPath, resourcesDistDir.resolve(targetIcnsFileName))
for (fileAssociation in customizer.fileAssociations) {
if (!fileAssociation.iconPath.isEmpty()) {
val source = Path.of(fileAssociation.iconPath)
val dest = resourcesDistDir.resolve(source.fileName)
Files.deleteIfExists(dest)
copyFile(source, dest)
}
}
val fullName = context.applicationInfo.productName
//todo[nik] improve
val minor = context.applicationInfo.minorVersion
val isNotRelease = context.applicationInfo.isEAP && !minor.contains("RC") && !minor.contains("Beta")
val version = if (isNotRelease) "EAP ${context.fullBuildNumber}" else "${context.applicationInfo.majorVersion}.${minor}"
val isEap = if (isNotRelease) "-EAP" else ""
val properties = Files.readAllLines(ideaPropertiesFile)
properties.addAll(platformProperties)
Files.write(macDistDir.resolve("bin/idea.properties"), properties)
val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val classPath = context.bootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val fileVmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties).toMutableList()
val additionalJvmArgs = context.getAdditionalJvmArguments(OsFamily.MACOS).toMutableList()
if (!bootClassPath.isEmpty()) {
//noinspection SpellCheckingInspection
additionalJvmArgs.add("-Xbootclasspath/a:$bootClassPath")
}
val predicate: (String) -> Boolean = { it.startsWith("-D") }
val launcherProperties = additionalJvmArgs.filter(predicate)
val launcherVmOptions = additionalJvmArgs.filterNot(predicate)
fileVmOptions.add("-XX:ErrorFile=\$USER_HOME/java_error_in_${executable}_%p.log")
fileVmOptions.add("-XX:HeapDumpPath=\$USER_HOME/java_error_in_${executable}.hprof")
VmOptionsGenerator.writeVmOptions(macDistDir.resolve("bin/${executable}.vmoptions"), fileVmOptions, "\n")
val urlSchemes = macCustomizer.urlSchemes
val urlSchemesString = if (urlSchemes.isEmpty()) {
""
}
else {
"""
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>Stacktrace</string>
<key>CFBundleURLSchemes</key>
<array>
${urlSchemes.joinToString(separator = "\n") { " <string>$it</string>" }}
</array>
</dict>
</array>
"""
}
val todayYear = LocalDate.now().year.toString()
//noinspection SpellCheckingInspection
substituteTemplatePlaceholders(
inputFile = macDistDir.resolve("Info.plist"),
outputFile = macDistDir.resolve("Info.plist"),
placeholder = "@@",
values = listOf(
Pair("build", context.fullBuildNumber),
Pair("doc_types", docTypes ?: ""),
Pair("executable", executable),
Pair("icns", targetIcnsFileName),
Pair("bundle_name", fullName),
Pair("product_state", isEap),
Pair("bundle_identifier", macCustomizer.bundleIdentifier),
Pair("year", todayYear),
Pair("version", version),
Pair("vm_options", optionsToXml(launcherVmOptions)),
Pair("vm_properties", propertiesToXml(launcherProperties, mapOf("idea.executable" to context.productProperties.baseFileName))),
Pair("class_path", classPath),
Pair("main_class_name", context.productProperties.mainClassName.replace('.', '/')),
Pair("url_schemes", urlSchemesString),
Pair("architectures", "<key>LSArchitecturePriority</key>\n <array>\n" +
macCustomizer.architectures.joinToString(separator = "\n") { " <string>$it</string>\n" } +
" </array>"),
Pair("min_osx", macCustomizer.minOSXVersion),
)
)
val distBinDir = macDistDir.resolve("bin")
Files.createDirectories(distBinDir)
val sourceScriptDir = context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/scripts")
Files.newDirectoryStream(sourceScriptDir).use { stream ->
val inspectCommandName = context.productProperties.inspectCommandName
for (file in stream) {
if (file.toString().endsWith(".sh")) {
var fileName = file.fileName.toString()
if (fileName == "inspect.sh" && inspectCommandName != "inspect") {
fileName = "${inspectCommandName}.sh"
}
val sourceFileLf = Files.createTempFile(context.paths.tempDir, file.fileName.toString(), "")
try {
// Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts
// https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri
Files.writeString(sourceFileLf, Files.readString(file).replace("\r", ""))
val target = distBinDir.resolve(fileName)
substituteTemplatePlaceholders(
sourceFileLf,
target,
"@@",
listOf(
Pair("product_full", fullName),
Pair("script_name", executable),
Pair("inspectCommandName", inspectCommandName),
),
false,
)
}
finally {
Files.delete(sourceFileLf)
}
}
}
}
}
override fun generateExecutableFilesPatterns(includeRuntime: Boolean): List<String> {
val executableFilePatterns = mutableListOf(
"bin/*.sh",
"bin/*.py",
"bin/fsnotifier",
"bin/printenv",
"bin/restarter",
"bin/repair",
"MacOS/*"
)
if (includeRuntime) {
executableFilePatterns += context.bundledRuntime.executableFilesPatterns(OsFamily.MACOS)
}
return executableFilePatterns + customizer.extraExecutables
}
private fun createBuildForArchTask(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
customizer: MacDistributionCustomizer,
context: BuildContext): ForkJoinTask<*> {
return createTask(spanBuilder("build macOS artifacts for specific arch").setAttribute("arch", arch.name)) {
val notarize = SystemProperties.getBooleanProperty("intellij.build.mac.notarize", true)
ForkJoinTask.invokeAll(buildForArch(builtinModule, arch, macZip, macZipWithoutRuntime, notarize, customizer, context))
Files.deleteIfExists(macZip)
}
}
private fun buildForArch(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
notarize: Boolean,
customizer: MacDistributionCustomizer,
context: BuildContext): List<ForkJoinTask<*>> {
val tasks = mutableListOf<ForkJoinTask<*>?>()
val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}"
val archStr = arch.name
if (context.options.buildMacArtifactsWithRuntime) {
tasks.add(createSkippableTask(
spanBuilder("build DMG with Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_jre_$archStr",
context
) {
signAndBuildDmg(builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZip,
isRuntimeBundled = true,
suffix = suffix,
notarize = notarize)
})
}
if (context.options.buildMacArtifactsWithoutRuntime) {
requireNotNull(macZipWithoutRuntime)
tasks.add(createSkippableTask(
spanBuilder("build DMG without Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_no_jre_$archStr",
context
) {
signAndBuildDmg(builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZipWithoutRuntime,
isRuntimeBundled = false,
suffix = "-no-jdk$suffix",
notarize = notarize)
})
}
return tasks.filterNotNull()
}
}
private fun optionsToXml(options: List<String>): String {
val buff = StringBuilder()
for (it in options) {
buff.append(" <string>").append(it).append("</string>\n")
}
return buff.toString().trim()
}
private fun propertiesToXml(properties: List<String>, moreProperties: Map<String, String>): String {
val buff = StringBuilder()
for (it in properties) {
val p = it.indexOf('=')
buff.append(" <key>").append(it.substring(2, p)).append("</key>\n")
buff.append(" <string>").append(it.substring(p + 1)).append("</string>\n")
}
moreProperties.forEach { (key, value) ->
buff.append(" <key>").append(key).append("</key>\n")
buff.append(" <string>").append(value).append("</string>\n")
}
return buff.toString().trim()
}
internal fun getMacZipRoot(customizer: MacDistributionCustomizer, context: BuildContext): String =
"${customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)}/Contents"
internal fun generateMacProductJson(builtinModule: BuiltinModulesFileData?, context: BuildContext, javaExecutablePath: String?): String {
val executable = context.productProperties.baseFileName
return generateMultiPlatformProductJson(
relativePathToBin = "../bin",
builtinModules = builtinModule,
launch = listOf(
ProductInfoLaunchData(
os = OsFamily.MACOS.osName,
launcherPath = "../MacOS/${executable}",
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = "../bin/${executable}.vmoptions",
startupWmClass = null,
)
), context = context
)
}
private fun MacDistributionBuilder.buildMacZip(targetFile: Path,
zipRoot: String,
productJson: String,
directories: List<Path>,
extraFiles: Collection<Map.Entry<Path, String>>,
executableFilePatterns: List<String>,
compressionLevel: Int,
errorsConsumer: (String) -> Unit) {
spanBuilder("build zip archive for macOS")
.setAttribute("file", targetFile.toString())
.setAttribute("zipRoot", zipRoot)
.setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns)
.use {
val fs = targetFile.fileSystem
val patterns = executableFilePatterns.map { fs.getPathMatcher("glob:$it") }
val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, file, relativePath ->
when {
patterns.any { it.matches(Path.of(relativePath)) } -> entry.unixMode = executableFileUnixMode
SystemInfoRt.isUnix && PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions (file) -> {
errorsConsumer("Executable permissions of $relativePath won't be set in $targetFile. " +
"Please make sure that executable file patterns are updated.")
}
}
}
writeNewFile(targetFile) { targetFileChannel ->
NoDuplicateZipArchiveOutputStream(targetFileChannel).use { zipOutStream ->
zipOutStream.setLevel(compressionLevel)
zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson.encodeToByteArray())
val fileFilter: (Path, String) -> Boolean = { sourceFile, relativePath ->
if (relativePath.endsWith(".txt") && !relativePath.contains('/')) {
zipOutStream.entry("$zipRoot/Resources/${relativePath}", sourceFile)
false
}
else {
true
}
}
for (dir in directories) {
zipOutStream.dir(dir, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
}
for ((file, relativePath) in extraFiles) {
zipOutStream.entry("$zipRoot/${FileUtilRt.toSystemIndependentName(relativePath)}${if (relativePath.isEmpty()) "" else "/"}${file.fileName}", file)
}
}
}
checkInArchive(archiveFile = targetFile, pathInArchive = "$zipRoot/Resources", context = context)
}
}
| apache-2.0 | 6316128356f3d754067db85ca1e38f02 | 44.389113 | 158 | 0.655532 | 5.089984 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/repository/CoverCache.kt | 1 | 3199 | package com.kelsos.mbrc.repository
import android.app.Application
import com.kelsos.mbrc.constants.Protocol
import com.kelsos.mbrc.data.CoverInfo
import com.kelsos.mbrc.data.key
import com.kelsos.mbrc.data.library.Cover
import com.kelsos.mbrc.data.library.key
import com.kelsos.mbrc.di.modules.AppDispatchers
import com.kelsos.mbrc.networking.ApiBase
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.withContext
import okio.ByteString.Companion.decodeBase64
import okio.buffer
import okio.sink
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class CoverCache
@Inject
constructor(
private val albumRepository: AlbumRepository,
private val api: ApiBase,
private val dispatchers: AppDispatchers,
app: Application
) {
private val cache = File(app.cacheDir, "covers")
init {
if (!cache.exists()) {
cache.mkdir()
}
}
suspend fun cache() {
val covers = withContext(dispatchers.db) {
val albumCovers = mutableListOf<CoverInfo>()
val covers = albumRepository.getAllCursor()
.map {
CoverInfo(
artist = it.artist ?: "",
album = it.album ?: "",
hash = it.cover ?: ""
)
}
withContext(dispatchers.io) {
val files = cache.listFiles()?.map { it.nameWithoutExtension } ?: emptyList()
for (cover in covers) {
if (cover.hash.isBlank() || files.contains(cover.key())) {
albumCovers.add(cover)
} else {
albumCovers.add(cover.copy(hash = ""))
}
}
}
albumCovers
}
withContext(dispatchers.io) {
val updated = mutableListOf<CoverInfo>()
api.getAll(Protocol.LibraryCover, covers, Cover::class).onCompletion {
Timber.v("Updated covers for ${updated.size} albums")
withContext(dispatchers.db) {
albumRepository.updateCovers(updated)
}
val storedCovers = albumRepository.getAllCursor().map { it.key() }
val coverFiles = cache.listFiles()
if (coverFiles != null) {
val notInDb = coverFiles.filter { !storedCovers.contains(it.nameWithoutExtension) }
Timber.v("deleting ${notInDb.size} covers no longer in db")
for (file in notInDb) {
runCatching { file.delete() }
}
}
}.collect { (payload, response) ->
if (response.status == 304) {
Timber.v("cover for $payload did not change")
return@collect
}
val cover = response.cover
val hash = response.hash
if (response.status == 200 && !cover.isNullOrEmpty() && !hash.isNullOrEmpty()) {
val result = runCatching {
val file = File(cache, payload.key())
val decodeBase64 = cover.decodeBase64()
if (decodeBase64 != null) {
file.sink().buffer().use { sink -> sink.write(decodeBase64) }
}
updated.add(payload.copy(hash = hash))
}
if (result.isFailure) {
Timber.e(result.exceptionOrNull(), "Could not save cover for $payload")
}
}
}
}
}
}
| gpl-3.0 | ceadeae41d1c8b17bdb3d141bc158e54 | 30.362745 | 93 | 0.618318 | 4.237086 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJvmNameHandler.kt | 4 | 3603 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.rename.PsiElementRenameHandler
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isPlain
import org.jetbrains.kotlin.psi.psiUtil.plainContent
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RenameJvmNameHandler : PsiElementRenameHandler() {
private fun getStringTemplate(dataContext: DataContext): KtStringTemplateExpression? {
val caret = CommonDataKeys.CARET.getData(dataContext) ?: return null
val ktFile = CommonDataKeys.PSI_FILE.getData(dataContext) as? KtFile ?: return null
return ktFile.findElementAt(caret.offset)?.getNonStrictParentOfType<KtStringTemplateExpression>()
}
override fun isAvailableOnDataContext(dataContext: DataContext): Boolean {
val nameExpression = getStringTemplate(dataContext) ?: return false
if (!nameExpression.isPlain()) return false
val entry = ((nameExpression.parent as? KtValueArgument)?.parent as? KtValueArgumentList)?.parent as? KtAnnotationEntry
?: return false
val annotationType = entry.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, entry.typeReference]
?: return false
return annotationType.constructor.declarationDescriptor?.importableFqName == DescriptorUtils.JVM_NAME
}
private fun wrapDataContext(dataContext: DataContext): DataContext? {
val nameExpression = getStringTemplate(dataContext) ?: return null
val name = nameExpression.plainContent
val entry = nameExpression.getStrictParentOfType<KtAnnotationEntry>() ?: return null
val newElement =
when (val annotationList = PsiTreeUtil.getParentOfType(entry, KtModifierList::class.java, KtFileAnnotationList::class.java)) {
is KtModifierList -> (annotationList.parent as? KtDeclaration)?.toLightMethods()?.firstOrNull { it.name == name }
?: return null
is KtFileAnnotationList -> annotationList.getContainingKtFile().findFacadeClass() ?: return null
else -> return null
}
return DataContext { id ->
if (CommonDataKeys.PSI_ELEMENT.`is`(id)) return@DataContext newElement
dataContext.getData(id)
}
}
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) {
super.invoke(project, editor, file, wrapDataContext(dataContext) ?: return)
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext) {
super.invoke(project, elements, wrapDataContext(dataContext) ?: return)
}
}
| apache-2.0 | e699b4e8fb306ae230ceae76a76fb504 | 51.217391 | 158 | 0.754094 | 5.081805 | false | false | false | false |
GunoH/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/request/GitLabProjectApi.kt | 2 | 2065 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.api.request
import com.intellij.collaboration.api.dto.GraphQLConnectionDTO
import com.intellij.collaboration.api.dto.GraphQLCursorPageInfoDTO
import com.intellij.collaboration.api.page.GraphQLPagesLoader
import org.jetbrains.plugins.gitlab.api.GitLabApi
import org.jetbrains.plugins.gitlab.api.GitLabGQLQueries
import org.jetbrains.plugins.gitlab.api.GitLabProjectCoordinates
import org.jetbrains.plugins.gitlab.api.dto.GitLabMemberDTO
import org.jetbrains.plugins.gitlab.mergerequest.api.dto.GitLabLabelDTO
suspend fun GitLabApi.loadAllProjectLabels(project: GitLabProjectCoordinates): List<GitLabLabelDTO> {
val pagesLoader = GraphQLPagesLoader<GitLabLabelDTO> { pagination ->
val parameters = GraphQLPagesLoader.arguments(pagination) + mapOf(
"fullPath" to project.projectPath.fullPath()
)
val request = gqlQuery(project.serverPath.gqlApiUri, GitLabGQLQueries.getProjectLabels, parameters)
loadGQLResponse(request, LabelConnection::class.java, "project", "labels").body()
}
return pagesLoader.loadAll()
}
suspend fun GitLabApi.getAllProjectMembers(project: GitLabProjectCoordinates): List<GitLabMemberDTO> {
val pagesLoader = GraphQLPagesLoader<GitLabMemberDTO> { pagination ->
val parameters = GraphQLPagesLoader.arguments(pagination) + mapOf(
"fullPath" to project.projectPath.fullPath()
)
val request = gqlQuery(project.serverPath.gqlApiUri, GitLabGQLQueries.getProjectMembers, parameters)
loadGQLResponse(request, ProjectMembersConnection::class.java, "project", "projectMembers").body()
}
return pagesLoader.loadAll()
}
private class LabelConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GitLabLabelDTO>)
: GraphQLConnectionDTO<GitLabLabelDTO>(pageInfo, nodes)
private class ProjectMembersConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GitLabMemberDTO>)
: GraphQLConnectionDTO<GitLabMemberDTO>(pageInfo, nodes) | apache-2.0 | 5e17488ff03bc1d284afccad3cec8c5c | 49.390244 | 120 | 0.812107 | 4.35654 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/segmentedprogressbar/SegmentedProgressBar.kt | 2 | 12270 | /*
MIT License
Copyright (c) 2020 Tiago Ornelas
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.thoughtcrime.securesms.components.segmentedprogressbar
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.ViewPager
import org.thoughtcrime.securesms.R
import java.util.concurrent.TimeUnit
/**
* Created by Tiago Ornelas on 18/04/2020.
* Represents a segmented progress bar on which, the progress is set by segments
* @see Segment
* And the progress of each segment is animated based on a set speed
*/
class SegmentedProgressBar : View, ViewPager.OnPageChangeListener, View.OnTouchListener {
companion object {
/**
* It is common now for devices to run at 60FPS
*/
val MILLIS_PER_FRAME = TimeUnit.MILLISECONDS.toMillis(17)
}
private val path = Path()
private val corners = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)
/**
* Number of total segments to draw
*/
var segmentCount: Int = resources.getInteger(R.integer.segmentedprogressbar_default_segments_count)
set(value) {
field = value
this.initSegments()
}
/**
* Mapping of segment index -> duration in millis. Negative durations
* ARE valid but they'll result in a call to SegmentedProgressBarListener#onRequestSegmentProgressPercentage
* which should return the current % position for the currently playing item. This helps
* to avoid synchronizing the seek bar to playback.
*/
var segmentDurations: Map<Int, Long> = mapOf()
set(value) {
field = value
this.initSegments()
}
var margin: Int = resources.getDimensionPixelSize(R.dimen.segmentedprogressbar_default_segment_margin)
private set
var radius: Int = resources.getDimensionPixelSize(R.dimen.segmentedprogressbar_default_corner_radius)
private set
var segmentStrokeWidth: Int =
resources.getDimensionPixelSize(R.dimen.segmentedprogressbar_default_segment_stroke_width)
private set
var segmentBackgroundColor: Int = Color.WHITE
private set
var segmentSelectedBackgroundColor: Int =
context.getThemeColor(R.attr.colorAccent)
private set
var segmentStrokeColor: Int = Color.BLACK
private set
var segmentSelectedStrokeColor: Int = Color.BLACK
private set
var timePerSegmentMs: Long =
resources.getInteger(R.integer.segmentedprogressbar_default_time_per_segment_ms).toLong()
private set
private var segments = mutableListOf<Segment>()
private val selectedSegment: Segment?
get() = segments.firstOrNull { it.animationState == Segment.AnimationState.ANIMATING }
private val selectedSegmentIndex: Int
get() = segments.indexOf(this.selectedSegment)
// Drawing
val strokeApplicable: Boolean
get() = segmentStrokeWidth * 4 <= measuredHeight
val segmentWidth: Float
get() = (measuredWidth - margin * (segmentCount - 1)).toFloat() / segmentCount
var viewPager: ViewPager? = null
@SuppressLint("ClickableViewAccessibility")
set(value) {
field = value
if (value == null) {
viewPager?.removeOnPageChangeListener(this)
viewPager?.setOnTouchListener(null)
} else {
viewPager?.addOnPageChangeListener(this)
viewPager?.setOnTouchListener(this)
}
}
/**
* Sets callbacks for progress bar state changes
* @see SegmentedProgressBarListener
*/
var listener: SegmentedProgressBarListener? = null
private var lastFrameTimeMillis: Long = 0L
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
val typedArray =
context.theme.obtainStyledAttributes(attrs, R.styleable.SegmentedProgressBar, 0, 0)
segmentCount =
typedArray.getInt(R.styleable.SegmentedProgressBar_totalSegments, segmentCount)
margin =
typedArray.getDimensionPixelSize(
R.styleable.SegmentedProgressBar_segmentMargins,
margin
)
radius =
typedArray.getDimensionPixelSize(
R.styleable.SegmentedProgressBar_segmentCornerRadius,
radius
)
segmentStrokeWidth =
typedArray.getDimensionPixelSize(
R.styleable.SegmentedProgressBar_segmentStrokeWidth,
segmentStrokeWidth
)
segmentBackgroundColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentBackgroundColor,
segmentBackgroundColor
)
segmentSelectedBackgroundColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentSelectedBackgroundColor,
segmentSelectedBackgroundColor
)
segmentStrokeColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentStrokeColor,
segmentStrokeColor
)
segmentSelectedStrokeColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentSelectedStrokeColor,
segmentSelectedStrokeColor
)
timePerSegmentMs =
typedArray.getInt(
R.styleable.SegmentedProgressBar_timePerSegment,
timePerSegmentMs.toInt()
).toLong()
typedArray.recycle()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
init {
setLayerType(LAYER_TYPE_SOFTWARE, null)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
segments.forEachIndexed { index, segment ->
val drawingComponents = getDrawingComponents(segment, index)
when (index) {
0 -> {
corners.indices.forEach { corners[it] = 0f }
corners[0] = radius.toFloat()
corners[1] = radius.toFloat()
corners[6] = radius.toFloat()
corners[7] = radius.toFloat()
}
segments.lastIndex -> {
corners.indices.forEach { corners[it] = 0f }
corners[2] = radius.toFloat()
corners[3] = radius.toFloat()
corners[4] = radius.toFloat()
corners[5] = radius.toFloat()
}
}
drawingComponents.first.forEachIndexed { drawingIndex, rectangle ->
when (index) {
0, segments.lastIndex -> {
path.reset()
path.addRoundRect(rectangle, corners, Path.Direction.CW)
canvas?.drawPath(path, drawingComponents.second[drawingIndex])
}
else -> canvas?.drawRect(
rectangle,
drawingComponents.second[drawingIndex]
)
}
}
}
onFrame(System.currentTimeMillis())
}
/**
* Start/Resume progress animation
*/
fun start() {
pause()
val segment = selectedSegment
if (segment == null) {
next()
} else {
isPaused = false
invalidate()
}
}
/**
* Pauses the animation process
*/
fun pause() {
isPaused = true
lastFrameTimeMillis = 0L
}
/**
* Resets the whole animation state and selected segments
* !Doesn't restart it!
* To restart, call the start() method
*/
fun reset() {
this.segments.map { it.animationState = Segment.AnimationState.IDLE }
this.invalidate()
}
/**
* Starts animation for the following segment
*/
fun next() {
loadSegment(offset = 1, userAction = true)
}
/**
* Starts animation for the previous segment
*/
fun previous() {
loadSegment(offset = -1, userAction = true)
}
/**
* Restarts animation for the current segment
*/
fun restartSegment() {
loadSegment(offset = 0, userAction = true)
}
/**
* Skips a number of segments
* @param offset number o segments fo skip
*/
fun skip(offset: Int) {
loadSegment(offset = offset, userAction = true)
}
/**
* Sets current segment to the
* @param position index
*/
fun setPosition(position: Int) {
loadSegment(offset = position - this.selectedSegmentIndex, userAction = true)
}
// Private methods
private fun loadSegment(offset: Int, userAction: Boolean) {
val oldSegmentIndex = this.segments.indexOf(this.selectedSegment)
val nextSegmentIndex = oldSegmentIndex + offset
// Index out of bounds, ignore operation
if (userAction && nextSegmentIndex !in 0 until segmentCount) {
if (nextSegmentIndex >= segmentCount) {
this.listener?.onFinished()
} else {
loadSegment(offset = 0, userAction = false)
}
return
}
segments.mapIndexed { index, segment ->
if (offset > 0) {
if (index < nextSegmentIndex) segment.animationState =
Segment.AnimationState.ANIMATED
} else if (offset < 0) {
if (index > nextSegmentIndex - 1) segment.animationState =
Segment.AnimationState.IDLE
} else if (offset == 0) {
if (index == nextSegmentIndex) segment.animationState = Segment.AnimationState.IDLE
}
}
val nextSegment = this.segments.getOrNull(nextSegmentIndex)
// Handle next segment transition/ending
if (nextSegment != null) {
pause()
nextSegment.animationState = Segment.AnimationState.ANIMATING
isPaused = false
invalidate()
this.listener?.onPage(oldSegmentIndex, this.selectedSegmentIndex)
viewPager?.currentItem = this.selectedSegmentIndex
} else {
pause()
this.listener?.onFinished()
}
}
private fun getSegmentProgressPercentage(segment: Segment, timeSinceLastFrameMillis: Long): Float {
return if (segment.animationDurationMillis > 0) {
segment.animationProgressPercentage + timeSinceLastFrameMillis.toFloat() / segment.animationDurationMillis
} else {
listener?.onRequestSegmentProgressPercentage() ?: 0f
}
}
private fun initSegments() {
this.segments.clear()
segments.addAll(
List(segmentCount) {
val duration = segmentDurations[it] ?: timePerSegmentMs
Segment(duration)
}
)
this.invalidate()
reset()
}
private var isPaused = true
private fun onFrame(frameTimeMillis: Long) {
if (isPaused) {
return
}
val lastFrameTimeMillis = this.lastFrameTimeMillis
this.lastFrameTimeMillis = frameTimeMillis
val selectedSegment = this.selectedSegment
if (selectedSegment == null) {
loadSegment(offset = 1, userAction = false)
} else if (lastFrameTimeMillis > 0L) {
val segmentProgressPercentage = getSegmentProgressPercentage(selectedSegment, frameTimeMillis - lastFrameTimeMillis)
selectedSegment.animationProgressPercentage = segmentProgressPercentage
if (selectedSegment.animationProgressPercentage >= 1f) {
loadSegment(offset = 1, userAction = false)
} else {
this.invalidate()
}
} else {
this.invalidate()
}
}
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
this.setPosition(position)
}
override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {
when (p1?.action) {
MotionEvent.ACTION_DOWN -> pause()
MotionEvent.ACTION_UP -> start()
}
return false
}
}
| gpl-3.0 | 73677350e8f466e3e29c92f6a708f3a7 | 28.495192 | 122 | 0.689487 | 4.609316 | false | false | false | false |
jk1/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/inferenceResults.kt | 3 | 6532 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.dataFlow.inference
import com.intellij.codeInsight.Nullability
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil
import com.intellij.codeInspection.dataFlow.Mutability
import com.intellij.lang.LighterASTNode
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.siyeh.ig.psiutils.ClassUtils
import java.util.*
/**
* @author peter
*/
data class ExpressionRange internal constructor (internal val startOffset: Int, internal val endOffset: Int) {
companion object {
@JvmStatic
fun create(expr: LighterASTNode, scopeStart: Int): ExpressionRange = ExpressionRange(
expr.startOffset - scopeStart, expr.endOffset - scopeStart)
}
fun restoreExpression(scope: PsiCodeBlock): PsiExpression? {
val scopeStart = scope.textRange.startOffset
return PsiTreeUtil.findElementOfClassAtRange(scope.containingFile, startOffset + scopeStart, endOffset + scopeStart,
PsiExpression::class.java)
}
}
data class PurityInferenceResult(internal val mutatedRefs: List<ExpressionRange>, internal val singleCall: ExpressionRange?) {
fun isPure(method: PsiMethod, body: () -> PsiCodeBlock): Boolean = !mutatesNonLocals(method, body) && callsOnlyPureMethods(body)
private fun mutatesNonLocals(method: PsiMethod, body: () -> PsiCodeBlock): Boolean {
return mutatedRefs.any { range -> !isLocalVarReference(range.restoreExpression(body()), method) }
}
private fun callsOnlyPureMethods(body: () -> PsiCodeBlock): Boolean {
if (singleCall == null) return true
val called = (singleCall.restoreExpression(body()) as PsiCall).resolveMethod()
return called != null && JavaMethodContractUtil.isPure(called)
}
private fun isLocalVarReference(expression: PsiExpression?, scope: PsiMethod): Boolean {
return when (expression) {
is PsiReferenceExpression -> expression.resolve().let { it is PsiLocalVariable || it is PsiParameter }
is PsiArrayAccessExpression -> (expression.arrayExpression as? PsiReferenceExpression)?.resolve().let { target ->
target is PsiLocalVariable && isLocallyCreatedArray(scope, target)
}
else -> false
}
}
private fun isLocallyCreatedArray(scope: PsiMethod, target: PsiLocalVariable): Boolean {
val initializer = target.initializer
if (initializer != null && initializer !is PsiNewExpression) {
return false
}
for (ref in ReferencesSearch.search(target, LocalSearchScope(scope)).findAll()) {
if (ref is PsiReferenceExpression && PsiUtil.isAccessedForWriting(ref)) {
val assign = PsiTreeUtil.getParentOfType(ref, PsiAssignmentExpression::class.java)
if (assign == null || assign.rExpression !is PsiNewExpression) {
return false
}
}
}
return true
}
}
interface MethodReturnInferenceResult {
fun getNullability(method: PsiMethod, body: () -> PsiCodeBlock): Nullability
fun getMutability(method: PsiMethod, body: () -> PsiCodeBlock): Mutability = Mutability.UNKNOWN
@Suppress("EqualsOrHashCode")
data class Predefined(internal val value: Nullability) : MethodReturnInferenceResult {
override fun hashCode(): Int = value.ordinal
override fun getNullability(method: PsiMethod, body: () -> PsiCodeBlock): Nullability = when {
value == Nullability.NULLABLE && InferenceFromSourceUtil.suppressNullable(
method) -> Nullability.UNKNOWN
else -> value
}
}
data class FromDelegate(internal val value: Nullability, internal val delegateCalls: List<ExpressionRange>) : MethodReturnInferenceResult {
override fun getNullability(method: PsiMethod, body: () -> PsiCodeBlock): Nullability {
if (value == Nullability.NULLABLE) {
return if (InferenceFromSourceUtil.suppressNullable(method)) Nullability.UNKNOWN
else Nullability.NULLABLE
}
return when {
delegateCalls.all { range -> isNotNullCall(range, body()) } -> Nullability.NOT_NULL
else -> Nullability.UNKNOWN
}
}
override fun getMutability(method: PsiMethod, body: () -> PsiCodeBlock): Mutability {
if (value == Nullability.NOT_NULL) {
return Mutability.UNKNOWN
}
return delegateCalls.stream().map { range -> getDelegateMutability(range, body()) }.reduce(
Mutability::union).orElse(
Mutability.UNKNOWN)
}
private fun getDelegateMutability(delegate: ExpressionRange, body: PsiCodeBlock): Mutability {
val call = delegate.restoreExpression(body) as PsiMethodCallExpression
val target = call.resolveMethod()
return when {
target == null -> Mutability.UNKNOWN
ClassUtils.isImmutable(target.returnType, false) -> Mutability.UNMODIFIABLE
else -> Mutability.getMutability(target)
}
}
private fun isNotNullCall(delegate: ExpressionRange, body: PsiCodeBlock): Boolean {
val call = delegate.restoreExpression(body) as PsiMethodCallExpression
if (call.type is PsiPrimitiveType) return true
val target = call.resolveMethod()
return target != null && NullableNotNullManager.isNotNull(target)
}
}
}
data class MethodData(
val methodReturn: MethodReturnInferenceResult?,
val purity: PurityInferenceResult?,
val contracts: List<PreContract>,
val notNullParameters: BitSet,
internal val bodyStart: Int,
internal val bodyEnd: Int
) {
fun methodBody(method: PsiMethodImpl): () -> PsiCodeBlock = {
if (method.stub != null)
CachedValuesManager.getCachedValue(method) { CachedValueProvider.Result(getDetachedBody(method), method) }
else
method.body!!
}
private fun getDetachedBody(method: PsiMethod): PsiCodeBlock {
val document = method.containingFile.viewProvider.document ?: return method.body!!
val bodyText = PsiDocumentManager.getInstance(method.project).getLastCommittedText(document).substring(bodyStart, bodyEnd)
return JavaPsiFacade.getElementFactory(method.project).createCodeBlockFromText(bodyText, method)
}
} | apache-2.0 | 49ce10555eaa82a28a5cda07907de9e8 | 40.348101 | 141 | 0.732547 | 4.878267 | false | false | false | false |
jk1/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ElementResolveResult.kt | 4 | 1306 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiSubstitutor
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState
open class ElementResolveResult<out T : PsiElement>(private val element: T) : GroovyResolveResult {
final override fun getElement(): T = element
override fun isValidResult(): Boolean = element.isValid && isStaticsOK && isAccessible && isApplicable
override fun isStaticsOK(): Boolean = true
override fun isAccessible(): Boolean = true
override fun getCurrentFileResolveContext(): PsiElement? = null
override fun getSubstitutor(): PsiSubstitutor = PsiSubstitutor.EMPTY
override fun isApplicable(): Boolean = true
override fun isInvokedOnProperty(): Boolean = false
override fun getSpreadState(): SpreadState? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ElementResolveResult<*>
return element == other.element
}
override fun hashCode(): Int = element.hashCode()
}
| apache-2.0 | b18da70e6a7f12849e6d1a643a8dba4e | 34.297297 | 140 | 0.760337 | 4.631206 | false | false | false | false |
marius-m/wt4 | models/src/main/java/lt/markmerkk/utils/LogFormatters.kt | 1 | 5572 | package lt.markmerkk.utils
import org.joda.time.format.DateTimeFormat
import lt.markmerkk.entities.Log
import org.joda.time.*
import org.joda.time.format.PeriodFormatterBuilder
import org.slf4j.LoggerFactory
object LogFormatters {
private val l = LoggerFactory.getLogger(LogFormatters::class.java)!!
const val TIME_SHORT_FORMAT = "HH:mm"
const val DATE_SHORT_FORMAT = "yyyy-MM-dd"
const val DATE_LONG_FORMAT = "yyyy-MM-dd HH:mm"
const val DATE_VERY_LONG_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS"
val formatTime = DateTimeFormat.forPattern(TIME_SHORT_FORMAT)!!
val formatDate = DateTimeFormat.forPattern(DATE_SHORT_FORMAT)!!
val longFormatDateTime = DateTimeFormat.forPattern(DATE_LONG_FORMAT)!!
val veryLongFormat = DateTimeFormat.forPattern(DATE_VERY_LONG_FORMAT)!!
val defaultDate = LocalDate(1970, 1, 1)
private val periodFormatter = PeriodFormatterBuilder()
.appendDays()
.appendSuffix("d")
.appendHours()
.appendSuffix("h")
.appendMinutes()
.appendSuffix("m")
.appendSeconds()
.appendSuffix("s")
.toFormatter()
private val periodFormatterShort = PeriodFormatterBuilder()
.appendDays()
.appendSuffix("d")
.appendHours()
.appendSuffix("h")
.appendMinutes()
.appendSuffix("m")
.appendSeconds()
.appendSuffix("s")
.toFormatter()
fun humanReadableDuration(duration: Duration): String {
return periodFormatter.print(duration.toPeriod())
}
fun humanReadableDurationShort(duration: Duration): String {
if (duration.standardMinutes <= 0)
return "0m"
val builder = StringBuilder()
val type = PeriodType.forFields(arrayOf(DurationFieldType.hours(), DurationFieldType.minutes()))
val period = Period(duration, type)
if (period.days != 0)
builder.append(period.days).append("d").append(" ")
if (period.hours != 0)
builder.append(period.hours).append("h").append(" ")
if (period.minutes != 0)
builder.append(period.minutes).append("m").append(" ")
if (builder.isNotEmpty() && builder[builder.length - 1] == " "[0])
builder.deleteCharAt(builder.length - 1)
return builder.toString()
}
fun formatLogsBasic(logs: List<Log>): String {
val hasMultipleDates = hasMultipleDates(logs)
return logs
.map { formatLogBasic(log = it, includeDate = hasMultipleDates) }
.joinToString("\n")
}
fun formatLogBasic(log: Log, includeDate: Boolean): String {
val startDate = LogFormatters.formatDate.print(log.time.start)
val formatStart = LogFormatters.formatTime.print(log.time.start)
val formatEnd = LogFormatters.formatTime.print(log.time.end)
val durationAsString = LogFormatters.humanReadableDurationShort(log.time.duration)
return StringBuilder()
.append(if (includeDate) "$startDate " else "")
.append("$formatStart - $formatEnd ($durationAsString)")
.append(" >> ")
.append(if (!log.code.isEmpty()) "'${log.code.code}' " else "")
.append("'${log.comment}'")
.toString()
}
/**
* @return logs are in span through multiple dates
*/
fun hasMultipleDates(logs: List<Log>): Boolean {
val logDates: Set<LocalDate> = logs
.map { it.time.start.toLocalDate() }
.toSet()
return logDates.size > 1
}
fun dtFromRawOrNull(
dateAsString: String,
timeAsString: String
): DateTime? {
return try {
val date = LogFormatters.formatDate.parseLocalDate(dateAsString)
val time = LogFormatters.formatTime.parseLocalTime(timeAsString)
date.toDateTime(time)
} catch (e: IllegalArgumentException) {
l.warn("Error parsing date time as string from ${dateAsString} / ${timeAsString}", e)
null
}
}
fun dateFromRawOrDefault(
dateAsString: String
): LocalDate {
return try {
formatDate.parseLocalDate(dateAsString)
} catch (e: IllegalArgumentException) {
l.warn("Error parsing date as string from ${dateAsString}", e)
defaultDate
}
}
fun timeFromRawOrDefault(
timeAsString: String
): LocalTime {
return try {
formatTime.parseLocalTime(timeAsString)
} catch (e: IllegalArgumentException) {
l.warn("Error parsing time as string from ${timeAsString}", e)
LocalTime.MIDNIGHT
}
}
/**
* Formats time
* If not the same day, will include date
* If next day, it will say tomorrow
*/
fun formatTime(
stringRes: StringRes,
dtCurrent: DateTime,
dtTarget: DateTime,
): String {
return when {
dtCurrent.toLocalDate().isEqual(dtTarget.toLocalDate()) -> formatTime.print(dtTarget)
dtCurrent.plusDays(1).toLocalDate().isEqual(dtTarget.toLocalDate()) -> {
"${stringRes.resTomorrow()} ${formatTime.print(dtTarget)}"
}
else -> longFormatDateTime.print(dtTarget)
}
}
interface StringRes {
fun resTomorrow(): String
}
}
fun Duration.toStringShort(): String {
return LogFormatters.humanReadableDurationShort(this)
} | apache-2.0 | f55fbbe572748e00e6948f7be5007ec9 | 34.050314 | 104 | 0.605887 | 4.482703 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/swift/SwiftSchemeManagementBuilder.kt | 1 | 1099 | package org.roylance.yaclib.core.services.swift
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.utilities.SwiftUtilities
class SwiftSchemeManagementBuilder(
private val projectInformation: YaclibModel.ProjectInformation) : IBuilder<YaclibModel.File> {
override fun build(): YaclibModel.File {
val file = YaclibModel.File.newBuilder()
.setFileExtension(YaclibModel.FileExtension.PLIST_EXT)
.setFileToWrite(InitialTemplate)
.setFileName("xcschememanagement")
.setFullDirectoryLocation("${SwiftUtilities.buildSwiftFullName(
projectInformation.mainDependency)}.xcodeproj/xcshareddata/xcshemes")
.build()
return file
}
private val InitialTemplate = """<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>${SwiftUtilities.buildSwiftFullName(projectInformation.mainDependency)}.xcscheme</key>
<dict></dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict></dict>
</dict>
</plist>
"""
} | mit | 0f9878b5e69d385feea3cb256ce896c5 | 31.352941 | 98 | 0.737944 | 4.025641 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/TimerDetails.kt | 1 | 15549 | /*
* Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments
import android.app.DatePickerDialog.OnDateSetListener
import android.app.Dialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.Button
import android.widget.DatePicker
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.SwitchCompat
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.math.NumberUtils
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.entities.Timer
import org.dvbviewer.controller.ui.base.BaseDialogFragment
import org.dvbviewer.controller.ui.widget.DateField
import org.dvbviewer.controller.utils.DateUtils
import java.util.*
/**
* The Class TimerDetails.
*
* @author RayBa
*/
class TimerDetails : BaseDialogFragment(), OnDateSetListener, OnClickListener, OnLongClickListener {
private var timer: Timer? = null
private var channelField: TextView? = null
private var titleField: TextView? = null
private var activeBox: SwitchCompat? = null
private var dateField: DateField? = null
private var startField: DateField? = null
private var stopField: DateField? = null
private var startTimeSetListener: OnTimeSetListener? = null
private var stopTimeSetListener: OnTimeSetListener? = null
private var cal: Calendar? = null
private var postRecordSpinner: Spinner? = null
private var mOntimeredEditedListener: OnTimerEditedListener? = null
private var monitoringSpinner: Spinner? = null
private var monitoringLabel: TextView? = null
private var preField: AppCompatEditText? = null
private var postField: AppCompatEditText? = null
/* (non-Javadoc)
* @see android.support.v4.app.DialogFragment#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
cal = GregorianCalendar.getInstance()
if (savedInstanceState == null) {
bundleToTimer(arguments!!)
} else {
bundleToTimer(savedInstanceState)
}
}
/* (non-Javadoc)
* @see com.actionbarsherlock.app.SherlockDialogFragment#onAttach(android.app.Activity)
*/
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnTimerEditedListener) {
mOntimeredEditedListener = context
}
}
/* (non-Javadoc)
* @see android.support.v4.app.DialogFragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (timer != null) {
val create = timer!!.id < 0L
titleField!!.text = timer!!.title
dateField!!.date = timer!!.start
val start = if (create) timer!!.start else DateUtils.addMinutes(timer!!.start, timer!!.pre)
val stop = if (create) timer!!.end else DateUtils.addMinutes(timer!!.end, timer!!.post * -1)
activeBox!!.isChecked = !timer!!.isFlagSet(Timer.FLAG_DISABLED)
start?.let { startField!!.setTime(it) }
stop?.let { stopField!!.setTime(it) }
preField!!.setText(timer!!.pre.toString())
postField!!.setText(timer!!.post.toString())
val invalidindex = timer!!.timerAction >= postRecordSpinner!!.count
postRecordSpinner!!.setSelection(if (invalidindex) 0 else timer!!.timerAction)
if (!TextUtils.isEmpty(timer!!.channelName)) {
channelField!!.text = timer!!.channelName
}
if (StringUtils.isNotBlank(timer!!.pdc)) {
monitoringSpinner!!.setSelection(timer!!.monitorPDC)
} else {
monitoringLabel!!.visibility = View.GONE
monitoringSpinner!!.visibility = View.GONE
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setTitle(if (timer != null && timer!!.id <= 0) R.string.createTimer else R.string.editTimer)
return dialog
}
/* (non-Javadoc)
* @see android.support.v4.app.DialogFragment#onSaveInstanceState(android.os.Bundle)
*/
override fun onSaveInstanceState(arg0: Bundle) {
super.onSaveInstanceState(arg0)
timerToBundle(timer!!, arg0)
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = activity!!.layoutInflater.inflate(R.layout.fragment_timer_details, container, false)
titleField = v.findViewById(R.id.titleField)
dateField = v.findViewById(R.id.dateField)
activeBox = v.findViewById(R.id.activeBox)
startField = v.findViewById(R.id.startField)
preField = v.findViewById(R.id.pre)
postField = v.findViewById(R.id.post)
postRecordSpinner = v.findViewById(R.id.postRecordingSpinner)
monitoringLabel = v.findViewById(R.id.monitoringCaption)
monitoringSpinner = v.findViewById(R.id.monitoringgSpinner)
startTimeSetListener = OnTimeSetListener { view, hourOfDay, minute ->
cal!!.time = startField!!.date
cal!!.set(Calendar.HOUR_OF_DAY, hourOfDay)
cal!!.set(Calendar.MINUTE, minute)
startField!!.setTime(cal!!.time)
}
stopTimeSetListener = OnTimeSetListener { view, hourOfDay, minute ->
cal!!.time = stopField!!.date
cal!!.set(Calendar.HOUR_OF_DAY, hourOfDay)
cal!!.set(Calendar.MINUTE, minute)
stopField!!.setTime(cal!!.time)
}
stopField = v.findViewById(R.id.stopField)
val cancelButton = v.findViewById<Button>(R.id.buttonCancel)
val okButton = v.findViewById<Button>(R.id.buttonOk)
channelField = v.findViewById(R.id.channelField)
dateField!!.setOnClickListener(this)
startField!!.setOnClickListener(this)
stopField!!.setOnClickListener(this)
cancelButton.setOnClickListener(this)
okButton.setOnClickListener(this)
dateField!!.setOnLongClickListener(this)
startField!!.setOnLongClickListener(this)
stopField!!.setOnLongClickListener(this)
return v
}
fun setOnTimerEditedListener(onTimerEditedListener: OnTimerEditedListener) {
this.mOntimeredEditedListener = onTimerEditedListener
}
/* (non-Javadoc)
* @see android.app.DatePickerDialog.OnDateSetListener#onDateSet(android.widget.DatePicker, int, int, int)
*/
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
val cal = GregorianCalendar.getInstance()
cal.time = dateField!!.date
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
dateField!!.date = cal.time
}
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
override fun onClick(v: View) {
val f: DateDialogFragment
when (v.id) {
R.id.dateField -> {
f = DateDialogFragment.newInstance(this@TimerDetails, dateField!!.date!!)
f.show(activity!!.supportFragmentManager, "datepicker")
}
R.id.startField -> {
f = DateDialogFragment.newInstance(startTimeSetListener!!, startField!!.date!!)
f.show(activity!!.supportFragmentManager, "startTimePicker")
}
R.id.stopField -> {
f = DateDialogFragment.newInstance(stopTimeSetListener!!, stopField!!.date!!)
f.show(activity!!.supportFragmentManager, "stopTimePicker")
}
R.id.buttonCancel -> {
if (mOntimeredEditedListener != null) {
mOntimeredEditedListener!!.timerEdited(null)
}
dismiss()
}
R.id.buttonOk -> {
calcStartEnd()
timer!!.title = titleField!!.text.toString()
timer!!.timerAction = postRecordSpinner!!.selectedItemPosition
timer!!.monitorPDC = monitoringSpinner!!.selectedItemPosition
timer!!.pre = NumberUtils.toInt(preField!!.text!!.toString())
timer!!.post = NumberUtils.toInt(postField!!.text!!.toString())
if (activeBox!!.isChecked) {
timer!!.unsetFlag(Timer.FLAG_DISABLED)
} else {
timer!!.setFlag(Timer.FLAG_DISABLED)
}
mOntimeredEditedListener?.timerEdited(timer)
if (dialog != null && dialog!!.isShowing) {
dismiss()
}
}
else -> {
}
}
}
private fun calcStartEnd() {
val day = GregorianCalendar.getInstance()
val start = GregorianCalendar.getInstance()
val end = GregorianCalendar.getInstance()
day.time = dateField!!.date
start.time = startField!!.date
start.set(Calendar.DAY_OF_YEAR, day.get(Calendar.DAY_OF_YEAR))
end.time = stopField!!.date
end.set(Calendar.DAY_OF_YEAR, day.get(Calendar.DAY_OF_YEAR))
if (end.before(start)) {
end.add(Calendar.DAY_OF_YEAR, 1)
}
start.set(Calendar.DAY_OF_YEAR, day.get(Calendar.DAY_OF_YEAR))
timer!!.start = start.time
timer!!.end = end.time
}
private fun bundleToTimer(bundle: Bundle) {
timer = Timer()
timer!!.id = bundle.getLong(EXTRA_ID, 0)
timer!!.title = bundle.getString(EXTRA_TITLE)
timer!!.channelName = bundle.getString(EXTRA_CHANNEL_NAME)
timer!!.channelId = bundle.getLong(EXTRA_CHANNEL_ID, 0)
timer!!.start = Date(bundle.getLong(EXTRA_START, System.currentTimeMillis()))
timer!!.end = Date(bundle.getLong(EXTRA_END, System.currentTimeMillis()))
timer!!.timerAction = bundle.getInt(EXTRA_ACTION, 0)
timer!!.pre = bundle.getInt(EXTRA_PRE, 5)
timer!!.post = bundle.getInt(EXTRA_POST, 5)
timer!!.eventId = bundle.getString(EXTRA_EVENT_ID)
timer!!.pdc = bundle.getString(EXTRA_PDC)
timer!!.adjustPAT = bundle.getInt(EXTRA_ADJUST_PAT, -1)
timer!!.allAudio = bundle.getInt(EXTRA_ALL_AUDIO, -1)
timer!!.dvbSubs = bundle.getInt(EXTRA_DVB_SUBS, -1)
timer!!.teletext = bundle.getInt(EXTRA_TELETEXT, -1)
timer!!.eitEPG = bundle.getInt(EXTRA_EIT_EPG, -1)
timer!!.monitorPDC = bundle.getInt(EXTRA_MONITOR_PDC, -1)
timer!!.runningStatusSplit = bundle.getInt(EXTRA_STATUS_SPLIT, -1)
if (!bundle.getBoolean(EXTRA_ACTIVE)) {
timer!!.setFlag(Timer.FLAG_DISABLED)
}
}
/* (non-Javadoc)
* @see android.view.View.OnLongClickListener#onLongClick(android.view.View)
*/
override fun onLongClick(v: View): Boolean {
return true
}
/**
* The listener interface for receiving onTimerEdited events.
* The class that is interested in processing a onTimerEdited
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's `addOnTimerEditedListener` method. When
* the onTimerEdited event occurs, that object's appropriate
* method is invoked.
*
* @author RayBa
`` */
interface OnTimerEditedListener {
/**
* Timer edited.
*
* @param timer the Timer which has been edited
*/
fun timerEdited(timer: Timer?)
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
val parentFragment = targetFragment
if (parentFragment is DialogInterface.OnDismissListener) {
(parentFragment as DialogInterface.OnDismissListener).onDismiss(dialog)
}
}
companion object {
val TIMER_RESULT = 0
val RESULT_CHANGED = 1
val EXTRA_ID = "_id"
val EXTRA_TITLE = "_title"
val EXTRA_CHANNEL_NAME = "_channel_name"
val EXTRA_CHANNEL_ID = "_channel_id"
val EXTRA_START = "_start"
val EXTRA_END = "_end"
val EXTRA_ACTION = "_action"
val EXTRA_ACTIVE = "_active"
val EXTRA_PRE = "_pre"
val EXTRA_POST = "_post"
val EXTRA_EVENT_ID = "_event_id"
val EXTRA_PDC = "_pdc"
val EXTRA_ADJUST_PAT = "AdjustPAT"
val EXTRA_ALL_AUDIO = "AllAudio"
val EXTRA_DVB_SUBS = "DVBSubs"
val EXTRA_TELETEXT = "Teletext"
val EXTRA_EIT_EPG = "EITEPG"
val EXTRA_MONITOR_PDC = "MonitorPDC"
val EXTRA_STATUS_SPLIT = "RunningStatusSplit"
/**
* New instance.
*
* @return the timer details©
*/
fun newInstance(): TimerDetails {
return TimerDetails()
}
fun buildBundle(timer: Timer): Bundle {
val bundle = Bundle()
timerToBundle(timer, bundle)
return bundle
}
private fun timerToBundle(timer: Timer, bundle: Bundle) {
bundle.putLong(EXTRA_ID, timer.id)
bundle.putString(EXTRA_TITLE, timer.title)
bundle.putString(EXTRA_CHANNEL_NAME, timer.channelName)
bundle.putLong(EXTRA_CHANNEL_ID, timer.channelId)
bundle.putLong(EXTRA_START, timer.start!!.time)
bundle.putLong(EXTRA_END, timer.end!!.time)
bundle.putInt(EXTRA_ACTION, timer.timerAction)
bundle.putInt(EXTRA_PRE, timer.pre)
bundle.putInt(EXTRA_POST, timer.post)
bundle.putString(EXTRA_EVENT_ID, timer.eventId)
bundle.putString(EXTRA_PDC, timer.pdc)
bundle.putString(EXTRA_PDC, timer.pdc)
bundle.putInt(EXTRA_ADJUST_PAT, timer.adjustPAT)
bundle.putInt(EXTRA_ALL_AUDIO, timer.allAudio)
bundle.putInt(EXTRA_DVB_SUBS, timer.dvbSubs)
bundle.putInt(EXTRA_TELETEXT, timer.teletext)
bundle.putInt(EXTRA_EIT_EPG, timer.eitEPG)
bundle.putInt(EXTRA_MONITOR_PDC, timer.monitorPDC)
bundle.putInt(EXTRA_STATUS_SPLIT, timer.runningStatusSplit)
bundle.putBoolean(EXTRA_ACTIVE, !timer.isFlagSet(Timer.FLAG_DISABLED))
}
}
}
| apache-2.0 | 1c072fb114fbd877688e74ffccd92c6d | 38.762148 | 125 | 0.640509 | 4.356122 | false | false | false | false |
ktorio/ktor | ktor-utils/jvm/src/io/ktor/util/AttributesJvm.kt | 1 | 2421 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util
import java.util.concurrent.*
/**
* Create JVM specific attributes instance.
*/
public actual fun Attributes(concurrent: Boolean): Attributes =
if (concurrent) ConcurrentSafeAttributes() else HashMapAttributes()
private abstract class AttributesJvmBase : Attributes {
protected abstract val map: MutableMap<AttributeKey<*>, Any?>
@Suppress("UNCHECKED_CAST")
public final override fun <T : Any> getOrNull(key: AttributeKey<T>): T? = map[key] as T?
public final override operator fun contains(key: AttributeKey<*>): Boolean = map.containsKey(key)
public final override fun <T : Any> put(key: AttributeKey<T>, value: T) {
map[key] = value
}
public final override fun <T : Any> remove(key: AttributeKey<T>) {
map.remove(key)
}
public final override val allKeys: List<AttributeKey<*>>
get() = map.keys.toList()
}
private class ConcurrentSafeAttributes : AttributesJvmBase() {
override val map: ConcurrentHashMap<AttributeKey<*>, Any?> = ConcurrentHashMap()
/**
* Gets a value of the attribute for the specified [key], or calls supplied [block] to compute its value.
* Note: [block] could be eventually evaluated twice for the same key.
* TODO: To be discussed. Workaround for android < API 24.
*/
override fun <T : Any> computeIfAbsent(key: AttributeKey<T>, block: () -> T): T {
@Suppress("UNCHECKED_CAST")
map[key]?.let { return it as T }
val result = block()
@Suppress("UNCHECKED_CAST")
return (map.putIfAbsent(key, result) ?: result) as T
}
}
private class HashMapAttributes : AttributesJvmBase() {
override val map: MutableMap<AttributeKey<*>, Any?> = HashMap()
/**
* Gets a value of the attribute for the specified [key], or calls supplied [block] to compute its value.
* Note: [block] could be eventually evaluated twice for the same key.
* TODO: To be discussed. Workaround for android < API 24.
*/
override fun <T : Any> computeIfAbsent(key: AttributeKey<T>, block: () -> T): T {
@Suppress("UNCHECKED_CAST")
map[key]?.let { return it as T }
val result = block()
@Suppress("UNCHECKED_CAST")
return (map.put(key, result) ?: result) as T
}
}
| apache-2.0 | 218104d5e434e7f27844803a10c3aed9 | 35.134328 | 119 | 0.659645 | 4.117347 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mcp/inspections/StackEmptyInspection.kt | 1 | 5830 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.inspections
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.platform.mcp.srg.SrgMemberReference
import com.demonwav.mcdev.util.MemberReference
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.fullQualifiedName
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiBinaryExpression
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiField
import com.intellij.psi.PsiReferenceExpression
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class StackEmptyInspection : BaseInspection() {
companion object {
const val STACK_FQ_NAME = "net.minecraft.item.ItemStack"
val STACK_JVM_NAME = STACK_FQ_NAME.replace('.', '/')
val EMPTY_SRG = SrgMemberReference.parse("$STACK_JVM_NAME/field_190927_a")
val IS_EMPTY_SRG = SrgMemberReference.parse("$STACK_JVM_NAME/func_190926_b")
}
@Nls
override fun getDisplayName() = "ItemStack comparison through ItemStack.EMPTY"
override fun buildErrorString(vararg infos: Any): String {
val compareExpression = infos[0] as PsiExpression
return "\"${compareExpression.text}\" compared with ItemStack.EMPTY"
}
override fun getStaticDescription() =
"Comparing an ItemStack to ItemStack.EMPTY to query stack emptiness can cause unwanted issues." +
"When a stack in an inventory is shrunk, the instance is not replaced with ItemStack.EMPTY, but" +
" the stack should still be considered empty. Instead, isEmpty() should be called."
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
return object : InspectionGadgetsFix() {
override fun getFamilyName() = "Replace with .isEmpty()"
override fun doFix(project: Project, descriptor: ProblemDescriptor) {
val compareExpression = infos[0] as PsiExpression
val binaryExpression = infos[2] as PsiBinaryExpression
val elementFactory = JavaPsiFacade.getElementFactory(project)
val mappedIsEmpty = compareExpression.findModule()?.getMappedMethod(IS_EMPTY_SRG)?.name ?: "isEmpty"
var expressionText = "${compareExpression.text}.$mappedIsEmpty()"
// If we were checking for != ItemStack.EMPTY, use !stack.isEmpty()
if (binaryExpression.operationSign.tokenType == JavaTokenType.NE) {
expressionText = "!$expressionText"
}
val replacedExpression = elementFactory.createExpressionFromText(expressionText, binaryExpression.context)
binaryExpression.replace(replacedExpression)
}
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitBinaryExpression(expression: PsiBinaryExpression) {
val operationType = expression.operationSign.tokenType
if (operationType == JavaTokenType.EQEQ || operationType == JavaTokenType.NE) {
val leftExpression = expression.lOperand
val rightExpression = expression.rOperand
// Check if both operands evaluate to an ItemStack
if (isExpressionStack(leftExpression) && isExpressionStack(rightExpression)) {
val leftEmpty = isExpressionEmptyConstant(leftExpression)
val rightEmpty = isExpressionEmptyConstant(rightExpression)
// Check that only one of the references are ItemStack.EMPTY
if (leftEmpty xor rightEmpty) {
// The other operand will be the stack
val compareExpression = if (leftEmpty) rightExpression else leftExpression
val emptyReference = if (leftEmpty) leftExpression else rightExpression
registerError(expression, compareExpression, emptyReference, expression)
}
}
}
}
private fun isExpressionStack(expression: PsiExpression?): Boolean {
return (expression?.type as? PsiClassType)?.resolve()?.fullQualifiedName == STACK_FQ_NAME
}
private fun isExpressionEmptyConstant(expression: PsiExpression?): Boolean {
val reference = expression as? PsiReferenceExpression ?: return false
val field = reference.resolve() as? PsiField ?: return false
val mappedEmpty = field.findModule()?.getMappedField(EMPTY_SRG)?.name ?: "EMPTY"
return field.name == mappedEmpty && field.containingClass?.fullQualifiedName == STACK_FQ_NAME
}
}
}
private fun Module.getMappedMethod(reference: MemberReference): MemberReference? {
val srgManager = MinecraftFacet.getInstance(this, McpModuleType)?.srgManager
return srgManager?.srgMapNow?.mapToMcpMethod(reference)
}
private fun Module.getMappedField(reference: MemberReference): MemberReference? {
val srgManager = MinecraftFacet.getInstance(this, McpModuleType)?.srgManager
return srgManager?.srgMapNow?.mapToMcpField(reference)
}
}
| mit | 392ce43b76b5036f202c252986a45b53 | 44.905512 | 122 | 0.672213 | 5.353535 | false | false | false | false |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/fragment/generator/SelectFontDialogFragment.kt | 1 | 1999 | package moe.pine.emoji.fragment.generator
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import moe.pine.emoji.activity.GeneratorActivity
import moe.pine.emoji.activity.binding.fontKey
import moe.pine.emoji.activity.binding.fontName
import moe.pine.emoji.lib.emoji.model.Font
/**
* Fragment for font selection dialog
* Created by pine on May 6, 2017.
*/
class SelectFontDialogFragment : DialogFragment() {
companion object {
val FONT_NAMES_KEY = "fontNames"
val FONT_KEYS_KEY = "fontKeys"
fun newInstance(fonts: List<Font>): SelectFontDialogFragment {
return SelectFontDialogFragment().also { fragment ->
val arguments = Bundle()
val fontNames = fonts.map(Font::name).toTypedArray()
val fontKeys = fonts.map(Font::key).toTypedArray()
arguments.putStringArray(FONT_NAMES_KEY, fontNames)
arguments.putStringArray(FONT_KEYS_KEY, fontKeys)
fragment.arguments = arguments
}
}
}
private lateinit var fontNames: Array<String>
private lateinit var fontKeys: Array<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.fontNames = this.arguments!!.getStringArray(FONT_NAMES_KEY)
this.fontKeys = this.arguments!!.getStringArray(FONT_KEYS_KEY)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(this.activity)
.setItems(this.fontNames) { dialog, which ->
dialog.dismiss()
this.updateFont(which)
}
.create()
}
private fun updateFont(position: Int) {
val activity = this.activity as GeneratorActivity
activity.fontName = this.fontNames[position]
activity.fontKey = this.fontKeys[position]
}
} | mit | 340429a76d65fe33033ea27bcfebb318 | 33.482759 | 72 | 0.65983 | 4.522624 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/user/internal/UserOrganisationUnitLinkStoreImpl.kt | 1 | 5778 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.user.internal
import android.database.Cursor
import java.lang.RuntimeException
import kotlin.Throws
import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.SQLStatementBuilderImpl
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementBinder
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementWrapper
import org.hisp.dhis.android.core.arch.db.stores.internal.LinkStoreImpl
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit
import org.hisp.dhis.android.core.user.UserOrganisationUnitLink
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkTableInfo
internal class UserOrganisationUnitLinkStoreImpl private constructor(
databaseAdapter: DatabaseAdapter,
masterColumn: String,
builder: SQLStatementBuilderImpl,
binder: StatementBinder<UserOrganisationUnitLink>
) : LinkStoreImpl<UserOrganisationUnitLink>(
databaseAdapter,
builder,
masterColumn,
binder,
{ cursor: Cursor -> UserOrganisationUnitLink.create(cursor) }
),
UserOrganisationUnitLinkStore {
@Throws(RuntimeException::class)
override fun queryRootCaptureOrganisationUnitUids(): List<String> {
return selectStringColumnsWhereClause(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
WhereClauseBuilder()
.appendKeyNumberValue(UserOrganisationUnitLinkTableInfo.Columns.ROOT, 1)
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
OrganisationUnit.Scope.SCOPE_DATA_CAPTURE
).build()
)
}
override fun queryOrganisationUnitUidsByScope(scope: OrganisationUnit.Scope): List<String> {
return selectStringColumnsWhereClause(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
WhereClauseBuilder()
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
scope.name
).build()
)
}
override fun queryAssignedOrganisationUnitUidsByScope(scope: OrganisationUnit.Scope): List<String> {
return selectStringColumnsWhereClause(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
WhereClauseBuilder()
.appendKeyNumberValue(UserOrganisationUnitLinkTableInfo.Columns.USER_ASSIGNED, 1)
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
scope.name
).build()
)
}
override fun isCaptureScope(organisationUnit: String): Boolean {
val whereClause = WhereClauseBuilder()
.appendKeyStringValue(UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT, organisationUnit)
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
OrganisationUnit.Scope.SCOPE_DATA_CAPTURE
)
.build()
return countWhere(whereClause) == 1
}
companion object {
private val BINDER =
StatementBinder<UserOrganisationUnitLink> { o: UserOrganisationUnitLink, w: StatementWrapper ->
w.bind(1, o.user())
w.bind(2, o.organisationUnit())
w.bind(3, o.organisationUnitScope())
w.bind(4, o.root())
w.bind(5, o.userAssigned())
}
@JvmStatic
fun create(databaseAdapter: DatabaseAdapter): UserOrganisationUnitLinkStore {
val statementBuilder = SQLStatementBuilderImpl(UserOrganisationUnitLinkTableInfo.TABLE_INFO)
return UserOrganisationUnitLinkStoreImpl(
databaseAdapter,
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
statementBuilder,
BINDER
)
}
}
}
| bsd-3-clause | 93d38a4faf193aefdee19f6effa401f5 | 44.857143 | 112 | 0.713223 | 5.055118 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/option/OptionService.kt | 1 | 532 | package org.hisp.dhis.android.core.option
import io.reactivex.Single
interface OptionService {
fun blockingSearchForOptions(
optionSetUid: String,
searchText: String? = null,
optionToHideUids: List<String>? = null,
optionToShowUids: List<String>? = null,
): List<Option>
fun searchForOptions(
optionSetUid: String,
searchText: String? = null,
optionToHideUids: List<String>? = null,
optionToShowUids: List<String>? = null,
): Single<List<Option>>
}
| bsd-3-clause | a6d3863c39ca563f6b2245abf8dc7ff1 | 27 | 47 | 0.654135 | 4.030303 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/ProgressIconShowcaseAction.kt | 7 | 1115 | // 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.internal.ui
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.ColorPicker
import com.intellij.ui.SpinningProgressIcon
import com.intellij.ui.components.dialog
import com.intellij.ui.dsl.builder.panel
/**
* @author Konstantin Bulenkov
*/
internal class ProgressIconShowcaseAction : DumbAwareAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
val icon = SpinningProgressIcon()
val panel = panel {
row {
icon(icon)
link("Change color") {
ColorPicker.showColorPickerPopup(null, icon.getIconColor()) { color, _ -> color?.let { icon.setIconColor(it) } }
}
}
}
val dialog = dialog(templatePresentation.text, panel)
dialog.isModal = false
dialog.setSize(600, 600)
dialog.show()
}
}
| apache-2.0 | 0ba44fd97d36ba9a24f779aea1e55057 | 29.972222 | 122 | 0.733632 | 4.239544 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/ControlFlow.kt | 1 | 3147 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* 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.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.KoresPart
import com.github.jonathanxd.kores.base.ControlFlow.Type
/**
* Control the flow of a statement.
*
* @property type Type of the flow control
* @property at Label to control flow (Note: [Type.CONTINUE] goes to Start of label and [Type.BREAK] goes to end of label).
* **Note**: [Type.CONTINUE] to a label is dangerous.
*/
data class ControlFlow(val type: Type, val at: Label?) : KoresPart, Instruction {
override fun builder(): Builder = Builder(this)
class Builder() : com.github.jonathanxd.kores.builder.Builder<ControlFlow, Builder> {
lateinit var type: Type
var at: Label? = null
constructor(defaults: ControlFlow) : this() {
this.type = defaults.type
this.at = defaults.at
}
/**
* See [ControlFlow.type]
*/
fun type(value: Type): Builder {
this.type = value
return this
}
/**
* See [ControlFlow.at]
*/
fun at(value: Label?): Builder {
this.at = value
return this
}
override fun build(): ControlFlow = ControlFlow(this.type, this.at)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: ControlFlow): Builder = Builder(defaults)
}
}
enum class Type {
/**
* Breaks to end of the flow
*/
BREAK,
/**
* Continue at start of the flow
*/
CONTINUE
}
}
| mit | 0f535b77dcabac137e98f2fbf8732fea | 31.78125 | 123 | 0.633937 | 4.482906 | false | false | false | false |
MasoodFallahpoor/InfoCenter | InfoCenter/src/main/java/com/fallahpoor/infocenter/fragments/CameraFragment.kt | 1 | 11855 | /*
Copyright (C) 2014-2016 Masood Fallahpoor
This file is part of Info Center.
Info Center 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.
Info Center 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 Info Center. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fallahpoor.infocenter.fragments
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.hardware.Camera
import android.hardware.Camera.CameraInfo
import android.os.AsyncTask
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import com.fallahpoor.infocenter.R
import com.fallahpoor.infocenter.Utils
import com.fallahpoor.infocenter.adapters.CustomArrayAdapter
import com.fallahpoor.infocenter.adapters.HeaderListItem
import com.fallahpoor.infocenter.adapters.ListItem
import com.fallahpoor.infocenter.adapters.OrdinaryListItem
import de.halfbit.pinnedsection.PinnedSectionListView
import kotlinx.android.synthetic.main.fragment_camera.*
import java.util.*
/**
* CameraFragment displays some properties of the camera(s) of the device,
* if any.
*/
// CHECK Is it possible for a device to have front camera but not rear camera?
// TODO Update the code to use the new Camera API introduced in Android Lollipop.
class CameraFragment : Fragment() {
private var utils: Utils? = null
private var getCameraParamsTask: GetCameraParamsTask? = null
private// how many cameras do we have in here?!
val listItems: ArrayList<ListItem>
get() {
val items = ArrayList<ListItem>()
when (Camera.getNumberOfCameras()) {
1 -> items.addAll(getCameraParams(CameraInfo.CAMERA_FACING_BACK))
2 -> {
items.add(HeaderListItem(getString(R.string.cam_item_back_camera)))
items.addAll(getCameraParams(CameraInfo.CAMERA_FACING_BACK))
items.add(HeaderListItem(getString(R.string.cam_item_front_camera)))
items.addAll(getCameraParams(CameraInfo.CAMERA_FACING_FRONT))
}
}
return items
}
private val itemsArray: Array<String>
get() = arrayOf(
getString(R.string.cam_item_camera_quality),
getString(R.string.cam_item_picture_size),
getString(R.string.cam_item_picture_format),
getString(R.string.cam_item_supported_video_sizes),
getString(R.string.cam_item_focal_length),
getString(R.string.cam_item_antibanding),
getString(R.string.cam_item_auto_exposure_lock),
getString(R.string.cam_item_auto_white_balance_lock),
getString(R.string.cam_item_color_effect),
getString(R.string.cam_item_flash),
getString(R.string.cam_item_scene_selection),
getString(R.string.cam_item_zoom),
getString(R.string.cam_item_video_snapshot)
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_camera, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
utils = Utils(activity!!)
(listView as PinnedSectionListView).setShadowVisible(false)
textView.setText(R.string.cam_no_camera)
if (ActivityCompat.checkSelfPermission(
activity!!,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
populateListView()
} else {
requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_CAMERA)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_CODE_CAMERA) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateListView()
} else {
listView.emptyView = textView
}
}
}
override fun onDestroy() {
super.onDestroy()
if (getCameraParamsTask != null) {
getCameraParamsTask!!.cancel(true)
getCameraParamsTask = null
}
if (progressWheel != null && progressWheel.isSpinning) {
progressWheel.stopSpinning()
}
}
private fun populateListView() {
if (Camera.getNumberOfCameras() > 0) {
getCameraParamsTask = GetCameraParamsTask()
getCameraParamsTask!!.execute()
} else {
listView.emptyView = textView
}
}
private fun getCameraInstance(cameraId: Int): Camera? {
var camera: Camera? = null
try {
camera = Camera.open(cameraId)
} catch (ignored: Exception) {
}
return camera
}
private fun getCameraParams(cameraFacing: Int): ArrayList<ListItem> {
val camParams = ArrayList<ListItem>()
val cameraParams: Camera.Parameters
val camera: Camera? = getCameraInstance(cameraFacing)
val items: Array<String>
val subItems: ArrayList<String>
if (camera != null) {
cameraParams = camera.parameters
releaseCamera(camera)
items = itemsArray
subItems = getParameters(cameraParams)
for (i in items.indices) {
camParams.add(OrdinaryListItem(items[i], subItems[i]))
}
} else { // camera is busy or for some other reason camera isn't available
if (cameraFacing == CameraInfo.CAMERA_FACING_BACK) {
camParams.add(
OrdinaryListItem(
getString(R.string.cam_sub_item_back_camera_info_unavailable), ""
)
)
} else {
camParams.add(
OrdinaryListItem(
getString(R.string.cam_sub_item_front_camera_info_unavailable), ""
)
)
}
}
return camParams
} // end method getCameraParams
private fun getParameters(cameraParams: Camera.Parameters): ArrayList<String> {
val params = ArrayList<String>()
val supported = getString(R.string.supported)
val unsupported = getString(R.string.unsupported)
params.add(getMegaPixels(cameraParams))
params.add(getPictureSize(cameraParams))
params.add(getPictureFormat(cameraParams))
params.add(getSupportedVideoSizes(cameraParams))
params.add(getFocalLength(cameraParams))
params.add(if (cameraParams.antibanding != null) supported else unsupported)
params.add(if (cameraParams.isAutoExposureLockSupported) supported else unsupported)
params.add(if (cameraParams.isAutoWhiteBalanceLockSupported) supported else unsupported)
params.add(if (cameraParams.colorEffect != null) supported else unsupported)
params.add(if (cameraParams.flashMode != null) supported else unsupported)
params.add(if (cameraParams.sceneMode != null) supported else unsupported)
params.add(if (cameraParams.isZoomSupported) supported else unsupported)
params.add(if (cameraParams.isVideoSnapshotSupported) supported else unsupported)
return params
} // end method getParameters
private fun getMegaPixels(cameraParams: Camera.Parameters): String {
val pictureSizes = cameraParams.supportedPictureSizes
var strMegaPixels = getString(R.string.unknown)
val dblMegaPixels: Double
var maxHeight = Integer.MIN_VALUE
var maxWidth = Integer.MIN_VALUE
for (pictureSize in pictureSizes) {
if (pictureSize.width > maxWidth) {
maxWidth = pictureSize.width
}
if (pictureSize.height > maxHeight) {
maxHeight = pictureSize.height
}
}
if (maxWidth != Integer.MIN_VALUE && maxHeight != Integer.MIN_VALUE) {
dblMegaPixels = (maxWidth * maxHeight).toDouble() / 1000000
strMegaPixels = String.format(
utils!!.locale, "%.1f %s",
dblMegaPixels, getString(R.string.cam_sub_item_mp)
)
}
return strMegaPixels
} // end method getMegaPixels
private fun getPictureSize(cameraParams: Camera.Parameters): String {
val width = cameraParams.pictureSize.width
val height = cameraParams.pictureSize.height
return String.format(utils!!.locale, "%d x %d", width, height)
}
private fun getPictureFormat(cameraParams: Camera.Parameters): String {
val intFormat = cameraParams.pictureFormat
val format: String
format = when (intFormat) {
ImageFormat.JPEG -> "JPEG"
ImageFormat.RGB_565 -> "RGB"
else -> getString(R.string.unknown)
}
return format
}
private fun getSupportedVideoSizes(cameraParams: Camera.Parameters): String {
var i = 0
val videoSizes = StringBuilder()
val supportedVideoSizes =
cameraParams.supportedVideoSizes ?: return getString(R.string.unknown)
while (i < supportedVideoSizes.size - 1) {
videoSizes.append(
String.format(
utils!!.locale, "%d x %d, ",
supportedVideoSizes[i].width,
supportedVideoSizes[i].height
)
)
i++
}
videoSizes.append(
String.format(
utils!!.locale, "%d x %d ",
supportedVideoSizes[i].width, supportedVideoSizes[i].height
)
)
return videoSizes.toString()
}
private fun getFocalLength(cameraParams: Camera.Parameters): String {
return try {
String.format(
utils!!.locale, "%.2f %s",
cameraParams.focalLength,
getString(R.string.cam_sub_item_mm)
)
} catch (ex: IllegalFormatException) {
getString(R.string.unknown)
}
}
private fun releaseCamera(camera: Camera?) {
camera?.release()
}
private inner class GetCameraParamsTask : AsyncTask<Void, Void, ArrayList<ListItem>>() {
override fun onPreExecute() {
super.onPreExecute()
progressWheel.visibility = View.VISIBLE
}
override fun doInBackground(vararg params: Void): ArrayList<ListItem> {
return listItems
}
override fun onPostExecute(result: ArrayList<ListItem>) {
super.onPostExecute(result)
listView.adapter = CustomArrayAdapter(activity, result)
getCameraParamsTask = null
progressWheel.visibility = View.INVISIBLE
progressWheel.stopSpinning()
}
}
companion object {
private const val REQUEST_CODE_CAMERA = 1001
}
} | gpl-3.0 | 8fcef7a5eb698a840f91b79bdb463d30 | 31.751381 | 100 | 0.626908 | 4.691334 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/column/ColumnExtra1.kt | 1 | 11579 | package jp.juggler.subwaytooter.column
import android.annotation.SuppressLint
import android.view.View
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.entity.EntityId
import jp.juggler.subwaytooter.api.entity.TimelineItem
import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.columnviewholder.ColumnViewHolder
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.util.LogCategory
import jp.juggler.util.getAdaptiveRippleDrawable
import jp.juggler.util.notZero
import jp.juggler.util.showToast
import org.jetbrains.anko.backgroundDrawable
private val log = LogCategory("ColumnExtra1")
///////////////////////////////////////////////////
// ViewHolderとの連携
fun Column.canRemoteOnly() = when (type) {
ColumnType.FEDERATE, ColumnType.FEDERATED_AROUND -> true
else -> false
}
fun Column.canReloadWhenRefreshTop(): Boolean = when (type) {
ColumnType.KEYWORD_FILTER,
ColumnType.SEARCH,
ColumnType.SEARCH_MSP,
ColumnType.SEARCH_TS,
ColumnType.SEARCH_NOTESTOCK,
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
ColumnType.LIST_LIST,
ColumnType.TREND_TAG,
ColumnType.FOLLOW_SUGGESTION,
ColumnType.PROFILE_DIRECTORY,
ColumnType.STATUS_HISTORY,
-> true
ColumnType.LIST_MEMBER,
ColumnType.MUTES,
ColumnType.FOLLOW_REQUESTS,
-> isMisskey
else -> false
}
// カラム操作的にリフレッシュを許容するかどうか
fun Column.canRefreshTopBySwipe(): Boolean =
canReloadWhenRefreshTop() ||
when (type) {
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
ColumnType.INSTANCE_INFORMATION,
-> false
else -> true
}
// カラム操作的に下端リフレッシュを許容するかどうか
fun Column.canRefreshBottomBySwipe(): Boolean = when (type) {
ColumnType.LIST_LIST,
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
ColumnType.INSTANCE_INFORMATION,
ColumnType.KEYWORD_FILTER,
ColumnType.SEARCH,
ColumnType.TREND_TAG,
ColumnType.FOLLOW_SUGGESTION,
ColumnType.STATUS_HISTORY,
-> false
ColumnType.FOLLOW_REQUESTS -> isMisskey
ColumnType.LIST_MEMBER -> !isMisskey
else -> true
}
// データ的にリフレッシュを許容するかどうか
fun Column.canRefreshTop(): Boolean = when (pagingType) {
ColumnPagingType.Default -> idRecent != null
else -> false
}
// データ的にリフレッシュを許容するかどうか
fun Column.canRefreshBottom(): Boolean = when (pagingType) {
ColumnPagingType.Default, ColumnPagingType.Cursor -> idOld != null
ColumnPagingType.None -> false
ColumnPagingType.Offset -> true
}
fun Column.getIconId(): Int = type.iconId(accessInfo.acct)
fun Column.getColumnName(long: Boolean) =
type.name2(this, long) ?: type.name1(context)
fun Column.getContentColor() = contentColor.notZero() ?: Column.defaultColorContentText
fun Column.getAcctColor() = acctColor.notZero() ?: Column.defaultColorContentAcct
fun Column.getHeaderPageNumberColor() =
headerFgColor.notZero() ?: Column.defaultColorHeaderPageNumber
fun Column.getHeaderNameColor() = headerFgColor.notZero() ?: Column.defaultColorHeaderName
fun Column.getHeaderBackgroundColor() = headerBgColor.notZero() ?: Column.defaultColorHeaderBg
fun Column.setHeaderBackground(view: View) {
view.backgroundDrawable = getAdaptiveRippleDrawable(
getHeaderBackgroundColor(),
getHeaderNameColor()
)
}
val Column.hasHashtagExtra: Boolean
get() = when {
isMisskey -> false
type == ColumnType.HASHTAG -> true
// ColumnType.HASHTAG_FROM_ACCT は追加のタグを指定しても結果に反映されない
else -> false
}
fun Column.getHeaderDesc(): String {
var cache = cacheHeaderDesc
if (cache != null) return cache
cache = when (type) {
ColumnType.SEARCH -> context.getString(R.string.search_desc_mastodon_api)
ColumnType.SEARCH_MSP -> loadSearchDesc(
R.raw.search_desc_msp_en,
R.raw.search_desc_msp_ja
)
ColumnType.SEARCH_TS -> loadSearchDesc(
R.raw.search_desc_ts_en,
R.raw.search_desc_ts_ja
)
ColumnType.SEARCH_NOTESTOCK -> loadSearchDesc(
R.raw.search_desc_notestock_en,
R.raw.search_desc_notestock_ja
)
else -> ""
}
cacheHeaderDesc = cache
return cache
}
fun Column.hasMultipleViewHolder(): Boolean = listViewHolder.size > 1
fun Column.addColumnViewHolder(cvh: ColumnViewHolder) {
// 現在のリストにあるなら削除する
removeColumnViewHolder(cvh)
// 最後に追加されたものが先頭にくるようにする
// 呼び出しの後に必ず追加されているようにする
listViewHolder.addFirst(cvh)
}
/////////////////////////////////////////////////////////////////
// ActMain の表示開始時に呼ばれる
fun Column.onActivityStart() {
// 破棄されたカラムなら何もしない
if (isDispose.get()) {
log.d("onStart: column was disposed.")
return
}
// 未初期化なら何もしない
if (!bFirstInitialized) {
log.d("onStart: column is not initialized.")
return
}
// 初期ロード中なら何もしない
if (bInitialLoading) {
log.d("onStart: column is in initial loading.")
return
}
// フィルタ一覧のリロードが必要
if (filterReloadRequired) {
filterReloadRequired = false
startLoading()
return
}
// 始端リフレッシュの最中だった
// リフレッシュ終了時に自動でストリーミング開始するはず
if (bRefreshingTop) {
log.d("onStart: bRefreshingTop is true.")
return
}
if (!bRefreshLoading &&
canAutoRefresh() &&
!PrefB.bpDontRefreshOnResume(appState.pref) &&
!dontAutoRefresh
) {
// リフレッシュしてからストリーミング開始
log.d("onStart: start auto refresh.")
startRefresh(bSilent = true, bBottom = false)
} else if (isSearchColumn) {
// 検索カラムはリフレッシュもストリーミングもないが、表示開始のタイミングでリストの再描画を行いたい
fireShowContent(reason = "Column onStart isSearchColumn", reset = true)
} else if (canStreamingState() && canStreamingType()) {
// ギャップつきでストリーミング開始
this.bPutGap = true
fireShowColumnStatus()
}
}
fun Column.cancelLastTask() {
if (lastTask != null) {
lastTask?.cancel()
lastTask = null
//
bInitialLoading = false
bRefreshLoading = false
mInitialLoadingError = context.getString(R.string.cancelled)
}
}
// @Nullable String parseMaxId( TootApiResult result ){
// if( result != null && result.link_older != null ){
// Matcher m = reMaxId.matcher( result.link_older );
// if( m.get() ) return m.group( 1 );
// }
// return null;
// }
fun Column.startLoading() {
cancelLastTask()
initFilter()
Column.showOpenSticker = PrefB.bpOpenSticker(appState.pref)
mRefreshLoadingErrorPopupState = 0
mRefreshLoadingError = ""
mInitialLoadingError = ""
bFirstInitialized = true
bInitialLoading = true
bRefreshLoading = false
idOld = null
idRecent = null
offsetNext = 0
pagingType = ColumnPagingType.Default
duplicateMap.clear()
listData.clear()
fireShowContent(reason = "loading start", reset = true)
@SuppressLint("StaticFieldLeak")
val task = ColumnTask_Loading(this)
this.lastTask = task
task.start()
}
fun Column.startRefresh(
bSilent: Boolean,
bBottom: Boolean,
postedStatusId: EntityId? = null,
refreshAfterToot: Int = -1,
) {
if (lastTask != null) {
if (!bSilent) {
context.showToast(true, R.string.column_is_busy)
val holder = viewHolder
if (holder != null) holder.refreshLayout.isRefreshing = false
}
return
} else if (bBottom && !canRefreshBottom()) {
if (!bSilent) {
context.showToast(true, R.string.end_of_list)
val holder = viewHolder
if (holder != null) holder.refreshLayout.isRefreshing = false
}
return
} else if (!bBottom && !canRefreshTop()) {
val holder = viewHolder
if (holder != null) holder.refreshLayout.isRefreshing = false
startLoading()
return
}
if (bSilent) {
val holder = viewHolder
if (holder != null) {
holder.refreshLayout.isRefreshing = true
}
}
if (!bBottom) {
bRefreshingTop = true
}
bRefreshLoading = true
mRefreshLoadingError = ""
@SuppressLint("StaticFieldLeak")
val task = ColumnTask_Refresh(this, bSilent, bBottom, postedStatusId, refreshAfterToot)
this.lastTask = task
task.start()
fireShowColumnStatus()
}
fun Column.startRefreshForPost(
refreshAfterPost: Int,
postedStatusId: EntityId,
postedReplyId: EntityId?,
) {
when (type) {
ColumnType.HOME,
ColumnType.LOCAL,
ColumnType.FEDERATE,
ColumnType.DIRECT_MESSAGES,
ColumnType.MISSKEY_HYBRID,
-> startRefresh(
bSilent = true,
bBottom = false,
postedStatusId = postedStatusId,
refreshAfterToot = refreshAfterPost
)
ColumnType.PROFILE -> {
if (profileTab == ProfileTab.Status && profileId == accessInfo.loginAccount?.id) {
startRefresh(
bSilent = true,
bBottom = false,
postedStatusId = postedStatusId,
refreshAfterToot = refreshAfterPost
)
}
}
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
-> {
// 会話への返信が行われたなら会話を更新する
try {
if (postedReplyId != null) {
for (item in listData) {
if (item is TootStatus && item.id == postedReplyId) {
startLoading()
break
}
}
}
} catch (_: Throwable) {
}
}
else -> Unit
}
}
fun Column.startGap(gap: TimelineItem?, isHead: Boolean) {
if (gap == null) {
context.showToast(true, "gap is null")
return
}
if (lastTask != null) {
context.showToast(true, R.string.column_is_busy)
return
}
@Suppress("UNNECESSARY_SAFE_CALL")
viewHolder?.refreshLayout?.isRefreshing = true
bRefreshLoading = true
mRefreshLoadingError = ""
@SuppressLint("StaticFieldLeak")
val task = ColumnTask_Gap(this, gap, isHead = isHead)
this.lastTask = task
task.start()
fireShowColumnStatus()
}
| apache-2.0 | 72098119f3342a741da8c82fa6a46ce4 | 26.127273 | 94 | 0.60615 | 4.054287 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/gradle/McpProjectResolverExtension.kt | 1 | 1787 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.gradle
import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG2Handler
import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG3Handler
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG2
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG3
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
class McpProjectResolverExtension : AbstractProjectResolverExtension() {
// Register our custom Gradle tooling API model in IntelliJ's project resolver
override fun getExtraProjectModelClasses(): Set<Class<out Any>> =
setOf(McpModelFG2::class.java, McpModelFG3::class.java)
override fun getToolingExtensionsClasses() = extraProjectModelClasses
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
var data: McpModelData? = null
for (handler in handlers) {
data = handler.build(gradleModule, ideModule.data, resolverCtx)
if (data != null) {
break
}
}
data?.let {
// Register our data in the module
ideModule.createChild(McpModelData.KEY, data)
}
// Process the other resolver extensions
super.populateModuleExtraModels(gradleModule, ideModule)
}
companion object {
private val handlers = listOf(McpModelFG2Handler, McpModelFG3Handler)
}
}
| mit | 3b86572519fd5bc42cf93572994d030a | 34.039216 | 103 | 0.733632 | 4.582051 | false | false | false | false |
vladmm/intellij-community | plugins/settings-repository/src/ReadOnlySourcesManager.kt | 9 | 2018 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.util.SmartList
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.jetbrains.annotations.TestOnly
import java.io.File
class ReadOnlySourcesManager(private val settings: IcsSettings, public val rootDir: File) {
private var _repositories: List<Repository>? = null
val repositories: List<Repository>
get() {
var r = _repositories
if (r == null) {
if (settings.readOnlySources.isEmpty()) {
r = emptyList()
}
else {
r = SmartList<Repository>()
for (source in settings.readOnlySources) {
try {
val path = source.path ?: continue
val dir = File(rootDir, path)
if (dir.exists()) {
r.add(FileRepositoryBuilder().setBare().setGitDir(dir).build())
}
else {
LOG.warn("Skip read-only source ${source.url} because dir doesn't exists")
}
}
catch (e: Exception) {
LOG.error(e)
}
}
}
_repositories = r
}
return r
}
fun setSources(sources: List<ReadonlySource>) {
settings.readOnlySources = sources
_repositories = null
}
@TestOnly fun sourceToDir(source: ReadonlySource) = File(rootDir, source.path!!)
} | apache-2.0 | 7fb07ba1574ee92584adc7432d485a17 | 31.047619 | 91 | 0.634787 | 4.406114 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/customize/transferSettings/TransferSettingsDataProvider.kt | 1 | 2258 | // 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.customize.transferSettings
import com.intellij.ide.customize.transferSettings.models.BaseIdeVersion
import com.intellij.ide.customize.transferSettings.models.FailedIdeVersion
import com.intellij.ide.customize.transferSettings.models.IdeVersion
import com.intellij.ide.customize.transferSettings.providers.TransferSettingsProvider
import com.intellij.openapi.diagnostic.logger
import java.util.*
import java.util.stream.Collectors
class TransferSettingsDataProvider(private val providers: List<TransferSettingsProvider>) {
val baseIdeVersions = mutableListOf<BaseIdeVersion>()
val ideVersions = mutableListOf<IdeVersion>()
val failedIdeVersions = mutableListOf<FailedIdeVersion>()
val orderedIdeVersions get() = ideVersions + failedIdeVersions
constructor(vararg providers: TransferSettingsProvider) : this(providers.toList())
fun refresh(): TransferSettingsDataProvider {
val newBase = TransferSettingsDataProviderSession(providers, baseIdeVersions.map { it.id }).baseIdeVersions
baseIdeVersions.addAll(newBase)
ideVersions.addAll(newBase.filterIsInstance<IdeVersion>())
ideVersions.sortByDescending { it.lastUsed }
failedIdeVersions.addAll(newBase.filterIsInstance<FailedIdeVersion>())
return this
}
}
private class TransferSettingsDataProviderSession(private val providers: List<TransferSettingsProvider>,
private val skipIds: List<String>?) {
private val logger = logger<TransferSettingsDataProviderSession>()
val baseIdeVersions: List<BaseIdeVersion> by lazy { createBaseIdeVersions() }
private fun createBaseIdeVersions() = providers
.parallelStream()
.flatMap { provider ->
if (!provider.isAvailable()) {
logger.info("Provider ${provider.name} is not available")
return@flatMap null
}
try {
provider.getIdeVersions(skipIds ?: emptyList()).stream()
}
catch (t: Throwable) {
logger.warn("Failed to get base ide versions", t)
return@flatMap null
}
}
.filter(Objects::nonNull)
.collect(Collectors.toList())
} | apache-2.0 | 121ebdab1f700150d534b9efc11cf8e1 | 37.948276 | 120 | 0.749779 | 4.855914 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ExtractedDirectoryPackagingElementEntityImpl.kt | 1 | 11040 | // 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.bridgeEntities.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.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.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.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ExtractedDirectoryPackagingElementEntityImpl(val dataSource: ExtractedDirectoryPackagingElementEntityData) : ExtractedDirectoryPackagingElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java,
PackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val filePath: VirtualFileUrl
get() = dataSource.filePath
override val pathInArchive: String
get() = dataSource.pathInArchive
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ExtractedDirectoryPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<ExtractedDirectoryPackagingElementEntity>(), ExtractedDirectoryPackagingElementEntity.Builder {
constructor() : this(ExtractedDirectoryPackagingElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ExtractedDirectoryPackagingElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isFilePathInitialized()) {
error("Field FileOrDirectoryPackagingElementEntity#filePath should be initialized")
}
if (!getEntityData().isPathInArchiveInitialized()) {
error("Field ExtractedDirectoryPackagingElementEntity#pathInArchive 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 ExtractedDirectoryPackagingElementEntity
this.entitySource = dataSource.entitySource
this.filePath = dataSource.filePath
this.pathInArchive = dataSource.pathInArchive
if (parents != null) {
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
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, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_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.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var filePath: VirtualFileUrl
get() = getEntityData().filePath
set(value) {
checkModificationAllowed()
getEntityData().filePath = value
changedProperty.add("filePath")
val _diff = diff
if (_diff != null) index(this, "filePath", value)
}
override var pathInArchive: String
get() = getEntityData().pathInArchive
set(value) {
checkModificationAllowed()
getEntityData().pathInArchive = value
changedProperty.add("pathInArchive")
}
override fun getEntityData(): ExtractedDirectoryPackagingElementEntityData = result
?: super.getEntityData() as ExtractedDirectoryPackagingElementEntityData
override fun getEntityClass(): Class<ExtractedDirectoryPackagingElementEntity> = ExtractedDirectoryPackagingElementEntity::class.java
}
}
class ExtractedDirectoryPackagingElementEntityData : WorkspaceEntityData<ExtractedDirectoryPackagingElementEntity>() {
lateinit var filePath: VirtualFileUrl
lateinit var pathInArchive: String
fun isFilePathInitialized(): Boolean = ::filePath.isInitialized
fun isPathInArchiveInitialized(): Boolean = ::pathInArchive.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ExtractedDirectoryPackagingElementEntity> {
val modifiable = ExtractedDirectoryPackagingElementEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ExtractedDirectoryPackagingElementEntity {
return getCached(snapshot) {
val entity = ExtractedDirectoryPackagingElementEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ExtractedDirectoryPackagingElementEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ExtractedDirectoryPackagingElementEntity(filePath, pathInArchive, entitySource) {
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ExtractedDirectoryPackagingElementEntityData
if (this.entitySource != other.entitySource) return false
if (this.filePath != other.filePath) return false
if (this.pathInArchive != other.pathInArchive) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ExtractedDirectoryPackagingElementEntityData
if (this.filePath != other.filePath) return false
if (this.pathInArchive != other.pathInArchive) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + filePath.hashCode()
result = 31 * result + pathInArchive.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + filePath.hashCode()
result = 31 * result + pathInArchive.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.filePath?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | ebb462b332a0299350a8ec732bf28dc7 | 39.588235 | 202 | 0.714674 | 5.844362 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringInspection.kt | 1 | 3210 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.substring
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.evaluatesTo
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.toResolvedCall
import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
abstract class ReplaceSubstringInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
protected abstract fun isApplicableInner(element: KtDotQualifiedExpression): Boolean
protected open val isAlwaysStable: Boolean = false
final override fun isApplicable(element: KtDotQualifiedExpression): Boolean =
if ((isAlwaysStable || element.receiverExpression.isStableSimpleExpression()) && element.isMethodCall("kotlin.text.substring")) {
isApplicableInner(element)
} else
false
override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis()
protected fun isIndexOfCall(expression: KtExpression?, expectedReceiver: KtExpression): Boolean {
return expression is KtDotQualifiedExpression
&& expression.isMethodCall("kotlin.text.indexOf")
&& expression.receiverExpression.evaluatesTo(expectedReceiver)
&& expression.callExpression!!.valueArguments.size == 1
}
private fun KtDotQualifiedExpression.isMethodCall(fqMethodName: String): Boolean {
val resolvedCall = toResolvedCall(BodyResolveMode.PARTIAL) ?: return false
return resolvedCall.resultingDescriptor.fqNameUnsafe.asString() == fqMethodName
}
protected fun KtDotQualifiedExpression.isFirstArgumentZero(): Boolean {
val bindingContext = analyze()
val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return false
val expression = resolvedCall.call.valueArguments[0].getArgumentExpression() as? KtConstantExpression ?: return false
val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) ?: return false
val constantType = bindingContext.getType(expression) ?: return false
return constant.getValue(constantType) == 0
}
protected fun KtDotQualifiedExpression.replaceWith(pattern: String, argument: KtExpression) {
val psiFactory = KtPsiFactory(project)
replace(psiFactory.createExpressionByPattern(pattern, receiverExpression, argument))
}
} | apache-2.0 | 3c408977e7f558776b1ebcf1c4407388 | 54.362069 | 158 | 0.787227 | 5.661376 | false | false | false | false |
square/okio | okio/src/nativeMain/kotlin/okio/PosixFileSystem.kt | 1 | 3559 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.get
import okio.Path.Companion.toPath
import okio.internal.toPath
import platform.posix.EEXIST
import platform.posix.closedir
import platform.posix.dirent
import platform.posix.errno
import platform.posix.opendir
import platform.posix.readdir
import platform.posix.set_posix_errno
internal object PosixFileSystem : FileSystem() {
private val SELF_DIRECTORY_ENTRY = ".".toPath()
private val PARENT_DIRECTORY_ENTRY = "..".toPath()
override fun canonicalize(path: Path) = variantCanonicalize(path)
override fun metadataOrNull(path: Path) = variantMetadataOrNull(path)
override fun list(dir: Path): List<Path> = list(dir, throwOnFailure = true)!!
override fun listOrNull(dir: Path): List<Path>? = list(dir, throwOnFailure = false)
private fun list(dir: Path, throwOnFailure: Boolean): List<Path>? {
val opendir = opendir(dir.toString())
?: if (throwOnFailure) throw errnoToIOException(errno) else return null
try {
val result = mutableListOf<Path>()
val buffer = Buffer()
set_posix_errno(0) // If readdir() returns null it's either the end or an error.
while (true) {
val dirent: CPointer<dirent> = readdir(opendir) ?: break
val childPath = buffer.writeNullTerminated(
bytes = dirent[0].d_name
).toPath(normalize = true)
if (childPath == SELF_DIRECTORY_ENTRY || childPath == PARENT_DIRECTORY_ENTRY) {
continue // exclude '.' and '..' from the results.
}
result += dir / childPath
}
if (errno != 0) {
if (throwOnFailure) throw errnoToIOException(errno)
else return null
}
result.sort()
return result
} finally {
closedir(opendir) // Ignore errno from closedir.
}
}
override fun openReadOnly(file: Path) = variantOpenReadOnly(file)
override fun openReadWrite(file: Path, mustCreate: Boolean, mustExist: Boolean): FileHandle {
return variantOpenReadWrite(file, mustCreate = mustCreate, mustExist = mustExist)
}
override fun source(file: Path) = variantSource(file)
override fun sink(file: Path, mustCreate: Boolean) = variantSink(file, mustCreate)
override fun appendingSink(file: Path, mustExist: Boolean) = variantAppendingSink(file, mustExist)
override fun createDirectory(dir: Path, mustCreate: Boolean) {
val result = variantMkdir(dir)
if (result != 0) {
if (errno == EEXIST) {
if (mustCreate) errnoToIOException(errno)
else return
}
throw errnoToIOException(errno)
}
}
override fun atomicMove(
source: Path,
target: Path
) {
variantMove(source, target)
}
override fun delete(path: Path, mustExist: Boolean) {
variantDelete(path, mustExist)
}
override fun createSymlink(source: Path, target: Path) = variantCreateSymlink(source, target)
override fun toString() = "PosixSystemFileSystem"
}
| apache-2.0 | e28ea1b59082557c5070fd98d5a06f06 | 30.495575 | 100 | 0.697668 | 4.030578 | false | false | false | false |
RanolP/Kubo | Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/client/objects/TelegramClientUser.kt | 1 | 1686 | package io.github.ranolp.kubo.telegram.client.objects
import com.github.badoualy.telegram.tl.api.TLUser
import io.github.ranolp.kubo.general.side.Side
import io.github.ranolp.kubo.telegram.Telegram
import io.github.ranolp.kubo.telegram.general.objects.TelegramUser
class TelegramClientUser(val user: TLUser) : TelegramUser {
override val side: Side = Telegram.CLIENT_SIDE
override val firstName: String
get() = user.firstName
override val lastName: String?
get() = user.lastName
override val username: String?
get() = user.username
override val isSelf: Boolean
get() = user.self
override val languageCode: String
get() = user.langCode
override val isBot: Boolean
get() = user.bot
override val id: Int
get() = user.id
val contact: Boolean
get() = user.contact
val mutualContact: Boolean
get() = user.mutualContact
val deleted: Boolean
get() = user.deleted
val botChatHistory: Boolean
get() = user.botChatHistory
val botNochats: Boolean
get() = user.botNochats
val verified: Boolean
get() = user.verified
val restricted: Boolean
get() = user.restricted
val min: Boolean
get() = user.min
val botInlineGeo: Boolean
get() = user.botInlineGeo
val accessHash: Long
get() = user.accessHash
val phone: String
get() = user.phone
// photo
// status
val botInfoVersion: Int
get() = user.botInfoVersion
val restrictionReason: String
get() = user.restrictionReason
val botInlinePlaceholder: String
get() = user.botInlinePlaceholder
} | mit | 240c431368ecc5419dd4440567bcc9dc | 29.672727 | 66 | 0.657177 | 4.19403 | false | false | false | false |