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
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/DialogBuilder.kt
1
14542
package com.pr0gramm.app.ui import android.app.Dialog import android.content.Context import android.content.SharedPreferences import android.text.SpannableString import android.text.util.Linkify import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.annotation.StyleRes import androidx.appcompat.app.AlertDialog import androidx.appcompat.view.ContextThemeWrapper import androidx.appcompat.widget.AppCompatCheckBox import androidx.core.content.edit import androidx.core.view.isVisible import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.pr0gramm.app.Logger import com.pr0gramm.app.R import com.pr0gramm.app.util.* import java.util.concurrent.atomic.AtomicBoolean typealias DialogClickListener = (Dialog) -> Unit typealias DialogOnShowListener = (Dialog) -> Unit typealias DialogOnCancelListener = (Dialog) -> Unit /** * Helper to build dialogs. */ class DialogBuilder(private val context: Context, private val bottomSheet: Boolean = false) { private val dialogButtons = intArrayOf(Dialog.BUTTON_NEGATIVE, Dialog.BUTTON_POSITIVE, Dialog.BUTTON_NEUTRAL) private val preferences: SharedPreferences by lazy { context.applicationContext.getSharedPreferences( "dialog-builder-v" + AndroidUtility.buildVersionCode(), Context.MODE_PRIVATE) } private val logger = Logger("DialogBuilder") private var buttonPositiveText: String? = null private var buttonPositiveClick: DialogClickListener? = null private var buttonNegativeText: String? = null private var buttonNegativeClick: DialogClickListener? = null private var buttonNeutralText: String? = null private var buttonNeutralClick: DialogClickListener? = null private var onShowListener: DialogOnShowListener? = null private var onCancelListener: DialogOnCancelListener? = null private var dismissOnClick = true private var dontShowAgainKey: String? = null private var cancelable = false private var title: CharSequence? = null private var contentText: CharSequence? = null private var contentViewId: Int? = null private var contentView: View? = null private var onNotShown: () -> Unit = {} fun content(@StringRes content: Int, vararg args: Any) { return content(getString(content, args)) } fun content(content: CharSequence) { contentText = content contentView = null contentViewId = null } fun contentWithLinks(content: String) { val s = SpannableString(content) Linkify.addLinks(s, Linkify.WEB_URLS) return content(s) } fun title(title: String) { this.title = title } fun title(@StringRes title: Int, vararg args: Any) { return title(getString(title, args)) } fun dontShowAgainKey(key: String) { dontShowAgainKey = key } fun onNotShown(fn: () -> Unit) { onNotShown = fn } fun layout(@LayoutRes view: Int) { contentViewId = view contentView = null contentText = null } fun contentView(view: View) { contentViewId = null contentView = view contentText = null } fun noAutoDismiss() { this.dismissOnClick = false } fun positive(@StringRes text: Int, onClick: DialogClickListener? = null) { return positive(getString(text), onClick) } fun positive(text: String = getString(R.string.okay), onClick: DialogClickListener? = null) { buttonPositiveText = text buttonPositiveClick = onClick } fun negative(@StringRes text: Int = R.string.cancel, onClick: DialogClickListener? = null) { return negative(getString(text), onClick) } fun negative(text: String, onClick: DialogClickListener? = null) { buttonNegativeText = text buttonNegativeClick = onClick } fun neutral(@StringRes text: Int, onClick: DialogClickListener? = null) { return neutral(getString(text), onClick) } fun neutral(text: String = getString(R.string.okay), onClick: DialogClickListener? = null) { buttonNeutralText = text buttonNeutralClick = onClick } fun cancelable() { cancelable = true } fun onShow(onShowListener: DialogOnShowListener) { this.onShowListener = onShowListener } fun onCancel(onCancelListener: DialogOnCancelListener) { this.onCancelListener = onCancelListener } private fun getString(@StringRes content: Int): String { return context.getString(content) } private fun getString(@StringRes content: Int, args: Array<out Any>): String { return context.getString(content, *args) } fun show(): Dialog { val dialog = build() if (shouldNotShowDialog()) { onNotShown() } else { dialog.show() } return dialog } fun build(): Dialog { if (shouldNotShowDialog()) { logger.info { "Not showing dialog '$dontShowAgainKey'." } // return a dialog that closes itself whens shown. val dialog = Dialog(context) dialog.setOnShowListener { it.dismiss() onNotShown() } return dialog } val dialog: Dialog = if (bottomSheet) { BottomSheetAlertDialog(context).let { b -> b.setCancelable(cancelable) buttonPositiveText?.let { b.setPositiveButton(it) } buttonNegativeText?.let { b.setNegativeButton(it) } buttonNeutralText?.let { b.setNeutralButton(it) } title?.let { b.setTitle(it) } when { contentText != null -> b.setTextContent(contentText!!) contentView != null -> b.setCustomContent(contentView!!) contentViewId != null -> b.setCustomContent(contentViewId!!) } // only one of those two is non zero. contentText?.let { b.setTextContent(it) } contentViewId?.let { b.setCustomContent(it) } b } } else { AlertDialog.Builder(context).let { b -> b.setCancelable(cancelable) buttonPositiveText?.let { b.setPositiveButton(it, null) } buttonNegativeText?.let { b.setNegativeButton(it, null) } buttonNeutralText?.let { b.setNeutralButton(it, null) } title?.let { b.setTitle(it) } when { contentText != null -> b.setMessage(contentText) contentView != null -> b.setView(contentView) contentViewId != null -> b.setView(contentViewId!!) } b.create() } } dialog.setOnShowListener { val messageView: View? = dialog.findViewById(android.R.id.message) if (messageView is TextView) { messageView.movementMethod = NonCrashingLinkMovementMethod } val dontShowAgainClicked = setupDontShowAgainView(messageView) // we handle the clicks to the buttons. for (button in dialogButtons) { val buttonView = when (dialog) { is AlertDialog -> dialog.getButton(button) is BottomSheetAlertDialog -> dialog.getButton(button) else -> null } buttonView?.setOnClickListener { onButtonClicked(button, dialog, dontShowAgainClicked.get()) } } if (dialog is BottomSheetDialog) { val bottomSheet = dialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) if (bottomSheet is FrameLayout) { catchAll { BottomSheetBehavior .from(bottomSheet) .setState(BottomSheetBehavior.STATE_EXPANDED) } } } if (cancelable) { onCancelListener?.let { cl -> dialog.setOnCancelListener { cl(dialog) } } } onShowListener?.invoke(dialog) } return dialog } private fun setupDontShowAgainView(messageView: View?): AtomicBoolean { val dontShowAgainClicked = AtomicBoolean() if (messageView != null && dontShowAgainKey != null) { val parent = messageView.parent if (parent is LinearLayout) { val checkbox = AppCompatCheckBox(messageView.context) checkbox.setText(R.string.dialog_dont_show_again) val params = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) params.leftMargin = messageView.paddingLeft params.rightMargin = messageView.paddingRight params.topMargin = params.leftMargin / 2 checkbox.layoutParams = params // remember changes here. checkbox.setOnCheckedChangeListener { _, checked -> dontShowAgainClicked.set(checked) } parent.addView(checkbox) } } return dontShowAgainClicked } private fun shouldNotShowDialog(): Boolean { return dontShowAgainKey != null && this.preferences.getBoolean(dontShowAgainKey, false) } private fun onButtonClicked(button: Int, dialog: Dialog, dontShowAgain: Boolean) { when (button) { Dialog.BUTTON_POSITIVE -> buttonPositiveClick?.invoke(dialog) Dialog.BUTTON_NEGATIVE -> buttonNegativeClick?.invoke(dialog) Dialog.BUTTON_NEUTRAL -> buttonNeutralClick?.invoke(dialog) } if (dismissOnClick) { dialog.dismiss() } dontShowAgainKey.takeIf { dontShowAgain }?.let { key -> logger.info { "Never show dialog '$key' again" } preferences.edit { putBoolean(key, true) } } } } fun resolveDialogTheme(context: Context, @StyleRes resid: Int): Int { // Check to see if this resourceId has a valid package ID. return if (resid.ushr(24) and 0x000000ff >= 0x00000001) { // start of real resource IDs. resid } else { val outValue = TypedValue() context.theme.resolveAttribute(androidx.appcompat.R.attr.alertDialogTheme, outValue, true) outValue.resourceId } } private class BottomSheetAlertDialog(ctx: Context, theme: Int = R.style.MyBottomSheetDialog) : BottomSheetDialog(ContextThemeWrapper(ctx, resolveDialogTheme(ctx, theme)), resolveDialogTheme(ctx, theme)) { private val view: ViewGroup = (ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater) .inflate(R.layout.bottom_sheet_alert_dialog) .also { setContentView(it) } as ViewGroup val buttonPositive: Button = view.find(android.R.id.button1) val buttonNegative: Button = view.find(android.R.id.button2) val buttonNeutral: Button = view.find(android.R.id.button3) private val titleSpacerNoTitle: View = view.find(R.id.titleSpacerNoTitle) private val textContent: TextView = view.find(R.id.textContent) private val customContent: ViewGroup = view.find(R.id.custom) private val title: TextView = view.find(R.id.title) fun setCustomContent(@LayoutRes content: Int) { customContent.removeAllViews() customContent.layoutInflater.inflate(content, customContent, true) } fun setCustomContent(@LayoutRes view: View) { customContent.removeAllViews() customContent.addView(view) } fun setTextContent(text: CharSequence) { textContent.text = text } override fun setTitle(text: CharSequence?) { super.setTitle(text) title.text = text title.isVisible = true titleSpacerNoTitle.isVisible = false } fun setPositiveButton(text: String) { buttonPositive.isVisible = true buttonPositive.text = text } fun setNegativeButton(text: String) { buttonNegative.isVisible = true buttonNegative.text = text } fun setNeutralButton(text: String) { buttonNeutral.isVisible = true buttonNeutral.text = text } fun getButton(idx: Int): Button? { return when (idx) { AlertDialog.BUTTON_POSITIVE -> buttonPositive AlertDialog.BUTTON_NEGATIVE -> buttonNegative AlertDialog.BUTTON_NEUTRAL -> buttonNeutral else -> null } } } inline fun dialog(fragment: androidx.fragment.app.Fragment, configure: DialogBuilder.() -> Unit): Dialog { return dialog(fragment.requireContext(), configure) } inline fun dialog(context: Context, configure: DialogBuilder.() -> Unit): Dialog { return DialogBuilder(context).apply(configure).build() } inline fun bottomSheet(fragment: androidx.fragment.app.Fragment, configure: DialogBuilder.() -> Unit): Dialog { return bottomSheet(fragment.requireContext(), configure) } inline fun bottomSheet(context: Context, configure: DialogBuilder.() -> Unit): Dialog { return DialogBuilder(context, bottomSheet = true).apply(configure).build() } inline fun showDialog(fragment: androidx.fragment.app.Fragment, configure: DialogBuilder.() -> Unit): Dialog { return showDialog(fragment.requireContext(), configure) } inline fun showDialog(context: Context, configure: DialogBuilder.() -> Unit): Dialog { return DialogBuilder(context).apply(configure).show() } inline fun showBottomSheet(fragment: androidx.fragment.app.Fragment, configure: DialogBuilder.() -> Unit): Dialog { return showBottomSheet(fragment.requireContext(), configure) } inline fun showBottomSheet(context: Context, configure: DialogBuilder.() -> Unit): Dialog { return DialogBuilder(context, bottomSheet = true).apply(configure).show() }
mit
a7b72573c3e8583e6029744dbfbe4e6e
31.975057
117
0.636295
4.881504
false
false
false
false
noseblowhorn/krog
src/main/kotlin/eu/fizzystuff/krog/model/dungeongenerators/RandomWalkCaveGenerator.kt
1
2116
package eu.fizzystuff.krog.model.dungeongenerators import com.google.inject.Inject import eu.fizzystuff.krog.model.DungeonLevel import eu.fizzystuff.krog.model.DungeonTransitionPoint import eu.fizzystuff.krog.model.Tile import eu.fizzystuff.krog.model.dungeongenerators.objects.DefaultObjectGenerator import org.apache.commons.math3.random.RandomGenerator class RandomWalkCaveGenerator @Inject constructor(random: RandomGenerator) : DungeonLevelGenerator { val random = random override fun generate(width: Int, height: Int): DungeonLevel { val level = DungeonLevel(width, height) level.fillWithTile(Tile.wallTile) // Unbounded worst case performance is certainly fun, but we want to be sure this terminates. // Wait, why am I writing the bogosort of dungeon generation again? val maximumWalkSteps = width * height // Initial position. var x = random.nextInt(width - 2) + 1 var y = random.nextInt(height - 2) + 1 level.transitionPoints.add(DungeonTransitionPoint(x, y, null)) for (i in 1..maximumWalkSteps) { level.setTileAt(x, y, Tile.floorTile) x += getNextStepX(x, width) y += getNextStepY(y, height) } DefaultObjectGenerator(random).generate(level) return level } private fun getNextStepX(x: Int, width: Int): Int { var dx = random.nextDouble() * 2.0 - 1.0 // we want this to be biased so edges of the map "repel" the walk if (x < 5) { dx += 0.2 * (5.0 - x) } else if (x > width - 5) { dx -= 0.2 * (width - x) } return if (dx <= -0.33) -1 else if (dx >= 0.33) 1 else 0 } private fun getNextStepY(y: Int, height: Int): Int { var dy = random.nextDouble() * 2.0 - 1.0 // we want this to be biased so edges of the map "repel" the walk if (y < 3) { dy += 0.34 * (3.0 - y) } else if (y > height - 3) { dy -= 0.34 * (height - y) } return if (dy <= -0.33) -1 else if (dy >= 0.33) 1 else 0 } }
apache-2.0
63d65a30a4c789ea8a670b3535e4f17a
31.569231
101
0.609641
3.598639
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/repo/internals/migrations/Migration49.kt
1
1704
package voice.data.repo.internals.migrations import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.squareup.anvil.annotations.ContributesMultibinding import voice.common.AppScope import voice.data.repo.internals.getInt import voice.data.repo.internals.getString import voice.data.repo.internals.moveToNextLoop import java.time.Instant import java.util.UUID import javax.inject.Inject @ContributesMultibinding( scope = AppScope::class, boundType = Migration::class, ) class Migration49 @Inject constructor() : IncrementalMigration(49) { override fun migrate(db: SupportSQLiteDatabase) { with(db) { execSQL("ALTER TABLE bookmark RENAME TO bookmark_old") execSQL( """CREATE TABLE `bookmark` |(`file` TEXT NOT NULL, |`title` TEXT, |`time` INTEGER NOT NULL, |`addedAt` TEXT NOT NULL, |`setBySleepTimer` INTEGER NOT NULL, |`id` TEXT NOT NULL, PRIMARY KEY(`id`)) """.trimMargin(), ) query("SELECT * FROM bookmark_old").moveToNextLoop { val file = getString("file") val time = getInt("time") val title = getString("title") insert( "bookmark", SQLiteDatabase.CONFLICT_FAIL, ContentValues().apply { put("file", file) put("title", title) put("time", time) put("addedAt", Instant.EPOCH.toString()) put("setBySleepTimer", false) put("id", UUID.randomUUID().toString()) }, ) } execSQL("DROP TABLE bookmark_old") } } }
gpl-3.0
f9aba8449342651a1b16585842d5469c
29.428571
61
0.649648
4.369231
false
false
false
false
FHannes/intellij-community
plugins/git4idea/src/git4idea/GitApplyChangesProcess.kt
2
21507
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.DvcsUtil.getShortRepositoryName import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil.pluralize import com.intellij.openapi.vcs.AbstractVcsHelper import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.merge.MergeDialogCustomizer import com.intellij.openapi.vcs.update.RefreshVFsSynchronously import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsFullCommitDetails import com.intellij.vcs.log.util.VcsUserUtil import git4idea.commands.* import git4idea.commands.GitSimpleEventDetector.Event.CHERRY_PICK_CONFLICT import git4idea.commands.GitSimpleEventDetector.Event.LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK import git4idea.merge.GitConflictResolver import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.util.GitUntrackedFilesHelper import java.util.concurrent.CountDownLatch import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import javax.swing.event.HyperlinkEvent /** * Applies the given Git operation (e.g. cherry-pick or revert) to the current working tree, * waits for the [ChangeListManager] update, shows the commit dialog and removes the changelist after commit, * if the commit was successful. */ class GitApplyChangesProcess(private val project: Project, private val commits: List<VcsFullCommitDetails>, private val autoCommit: Boolean, private val operationName: String, private val appliedWord: String, private val command: (GitRepository, Hash, Boolean, List<GitLineHandlerListener>) -> GitCommandResult, private val emptyCommitDetector: (GitCommandResult) -> Boolean, private val defaultCommitMessageGenerator: (VcsFullCommitDetails) -> String, private val findLocalChanges: (Collection<Change>) -> Collection<Change>, private val cleanupBeforeCommit: (GitRepository) -> Unit = {}) { private val LOG = logger<GitApplyChangesProcess>() private val git = Git.getInstance() private val repositoryManager = GitRepositoryManager.getInstance(project) private val vcsNotifier = VcsNotifier.getInstance(project) private val changeListManager = ChangeListManager.getInstance(project) private val vcsHelper = AbstractVcsHelper.getInstance(project) fun execute() { val commitsInRoots = DvcsUtil.groupCommitsByRoots<GitRepository>(repositoryManager, commits) LOG.info("${operationName}ing commits: " + toString(commitsInRoots)) val successfulCommits = mutableListOf<VcsFullCommitDetails>() val skippedCommits = mutableListOf<VcsFullCommitDetails>() val token = DvcsUtil.workingTreeChangeStarted(project) try { for ((repository, value) in commitsInRoots) { val result = executeForRepo(repository, value, successfulCommits, skippedCommits) repository.update() if (!result) { return } } notifyResult(successfulCommits, skippedCommits) } finally { token.finish() } } // return true to continue with other roots, false to break execution private fun executeForRepo(repository: GitRepository, commits: List<VcsFullCommitDetails>, successfulCommits: MutableList<VcsFullCommitDetails>, alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean { for (commit in commits) { val conflictDetector = GitSimpleEventDetector(CHERRY_PICK_CONFLICT) val localChangesOverwrittenDetector = GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK) val untrackedFilesDetector = GitUntrackedFilesOverwrittenByOperationDetector(repository.root) val result = command(repository, commit.id, autoCommit, listOf(conflictDetector, localChangesOverwrittenDetector, untrackedFilesDetector)) if (result.success()) { if (autoCommit) { successfulCommits.add(commit) } else { val committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commit, successfulCommits, alreadyPicked) if (!committed) { notifyCommitCancelled(commit, successfulCommits) return false } } } else if (conflictDetector.hasHappened()) { val mergeCompleted = ConflictResolver(project, git, repository.root, commit.id.asString(), VcsUserUtil.getShortPresentation(commit.author), commit.subject, operationName).merge() if (mergeCompleted) { val committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commit, successfulCommits, alreadyPicked) if (!committed) { notifyCommitCancelled(commit, successfulCommits) return false } } else { updateChangeListManager(commit) notifyConflictWarning(repository, commit, successfulCommits) return false } } else if (untrackedFilesDetector.wasMessageDetected()) { var description = commitDetails(commit) + "<br/>Some untracked working tree files would be overwritten by $operationName.<br/>" + "Please move, remove or add them before you can $operationName. <a href='view'>View them</a>" description += getSuccessfulCommitDetailsIfAny(successfulCommits) GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, repository.root, untrackedFilesDetector.relativeFilePaths, operationName, description) return false } else if (localChangesOverwrittenDetector.hasHappened()) { notifyError("Your local changes would be overwritten by $operationName.<br/>Commit your changes or stash them to proceed.", commit, successfulCommits) return false } else if (emptyCommitDetector(result)) { alreadyPicked.add(commit) } else { notifyError(result.errorOutputAsHtmlString, commit, successfulCommits) return false } } return true } private fun updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository: GitRepository, commit: VcsFullCommitDetails, successfulCommits: MutableList<VcsFullCommitDetails>, alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean { val data = updateChangeListManager(commit) if (data == null) { alreadyPicked.add(commit) return true } val committed = showCommitDialogAndWaitForCommit(repository, commit, data.changeList, data.commitMessage) if (committed) { changeListManager.removeChangeList(data.changeList) successfulCommits.add(commit) return true } return false } private fun updateChangeListManager(commit: VcsFullCommitDetails): ChangeListData? { val changes = commit.changes RefreshVFsSynchronously.updateChanges(changes) val commitMessage = defaultCommitMessageGenerator(commit) val paths = ChangesUtil.getPaths(changes) val changeList = createChangeListAfterUpdate(commit, paths, commitMessage) return if (changeList == null) null else ChangeListData(changeList, commitMessage) } private fun createChangeListAfterUpdate(commit: VcsFullCommitDetails, paths: Collection<FilePath>, commitMessage: String): LocalChangeList? { val waiter = CountDownLatch(1) val changeList = Ref.create<LocalChangeList>() changeListManager.invokeAfterUpdate({ changeList.set(createChangeListIfThereAreChanges(commit, commitMessage)) waiter.countDown() }, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, operationName.capitalize(), { vcsDirtyScopeManager -> vcsDirtyScopeManager.filePathsDirty(paths, null) }, ModalityState.NON_MODAL) try { val success = waiter.await(100, TimeUnit.SECONDS) if (!success) { LOG.error("Couldn't await for changelist manager refresh") } } catch (e: InterruptedException) { LOG.error(e) return null } return changeList.get() } private fun showCommitDialogAndWaitForCommit(repository: GitRepository, commit: VcsFullCommitDetails, changeList: LocalChangeList, commitMessage: String): Boolean { val commitSucceeded = AtomicBoolean() val sem = Semaphore(0) ApplicationManager.getApplication().invokeAndWait({ try { cleanupBeforeCommit(repository) val changes = commit.changes val commitNotCancelled = vcsHelper.commitChanges( changes, changeList, commitMessage, object : CommitResultHandler { override fun onSuccess(commitMessage1: String) { commitSucceeded.set(true) sem.release() } override fun onFailure() { commitSucceeded.set(false) sem.release() } }) if (!commitNotCancelled) { commitSucceeded.set(false) sem.release() } } catch (t: Throwable) { LOG.error(t) commitSucceeded.set(false) sem.release() } }, ModalityState.NON_MODAL) // need additional waiting, because commitChanges is asynchronous try { sem.acquire() } catch (e: InterruptedException) { LOG.error(e) return false } return commitSucceeded.get() } private fun createChangeListIfThereAreChanges(commit: VcsFullCommitDetails, commitMessage: String): LocalChangeList? { val originalChanges = commit.changes if (originalChanges.isEmpty()) { LOG.info("Empty commit " + commit.id) return null } if (noChangesAfterApply(originalChanges)) { LOG.info("No changes after executing for commit ${commit.id}") return null } val adjustedMessage = commitMessage.replace('\n', ' ').replace("[ ]{2,}".toRegex(), " ") val changeListName = createNameForChangeList(adjustedMessage, 0) val createdChangeList = (changeListManager as ChangeListManagerEx).addChangeList(changeListName, commitMessage, commit) val actualChangeList = moveChanges(originalChanges, createdChangeList) if (actualChangeList != null && !actualChangeList.changes.isEmpty()) { return createdChangeList } LOG.warn("No changes were moved to the changelist. Changes from commit: " + originalChanges + "\nAll changes: " + changeListManager.getAllChanges()) changeListManager.removeChangeList(createdChangeList) return null } private fun noChangesAfterApply(originalChanges: Collection<Change>): Boolean { return findLocalChanges(originalChanges).isEmpty() } private fun moveChanges(originalChanges: Collection<Change>, targetChangeList: LocalChangeList): LocalChangeList? { val localChanges = findLocalChanges(originalChanges) // 1. We have to listen to CLM changes, because moveChangesTo is asynchronous // 2. We have to collect the real target change list, because the original target list (passed to moveChangesTo) is not updated in time. val moveChangesWaiter = CountDownLatch(1) val resultingChangeList = AtomicReference<LocalChangeList>() val listener = object : ChangeListAdapter() { override fun changesMoved(changes: Collection<Change>, fromList: ChangeList, toList: ChangeList) { if (toList is LocalChangeList && targetChangeList.id == toList.id) { resultingChangeList.set(toList) moveChangesWaiter.countDown() } } } try { changeListManager.addChangeListListener(listener) changeListManager.moveChangesTo(targetChangeList, *ArrayUtil.toObjectArray(localChanges, Change::class.java)) val success = moveChangesWaiter.await(100, TimeUnit.SECONDS) if (!success) { LOG.error("Couldn't await for changes move.") } return resultingChangeList.get() } catch (e: InterruptedException) { LOG.error(e) return null } finally { changeListManager.removeChangeListListener(listener) } } private fun createNameForChangeList(proposedName: String, step: Int): String { return if (changeListManager.changeLists.any { it.name == nameWithStep(proposedName, step) }) createNameForChangeList(proposedName, step + 1) else nameWithStep(proposedName, step) } private fun nameWithStep(name: String, step: Int) = if (step == 0) name else name + "-" + step private fun notifyResult(successfulCommits: List<VcsFullCommitDetails>, skipped: List<VcsFullCommitDetails>) { if (skipped.isEmpty()) { vcsNotifier.notifySuccess("${operationName.capitalize()} successful", getCommitsDetails(successfulCommits)) } else if (!successfulCommits.isEmpty()) { val title = String.format("${operationName.capitalize()}ed %d commits from %d", successfulCommits.size, successfulCommits.size + skipped.size) val description = getCommitsDetails(successfulCommits) + "<hr/>" + formSkippedDescription(skipped, true) vcsNotifier.notifySuccess(title, description) } else { vcsNotifier.notifyImportantWarning("Nothing to $operationName", formSkippedDescription(skipped, false)) } } private fun notifyConflictWarning(repository: GitRepository, commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { val resolveLinkListener = ResolveLinkListener(repository.root, commit.id.toShortString(), VcsUserUtil.getShortPresentation(commit.author), commit.subject) var description = commitDetails(commit) + "<br/>Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/>" description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyImportantWarning("${operationName.capitalize()}ed with conflicts", description, resolveLinkListener) } private fun notifyCommitCancelled(commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { if (successfulCommits.isEmpty()) { // don't notify about cancelled commit. Notify just in the case when there were already successful commits in the queue. return } var description = commitDetails(commit) description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyMinorWarning("${operationName.capitalize()} cancelled", description, null) } private fun notifyError(content: String, failedCommit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { var description = commitDetails(failedCommit) + "<br/>" + content description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyError("${operationName.capitalize()} Failed", description) } private fun getSuccessfulCommitDetailsIfAny(successfulCommits: List<VcsFullCommitDetails>): String { var description = "" if (!successfulCommits.isEmpty()) { description += "<hr/>However ${operationName} succeeded for the following " + pluralize("commit", successfulCommits.size) + ":<br/>" description += getCommitsDetails(successfulCommits) } return description } private fun formSkippedDescription(skipped: List<VcsFullCommitDetails>, but: Boolean): String { val hashes = StringUtil.join(skipped, { commit -> commit.id.toShortString() }, ", ") if (but) { val was = if (skipped.size == 1) "was" else "were" val it = if (skipped.size == 1) "it" else "them" return String.format("%s %s skipped, because all changes have already been ${appliedWord}.", hashes, was, it) } return String.format("All changes from %s have already been ${appliedWord}", hashes) } private fun getCommitsDetails(successfulCommits: List<VcsFullCommitDetails>): String { var description = "" for (commit in successfulCommits) { description += commitDetails(commit) + "<br/>" } return description.substring(0, description.length - "<br/>".length) } private fun commitDetails(commit: VcsFullCommitDetails): String { return commit.id.toShortString() + " " + commit.subject } private fun toString(commitsInRoots: Map<GitRepository, List<VcsFullCommitDetails>>): String { return commitsInRoots.entries.joinToString("; ") { entry -> val commits = entry.value.joinToString { it.id.asString() } getShortRepositoryName(entry.key) + ": [" + commits + "]" } } private inner class ResolveLinkListener(private val root: VirtualFile, private val hash: String, private val author: String, private val message: String) : NotificationListener { override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) { if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) { if (event.description == "resolve") { GitApplyChangesProcess.ConflictResolver(project, git, root, hash, author, message, operationName).mergeNoProceed() } } } } private data class ChangeListData(val changeList: LocalChangeList, val commitMessage: String) class ConflictResolver(project: Project, git: Git, root: VirtualFile, commitHash: String, commitAuthor: String, commitMessage: String, operationName: String ) : GitConflictResolver(project, git, setOf(root), makeParams(commitHash, commitAuthor, commitMessage, operationName)) { override fun notifyUnresolvedRemain() {/* we show a [possibly] compound notification after applying all commits.*/ } } } private fun makeParams(commitHash: String, commitAuthor: String, commitMessage: String, operationName: String): GitConflictResolver.Params { val params = GitConflictResolver.Params() params.setErrorNotificationTitle("${operationName.capitalize()}ed with conflicts") params.setMergeDialogCustomizer(MergeDialogCustomizer(commitHash, commitAuthor, commitMessage, operationName)) return params } private class MergeDialogCustomizer(private val commitHash: String, private val commitAuthor: String, private val commitMessage: String, private val operationName: String) : MergeDialogCustomizer() { override fun getMultipleFileMergeDescription(files: Collection<VirtualFile>) = "<html>Conflicts during ${operationName}ing commit <code>$commitHash</code> " + "made by $commitAuthor<br/><code>\"$commitMessage\"</code></html>" override fun getLeftPanelTitle(file: VirtualFile) = "Local changes" override fun getRightPanelTitle(file: VirtualFile, revisionNumber: VcsRevisionNumber?) = "<html>Changes from $operationName <code>$commitHash</code>" }
apache-2.0
f2ad4ddbb49a5a5bf12b0772bc16f84e
44.857143
142
0.670061
5.289474
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/utils/ImageUtils.kt
1
10675
package com.quickblox.sample.chat.kotlin.utils import android.annotation.SuppressLint import android.content.ContentUris import android.content.Context import android.content.CursorLoader import android.content.Intent import android.database.Cursor import android.net.Uri import android.os.Build import android.os.Environment import android.provider.DocumentsContract import android.provider.MediaStore import android.provider.OpenableColumns import android.text.TextUtils import android.util.Log import androidx.core.content.FileProvider import androidx.fragment.app.Fragment import com.quickblox.sample.chat.kotlin.App import com.quickblox.sample.chat.kotlin.R import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* private const val CAMERA_FILE_NAME_PREFIX = "CAMERA_" private const val FILES_MIME = "*/*" private const val VIDEO_OR_IMAGE_MIME = "image/* video/*" private const val IMAGE_MIME = "image/*" private const val EXTERNAL_STORAGE_URI = "com.android.externalstorage.documents" private const val DOWNLOADS_URI = "com.android.providers.downloads.documents" private const val MEDIA_URI = "com.android.providers.media.documents" private const val GOOGLE_PHOTOS_URI = "com.google.android.apps.photos.content" private const val GOOGLE_DOCS_URI = "com.google.android.apps.docs.storage" const val GALLERY_REQUEST_CODE = 183 const val CAMERA_REQUEST_CODE = 212 const val FILE_REQUEST_CODE = 189 private val isKitkatSupportDevice = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT private fun isExtStorageDocument(uri: Uri): Boolean { return EXTERNAL_STORAGE_URI == uri.authority } private fun isDownloadsDocument(uri: Uri): Boolean { return DOWNLOADS_URI == uri.authority } private fun isMediaDocument(uri: Uri): Boolean { return MEDIA_URI == uri.authority } private fun isGooglePhotosUri(uri: Uri): Boolean { return GOOGLE_PHOTOS_URI == uri.authority } private fun isGoogleDriveUri(uri: Uri): Boolean { return uri.authority!!.contains(GOOGLE_DOCS_URI) } fun getFilePath(context: Context, uri: Uri): String? { return if (isKitkatSupportDevice) { getFilePathFromUriForNewAPI(context, uri) } else { getFilePathFromUriForOldAPI(context, uri) } } private fun getFilePathFromUriForOldAPI(context: Context, uri: Uri): String? { val projection = arrayOf(MediaStore.Images.Media.DATA) var result: String? = null val cursorLoader = CursorLoader(context, uri, projection, null, null, null) val cursor = cursorLoader.loadInBackground() if (cursor != null) { val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() result = cursor.getString(columnIndex) cursor.close() } return result } @SuppressLint("NewApi") private fun getFilePathFromUriForNewAPI(context: Context, uri: Uri): String? { if (isKitkatSupportDevice && DocumentsContract.isDocumentUri(context, uri)) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] if (isExtStorageDocument(uri)) { if ("primary".equals(type, ignoreCase = true)) { return Environment.getExternalStorageDirectory().toString() + "/" + split[1] } } else if (isDownloadsDocument(uri)) { var cursor: Cursor? = null try { cursor = context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null) cursor!!.moveToNext() val fileName = cursor.getString(0) val path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName if (!TextUtils.isEmpty(path)) { return path } } finally { cursor?.close() } val id = DocumentsContract.getDocumentId(uri) if (id.startsWith("raw:")) { return id.replaceFirst("raw:".toRegex(), "") } val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads"), java.lang.Long.valueOf(id)) return getDataColumn(context, contentUri, null, null) } else if (isMediaDocument(uri)) { var contentUri: Uri? = null when (type) { "audio" -> contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI "video" -> contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI "image" -> contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI } val selection = "_id=?" val selectionArgs = arrayOf(split[1]) return getDataColumn(context, contentUri, selection, selectionArgs) } } else if (isGoogleDriveUri(uri)) { val file = loadFileFromGoogleDocs(uri, context) return file?.path } else if ("content".equals(uri.scheme!!, ignoreCase = true)) { if (isGooglePhotosUri(uri)) { return uri.lastPathSegment } else { return getDataColumn(context, uri, null, null) } } else if ("file".equals(uri.scheme!!, ignoreCase = true)) { return uri.path } if (DocumentsContract.isDocumentUri(context, uri) && isGoogleDriveUri(uri)) { val driveFile = loadFileFromGoogleDocs(uri, context) return driveFile?.path } else { return null } } private fun loadFileFromGoogleDocs(uri: Uri, context: Context): File? { var driveFile: File? = null val cursor = App.getInstance().contentResolver.query(uri, null, null, null, null) if (cursor != null) { val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) cursor.moveToFirst() val name = cursor.getString(nameIndex) driveFile = File(context.cacheDir, name) val input = context.contentResolver.openInputStream(uri) val output = FileOutputStream(driveFile) try { input.use { output.use { input?.copyTo(output) } } } catch (e: Exception) { Log.d("ImageUtils", e.message.toString()) } finally { cursor.close() } } return driveFile } private fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? { var cursor: Cursor? = null val column = "_data" val projection = arrayOf(column) try { cursor = context.contentResolver.query(uri!!, projection, selection, selectionArgs, null) if (cursor != null && cursor.moveToFirst()) { val index = cursor.getColumnIndexOrThrow(column) return cursor.getString(index) } } finally { cursor?.close() } return null } private fun getAppExternalDataDirectoryFile(): File { val dataDirectoryFile = File(getAppExternalDataDirectoryPath()) dataDirectoryFile.mkdirs() return dataDirectoryFile } private fun getAppExternalDataDirectoryPath(): String { val sb = StringBuilder() sb.append(Environment.getExternalStorageDirectory()) .append(File.separator) .append("Android") .append(File.separator) .append("data") .append(File.separator) .append(App.getInstance().packageName) .append(File.separator) return sb.toString() } fun startFilePicker(fragment: Fragment) { val intent = Intent(Intent.ACTION_GET_CONTENT) intent.type = FILES_MIME intent.addCategory(Intent.CATEGORY_OPENABLE) fragment.startActivityForResult(Intent.createChooser(intent, "Select File"), FILE_REQUEST_CODE) } fun startMediaPicker(fragment: Fragment) { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI) intent.type = VIDEO_OR_IMAGE_MIME // TODO Files: Delete further single string to add sending all file types intent.type = IMAGE_MIME // intent.action = Intent.ACTION_GET_CONTENT fragment.startActivityForResult(Intent.createChooser(intent, fragment.getString(R.string.dlg_choose_file_from)), GALLERY_REQUEST_CODE) } fun startCameraForResult(fragment: Fragment) { val pictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // TODO Files: Uncomment to add sending all file types //val videoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE) val chooser = Intent.createChooser(pictureIntent, "Capture Video or Photo") // TODO Files: Uncomment to add sending all file types //chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(videoIntent)) chooser.resolveActivity(App.getInstance().packageManager)?.let { val mediaFile = getTemporaryCameraFile(fragment.context) mediaFile?.let { pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, getValidUri(mediaFile, fragment.context)) fragment.startActivityForResult(chooser, CAMERA_REQUEST_CODE) } } } fun getTemporaryCameraFile(context: Context?): File? { val imageFileName = getTemporaryCameraFileName() val storageDir = context?.getExternalFilesDir(Environment.DIRECTORY_PICTURES) var createdSuccessful = true var image: File? = null try { image = File.createTempFile(imageFileName, ".jpg", storageDir) } catch (e: IOException) { Log.e("ImageUtils", "Cannot create file: " + e.message) e.printStackTrace() createdSuccessful = false } return if (createdSuccessful) { image!! } else { null } } fun getLastUsedCameraFile(context: Context?): File? { val dataDir = context?.getExternalFilesDir(Environment.DIRECTORY_PICTURES) val files = dataDir?.listFiles() val filteredFiles = ArrayList<File>() for (file in files!!) { if (file.name.startsWith(CAMERA_FILE_NAME_PREFIX)) { filteredFiles.add(file) } } filteredFiles.sort() return if (filteredFiles.isNotEmpty()) { filteredFiles[filteredFiles.size - 1] } else { null } } private fun getValidUri(file: File, context: Context?): Uri { val outputUri: Uri if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val authority = context!!.packageName + ".provider" outputUri = FileProvider.getUriForFile(context, authority, file) } else { outputUri = Uri.fromFile(file) } return outputUri } private fun getTemporaryCameraFileName(): String { return CAMERA_FILE_NAME_PREFIX + System.currentTimeMillis() + ".jpg" }
bsd-3-clause
44a69f0b4b9a77c6dd6f3a1e69730e93
33.888889
138
0.669789
4.362485
false
false
false
false
deadpixelsociety/sodag
core/src/com/thedeadpixelsociety/sodag/verlet/Body.kt
1
2694
package com.thedeadpixelsociety.sodag.verlet import com.badlogic.gdx.math.Vector2 data class Body(val id: Long) { companion object { val EMPTY = Body(0L) private var id = 0L private val vp = Vector2() fun create() = Body(++id) fun collide(a: Body, b: Body): Collision { var minLength = Float.MAX_VALUE val normal = Vector2() var edge = Edge.EMPTY var vertex = Vertex.EMPTY fun test(edges: List<Edge>): Boolean { edges.forEach { vp.set(it.a.position.y - it.b.position.y, it.b.position.x - it.a.position.x) vp.nor() val projA = a.project(vp) val projB = b.project(vp) val dist = if (projA.min < projB.min) { projB.min - projA.max } else { projA.min - projB.max } if (dist > 0f) return false if (Math.abs(dist) < minLength) { minLength = dist normal.set(vp) edge = it } } return true } if (test(a.edges) || test(b.edges)) { var b1 = a var b2 = b if (edge.body != b2) { var t = b2 b2 = b1 b1 = b2 } vp.set(b1.center).sub(b2.center) val sgn = Math.signum(normal.dot(vp)) if (sgn <= 0f) normal.set(-normal.x, -normal.y) var d = Float.MAX_VALUE b1.vertices.forEach { vp.set(it.position).sub(b2.center) val dist = normal.dot(vp) if (dist < d) { d = dist vertex = it } } return Collision(vertex, edge, normal, minLength) } return Collision.NONE } } private val vertices = arrayListOf<Vertex>() private val edges = arrayListOf<Edge>() val center = Vector2() fun project(axis: Vector2): AxisProjection { if (vertices.isEmpty()) return AxisProjection.INVALID var dp = axis.dot(vertices[0].position) var min = dp var max = dp for (i in 1 until vertices.size) { dp = axis.dot(vertices[i].position) min = Math.min(dp, min) max = Math.min(dp, max) } return AxisProjection(min, max) } }
mit
7c1346f68c712a56f3030b7f132d6ce7
28.615385
96
0.430586
4.296651
false
false
false
false
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/settings/SettingsActivity.kt
1
2308
/* * Copyright 2016-2019 Adrian Cotfas * * 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.apps.adrcotfas.goodtime.settings import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import android.os.Bundle import android.view.MenuItem import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import com.apps.adrcotfas.goodtime.util.ThemeHelper import androidx.databinding.DataBindingUtil import com.apps.adrcotfas.goodtime.R import com.apps.adrcotfas.goodtime.databinding.GenericMainBinding @AndroidEntryPoint class SettingsActivity : AppCompatActivity() { @Inject lateinit var preferenceHelper: PreferenceHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ThemeHelper.setTheme(this, preferenceHelper.isAmoledTheme()) val binding: GenericMainBinding = DataBindingUtil.setContentView(this, R.layout.generic_main) binding.layout.alpha = 0f binding.layout.animate().alpha(1f).duration = 100 setSupportActionBar(binding.toolbarWrapper.toolbar) if (supportActionBar != null) { supportActionBar!!.setDisplayHomeAsUpEnabled(true) } if (savedInstanceState == null) { val fragment = SettingsFragment() val ft = supportFragmentManager.beginTransaction() ft.replace(R.id.fragment, fragment) ft.commitAllowingStateLoss() } } override fun onAttachedToWindow() { window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return false } }
apache-2.0
fda5aed5a3d7f96b57369fc74ec333ba
36.241935
128
0.721837
4.879493
false
false
false
false
nemerosa/ontrack
ontrack-extension-git/src/test/java/net/nemerosa/ontrack/extension/git/service/GitCommitIndexationIT.kt
1
3225
package net.nemerosa.ontrack.extension.git.service import net.nemerosa.ontrack.extension.git.AbstractGitTestJUnit4Support import net.nemerosa.ontrack.extension.git.property.GitProjectConfigurationPropertyType import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class GitCommitIndexationIT : AbstractGitTestJUnit4Support() { @Test fun `Indexation job catching up with missing commits`() { createRepo { commits(10, pauses = false) } and { repo, commits -> project { gitProject(repo) branch { gitBranch { commitAsProperty() } // Creates 10 builds with a commit property (but for n°6) commits.forEach { no, commit -> build(name = "$no") { if (no != 6) { gitCommitProperty(commit) } } } // Checks that NO indexed Git commit is stored for this build val build = structureService.findBuildByName(project.name, name, "6").orElse(null)!! var commitForBuild = gitService.getCommitForBuild(build) assertNull(commitForBuild, "No commit stored for build") // Before setting the Git commit property for the build // we have to simulate the fact that the indexation won't work val projectProperty = asAdmin().call { val property = propertyService.getProperty(project, GitProjectConfigurationPropertyType::class.java).value propertyService.deleteProperty(project, GitProjectConfigurationPropertyType::class.java) property }!! // Setting the property build.gitCommitProperty(commits.getValue(6)) // Checks it's not set commitForBuild = gitService.getCommitForBuild(build) assertNull(commitForBuild, "No commit stored for build yet") // Resets the project configuration asAdmin().execute { propertyService.editProperty( project, GitProjectConfigurationPropertyType::class.java, projectProperty ) } // Indexation of the branch in an incremental way gitService.collectIndexableGitCommitForBranch(this, overrides = false) // Checks the commit is set commitForBuild = gitService.getCommitForBuild(build) assertNotNull(commitForBuild, "Commit is now stored for build") { assertEquals( commits[6], it.commit.id ) } } } } } }
mit
19533094dbd2c0ff27e0d441fc1de5a5
40.883117
130
0.511787
6.396825
false
true
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/epg/EpgChannelListRecyclerViewAdapter.kt
1
2442
package org.tvheadend.tvhclient.ui.features.epg import android.view.LayoutInflater import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.RecyclerView import org.tvheadend.data.entity.EpgChannel import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.EpgChannelRecyclerviewAdapterBinding import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import java.util.* class EpgChannelListRecyclerViewAdapter(private val viewModel: EpgViewModel, private val clickCallback: RecyclerViewClickInterface, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<EpgChannelListRecyclerViewAdapter.EpgChannelViewHolder>() { private val channelList = ArrayList<EpgChannel>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EpgChannelViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = EpgChannelRecyclerviewAdapterBinding.inflate(layoutInflater, parent, false) val viewHolder = EpgChannelViewHolder(itemBinding, viewModel) itemBinding.lifecycleOwner = lifecycleOwner return viewHolder } override fun onBindViewHolder(holder: EpgChannelViewHolder, position: Int) { val channel = channelList[position] holder.bind(channel, position, clickCallback) } fun addItems(list: List<EpgChannel>) { channelList.clear() channelList.addAll(list) notifyDataSetChanged() } override fun getItemCount(): Int { return channelList.size } override fun getItemViewType(position: Int): Int { return R.layout.epg_channel_recyclerview_adapter } fun getItem(position: Int): EpgChannel? { return if (channelList.size > position && position >= 0) { channelList[position] } else { null } } class EpgChannelViewHolder(private val binding: EpgChannelRecyclerviewAdapterBinding, private val viewModel: EpgViewModel) : RecyclerView.ViewHolder(binding.root) { fun bind(channel: EpgChannel, position: Int, clickCallback: RecyclerViewClickInterface) { binding.channel = channel binding.position = position binding.callback = clickCallback binding.viewModel = viewModel binding.executePendingBindings() } } }
gpl-3.0
f76d75148219d1c2dd884f150781a1f0
37.15625
258
0.725225
5.162791
false
false
false
false
kotlin-graphics/imgui
core/src/main/kotlin/imgui/api/childWindows.kt
1
3963
package imgui.api import gli_.has import glm_.glm import glm_.vec2.Vec2 import imgui.* import imgui.ImGui.beginChildEx import imgui.ImGui.currentWindow import imgui.ImGui.end import imgui.ImGui.itemAdd import imgui.ImGui.itemSize import imgui.ImGui.renderNavHighlight import imgui.internal.sections.Axis import imgui.internal.sections.NavHighlightFlag import imgui.internal.classes.Rect import imgui.internal.sections.shl import imgui.WindowFlag as Wf interface childWindows { // Child Windows /** - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. * - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size * / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). * - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. * Always call a matching EndChild() for each BeginChild() call, regardless of its return value. * [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, * BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function * returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] */ fun beginChild(strId: String, size: Vec2 = Vec2(), border: Boolean = false, flags: WindowFlags = 0): Boolean = beginChildEx(strId, currentWindow.getID(strId), size, border, flags) /** begin a scrolling region. * size == 0f: use remaining window size * size < 0f: use remaining window size minus abs(size) * size > 0f: fixed size. each axis can use a different mode, e.g. Vec2(0, 400). */ fun beginChild(id: ID, sizeArg: Vec2 = Vec2(), border: Boolean = false, flags: WindowFlags = Wf.None.i): Boolean { assert(id != 0) return beginChildEx("", id, sizeArg, border, flags) } /** Always call even if BeginChild() return false (which indicates a collapsed or clipping child window) */ fun endChild() { val window = currentWindow assert(!g.withinEndChild) assert(window.flags has Wf._ChildWindow) { "Mismatched BeginChild()/EndChild() callss" } g.withinEndChild = true if (window.beginCount > 1) end() else { /* When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. */ val sz = Vec2(window.size) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f if (window.autoFitChildAxes has (1 shl Axis.X)) sz.x = glm.max(4f, sz.x) if (window.autoFitChildAxes has (1 shl Axis.Y)) sz.y = glm.max(4f, sz.y) end() val parentWindow = currentWindow val bb = Rect(parentWindow.dc.cursorPos, parentWindow.dc.cursorPos + sz) itemSize(sz) if ((window.dc.navLayerActiveMask != 0 || window.dc.navHasScroll) && window.flags hasnt Wf._NavFlattened) { itemAdd(bb, window.childId) renderNavHighlight(bb, window.childId) // When browsing a window that has no activable items (scroll only) we keep a highlight on the child if (window.dc.navLayerActiveMask == 0 && window === g.navWindow) renderNavHighlight(Rect(bb.min - 2, bb.max + 2), g.navId, NavHighlightFlag.TypeThin.i) } else // Not navigable into itemAdd(bb, 0) } g.withinEndChild = false g.logLinePosY = -Float.MAX_VALUE // To enforce a carriage return } }
mit
5970776323debf99e4af27376cea6f88
47.341463
160
0.655816
3.963
false
false
false
false
rhdunn/marklogic-intellij-plugin
src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/query/JavaScriptBuilder.kt
1
1419
/* * Copyright (C) 2017 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.marklogic.query import com.intellij.execution.executors.DefaultRunExecutor import uk.co.reecedunn.intellij.plugin.marklogic.server.MarkLogicVersion object JavaScriptBuilder : QueryBuilder { override fun createEvalBuilder(executorId: String, markLogicVersion: MarkLogicVersion): Function? { return if (DefaultRunExecutor.EXECUTOR_ID == executorId && markLogicVersion.major >= 8) { Function.XDMP_JAVASCRIPT_EVAL_80 } else { null } } override fun createInvokeBuilder(executorId: String, markLogicVersion: MarkLogicVersion): Function? { return if (DefaultRunExecutor.EXECUTOR_ID == executorId && markLogicVersion.major >= 8) { Function.XDMP_INVOKE_70 } else { null } } }
apache-2.0
a9c48c769e979111bf8f4dd9e9321434
37.351351
105
0.711769
4.37963
false
false
false
false
pyamsoft/pasterino
app/src/main/java/com/pyamsoft/pasterino/settings/SettingsViewModel.kt
1
1903
/* * Copyright 2020 Peter Kenji Yamanaka * * 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.pyamsoft.pasterino.settings import androidx.lifecycle.viewModelScope import com.pyamsoft.pasterino.api.PasteServiceInteractor import com.pyamsoft.pydroid.arch.UiViewModel import com.pyamsoft.pydroid.arch.UnitControllerEvent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject internal class SettingsViewModel @Inject internal constructor( private val interactor: PasteServiceInteractor, ) : UiViewModel<SettingsViewState, UnitControllerEvent>( SettingsViewState( delayTime = 0, isDeepSearch = false, ), ) { init { viewModelScope.launch(context = Dispatchers.Default) { val isDeepSearch = interactor.isDeepSearchEnabled() val delayTime = interactor.getPasteDelayTime() setState { copy( isDeepSearch = isDeepSearch, delayTime = delayTime, ) } } } fun handleDelayTimeChanged(time: Long) { setState( stateChange = { copy(delayTime = time) }, andThen = { interactor.setPasteDelayTime(time) }, ) } fun handleDeepSearchChanged(deep: Boolean) { setState( stateChange = { copy(isDeepSearch = deep) }, andThen = { interactor.setDeepSearchEnabled(deep) }, ) } }
apache-2.0
feb31714ae24299852d2e23e1a391eec
28.276923
75
0.704151
4.425581
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/State01SendingLobbyAuth.kt
1
1652
package org.pixelndice.table.pixelclient.connection.lobby.client import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.isGm import org.pixelndice.table.pixelclient.myAccount import org.pixelndice.table.pixelprotocol.ChannelCanceledException import org.pixelndice.table.pixelprotocol.Protobuf private val logger = LogManager.getLogger(State01SendingLobbyAuth::class.java) /** * State that sends auth request to lobby server. * The GM mus respond. * @author Marcelo Costa Toyama */ class State01SendingLobbyAuth: State { init { logger.debug("State01SendingLobbyAuth constructor") } /** * Process the context */ override fun process(ctx: Context) { val resp: Protobuf.Packet.Builder = Protobuf.Packet.newBuilder() val auth = Protobuf.LobbyAuth.newBuilder() resp.sender = Protobuf.SenderEnum.FROM_ACCOUNT resp.from = myAccount.toProtobuf().build() resp.receiver = Protobuf.ReceiverEnum.TO_GM resp.lobbyAuth = auth.build() try{ ctx.channel.packet = resp.build() }catch (e: ChannelCanceledException){ logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } if( isGm() ){ ctx.state = StateRunning() ApplicationBus.post(ApplicationBus.LoadTableApp()) }else{ ctx.state = State02WaitingLobbyAuthResponse() ApplicationBus.post(ApplicationBus.WaitingGMApprovalStart()) } logger.debug("Sending Lobby Auth: $myAccount") } }
bsd-2-clause
cc08391bd54e6dea6cbd0eb379aabb86
28.517857
92
0.690678
4.358839
false
false
false
false
shlusiak/Freebloks-Android
app/src/main/java/de/saschahlusiak/freebloks/game/dialogs/CustomGameFragment.kt
1
10063
package de.saschahlusiak.freebloks.game.dialogs import android.app.Dialog import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.CheckBox import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import androidx.preference.PreferenceManager import com.shawnlin.numberpicker.NumberPicker import de.saschahlusiak.freebloks.R import de.saschahlusiak.freebloks.databinding.CustomGameFragmentBinding import de.saschahlusiak.freebloks.game.OnStartCustomGameListener import de.saschahlusiak.freebloks.model.* import de.saschahlusiak.freebloks.model.GameMode.* import de.saschahlusiak.freebloks.utils.MaterialDialogFragment import de.saschahlusiak.freebloks.utils.viewBinding class CustomGameFragment : MaterialDialogFragment(R.layout.custom_game_fragment), OnSeekBarChangeListener, View.OnClickListener, OnItemSelectedListener { // the values of the difficulty slider for each index private val difficultyValues = intArrayOf( 200, 150, 130, 90, 60, 40, 20, 10, 5, 2, 1 ) private lateinit var players: Array<CheckBox> private lateinit var picker: Array<NumberPicker> private val listener get() = requireActivity() as OnStartCustomGameListener private val prefs by lazy { PreferenceManager.getDefaultSharedPreferences(requireContext()) } private val binding by viewBinding(CustomGameFragmentBinding::bind) /** * Convenient getter/setter for GameMode */ private var gameMode: GameMode get() = GameMode.from(binding.gameModeSpinner.selectedItemPosition) set(value) = binding.gameModeSpinner.setSelection(value.ordinal) /** * Convenient getter/setter for field size */ private var fieldSize: Int get() = GameConfig.FIELD_SIZES[binding.fieldSizeSpinner.selectedItemPosition] set(value) { val selection = GameConfig.FIELD_SIZES.indexOfFirst { it == value } if (selection >= 0) binding.fieldSizeSpinner.setSelection(selection) else binding.fieldSizeSpinner.setSelection(4) } /** * Convenient getter for the selected stones */ private val stones: IntArray get() = IntArray(Shape.COUNT) { picker[Shape.get(it).points - 1].value } /** * Convenient getter for the difficulty slider to value */ private var difficulty: Int get() = difficultyValues[binding.difficultySlider.progress] set(value) { val selection = difficultyValues.indexOfFirst { it == value } if (selection >= 0) binding.difficultySlider.progress = selection else // this is really just when the value is not found, which should never happen binding.difficultySlider.progress = difficultyValues.size - 1 } private val playersAsBooleanArray get() = BooleanArray(4) { /* this would otherwise request players two times, the server would hand out 2x2 = 4 players */ players[it].isChecked && (gameMode != GAMEMODE_4_COLORS_2_PLAYERS || it < 2) } override fun getTheme() = R.style.Theme_Freebloks_DayNight_Dialog_MinWidth override fun onViewCreated(view: View, savedInstanceState: Bundle?) = with(binding) { difficultySlider.setOnSeekBarChangeListener(this@CustomGameFragment) difficultySlider.max = difficultyValues.size - 1 players = arrayOf(player1, player2, player3, player4) picker = arrayOf(picker1, picker2, picker3, picker4, picker5) gameModeSpinner.onItemSelectedListener = this@CustomGameFragment advanced.setOnClickListener(this@CustomGameFragment) player1.setOnClickListener(this@CustomGameFragment) player2.setOnClickListener(this@CustomGameFragment) cancel.setOnClickListener(this@CustomGameFragment) ok.setOnClickListener(this@CustomGameFragment) difficulty = prefs.getInt("difficulty", GameConfig.DEFAULT_DIFFICULTY) gameMode = GameMode.from(prefs.getInt("gamemode", GAMEMODE_4_COLORS_4_PLAYERS.ordinal)) fieldSize = prefs.getInt("fieldsize", Board.DEFAULT_BOARD_SIZE) setupDialog() } private fun setupDialog() { players.forEach { it.isChecked = false } val p = when(gameMode) { GAMEMODE_2_COLORS_2_PLAYERS -> (Math.random() * 2.0).toInt() * 2 GAMEMODE_DUO, GAMEMODE_JUNIOR -> (Math.random() * 2.0).toInt() * 2 GAMEMODE_4_COLORS_2_PLAYERS -> (Math.random() * 2.0).toInt() GAMEMODE_4_COLORS_4_PLAYERS -> (Math.random() * 4.0).toInt() } players[p].isChecked = true if (gameMode === GAMEMODE_4_COLORS_2_PLAYERS) { players[2].isChecked = players[0].isChecked players[3].isChecked = players[1].isChecked } updateColorNames() updateDifficultyLabel() requireView().visibility = View.VISIBLE binding.customStonesLayout.visibility = View.GONE } private fun buildGameConfig() = GameConfig( null, gameMode, false, playersAsBooleanArray, difficulty, stones, fieldSize ) override fun onClick(v: View) { view?.run { when (v.id) { R.id.ok -> { saveSettings() // we don't need to request a player name, because we overwrite it locally anyway when displaying listener.onStartClientGameWithConfig(buildGameConfig(), null) dismiss() } R.id.cancel -> { dismiss() } R.id.advanced -> with(binding) { advanced.visibility = View.GONE customStonesLayout.visibility = View.VISIBLE } R.id.player1 -> if (gameMode == GAMEMODE_4_COLORS_2_PLAYERS) with(binding) { player3.isChecked = player1.isChecked } R.id.player2 -> if (gameMode == GAMEMODE_4_COLORS_2_PLAYERS) with(binding) { player4.isChecked = player2.isChecked } } } } /** * New game mode is selected */ override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { when (gameMode) { GAMEMODE_DUO, GAMEMODE_JUNIOR -> { players[0].isEnabled = true players[1].isEnabled = false players[2].isEnabled = true players[3].isEnabled = false if (players[1].isChecked) players[0].isChecked = true if (players[3].isChecked) players[2].isChecked = true players[1].isChecked = false players[3].isChecked = false /* FIXME: on first create this is called after prepare, which does seem to not persist the * last set size if != 14 */ fieldSize = 14 } GAMEMODE_2_COLORS_2_PLAYERS -> { players[0].isEnabled = true players[2].isEnabled = true players[1].isEnabled = false players[3].isEnabled = false if (players[1].isChecked) players[0].isChecked = true if (players[3].isChecked) players[2].isChecked = true players[1].isChecked = false players[3].isChecked = false /* FIXME: on first create this is called after prepare, which does seem to not persist the * last set size if != 15 */ fieldSize = 15 } GAMEMODE_4_COLORS_2_PLAYERS -> { var e: Boolean players[0].isEnabled = true players[1].isEnabled = true players[2].isEnabled = false players[3].isEnabled = false e = players[0].isChecked || players[2].isChecked players[0].isChecked = e players[2].isChecked = e e = players[1].isChecked || players[3].isChecked players[1].isChecked = e players[3].isChecked = e } GAMEMODE_4_COLORS_4_PLAYERS -> { players[0].isEnabled = true players[1].isEnabled = true players[2].isEnabled = true players[3].isEnabled = true } } updateColorNames() } private fun updateColorNames() { players.forEachIndexed { index, checkBox -> checkBox.text = gameMode.colorOf(index).getName(requireContext().resources) } } private fun saveSettings() { prefs.edit() .putInt("difficulty", difficulty) .putInt("gamemode", gameMode.ordinal) .putInt("fieldsize", fieldSize) .apply() } private fun updateDifficultyLabel() { // 5 values, from hardest to easiest val labels = requireContext().resources.getStringArray(R.array.difficulties) val value = difficulty var text = 0 if (value >= 5) text = 1 if (value >= 40) text = 2 if (value >= 80) text = 3 if (value >= 160) text = 4 binding.difficultyLabel.text = String.format("%s (%d)", labels[text], binding.difficultySlider.progress) } override fun onProgressChanged(seekBar: SeekBar, arg1: Int, arg2: Boolean) { updateDifficultyLabel() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return super.onCreateDialog(savedInstanceState).apply { setTitle(R.string.custom_game) } } }
gpl-2.0
3a4796d796e126e7f9c881eb2c48ef62
37.121212
153
0.609162
4.764678
false
false
false
false
akvo/akvo-caddisfly
caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/MainActivity.kt
1
9691
/* * Copyright (C) Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Caddisfly. * * Akvo Caddisfly 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. * * Akvo Caddisfly 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 Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.caddisfly.ui import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.app.Activity import android.content.DialogInterface import android.content.Intent import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.Bundle import android.os.Handler import android.os.Message import android.os.Process import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager.OnPageChangeListener import kotlinx.android.synthetic.main.activity_main.* import org.akvo.caddisfly.R import org.akvo.caddisfly.R.* import org.akvo.caddisfly.app.CaddisflyApp import org.akvo.caddisfly.common.AppConstants.FLOW_SURVEY_PACKAGE_NAME import org.akvo.caddisfly.databinding.ActivityMainBinding import org.akvo.caddisfly.helper.ApkHelper import org.akvo.caddisfly.preference.AppPreferences import org.akvo.caddisfly.preference.AppPreferences.isDiagnosticMode import org.akvo.caddisfly.preference.SettingsActivity import org.akvo.caddisfly.util.AlertUtil import org.akvo.caddisfly.util.AnimatedColor import org.akvo.caddisfly.util.PreferencesUtil import java.lang.ref.WeakReference const val FIRST_PAGE = 0 const val INTRO_PAGE_COUNT = 2 class MainActivity : AppUpdateActivity() { private val refreshHandler = WeakRefHandler(this) private var b: ActivityMainBinding? = null private var statusBarColors: AnimatedColor? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) b = DataBindingUtil.setContentView<ActivityMainBinding?>(this, layout.activity_main) b!!.pageIndicator.setPageCount(INTRO_PAGE_COUNT) setTitle(string.appName) try { // If app has expired then close this activity ApkHelper.isAppVersionExpired(this) } catch (e: Exception) { e.printStackTrace() } hideActionBar() b!!.viewPager.addOnPageChangeListener(object : OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { b!!.pageIndicator.setActiveIndex(position) if (position == 1) { b!!.buttonNext.visibility = View.GONE b!!.buttonOk.visibility = View.VISIBLE } else { b!!.buttonNext.visibility = View.VISIBLE b!!.buttonOk.visibility = View.GONE } } override fun onPageScrollStateChanged(state: Int) {} }) b!!.buttonInfo.setOnClickListener { val intent = Intent(baseContext, AboutActivity::class.java) startActivity(intent) } Handler().post { setUpViews() } } private fun hideActionBar() { val supportActionBar = supportActionBar supportActionBar?.hide() } private fun setUpViews() { b!!.viewPager.adapter = IntroFragmentAdapter(supportFragmentManager) b!!.pageIndicator.setActiveIndex(0) if (b!!.viewPager.currentItem == 1) { b!!.buttonNext.visibility = View.GONE b!!.buttonOk.visibility = View.VISIBLE } else { b!!.buttonNext.visibility = View.VISIBLE b!!.buttonOk.visibility = View.GONE } switchLayoutForDiagnosticOrUserMode() // Setting text here as some phones not translating text // Could probably be removed after review b!!.buttonNext.text = getString(string.next) b!!.buttonOk.text = getString(string.go_to_external_app) } override fun onResume() { super.onResume() if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { statusBarColors = if (isDiagnosticMode()) { AnimatedColor( ContextCompat.getColor(this, color.colorPrimaryDark), ContextCompat.getColor(this, color.diagnostic_status)) } else { AnimatedColor( ContextCompat.getColor(this, color.colorPrimaryDark), ContextCompat.getColor(this, color.black_main)) } animateStatusBar() } CaddisflyApp.getApp().setAppLanguage(this, null, false, refreshHandler) if (PreferencesUtil.getBoolean(this, string.refreshKey, false)) { PreferencesUtil.removeKey(this, string.refreshKey) refreshHandler.sendEmptyMessage(0) return } Handler().postDelayed({ setUpViews() }, 300) } fun onSettingsClick(@Suppress("UNUSED_PARAMETER") item: MenuItem?) { startActivity(Intent(this, SettingsActivity::class.java)) } override fun onCreateOptionsMenu(menu: Menu): Boolean { if (isDiagnosticMode()) { menuInflater.inflate(R.menu.menu_main_diagnostic, menu) } else { menuInflater.inflate(R.menu.menu_main, menu) } return true } fun onNextClicked(@Suppress("UNUSED_PARAMETER") view: View?) { b!!.viewPager.setCurrentItem(1, true) } fun onOkClicked(@Suppress("UNUSED_PARAMETER") view: View?) { val intent: Intent? = packageManager .getLaunchIntentForPackage(FLOW_SURVEY_PACKAGE_NAME) if (intent != null) { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(intent) closeApp(1000) } else { alertDependantAppNotFound() } } private fun alertDependantAppNotFound() { val message = String.format("%s\r\n\r\n%s", getString(string.external_app_not_installed), getString(string.install_external_app)) AlertUtil.showAlert(this, string.notFound, message, string.close, DialogInterface.OnClickListener { _: DialogInterface?, _: Int -> closeApp(0) }, null, null) } private fun closeApp(delay: Int) { Handler().postDelayed({ if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { finishAndRemoveTask() } else { val pid = Process.myPid() Process.killProcess(pid) } }, delay.toLong()) } @RequiresApi(api = VERSION_CODES.LOLLIPOP) private fun animateStatusBar() { val animator: ValueAnimator = ObjectAnimator.ofFloat(0f, 1f).setDuration(1000) animator.addUpdateListener { animation: ValueAnimator -> val v = animation.animatedValue as Float window.statusBarColor = statusBarColors!!.with(v) } animator.start() } /** * Handler to restart the app after language has been changed. */ private class WeakRefHandler internal constructor(ref: Activity) : Handler() { private val ref: WeakReference<Activity> = WeakReference(ref) override fun handleMessage(msg: Message) { val f = ref.get() f?.recreate() } } override fun onBackPressed() { if (b!!.viewPager.currentItem > 0) { b!!.viewPager.currentItem = b!!.viewPager.currentItem - 1 } else { super.onBackPressed() } } /** * Disables diagnostic mode. */ fun disableDiagnosticsMode(@Suppress("UNUSED_PARAMETER") view: View?) { Toast.makeText(baseContext, getString(string.diagnosticModeDisabled), Toast.LENGTH_SHORT).show() AppPreferences.disableDiagnosticMode() switchLayoutForDiagnosticOrUserMode() changeActionBarStyleBasedOnCurrentMode() } private fun switchLayoutForDiagnosticOrUserMode() { if (isDiagnosticMode()) { text_diagnostic_mode.visibility = View.VISIBLE fabDisableDiagnostics.show() } else { text_diagnostic_mode.visibility = View.GONE fabDisableDiagnostics.hide() } } internal inner class IntroFragmentAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment { return if (position == FIRST_PAGE) { Intro1Fragment.newInstance() } else { Intro2Fragment.newInstance() } } override fun getCount(): Int { return INTRO_PAGE_COUNT } override fun getItemPosition(`object`: Any): Int { return PagerAdapter.POSITION_NONE } } }
gpl-3.0
986b51d59e3db4c53fa4595c75373d65
33.859712
107
0.649056
4.764503
false
false
false
false
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/view/ExpiryDateEditTextTest.kt
1
14677
package com.stripe.android.view import android.content.Context import android.text.TextWatcher import androidx.appcompat.view.ContextThemeWrapper import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.R import com.stripe.android.model.ExpirationDate import com.stripe.android.testharness.ViewTestUtils import com.stripe.android.utils.TestUtils.idleLooper import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import org.robolectric.RobolectricTestRunner import java.util.Calendar import kotlin.test.Test /** * Test class for [ExpiryDateEditText]. */ @RunWith(RobolectricTestRunner::class) class ExpiryDateEditTextTest { private val context: Context = ApplicationProvider.getApplicationContext<Context>() private val expiryDateEditText = ExpiryDateEditText( ContextThemeWrapper( ApplicationProvider.getApplicationContext(), R.style.StripeDefaultTheme ) ) @Test fun afterInputTwoDigits_textContainsSlash() { expiryDateEditText.append("1") expiryDateEditText.append("2") assertThat(expiryDateEditText.text.toString()) .isEqualTo("12/") } @Test fun inputSingleDigit_whenDigitIsTooLargeForMonth_prependsZero() { expiryDateEditText.append("4") assertThat(expiryDateEditText.text.toString()) .isEqualTo("04/") assertThat(expiryDateEditText.selectionStart) .isEqualTo(3) } @Test fun inputSingleDigit_whenDigitIsZeroOrOne_doesNotPrependZero() { expiryDateEditText.append("1") assertThat(expiryDateEditText.text.toString()) .isEqualTo("1") assertThat(expiryDateEditText.selectionStart) .isEqualTo(1) } @Test fun inputSingleDigit_whenAtFirstCharacterButTextNotEmpty_doesNotPrependZero() { expiryDateEditText.append("1") // This case can occur when the user moves the cursor behind the already-entered text. expiryDateEditText.setSelection(0) expiryDateEditText.editableText.replace(0, 0, "3", 0, 1) assertThat(expiryDateEditText.text.toString()) .isEqualTo("31") assertThat(expiryDateEditText.selectionStart) .isEqualTo(1) } @Test fun inputMultipleValidDigits_whenEmpty_doesNotPrependZeroOrShowErrorState() { expiryDateEditText.append("11") assertThat(expiryDateEditText.text.toString()) .isEqualTo("11/") assertThat(expiryDateEditText.shouldShowError) .isFalse() assertThat(expiryDateEditText.selectionStart) .isEqualTo(3) } @Test fun afterInputThreeDigits_whenDeletingOne_textDoesNotContainSlash() { expiryDateEditText.append("1") expiryDateEditText.append("2") expiryDateEditText.append("3") ViewTestUtils.sendDeleteKeyEvent(expiryDateEditText) assertThat(expiryDateEditText.text.toString()) .isEqualTo("12") } @Test fun afterAddingFinalDigit_whenGoingFromInvalidToValid_callsListener() { var invocations = 0 expiryDateEditText.completionCallback = { invocations++ } assertThat(Calendar.getInstance().get(Calendar.YEAR) <= 2059) .isTrue() expiryDateEditText.append("1") expiryDateEditText.append("2") expiryDateEditText.append("5") assertThat(invocations) .isEqualTo(0) expiryDateEditText.append("9") assertThat(expiryDateEditText.isDateValid) .isTrue() assertThat(invocations) .isEqualTo(1) } @Test fun afterAddingFinalDigit_whenDeletingItem_revertsToInvalidState() { var invocations = 0 expiryDateEditText.completionCallback = { invocations++ } assertThat(Calendar.getInstance().get(Calendar.YEAR) <= 2059) .isTrue() expiryDateEditText.append("12") expiryDateEditText.append("59") assertThat(expiryDateEditText.isDateValid) .isTrue() ViewTestUtils.sendDeleteKeyEvent(expiryDateEditText) assertThat(invocations) .isEqualTo(1) assertThat(expiryDateEditText.isDateValid) .isFalse() } @Test fun updateSelectionIndex_whenMovingAcrossTheGap_movesToEnd() { assertThat( expiryDateEditText.updateSelectionIndex(3, 1, 1, 5) ).isEqualTo(3) } @Test fun updateSelectionIndex_atStart_onlyMovesForwardByOne() { assertThat( expiryDateEditText.updateSelectionIndex(1, 0, 1, 5) ).isEqualTo(1) } @Test fun updateSelectionIndex_whenDeletingAcrossTheGap_staysAtEnd() { assertThat( expiryDateEditText.updateSelectionIndex(2, 4, 0, 5) ).isEqualTo(2) } @Test fun updateSelectionIndex_whenInputVeryLong_respectMaxInputLength() { assertThat( expiryDateEditText.updateSelectionIndex(6, 4, 2, 5) ).isEqualTo(5) } @Test fun inputZero_whenEmpty_doesNotShowErrorState() { expiryDateEditText.append("0") assertThat(expiryDateEditText.shouldShowError) .isFalse() assertThat(expiryDateEditText.text.toString()) .isEqualTo("0") } @Test fun inputOne_whenEmpty_doesNotShowErrorState() { expiryDateEditText.append("1") assertThat(expiryDateEditText.shouldShowError) .isFalse() assertThat(expiryDateEditText.text.toString()) .isEqualTo("1") } @Test fun inputTwoDigitMonth_whenInvalid_showsErrorAndDoesNotAddSlash() { expiryDateEditText.append("14") assertThat(expiryDateEditText.shouldShowError) .isTrue() assertThat(expiryDateEditText.errorMessage) .isEqualTo(context.getString(R.string.incomplete_expiry_date)) assertThat(expiryDateEditText.text.toString()) .isEqualTo("14") } @Test fun inputThreeDigits_whenInvalid_showsErrorAndDoesAddSlash() { expiryDateEditText.append("143") assertThat(expiryDateEditText.shouldShowError) .isTrue() assertThat(expiryDateEditText.errorMessage) .isEqualTo(context.getString(R.string.incomplete_expiry_date)) assertThat(expiryDateEditText.text.toString()) .isEqualTo("14/3") } @Test fun delete_whenAcrossSeparator_deletesSeparatorAndLastCharacterBeforeSeparator() { expiryDateEditText.append("12") assertThat(expiryDateEditText.text.toString()) .isEqualTo("12/") ViewTestUtils.sendDeleteKeyEvent(expiryDateEditText) assertThat(expiryDateEditText.text.toString()) .isEqualTo("1") } @Test fun inputCompleteDate_whenInPast_showsInvalid() { var invocations = 0 expiryDateEditText.completionCallback = { invocations++ } // This test will be invalid if run between 2080 and 2112. Please update the code. assertThat(Calendar.getInstance().get(Calendar.YEAR) < 2080) .isTrue() // Date translates to December, 2012 UNTIL the 2080, at which point it translates to // December, 2112. Also, this simulates a PASTE action. expiryDateEditText.append("1212") assertThat(expiryDateEditText.shouldShowError) .isTrue() assertThat(expiryDateEditText.errorMessage) .isEqualTo(context.getString(R.string.invalid_expiry_year)) assertThat(invocations) .isEqualTo(0) } @Test fun inputCompleteDateInPast_thenDelete_showsValid() { var invocations = 0 expiryDateEditText.completionCallback = { invocations++ } // This test will be invalid if run between 2080 and 2112. Please update the code. assertThat(Calendar.getInstance().get(Calendar.YEAR) < 2080) .isTrue() // Date translates to December, 2012 UNTIL the 2080, at which point it translates to // December, 2112. expiryDateEditText.append("12/12") assertThat(expiryDateEditText.shouldShowError) .isTrue() assertThat(expiryDateEditText.errorMessage) .isEqualTo(context.getString(R.string.invalid_expiry_year)) ViewTestUtils.sendDeleteKeyEvent(expiryDateEditText) assertThat(expiryDateEditText.text.toString()) .isEqualTo("12/1") assertThat(expiryDateEditText.shouldShowError) .isFalse() // The date is no longer "in error", but it still shouldn't have triggered the listener. assertThat(invocations) .isEqualTo(0) } @Test fun clearingDate_doesNotShowError() { expiryDateEditText.append("15") assertThat(expiryDateEditText.shouldShowError).isTrue() expiryDateEditText.setText("") assertThat(expiryDateEditText.text.isNullOrBlank()).isTrue() assertThat(expiryDateEditText.shouldShowError).isFalse() } @Test fun inputCompleteDate_whenMonthInvalid_showsInvalidMonth() { expiryDateEditText.append("15") expiryDateEditText.append("50") assertThat(expiryDateEditText.shouldShowError) .isTrue() assertThat(expiryDateEditText.errorMessage) .isEqualTo(context.getString(R.string.invalid_expiry_month)) } @Test fun validatedDate_whenDataIsValid_returnsExpectedValues() { // This test will be invalid if run after the year 2050. Please update the code. assertThat(Calendar.getInstance().get(Calendar.YEAR) < 2050) .isTrue() expiryDateEditText.append("12") expiryDateEditText.append("50") assertThat( expiryDateEditText.validatedDate ).isEqualTo( ExpirationDate.Validated( month = 12, year = 2050 ) ) } @Test fun validatedDate_whenDateIsValidFormatButExpired_returnsNull() { // This test will be invalid if run after the year 2080. Please update the code. assertThat(Calendar.getInstance().get(Calendar.YEAR) < 2080) .isTrue() expiryDateEditText.append("12") expiryDateEditText.append("12") // 12/12 is an invalid date until 2080, at which point it will be interpreted as 12/2112 assertThat(expiryDateEditText.validatedDate) .isNull() } @Test fun validatedDate_whenDateIsIncomplete_returnsNull() { expiryDateEditText.append("4") assertThat(expiryDateEditText.validatedDate) .isNull() } @Test fun validatedDate_whenDateIsValidAndThenChangedToInvalid_returnsNull() { // This test will be invalid if run after the year 2050. Please update the code. assertThat(Calendar.getInstance().get(Calendar.YEAR) < 2050) .isTrue() expiryDateEditText.append("12") expiryDateEditText.append("50") ViewTestUtils.sendDeleteKeyEvent(expiryDateEditText) assertThat(expiryDateEditText.validatedDate) .isNull() } @Test fun `input with includeSeparatorGaps=true should have expected fieldText and validatedDate values`() { expiryDateEditText.includeSeparatorGaps = true expiryDateEditText.append("12") expiryDateEditText.append("50") assertThat(expiryDateEditText.fieldText) .isEqualTo("12 / 50") assertThat(expiryDateEditText.validatedDate) .isEqualTo(ExpirationDate.Validated(12, 2050)) } @Test fun `input with includeSeparatorGaps=true should correctly handle delete key`() { expiryDateEditText.includeSeparatorGaps = true expiryDateEditText.append("12") expiryDateEditText.append("50") assertThat(expiryDateEditText.fieldText) .isEqualTo("12 / 50") ViewTestUtils.sendDeleteKeyEvent(expiryDateEditText) assertThat(expiryDateEditText.fieldText) .isEqualTo("12 / 5") ViewTestUtils.sendDeleteKeyEvent(expiryDateEditText) assertThat(expiryDateEditText.fieldText) .isEqualTo("12") } @Test fun `test setText with null month`() { expiryDateEditText.setText(null as Int?, null as Int?) assertThat(expiryDateEditText.fieldText) .isEqualTo("") } @Test fun `test setText with month and year`() { expiryDateEditText.setText(3, 4) assertThat(expiryDateEditText.fieldText) .isEqualTo("03/04") } @Test fun verifyAdditionalTextChangeListenerGetTriggeredOnlyOnce() { val textChangeListener = mock<TextWatcher>() expiryDateEditText.addTextChangedListener(textChangeListener) expiryDateEditText.setText("1") idleLooper() verify(textChangeListener, times(1)).afterTextChanged(any()) } @Test fun `when losing focus and has invalid date then error message listener should trigger`() { val errorMessageListener = mock<StripeEditText.ErrorMessageListener>() expiryDateEditText.requestFocus() expiryDateEditText.append("1") expiryDateEditText.setErrorMessageListener(errorMessageListener) expiryDateEditText.clearFocus() idleLooper() verify(errorMessageListener).displayErrorMessage(context.getString(R.string.incomplete_expiry_date)) } @Test fun `when losing focus and has valid date then error message listener should not trigger`() { val errorMessageListener = mock<StripeEditText.ErrorMessageListener>() expiryDateEditText.requestFocus() expiryDateEditText.append("12/50") expiryDateEditText.setErrorMessageListener(errorMessageListener) expiryDateEditText.clearFocus() idleLooper() verifyNoMoreInteractions(errorMessageListener) } @Test fun `when losing focus and has empty text then error message listener should not trigger`() { val errorMessageListener = mock<StripeEditText.ErrorMessageListener>() expiryDateEditText.requestFocus() expiryDateEditText.append("1") expiryDateEditText.setText("") expiryDateEditText.setErrorMessageListener(errorMessageListener) expiryDateEditText.clearFocus() idleLooper() verifyNoMoreInteractions(errorMessageListener) } }
mit
91e1ff9b7762b0ca6d0bf35f6ceaffd6
31.908072
108
0.670164
5.054063
false
true
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/SequenceConstruct.kt
1
2708
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.linalg.api.ops.impl.shape.tensorops.TensorArray import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * A port of sequence_construct.py from onnx tensorflow for samediff: * https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/sequence_construct.py * * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["SequenceConstruct"],frameworkName = "onnx") class SequenceConstruct : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { val outputVarName = outputNames[0] var ret = TensorArray.createTensorArrayFrom(sd,op.inputsToOp.map { input -> sd.getVariable(input) }.toTypedArray(),outputVarName) return mapOf(outputVarName to listOf(ret)) } }
apache-2.0
69b404c114230f1c110e98458d11640c
45.706897
184
0.71935
4.278041
false
false
false
false
pyamsoft/padlock
padlock-base/src/main/java/com/pyamsoft/padlock/base/BaseProvider.kt
1
1612
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.base import androidx.annotation.CheckResult import com.pyamsoft.padlock.model.ForegroundEvent import com.pyamsoft.padlock.model.LockWhitelistedEvent import com.pyamsoft.pydroid.core.bus.Listener import com.pyamsoft.pydroid.core.bus.Publisher import com.pyamsoft.pydroid.core.bus.RxBus import dagger.Module import dagger.Provides @Module object BaseProvider { private val foregroundBus = RxBus.create<ForegroundEvent>() private val whitelistBus = RxBus.create<LockWhitelistedEvent>() @JvmStatic @Provides @CheckResult fun provideForegroundPublisher(): Publisher<ForegroundEvent> = foregroundBus @JvmStatic @Provides @CheckResult fun provideForegroundListener(): Listener<ForegroundEvent> = foregroundBus @JvmStatic @Provides @CheckResult fun provideWhitelistPublisher(): Publisher<LockWhitelistedEvent> = whitelistBus @JvmStatic @Provides @CheckResult fun provideWhitelistListener(): Listener<LockWhitelistedEvent> = whitelistBus }
apache-2.0
cf9e32f45502302b57948027ac2e9be6
28.309091
81
0.782258
4.380435
false
false
false
false
jackping/AppBase
base/src/main/java/com/yima/base/SimpleUi.kt
1
2785
package com.yima.base import android.app.Activity import android.content.Context import android.os.Bundle import android.support.v7.widget.Toolbar import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import me.yokeyword.fragmentation.SupportActivity import me.yokeyword.fragmentation.SupportFragment /** * SimpleActivity * Created by yima on 2017/3/28. */ abstract class SimpleActivity : SupportActivity() { protected lateinit var mContext: Activity var isForeground: Boolean = false private set(value) { field = value } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) inflateView() mContext = this BaseApp.getApp().addActivity(this) } protected fun initToolBar(toolbar: Toolbar?) { setSupportActionBar(toolbar) supportActionBar!!.setDisplayShowTitleEnabled(false) } override fun onDestroy() { super.onDestroy() BaseApp.getApp().removeActivity(this) } protected abstract val layoutId: Int protected open fun inflateView() { setContentView(layoutId) } override fun onResume() { super.onResume() isForeground = true } override fun onPause() { super.onPause() isForeground = false } } /** * SimpleFragment * Created by yima on 2017/3/28. */ abstract class SimpleFragment : SupportFragment() { protected lateinit var mView: View protected lateinit var mActivity: Activity protected lateinit var mContext: Context private var isInit = false override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) mActivity = activity as Activity mContext = context ?: BaseApp.getApp() } override fun onAttach(context: Context?) { super.onAttach(context) mActivity = context as Activity mContext = context } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mView = inflater.inflate(layoutId, null) return mView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (!isHidden) { isInit = true initView() } } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (!isInit && !hidden) { isInit = true initView() } } open fun onKeyDown(keyCode: Int, event: KeyEvent?) = false protected abstract val layoutId: Int protected abstract fun initView() }
apache-2.0
873fcf2077e27fbe8dfa6c44f01cfd6e
24.318182
116
0.667145
5.008993
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/inspections/lints/RsUnreachableCodeInspectionTest.kt
2
7891
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.lints import org.rust.MockAdditionalCfgOptions import org.rust.ProjectDescriptor import org.rust.WithStdlibRustProjectDescriptor import org.rust.ide.inspections.RsInspectionsTestBase class RsUnreachableCodeInspectionTest : RsInspectionsTestBase(RsUnreachableCodeInspection::class) { fun `test straightline with return`() = checkByText(""" fn main() { let x = 1; return; <warning descr="Unreachable code">let y = 2; let z = 3;</warning> } """) fun `test complex code after return`() = checkByText(""" fn foo(flag: bool, bar: bool) { let x = 1; return; <warning descr="Unreachable code">let y = 2; if foo { 1; } 2; if bar { 2; }</warning> } """) fun `test return tail expr`() = checkByText(""" fn main() { return; } """) fun `test unreachable tail expr`() = checkByText(""" fn foo() -> i32 { return 42; <warning descr="Unreachable code">123</warning> } """) fun `test code after loop`() = checkByText(""" fn main() { loop { 1; } <warning descr="Unreachable code">2;</warning> } """) fun `test loop with break`() = checkByText(""" fn foo(flag: bool) { loop { 1; if flag { break; } 2; } 3; } """) fun `test complex loop with break`() = checkByText(""" enum E { A, B } fn foo(e: E, flag: bool) { loop { 1; match e { E::A => { 2; if flag { break; } } E::B => { 3; } } 4; } 5; } """) @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test unreachable in closure call`() = checkByText(""" fn foo(f: fn(i32)) {} fn main() { foo(|x| { if x > 0 { panic!(); <warning descr="Unreachable code">1;</warning> } }); 2; } """) fun `test closure call with loop`() = checkByText(""" fn foo(f: fn(i32)) {} fn main() { foo(|x| { 1; loop { 2; } <warning descr="Unreachable code">3;</warning> }); 4; } """) fun `test if else stmt unconditional return`() = checkByText(""" fn main() { if a { 1; return; <warning descr="Unreachable code">2; 3;</warning> } else { 4; return; <warning descr="Unreachable code">5;</warning> } <warning descr="Unreachable code">6;</warning> } """) fun `test if else tail expr unconditional return`() = checkByText(""" fn foo(flag: bool) { if flag { 1; return; <warning descr="Unreachable code">2; 3;</warning> } else { 4; return; <warning descr="Unreachable code">5;</warning> } } """) fun `test let declaration with unreachable init`() = checkByText(""" fn main() { let x = return; } """) fun `test multiple return`() = checkByText(""" fn main() { return; <warning descr="Unreachable code">1; return; 2; return;</warning> } """) fun `test remove unreachable code fix`() = checkFixByText("Remove unreachable code", """ fn main() { 1; if flag1 { 2; return; <warning descr="Unreachable code">3;/*caret*/ if flag2 { 4; }</warning> } 5; } """, """ fn main() { 1; if flag1 { 2; return; } 5; } """) @MockAdditionalCfgOptions("intellij_rust") fun `test ignore conditionally disabled unreachable code`() = checkByText(""" fn foo() -> i32 { return 1; #[cfg(not(intellij_rust))] return 2; } """) @MockAdditionalCfgOptions("intellij_rust") fun `test annotate conditionally enabled unreachable code`() = checkByText(""" fn foo() -> i32 { return 1; <warning descr="Unreachable code">#[cfg(intellij_rust)] return 2;</warning> } """) fun `test allow unreachable_code`() = checkByText(""" #[allow(unreachable_code)] fn foo() -> i32 { return 1; return 2; } """) fun `test tail macro expr`() = checkByText(""" fn main() { return; <warning descr="Unreachable code">foo!()</warning> } """) fun `test tail unit expr`() = checkByText(""" fn main() { return; <warning descr="Unreachable code">()</warning> } """) fun `test incomplete match expr reachable`() = checkByText(""" fn main() { let x = match 3 { }; return; } """) fun `test incomplete match stmt reachable`() = checkByText(""" enum Foo { A(u32), B } fn main() { match f() { }; return; } fn f() -> Foo { loop {} } """) fun `test incomplete match with noreturn branch`() = checkByText(""" enum Foo { A(u32), B } fn main() { match f() { Foo::B => loop {}, }; <warning descr="Unreachable code">return;</warning> } fn f() -> Foo { loop {} } """) fun `test incomplete match with noreturn discriminant 1`() = checkByText(""" fn main() { <warning descr="Unreachable code">let x = match (loop {}) { }; return;</warning> } """) fun `test incomplete match with noreturn discriminant 2`() = checkByText(""" fn main() { <warning descr="Unreachable code">let x = match (return) { }; return;</warning> } """) fun `test incomplete match with noreturn discriminant 3`() = checkByText(""" fn main() { loop { <warning descr="Unreachable code">let x = match (break) { }; return;</warning> } } """) fun `test incomplete match with noreturn discriminant 4`() = checkByText(""" fn f() -> ! { } fn main() { <warning descr="Unreachable code">let x = match f() { }; return;</warning> } """) // Issue https://github.com/intellij-rust/intellij-rust/issues/9355 @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test no false-positive when todo macro is used`() = checkByText(""" fn foo(a: u32) -> u32 { match a { 42 => todo!(), _ => return 123, } } """) }
mit
7deb027c58ffe326acae0aa26ea97795
24.872131
99
0.424788
4.956658
false
true
false
false
yzbzz/beautifullife
app/src/main/java/com/ddu/ui/fragment/TestFragment.kt
2
18960
//package com.ddu.ui.fragment // //import android.Manifest //import android.content.ActivityNotFoundException //import android.content.Intent //import android.content.pm.PackageManager //import android.graphics.drawable.Drawable //import android.net.Uri //import android.net.http.SslError //import android.os.Bundle //import android.support.v4.app.ActivityCompat //import android.support.v4.content.ContextCompat //import android.text.TextUtils //import android.util.Log //import android.view.LayoutInflater //import android.view.View //import android.webkit.* //import android.widget.LinearLayout //import com.bumptech.glide.Glide //import com.bumptech.glide.request.target.ImageViewTarget //import com.bumptech.glide.request.transition.Transition //import com.ddu.R //import com.ddu.app.BaseApp //import com.ddu.icore.ui.fragment.DefaultFragment //import com.ddu.icore.util.PopupUtils //import com.ddu.icore.util.UrlUtils //import com.ddu.sdk.network.OkHttpUtils //import com.ddu.ui.helper.WebAppInterface //import com.ddu.util.HttpUtils //import kotlinx.android.synthetic.main.fragment_test_web.* //import kotlinx.coroutines.android.UI //import kotlinx.coroutines.async //import okhttp3.* //import org.jetbrains.anko.coroutines.experimental.bg //import org.json.JSONObject //import java.io.IOException //import java.io.InputStream //import java.net.URISyntaxException // ///** // * Created by yzbzz on 16/4/6. // */ //class TestFragment : DefaultFragment() { // // lateinit var mWebSettings: WebSettings // lateinit var mTitle: String // var url: String? = null // // val isLoadFirst: Boolean = false // // val webChromeClient = object : WebChromeClient() { // // override fun onReceivedTitle(view: WebView, title: String) { // super.onReceivedTitle(view, title) // if (!TextUtils.isEmpty(title)) { // setDefaultTitle(title) // } // } // // } // // private val webViewClient = object : WebViewClient() { // // override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) { // handler.proceed() // } // // // override fun onPageFinished(view: WebView, url: String) { // // view.loadUrl("javascript:MyApp.resize(document.querySelector('body').offsetHeight);"); // // view.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)"); // super.onPageFinished(view, url) // // pbWeb.setVisibility(View.GONE); // val title = view.title // if (!TextUtils.isEmpty(title)) { // setDefaultTitle(title) // } // wv_web.visibility = View.VISIBLE // } // // override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { // view.loadUrl(url) // return true // // return super.shouldOverrideUrlLoading(view, data); // } // // } // // override fun initData(savedInstanceState: Bundle?) { // val bundle = arguments // if (null != bundle) { // mTitle = bundle.getString("mTitle") // url = bundle.getString("data") // } // } // // override fun getLayoutId(): Int { // return R.layout.fragment_test_web // } // // override fun initView() { // mWebSettings = wv_web.settings // mWebSettings.javaScriptEnabled = true // mWebSettings.cacheMode = WebSettings.LOAD_NO_CACHE // mWebSettings.setSupportZoom(true) // mWebSettings.useWideViewPort = true // mWebSettings.loadWithOverviewMode = true // // mWebSettings.javaScriptEnabled = true // mWebSettings.javaScriptCanOpenWindowsAutomatically = true // mWebSettings.cacheMode = WebSettings.LOAD_NO_CACHE // mWebSettings.domStorageEnabled = true // mWebSettings.databaseEnabled = true // mWebSettings.setAppCacheEnabled(true) // mWebSettings.allowFileAccess = true // mWebSettings.savePassword = true // mWebSettings.setSupportZoom(true) // mWebSettings.builtInZoomControls = true // mWebSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS // mWebSettings.useWideViewPort = true // // wv_web.webViewClient = webViewClient // wv_web.webChromeClient = webChromeClient // // // reload("protocol.html"); // wv_web.addJavascriptInterface(WebAppInterface(mContext), "SBridge") // wv_web.addJavascriptInterface(this, "SBridge") // initTitle() // btn_reload.setOnClickListener { post() } // // // final ObjectAnimator anim = ObjectAnimator.ofInt(iv_place, "ImageLevel", 0, 10000); // // anim.setDuration(800); // // anim.setRepeatCount(ObjectAnimator.INFINITE); // // anim.start(); // // // // iv_progress.setImageResource(R.drawable.glide_rotate); // // iv_place.setImageResource(R.drawable.glide_rotate); // Glide.with(this).load("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2760457749,4161462131&fm=27&gp=0.jpg").into<ImageViewTarget<Drawable>>(object : ImageViewTarget<Drawable>(iv_place) { // override fun setResource(resource: Drawable?) { // Log.v("lhz", "setResource") // } // // override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) { // super.onResourceReady(resource, transition) // // Log.v("lhz", "onResourceReady"); // iv_place.setImageDrawable(resource) // // pb_loading.setVisibility(View.GONE); // } // // override fun onLoadFailed(errorDrawable: Drawable?) { // super.onLoadFailed(errorDrawable) // // Log.v("lhz", "onLoadFailed"); // } // // override fun onLoadCleared(placeholder: Drawable?) { // super.onLoadCleared(placeholder) // // Log.v("lhz", "onLoadCleared"); // } // }) // // // GlideApp.with(this).load("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2760457749,4161462131&fm=27&gp=0.jpg").listener(new RequestListener<Drawable>() { // // @Override // // public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { // // Log.v("lhz", "onLoadFailed"); // // return false; // // } // // // // @Override // // public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { // // Log.v("lhz", "onResourceReady"); // // return false; // // } // // }).into(new ImageViewTarget<Drawable>(iv_place) { // // @Override // // protected void setResource(@Nullable Drawable resource) { // // iv_place.setImageDrawable(resource); // // Log.v("lhz", "setResource"); // // } // // }); // } // // private fun post1(appId: String, appSecret: String) { // val token = async(UI) { // val urlParams = hashMapOf<String, String>() // urlParams.put("grant_type", "client_credential") // urlParams.put("appid", appId) // urlParams.put("secret", appSecret) // // val getUrl = OkHttpUtils.appendUrl("https://api.weixin.qq.com/cgi-bin/token", urlParams) // val okHttpClient = OkHttpClient().newBuilder().build() // val builder = Request.Builder() // builder.url(getUrl) // // val request = builder.build() // val call = okHttpClient.newCall(request) // val response = bg { // call.execute() // } // val data = response.await().body()?.string() // val jsonObject = JSONObject(data) // val tokenString = jsonObject["access_token"] as String // return@async tokenString // } // } // // fun excute(method: String, json: String) { // BaseApp.post(Runnable { wv_web.loadUrl("javascript:$method($json)") }) // } // // // private fun post() { // // val okHttpClient = OkHttpClient().newBuilder().build() // val builder = Request.Builder() // // val jsonObject = JSONObject() // try { // jsonObject.put("scene", "park2218") // jsonObject.put("page", "pages/main/main") // jsonObject.put("width", 1024) // jsonObject.put("auto_color", true) // // val jsonObject1 = JSONObject() // jsonObject1.put("r", "0") // jsonObject1.put("g", "0") // jsonObject1.put("b", "0") // // jsonObject.put("line_color", jsonObject1) // } catch (e: Exception) { // // } // // val line_color = jsonObject.toString() // Log.v("lhz", "data: " + line_color) // val JSON = MediaType.parse("application/json;charset=utf-8") // // val requestBody = RequestBody.create(JSON, line_color) // builder.addHeader("content-type", "application/json;charset:utf-8") // // val appId = "" // val appSecret = "" // val token = getToken(appId, appSecret) // async { // val accessToken = token.await() as String // val url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken // builder.url(url) // builder.post(requestBody) // val request = builder.build() // // val call = okHttpClient.newCall(request) // val response = bg { // call.execute() // } // val responseBody = response.await().body() // saveAdData(responseBody?.byteStream()!!) // } // } // // inline fun getToken(appId: String, appSecret: String) = async { // val urlParams = hashMapOf<String, String>() // urlParams.put("grant_type", "client_credential") // urlParams.put("appid", appId) // urlParams.put("secret", appSecret) // // val getUrl = OkHttpUtils.appendUrl("https://api.weixin.qq.com/cgi-bin/token", urlParams) // val okHttpClient = OkHttpClient().newBuilder().build() // val builder = Request.Builder() // builder.url(getUrl) // // val request = builder.build() // val call = okHttpClient.newCall(request) // val response = bg { // call.execute() // } // val data = response.await().body()?.string() // val jsonObject = JSONObject(data) // val token = jsonObject["access_token"] // return@async token // } // // // private fun saveAdData(inputStream: InputStream) { // val isGranted = ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED // if (!isGranted) { // ActivityCompat.requestPermissions(mActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0) // } else { // HttpUtils.saveAd(inputStream) // } // } // // private fun getQRCode() { // // } // // // private fun reload(xml: String) { // wv_web.clearView() // wv_web.measure(10, 10) // val am = mContext.assets // try { // val `is` = am.open(xml) // val buffer = ByteArray(10000) // `is`.read(buffer) // val data = String(buffer) // wv_web.loadData(data, "text/html; charset=UTF-8", null) // wv_web.requestLayout() // } catch (e: IOException) { // e.printStackTrace() // } // // } // // @JavascriptInterface // fun resize(json: String) { // Log.v("lhz", "json: " + json) // wv_web.post { // try { // val jsonObject = JSONObject(json) // val type = jsonObject.getString("type") // val height = jsonObject.getDouble("height") // Log.v("lhz", "height: " + height + " " + wv_web.height) // val heightT = (height * resources.displayMetrics.density).toInt() // wv_web.layoutParams = LinearLayout.LayoutParams(resources.displayMetrics.widthPixels, heightT) // } catch (e: Exception) { // // } // } // } // // private fun initTitle() { // setDefaultTitle(mTitle) // setRightImg(R.drawable.ic_more_add_selector, object : View.OnClickListener { // override fun onClick(v: View?) { // wv_web.pageUp(true) // } // }) // setRightImg(R.drawable.ic_more_add_selector, object : View.OnClickListener { // override fun onClick(v: View?) { // } // }) // titleBar?.setOnClickListener { } // // setTitleBarOnClickListener(object : View.OnClickListener { // override fun onClick(v: View?) { // wv_web.pageUp(true) // } // }) // } // // private fun showPopupWindow(v: View) { // val view = LayoutInflater.from(mContext).inflate(R.layout.fragemt_web_more_popup, null) // // PopupUtils.showTopRightPopupWindow(baseActivity, v, view); // // PopupUtils.showPopupWindow(view).showAtLocation(v.getParent(), Gravity.RIGHT,); // PopupUtils.showPopupWindow(view).showAsDropDown(v) // } // // private fun startActivityForUrl(url: String): Boolean { // var intent: Intent // // perform generic parsing of the URI to turn it into an Intent. // try { // intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME) // } catch (ex: URISyntaxException) { // Log.w("Browser", "Bad URI " + url + ": " + ex.message) // return false // } // // // check whether the intent can be resolved. If not, we will see // // whether we can download it from the Market. // // if (mContext.packageManager.resolveActivity(intent, 0) == null) { // val packagename = intent.`package` // if (packagename != null) { // try { // intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:" + packagename)) // intent.addCategory(Intent.CATEGORY_BROWSABLE) // startActivity(intent) // } catch (e: Exception) { // e.printStackTrace() // baseActivity.finish() // return false // } // // // before leaving BrowserActivity, close the empty child tab. // // If a new tab is created through JavaScript open to load this // // data, we would like to close it as we will load this data in a // // different Activity. // // mController.closeEmptyTab(); // return true // } else { // return false // } // } // // // sanitize the Intent, ensuring web pages can not bypass browser // // security (only access to BROWSABLE activities). // intent.addCategory(Intent.CATEGORY_BROWSABLE) // intent.component = null // // Re-use the existing tab if the intent comes back to us // // if (tab != null) { // // if (tab.getAppId() == null) { // // tab.setAppId(mActivity.getPackageName() + "-" + tab.getId()); // // } // // intent.putExtra(Browser.EXTRA_APPLICATION_ID, tab.getAppId()); // // } // // Make sure webkit can handle it ly before checking for specialized // // handlers. If webkit can't handle it ly, we need to call // // startActivityIfNeeded // val m = UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url) // if (m.matches()) { //&& !isSpecializedHandlerAvailable(intent)) { // return false // } // try { // intent.putExtra(UrlUtils.EXTRA_DISABLE_URL_OVERRIDE, true) // if (baseActivity.startActivityIfNeeded(intent, -1)) { // // before leaving BrowserActivity, close the empty child tab. // // If a new tab is created through JavaScript open to load this // // data, we would like to close it as we will load this data in a // // different Activity. // // mController.closeEmptyTab(); // return true // } // } catch (ex: ActivityNotFoundException) { // // ignore the error. If no application can handle the URL, // // eg about:blank, assume the browser can handle it. // } // // return false // } // // private fun isSpecializedHandlerAvailable(intent: Intent): Boolean { // val pm = mContext.packageManager // val handlers = pm.queryIntentActivities(intent, PackageManager.GET_RESOLVED_FILTER) // if (handlers == null || handlers.size == 0) { // return false // } // for (resolveInfo in handlers) { // val filter = resolveInfo.filter ?: // No intent filter matches this intent? // // Error on the side of staying in the browser, ignore // continue // if (filter.countDataAuthorities() == 0 && filter.countDataPaths() == 0) { // // Generic handler, skip // continue // } // return true // } // return false // } // // override fun onDestroy() { // super.onDestroy() // if (null != wv_web) { // wv_web.removeAllViews() // wv_web.destroy() // } // } // // companion object { // // // fun newInstance(title: String, url: String): TestFragment { // val fragment = TestFragment() // val args = Bundle() // args.putString("mTitle", title) // args.putString("data", url) // fragment.arguments = args // return fragment // } // // // fun appendUrl(url: String?, urlParams: Map<String, String>?): String { // if (null == url) { // return "" // } // if (urlParams == null || urlParams.size <= 0) { // return url // } // val httpUrl = HttpUrl.parse(url) ?: return url // val urlBuilder = httpUrl.newBuilder() // for ((key, value) in urlParams) { // urlBuilder.addQueryParameter(key, value) // } // return urlBuilder.build().toString() // } // } //}
apache-2.0
4e27ad565463912201f2f6d3748a5860
38.092784
208
0.556329
3.97401
false
false
false
false
androidx/androidx
camera/integration-tests/coretestapp/src/androidTest/java/androidx/camera/integration/core/util/YuvToRgbConverter.kt
3
8475
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 androidx.camera.integration.core.util import android.content.Context import android.graphics.Bitmap import android.graphics.ImageFormat import android.graphics.Rect import android.media.Image /** * Copy from the github for testing. * Please reference: https://github.com/android/camera-samples/ * * Helper class used to efficiently convert a Media.Image object from * [ImageFormat.YUV_420_888] format to an RGB [Bitmap] object. * * The [yuvToRgb] method is able to achieve the same FPS as the CameraX image * analysis use case on a Pixel 3 XL device at the default analyzer resolution, * which is 30 FPS with 640x480. * * NOTE: This has been tested in a limited number of devices and is not * considered production-ready code. It was created for illustration purposes, * since this is not an efficient camera pipeline due to the multiple copies * required to convert each frame. */ @Suppress("DEPRECATION") class YuvToRgbConverter(context: Context) { private val rs = android.renderscript.RenderScript.create(context) private val scriptYuvToRgb = android.renderscript.ScriptIntrinsicYuvToRGB.create( rs, android.renderscript.Element.U8_4(rs) ) private var pixelCount: Int = -1 private lateinit var yuvBuffer: ByteArray private lateinit var inputAllocation: android.renderscript.Allocation private lateinit var outputAllocation: android.renderscript.Allocation @Synchronized fun yuvToRgb(image: Image, output: Bitmap) { // Ensure that the intermediate output byte buffer is allocated if (!::yuvBuffer.isInitialized) { pixelCount = image.cropRect.width() * image.cropRect.height() // Bits per pixel is an average for the whole image, so it's useful to compute the size // of the full buffer but should not be used to determine pixel offsets val pixelSizeBits = ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888) yuvBuffer = ByteArray(pixelCount * pixelSizeBits / 8) } // Get the YUV data in byte array form using NV21 format imageToByteArray(image, yuvBuffer) // Ensure that the RenderScript inputs and outputs are allocated if (!::inputAllocation.isInitialized) { // Explicitly create an element with type NV21, since that's the pixel format we use val elemType = android.renderscript.Type.Builder(rs, android.renderscript.Element.YUV(rs)) .setYuvFormat(ImageFormat.NV21).create() inputAllocation = android.renderscript.Allocation.createSized(rs, elemType.element, yuvBuffer.size) } if (!::outputAllocation.isInitialized) { outputAllocation = android.renderscript.Allocation.createFromBitmap(rs, output) } // Convert NV21 format YUV to RGB inputAllocation.copyFrom(yuvBuffer) scriptYuvToRgb.setInput(inputAllocation) scriptYuvToRgb.forEach(outputAllocation) outputAllocation.copyTo(output) } private fun imageToByteArray(image: Image, outputBuffer: ByteArray) { assert(image.format == ImageFormat.YUV_420_888) val imageCrop = image.cropRect val imagePlanes = image.planes imagePlanes.forEachIndexed { planeIndex, plane -> // How many values are read in input for each output value written // Only the Y plane has a value for every pixel, U and V have half the resolution i.e. // // Y Plane U Plane V Plane // =============== ======= ======= // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y U U U U V V V V // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y val outputStride: Int // The index in the output buffer the next value will be written at // For Y it's zero, for U and V we start at the end of Y and interleave them i.e. // // First chunk Second chunk // =============== =============== // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y V U V U V U V U // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y // Y Y Y Y Y Y Y Y var outputOffset: Int when (planeIndex) { 0 -> { outputStride = 1 outputOffset = 0 } 1 -> { outputStride = 2 // For NV21 format, U is in odd-numbered indices outputOffset = pixelCount + 1 } 2 -> { outputStride = 2 // For NV21 format, V is in even-numbered indices outputOffset = pixelCount } else -> { // Image contains more than 3 planes, something strange is going on return@forEachIndexed } } val planeBuffer = plane.buffer val rowStride = plane.rowStride val pixelStride = plane.pixelStride // We have to divide the width and height by two if it's not the Y plane val planeCrop = if (planeIndex == 0) { imageCrop } else { Rect( imageCrop.left / 2, imageCrop.top / 2, imageCrop.right / 2, imageCrop.bottom / 2 ) } val planeWidth = planeCrop.width() val planeHeight = planeCrop.height() // Intermediate buffer used to store the bytes of each row val rowBuffer = ByteArray(plane.rowStride) // Size of each row in bytes val rowLength = if (pixelStride == 1 && outputStride == 1) { planeWidth } else { // Take into account that the stride may include data from pixels other than this // particular plane and row, and that could be between pixels and not after every // pixel: // // |---- Pixel stride ----| Row ends here --> | // | Pixel 1 | Other Data | Pixel 2 | Other Data | ... | Pixel N | // // We need to get (N-1) * (pixel stride bytes) per row + 1 byte for the last pixel (planeWidth - 1) * pixelStride + 1 } for (row in 0 until planeHeight) { // Move buffer position to the beginning of this row planeBuffer.position( (row + planeCrop.top) * rowStride + planeCrop.left * pixelStride ) if (pixelStride == 1 && outputStride == 1) { // When there is a single stride value for pixel and output, we can just copy // the entire row in a single step planeBuffer.get(outputBuffer, outputOffset, rowLength) outputOffset += rowLength } else { // When either pixel or output have a stride > 1 we must copy pixel by pixel planeBuffer.get(rowBuffer, 0, rowLength) for (col in 0 until planeWidth) { outputBuffer[outputOffset] = rowBuffer[col * pixelStride] outputOffset += outputStride } } } } } }
apache-2.0
718e2be3d6f2b33604a6e3503f52e8b0
40.544118
99
0.561888
4.697894
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/custom/view/EllipsizingTextView.kt
1
11710
/* * Copyright (C) 2011 Micah Hainline * Copyright (C) 2012 Triposo * Copyright (C) 2013 Paul Imhoff * Copyright (C) 2014 Shahin Yousefi * * 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.sedsoftware.yaptalker.presentation.custom.view import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.text.Layout import android.text.Layout.Alignment import android.text.SpannableStringBuilder import android.text.Spanned import android.text.StaticLayout import android.text.TextUtils import android.text.TextUtils.TruncateAt import android.util.AttributeSet import android.widget.TextView import com.mikepenz.iconics.view.IconicsTextView import java.util.ArrayList import java.util.regex.Pattern /** * A [android.widget.TextView] that ellipsizes more intelligently. * This class supports ellipsizing multiline text through setting `android:ellipsize` * and `android:maxLines`. */ @Suppress("UnsafeCallOnNullableType") class EllipsizingTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = android.R.attr.textViewStyle ) : IconicsTextView(context, attrs, defStyle) { interface EllipsizeListener { fun ellipsizeStateChanged(ellipsized: Boolean) } companion object { private const val ELLIPSIS = "\u2026" private val DEFAULT_END_PUNCTUATION = Pattern.compile("[.!?,;:\u2026]*$", Pattern.DOTALL) } private val mEllipsizeListeners = ArrayList<EllipsizeListener>() private var mEllipsizeStrategy: EllipsizeStrategy? = null private var isEllipsized: Boolean = false private var isStale: Boolean = false private var programmaticChange: Boolean = false private var mFullText: CharSequence? = null private var mMaxLines: Int = 0 private var mLineSpacingMult = 1.0f private var mLineAddVertPad = 0.0f private var mEndPunctPattern: Pattern? = null init { val attr = context.obtainStyledAttributes(attrs, intArrayOf(android.R.attr.maxLines), defStyle, 0) maxLines = attr.getInt(0, Integer.MAX_VALUE) attr.recycle() setEndPunctuationPattern(DEFAULT_END_PUNCTUATION) } private fun setEndPunctuationPattern(pattern: Pattern) { mEndPunctPattern = pattern } @SuppressLint("Override") override fun getMaxLines(): Int = mMaxLines override fun setMaxLines(maxLines: Int) { super.setMaxLines(maxLines) mMaxLines = maxLines isStale = true } fun ellipsizingLastFullyVisibleLine(): Boolean = mMaxLines == Integer.MAX_VALUE override fun setLineSpacing(add: Float, mult: Float) { mLineAddVertPad = add mLineSpacingMult = mult super.setLineSpacing(add, mult) } override fun setText(text: CharSequence, type: TextView.BufferType) { if (!programmaticChange) { mFullText = text isStale = true } super.setText(text, type) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) if (ellipsizingLastFullyVisibleLine()) isStale = true } override fun setPadding(left: Int, top: Int, right: Int, bottom: Int) { super.setPadding(left, top, right, bottom) if (ellipsizingLastFullyVisibleLine()) isStale = true } override fun onDraw(canvas: Canvas) { if (isStale) resetText() super.onDraw(canvas) } private fun resetText() { val maxLines = maxLines var workingText = mFullText var ellipsized = false if (maxLines != -1) { if (mEllipsizeStrategy == null) ellipsize = null workingText = mEllipsizeStrategy!!.processText(mFullText) ellipsized = !mEllipsizeStrategy!!.isInLayout(mFullText) } if (workingText != text) { programmaticChange = true try { text = workingText } finally { programmaticChange = false } } isStale = false if (ellipsized != isEllipsized) { isEllipsized = ellipsized for (listener in mEllipsizeListeners) { listener.ellipsizeStateChanged(ellipsized) } } } override fun setEllipsize(where: TruncateAt?) { if (where == null) { mEllipsizeStrategy = EllipsizeNoneStrategy() return } when (where) { TextUtils.TruncateAt.END -> mEllipsizeStrategy = EllipsizeEndStrategy() TextUtils.TruncateAt.START -> mEllipsizeStrategy = EllipsizeStartStrategy() TextUtils.TruncateAt.MIDDLE -> mEllipsizeStrategy = EllipsizeMiddleStrategy() TextUtils.TruncateAt.MARQUEE -> { super.setEllipsize(where) isStale = false mEllipsizeStrategy = EllipsizeNoneStrategy() } else -> mEllipsizeStrategy = EllipsizeNoneStrategy() } } private abstract inner class EllipsizeStrategy { protected val linesCount: Int get() { return if (ellipsizingLastFullyVisibleLine()) { val fullyVisibleLinesCount = fullyVisibleLinesCount if (fullyVisibleLinesCount == -1) 1 else fullyVisibleLinesCount } else { mMaxLines } } protected val fullyVisibleLinesCount: Int get() { val layout = createWorkingLayout("") val height = height - compoundPaddingTop - compoundPaddingBottom val lineHeight = layout.getLineBottom(0) return height / lineHeight } fun processText(text: CharSequence?): CharSequence? = if (!isInLayout(text)) createEllipsizedText(text) else text fun isInLayout(text: CharSequence?): Boolean { val layout = createWorkingLayout(text) return layout.lineCount <= linesCount } protected fun createWorkingLayout(workingText: CharSequence?): Layout = StaticLayout( workingText, paint, measuredWidth - paddingLeft - paddingRight, Alignment.ALIGN_NORMAL, mLineSpacingMult, mLineAddVertPad, false /* includepad */ ) protected abstract fun createEllipsizedText(fullText: CharSequence?): CharSequence? } private inner class EllipsizeNoneStrategy : EllipsizeStrategy() { override fun createEllipsizedText(fullText: CharSequence?): CharSequence? = fullText } private inner class EllipsizeEndStrategy : EllipsizeStrategy() { override fun createEllipsizedText(fullText: CharSequence?): CharSequence { val layout = createWorkingLayout(fullText) val cutOffIndex = layout.getLineEnd(mMaxLines - 1) val textLength = fullText!!.length var cutOffLength = textLength - cutOffIndex if (cutOffLength < ELLIPSIS.length) cutOffLength = ELLIPSIS.length var workingText = TextUtils.substring(fullText, 0, textLength - cutOffLength).trim { it <= ' ' } var strippedText = stripEndPunctuation(workingText) while (!isInLayout(strippedText + ELLIPSIS)) { val lastSpace = workingText.lastIndexOf(' ') if (lastSpace == -1) break workingText = workingText.substring(0, lastSpace).trim { it <= ' ' } strippedText = stripEndPunctuation(workingText) } workingText = strippedText + ELLIPSIS val dest = SpannableStringBuilder(workingText) if (fullText is Spanned) { TextUtils.copySpansFrom(fullText as Spanned?, 0, workingText.length, null, dest, 0) } return dest } fun stripEndPunctuation(workingText: CharSequence): String = mEndPunctPattern!!.matcher(workingText).replaceFirst("") } private inner class EllipsizeStartStrategy : EllipsizeStrategy() { override fun createEllipsizedText(fullText: CharSequence?): CharSequence { val layout = createWorkingLayout(fullText) val cutOffIndex = layout.getLineEnd(mMaxLines - 1) val textLength = fullText!!.length var cutOffLength = textLength - cutOffIndex if (cutOffLength < ELLIPSIS.length) cutOffLength = ELLIPSIS.length var workingText = TextUtils.substring(fullText, cutOffLength, textLength).trim { it <= ' ' } while (!isInLayout(ELLIPSIS + workingText)) { val firstSpace = workingText.indexOf(' ') if (firstSpace == -1) break workingText = workingText.substring(firstSpace, workingText.length).trim { it <= ' ' } } workingText = ELLIPSIS + workingText val dest = SpannableStringBuilder(workingText) if (fullText is Spanned) { TextUtils.copySpansFrom( fullText as Spanned?, textLength - workingText.length, textLength, null, dest, 0 ) } return dest } } private inner class EllipsizeMiddleStrategy : EllipsizeStrategy() { override fun createEllipsizedText(fullText: CharSequence?): CharSequence { val layout = createWorkingLayout(fullText) val cutOffIndex = layout.getLineEnd(mMaxLines - 1) val textLength = fullText!!.length var cutOffLength = textLength - cutOffIndex if (cutOffLength < ELLIPSIS.length) cutOffLength = ELLIPSIS.length cutOffLength += cutOffIndex % 2 // Make it even. var firstPart = TextUtils.substring( fullText, 0, textLength / 2 - cutOffLength / 2 ).trim { it <= ' ' } var secondPart = TextUtils.substring( fullText, textLength / 2 + cutOffLength / 2, textLength ).trim { it <= ' ' } while (!isInLayout(firstPart + ELLIPSIS + secondPart)) { val lastSpaceFirstPart = firstPart.lastIndexOf(' ') val firstSpaceSecondPart = secondPart.indexOf(' ') if (lastSpaceFirstPart == -1 || firstSpaceSecondPart == -1) break firstPart = firstPart.substring(0, lastSpaceFirstPart).trim { it <= ' ' } secondPart = secondPart.substring(firstSpaceSecondPart, secondPart.length).trim { it <= ' ' } } val firstDest = SpannableStringBuilder(firstPart) val secondDest = SpannableStringBuilder(secondPart) if (fullText is Spanned) { TextUtils.copySpansFrom(fullText as Spanned?, 0, firstPart.length, null, firstDest, 0) TextUtils.copySpansFrom( fullText as Spanned?, textLength - secondPart.length, textLength, null, secondDest, 0 ) } return TextUtils.concat(firstDest, ELLIPSIS, secondDest) } } }
apache-2.0
1ecafed6c1b9efe681d8e28fbdc5475b
36.652733
109
0.630316
4.809035
false
false
false
false
mvaldez/kotlin-examples
src/ii_collections/_15_AllAnyAndOtherPredicates.kt
1
1118
package ii_collections fun example2(list: List<Int>) { val isZero: (Int) -> Boolean = { it == 0 } val hasZero: Boolean = list.any(isZero) val allZeros: Boolean = list.all(isZero) val numberOfZeros: Int = list.count(isZero) val firstPositiveNumber: Int? = list.firstOrNull { it > 0 } } fun Customer.isFrom(city: City): Boolean { return this.city == city } fun Shop.checkAllCustomersAreFrom(city: City): Boolean { // Return true if all customers are from the given city return this.getCustomersFrom(city).size == this.customers.size } fun Shop.hasCustomerFrom(city: City): Boolean { // Return true if there is at least one customer from the given city return this.customers.filter { it.city == city }.size > 0 } fun Shop.countCustomersFrom(city: City): Int { // Return the number of customers from the given city return this.customers.filter { it.city == city }.size } fun Shop.findAnyCustomerFrom(city: City): Customer? { // Return a customer who lives in the given city, or null if there is none return this.customers.find { it -> it.city == city } }
mit
9091a2bce77f281f0a8f8ce2ddc985c9
28.421053
78
0.690519
3.73913
false
false
false
false
myTrackerSDK/mytracker-android
myTrackerDemo/app/src/main/java/com/my/mytrackerdemoapp/MainActivity.kt
1
2962
package com.my.mytrackerdemoapp import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.my.tracker.MyTracker import java.util.* class MainActivity : AppCompatActivity() { fun trackLogin(ignored: View) { // you can add custom params you want to track to all events // can be omitted or null val eventCustomParams: MutableMap<String, String> = HashMap() eventCustomParams["someParamKey"] = "someParamValue" MyTracker.trackLoginEvent("custom_user_id", "vk_connect_id", eventCustomParams) Toast.makeText(this, "Tracking login", Toast.LENGTH_SHORT).show() } fun trackInvite(ignored: View) { MyTracker.trackInviteEvent() Toast.makeText(this, "Tracking invite", Toast.LENGTH_SHORT).show() } fun trackRegistration(ignored: View) { MyTracker.trackRegistrationEvent("custom_user_id", "vk_connect_id") Toast.makeText(this, "Tracking registration", Toast.LENGTH_SHORT).show() } fun trackPurchase(ignored: View) { // Create buy bundle // Bundle buyIntentBundle = callMethodToReceiveBundle(); // Extracting pending intent from bundle // PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); // Starting intent sender // startIntentSenderForResult(pendingIntent.getIntentSender(), // PURCHASE_REQUEST_CODE, // new Intent(), // 0, // 0, // 0); } fun trackLevel(ignored: View) { MyTracker.trackLevelEvent() Toast.makeText(this, "Tracking level", Toast.LENGTH_SHORT).show() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) MyTracker.getTrackerConfig().isTrackingEnvironmentEnabled = true handleDeeplink(intent) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) handleDeeplink(intent) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Checking if the request code is PURCHASE_REQUEST_CODE if (PURCHASE_REQUEST_CODE == requestCode) { MyTracker.onActivityResult(resultCode, data) } } fun handleDeeplink(intent: Intent?) { Toast.makeText(this, "Handling deeplink", Toast.LENGTH_SHORT).show() val deeplink: String? = MyTracker.handleDeeplink(intent) if (deeplink.isNullOrEmpty()) { return } Toast.makeText(this, "Deeplink tracked: $deeplink", Toast.LENGTH_SHORT).show() } companion object { const val PURCHASE_REQUEST_CODE = 1001 } }
lgpl-3.0
a4b567f224f8963725c00b4e696b54bc
28.929293
87
0.645172
4.47432
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/commands/music/dj/MoveCommand.kt
1
1550
package xyz.gnarbot.gnar.commands.music.dj import xyz.gnarbot.gnar.commands.* import xyz.gnarbot.gnar.commands.music.MusicCommandExecutor import xyz.gnarbot.gnar.commands.template.parser.Parsers import xyz.gnarbot.gnar.music.MusicManager @Command( aliases = ["move"], description = "Move the bot to another channel." ) @BotInfo( id = 77, category = Category.MUSIC, scope = Scope.VOICE, roleRequirement = "DJ" ) class MoveCommand : MusicCommandExecutor(false, false) { override fun execute(context: Context, label: String, args: Array<String>, manager: MusicManager) { val targetChannel = if (args.isEmpty()) { context.voiceChannel } else { Parsers.VOICE_CHANNEL.parse(context, args.joinToString(" ")) } if (targetChannel == null) { context.send().error("That's not a valid music channel.").queue() return } if (targetChannel == context.selfMember.voiceState?.channel) { context.send().error("That's the same channel.").queue() return } if (context.data.music.channels.isNotEmpty()) { if (targetChannel.id !in context.data.music.channels) { context.send().error("Can not join `${targetChannel.name}`, it isn't one of the designated music channels.").queue() return } } context.guild.audioManager.openAudioConnection(targetChannel) // assume magic from VoiceListener.kt } }
mit
554a9b5b81980f9eaa83c05850fcb68d
32.695652
132
0.623871
4.353933
false
false
false
false
inorichi/tachiyomi-extensions
src/en/mangarockes/src/eu/kanade/tachiyomi/extension/en/mangarockes/MangaRockEs.kt
1
12357
package eu.kanade.tachiyomi.extension.en.mangarockes import com.github.salomonbrys.kotson.fromJson import com.google.gson.Gson import com.google.gson.JsonArray import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import kotlin.experimental.and import kotlin.experimental.xor class MangaRockEs : ParsedHttpSource() { override val name = "MangaRock.es" override val baseUrl = "https://mangarock.es" override val lang = "en" override val supportsLatest = true // Handles the page decoding override val client: OkHttpClient = network.cloudflareClient.newBuilder().addInterceptor( fun(chain): Response { val url = chain.request().url.toString() val response = chain.proceed(chain.request()) if (!url.endsWith(".mri")) return response val decoded: ByteArray = decodeMri(response) val mediaType = "image/webp".toMediaTypeOrNull() val rb = decoded.toResponseBody(mediaType) return response.newBuilder().body(rb).build() } ).build() // Popular override fun popularMangaRequest(page: Int) = GET("$baseUrl/manga/$page?sort=rank", headers) override fun popularMangaSelector() = "div.col-five" override fun popularMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("h3 a").let { title = it.text() setUrlWithoutDomain(it.attr("href")) } thumbnail_url = element.select("img").attr("abs:src") } } override fun popularMangaNextPageSelector() = "a.page-link:contains(next)" // Latest override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/manga/latest/$page?sort=date", headers) override fun latestUpdatesSelector() = "div.product-item-detail" override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() // Search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return if (query.isNotBlank()) { GET("$baseUrl/search/${query.replace(" ", "+")}/$page", headers) } else { val url = ("$baseUrl/manga" + if (page > 1) "/$page" else "").toHttpUrl().newBuilder() filters.forEach { filter -> when (filter) { is StatusFilter -> url.addQueryParameter("status", filter.toUriPart()) is RankFilter -> url.addQueryParameter("rank", filter.toUriPart()) is SortBy -> url.addQueryParameter("sort", filter.toUriPart()) is GenreList -> { val genres = filter.state .filter { it.state } .joinToString(".") { it.uriPart } url.addQueryParameter("genres", genres) } } } GET(url.toString(), headers) } } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() // Details override fun mangaDetailsParse(document: Document) = SManga.create().apply { return SManga.create().apply { document.select("div.block-info-manga").let { info -> thumbnail_url = info.select("div.thumb_inner").attr("style") .substringAfter("'").substringBefore("'") title = info.select("h1").text() author = info.select("div.author_item").text() status = info.select("div.status_chapter_item").text().substringBefore(" ").let { when { it.contains("Ongoing", ignoreCase = true) -> SManga.ONGOING it.contains("Completed", ignoreCase = true) -> SManga.COMPLETED else -> SManga.UNKNOWN } } } genre = document.select("div.tags a").joinToString { it.text() } description = document.select("div.full.summary p").filterNot { it.text().isNullOrEmpty() }.joinToString("\n") } } // Chapters override fun chapterListSelector(): String = "tbody[data-test=chapter-table] tr" override fun chapterFromElement(element: Element): SChapter { return SChapter.create().apply { element.select("a").let { name = it.text() setUrlWithoutDomain(it.attr("href")) } date_upload = element.select("td").lastOrNull()?.text()?.let { date -> if (date.contains("ago", ignoreCase = true)) { val trimmedDate = date.substringBefore(" ago").removeSuffix("s").split(" ") val calendar = Calendar.getInstance() when (trimmedDate[1]) { "day" -> calendar.apply { add(Calendar.DAY_OF_MONTH, -trimmedDate[0].toInt()) } "hour" -> calendar.apply { add(Calendar.HOUR_OF_DAY, -trimmedDate[0].toInt()) } "minute" -> calendar.apply { add(Calendar.MINUTE, -trimmedDate[0].toInt()) } "second" -> calendar.apply { add(Calendar.SECOND, -trimmedDate[0].toInt()) } } calendar.timeInMillis } else { SimpleDateFormat("MMM d, yyyy", Locale.US).parse(date)?.time ?: 0L } } ?: 0 } } // Pages private val gson by lazy { Gson() } override fun pageListParse(response: Response): List<Page> { val responseString = response.body!!.string() return Regex("""mangaData = (\[.*]);""", RegexOption.IGNORE_CASE).find(responseString)?.groupValues?.get(1)?.let { array -> gson.fromJson<JsonArray>(array) .mapIndexed { i, jsonElement -> Page(i, "", jsonElement.asJsonObject["url"].asString) } } ?: Regex("""getManga\(\d+, '(http.*)',""").findAll(responseString).toList() .mapIndexed { i, mr -> Page(i, "", mr.groupValues[1]) } } override fun pageListParse(document: Document): List<Page> = throw UnsupportedOperationException("This method should not be called!") override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("This method should not be called!") // Filters // See drawWebpToCanvas function in the site's client.js file // Extracted code: https://jsfiddle.net/6h2sLcs4/30/ private fun decodeMri(response: Response): ByteArray { val data = response.body!!.bytes() // Decode file if it starts with "E" (space when XOR-ed later) if (data[0] != 69.toByte()) return data // Reconstruct WEBP header // Doc: https://developers.google.com/speed/webp/docs/riff_container#webp_file_header val buffer = ByteArray(data.size + 15) val size = data.size + 7 buffer[0] = 82 // R buffer[1] = 73 // I buffer[2] = 70 // F buffer[3] = 70 // F buffer[4] = (255.toByte() and size.toByte()) buffer[5] = (size ushr 8).toByte() and 255.toByte() buffer[6] = (size ushr 16).toByte() and 255.toByte() buffer[7] = (size ushr 24).toByte() and 255.toByte() buffer[8] = 87 // W buffer[9] = 69 // E buffer[10] = 66 // B buffer[11] = 80 // P buffer[12] = 86 // V buffer[13] = 80 // P buffer[14] = 56 // 8 // Decrypt file content using XOR cipher with 101 as the key val cipherKey = 101.toByte() for (r in data.indices) { buffer[r + 15] = cipherKey xor data[r] } return buffer } // Filters private class StatusFilter : UriPartFilter( "Status", arrayOf( Pair("All", "all"), Pair("Completed", "completed"), Pair("Ongoing", "ongoing") ) ) private class RankFilter : UriPartFilter( "Rank", arrayOf( Pair("All", "all"), Pair("1 - 999", "1-999"), Pair("1k - 2k", "1000-2000"), Pair("2k - 3k", "2000-3000"), Pair("3k - 4k", "3000-4000"), Pair("4k - 5k", "4000-5000"), Pair("5k - 6k", "5000-6000"), Pair("6k - 7k", "6000-7000"), Pair("7k - 8k", "7000-8000"), Pair("8k - 9k", "8000-9000"), Pair("9k - 19k", "9000-10000"), Pair("10k - 11k", "10000-11000") ) ) private class SortBy : UriPartFilter( "Sort by", arrayOf( Pair("Name", "name"), Pair("Rank", "rank") ) ) private class Genre(name: String, val uriPart: String) : Filter.CheckBox(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Genres", genres) override fun getFilterList() = FilterList( // Search and filter don't work at the same time Filter.Header("NOTE: Ignored if using text search!"), Filter.Separator(), StatusFilter(), RankFilter(), SortBy(), GenreList(getGenreList()) ) // [...document.querySelectorAll('._2DMqI .mdl-checkbox')].map(n => `Genre("${n.querySelector('.mdl-checkbox__label').innerText}", "${n.querySelector('input').dataset.oid}")`).sort().join(',\n') // on https://mangarock.com/manga private fun getGenreList() = listOf( Genre("4-koma", "4-koma"), Genre("Action", "action"), Genre("Adult", "adult"), Genre("Adventure", "adventure"), Genre("Comedy", "comedy"), Genre("Demons", "demons"), Genre("Doujinshi", "doujinshi"), Genre("Drama", "drama"), Genre("Ecchi", "ecchi"), Genre("Fantasy", "fantasy"), Genre("Gender Bender", "gender-bender"), Genre("Harem", "harem"), Genre("Historical", "historical"), Genre("Horror", "horror"), Genre("Isekai", "isekai"), Genre("Josei", "josei"), Genre("Kids", "kids"), Genre("Magic", "magic"), Genre("Martial Arts", "martial-arts"), Genre("Mature", "mature"), Genre("Mecha", "mecha"), Genre("Military", "military"), Genre("Music", "music"), Genre("Mystery", "mystery"), Genre("One Shot", "one-shot"), Genre("Parody", "parody"), Genre("Police", "police"), Genre("Psychological", "psychological"), Genre("Romance", "romance"), Genre("School Life", "school-life"), Genre("Sci-Fi", "sci-fi"), Genre("Seinen", "seinen"), Genre("Shoujo Ai", "shoujo-ai"), Genre("Shoujo", "shoujo"), Genre("Shounen Ai", "shounen-ai"), Genre("Shounen", "shounen"), Genre("Slice of Life", "slice-of-life"), Genre("Smut", "smut"), Genre("Space", "space"), Genre("Sports", "sports"), Genre("Super Power", "super-power"), Genre("Supernatural", "supernatural"), Genre("Tragedy", "tragedy"), Genre("Vampire", "vampire"), Genre("Webtoons", "webtoons"), Genre("Yaoi", "yaoi"), Genre("Yuri", "yuri") ) private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } }
apache-2.0
8cd1d0bd4621e885f31b9c179d581331
37.138889
198
0.573521
4.386581
false
false
false
false
googleads/googleads-mobile-android-examples
kotlin/admanager/InterstitialExample/app/src/main/kotlin/com/google/android/gms/example/interstitialexample/MyActivity.kt
1
5952
/* * Copyright (C) 2013 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.example.interstitialexample import android.os.Bundle import android.os.CountDownTimer import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.ads.AdError import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.MobileAds import com.google.android.gms.ads.admanager.AdManagerAdRequest import com.google.android.gms.ads.admanager.AdManagerInterstitialAd import com.google.android.gms.ads.admanager.AdManagerInterstitialAdLoadCallback import com.google.android.gms.example.interstitialexample.databinding.ActivityMyBinding const val GAME_LENGTH_MILLISECONDS: Long = 3000 const val AD_UNIT_ID = "/6499/example/interstitial" /** Main Activity. Inflates main activity xml. */ class MyActivity : AppCompatActivity() { private lateinit var binding: ActivityMyBinding private var mInterstitialAd: AdManagerInterstitialAd? = null private var mCountDownTimer: CountDownTimer? = null private var mGameIsInProgress: Boolean = false private var mAdIsLoading: Boolean = false private var mTimerMilliseconds: Long = 0 private var TAG = "MyActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMyBinding.inflate(layoutInflater) val view = binding.root setContentView(view) // Log the Mobile Ads SDK version. Log.d(TAG, "Google Mobile Ads SDK Version: " + MobileAds.getVersion()) // Initialize the Mobile Ads SDK with an empty completion listener. MobileAds.initialize(this) {} loadAd() // Create the "retry" button, which tries to show an interstitial between game plays. binding.retryButton.visibility = View.INVISIBLE binding.retryButton.setOnClickListener { showInterstitial() } startGame() } private fun loadAd() { var adRequest = AdManagerAdRequest.Builder().build() AdManagerInterstitialAd.load( this, AD_UNIT_ID, adRequest, object : AdManagerInterstitialAdLoadCallback() { override fun onAdFailedToLoad(adError: LoadAdError) { Log.d(TAG, adError?.message) mInterstitialAd = null mAdIsLoading = false val error = "domain: ${adError.domain}, code: ${adError.code}, " + "message: ${adError.message}" Toast.makeText( this@MyActivity, "onAdFailedToLoad() with error $error", Toast.LENGTH_SHORT ) .show() } override fun onAdLoaded(interstitialAd: AdManagerInterstitialAd) { Log.d(TAG, "Ad was loaded.") mInterstitialAd = interstitialAd mAdIsLoading = false Toast.makeText(this@MyActivity, "onAdLoaded()", Toast.LENGTH_SHORT).show() } } ) } private fun createTimer(milliseconds: Long) { // Create the game timer, which counts down to the end of the level // and shows the "retry" button. mCountDownTimer?.cancel() mCountDownTimer = object : CountDownTimer(milliseconds, 50) { override fun onTick(millisUntilFinished: Long) { mTimerMilliseconds = millisUntilFinished binding.timer.text = getString(R.string.seconds_remaining, (millisUntilFinished / 1000 + 1)) } override fun onFinish() { mGameIsInProgress = false binding.timer.setText(R.string.done) binding.retryButton.visibility = View.VISIBLE } } } public override fun onResume() { // Start or resume the game. super.onResume() if (mGameIsInProgress) { resumeGame(mTimerMilliseconds) } } public override fun onPause() { // Cancel the timer if the game is paused. mCountDownTimer?.cancel() super.onPause() } private fun showInterstitial() { // Show the ad if it's ready. Otherwise toast and restart the game. if (mInterstitialAd != null) { mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() { override fun onAdDismissedFullScreenContent() { mInterstitialAd = null Log.d(TAG, "Ad was dismissed.") } override fun onAdFailedToShowFullScreenContent(adError: AdError) { mInterstitialAd = null Log.d(TAG, "Ad failed to show.") } override fun onAdShowedFullScreenContent() { Log.d(TAG, "Ad showed fullscreen content.") startGame() } } mInterstitialAd?.show(this) } else { Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show() startGame() } } private fun startGame() { // Request a new ad if one isn't already loaded, hide the button, and kick off the timer. if (!mAdIsLoading && mInterstitialAd == null) { mAdIsLoading = true loadAd() } binding.retryButton.visibility = View.INVISIBLE resumeGame(GAME_LENGTH_MILLISECONDS) } private fun resumeGame(milliseconds: Long) { // Create a new timer for the correct length and start it. mGameIsInProgress = true mTimerMilliseconds = milliseconds createTimer(milliseconds) mCountDownTimer?.start() } }
apache-2.0
69e016960fa7d33000a4576a5c6887bd
31.703297
96
0.683636
4.445108
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course/interactor/CourseEnrollmentInteractor.kt
1
4747
package org.stepik.android.domain.course.interactor import io.reactivex.Completable import io.reactivex.Single import io.reactivex.subjects.PublishSubject import okhttp3.ResponseBody import org.stepic.droid.analytic.Analytic import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.util.then import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.course.repository.CourseRepository import org.stepik.android.domain.course.repository.EnrollmentRepository import org.stepik.android.domain.lesson.repository.LessonRepository import org.stepik.android.domain.personal_deadlines.repository.DeadlinesRepository import org.stepik.android.domain.user_courses.interactor.UserCoursesInteractor import org.stepik.android.domain.wishlist.interactor.WishlistInteractor import org.stepik.android.domain.wishlist.model.WishlistOperationData import org.stepik.android.model.Course import org.stepik.android.presentation.wishlist.model.WishlistAction import org.stepik.android.view.injection.course.EnrollmentCourseUpdates import retrofit2.HttpException import retrofit2.Response import ru.nobird.android.core.model.mutate import java.net.HttpURLConnection import javax.inject.Inject class CourseEnrollmentInteractor @Inject constructor( private val analytic: Analytic, private val enrollmentRepository: EnrollmentRepository, private val sharedPreferenceHelper: SharedPreferenceHelper, private val courseRepository: CourseRepository, private val lessonRepository: LessonRepository, private val deadlinesRepository: DeadlinesRepository, @EnrollmentCourseUpdates private val enrollmentSubject: PublishSubject<Course>, private val userCoursesInteractor: UserCoursesInteractor, private val wishlistInteractor: WishlistInteractor ) { companion object { private val UNAUTHORIZED_EXCEPTION_STUB = HttpException(Response.error<Nothing>(HttpURLConnection.HTTP_UNAUTHORIZED, ResponseBody.create(null, ""))) } private val requireAuthorization: Completable = Completable.create { emitter -> if (sharedPreferenceHelper.authResponseFromStore != null) { emitter.onComplete() } else { emitter.onError(UNAUTHORIZED_EXCEPTION_STUB) } } fun fetchCourseEnrollmentAfterPurchaseInWeb(courseId: Long): Completable = requireAuthorization then courseRepository .getCourse(courseId, sourceType = DataSourceType.REMOTE, allowFallback = false) .toSingle() .flatMapCompletable { course -> if (course.enrollment > 0) { userCoursesInteractor.addUserCourse(course.id) .andThen(lessonRepository.removeCachedLessons(course.id)) .doOnComplete { enrollmentSubject.onNext(course) } } else { Completable.complete() } } fun enrollCourse(courseId: Long): Single<Course> = requireAuthorization then enrollmentRepository .addEnrollment(courseId) .andThen(userCoursesInteractor.addUserCourse(courseId)) .andThen(lessonRepository.removeCachedLessons(courseId)) .andThen(removeCourseFromWishlist(courseId)) .andThen(courseRepository.getCourse(courseId, sourceType = DataSourceType.REMOTE, allowFallback = false).toSingle()) .doOnSuccess(enrollmentSubject::onNext) // notify everyone about changes fun dropCourse(courseId: Long): Single<Course> = requireAuthorization then enrollmentRepository .removeEnrollment(courseId) .andThen(deadlinesRepository.removeDeadlineRecordByCourseId(courseId).onErrorComplete()) .andThen(userCoursesInteractor.removeUserCourse(courseId)) .andThen(lessonRepository.removeCachedLessons(courseId)) .andThen(courseRepository.getCourse(courseId, sourceType = DataSourceType.REMOTE, allowFallback = false).toSingle()) .doOnSuccess(enrollmentSubject::onNext) // notify everyone about changes private fun removeCourseFromWishlist(courseId: Long): Completable = wishlistInteractor .getWishlist(dataSourceType = DataSourceType.CACHE) .flatMapCompletable { wishlistEntity -> val updatedWishlist = wishlistEntity.copy( courses = wishlistEntity.courses.mutate { remove(courseId) } ) wishlistInteractor .updateWishlistWithOperation(updatedWishlist, WishlistOperationData(courseId, WishlistAction.REMOVE)) .ignoreElement() } }
apache-2.0
bd5309e198adcf7155edc0ac7865eb2d
44.653846
128
0.724458
5.382086
false
false
false
false
quarck/SmartNotify
app/src/main/java/com/github/quarck/smartnotify/CallStateTracker.kt
1
3368
/* * Copyright (c) 2014, Sergey Parshin, [email protected] * 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 developer (Sergey Parshin) nor the * names of other project 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 <COPYRIGHT HOLDER> 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 com.github.quarck.smartnotify import android.content.Context import android.telephony.PhoneStateListener import android.telephony.TelephonyManager class CallStateTracker : PhoneStateListener() { private var global: GlobalState? = null override fun onCallStateChanged(state: Int, incomingNumber: String?) { var isOnCall = false Lw.d(TAG, "onCallStateChanged, new state: " + state) when (state) { TelephonyManager.CALL_STATE_RINGING -> { isOnCall = true Lw.d(TAG, "CALL_STATE_RINGING") } TelephonyManager.CALL_STATE_OFFHOOK -> { isOnCall = true Lw.d(TAG, "CALL_STATE_OFFHOOK") } TelephonyManager.CALL_STATE_IDLE -> { isOnCall = false Lw.d(TAG, "CALL_STATE_IDLE") } } if (incomingNumber != null) Lw.d(TAG, "incomingNumber = " + incomingNumber) if (global != null) global!!.isOnCall = isOnCall else Lw.e(TAG, "Can't access global state") } private fun register(ctx: Context) { Lw.d(TAG, "Registering listener") val tm = ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager tm.listen(this, PhoneStateListener.LISTEN_CALL_STATE) global = GlobalState.instance(ctx) } @SuppressWarnings("unused") private fun unregister(ctx: Context) { Lw.d(TAG, "Unregistering listener") val tm = ctx.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager tm.listen(this, PhoneStateListener.LISTEN_NONE) } companion object { private val TAG = "CallStateTracker" private var instance: CallStateTracker? = null fun start(ctx: Context) { Lw.d(TAG, "start()") synchronized (CallStateTracker::class.java) { if (instance == null) instance = CallStateTracker() instance!!.register(ctx) } } } }
bsd-3-clause
15bd8a58bf8bc322c36be73f2a0cdacd
29.080357
87
0.724466
3.849143
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/ui/wedgit/entity/RatioImageView.kt
1
4659
package com.gkzxhn.mygithub.ui.wedgit.entity import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.widget.ImageView import com.gkzxhn.mygithub.R /** * Created by 方 on 2018/1/24. */ class RatioImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ImageView(context, attrs, defStyleAttr) { /* 优先级从大到小: mIsWidthFitDrawableSizeRatio mIsHeightFitDrawableSizeRatio mWidthRatio mHeightRatio 即如果设置了mIsWidthFitDrawableSizeRatio为true,则优先级较低的三个值不生效 */ private var mDrawableSizeRatio = -1f // src图片(前景图)的宽高比例 // 根据前景图宽高比例测量View,防止图片缩放变形 private var mIsWidthFitDrawableSizeRatio: Boolean = false // 宽度是否根据src图片(前景图)的比例来测量(高度已知) private var mIsHeightFitDrawableSizeRatio: Boolean = false // 高度是否根据src图片(前景图)的比例来测量(宽度已知) // 宽高比例 private var mWidthRatio = -1f // 宽度 = 高度*mWidthRatio private var mHeightRatio = -1f // 高度 = 宽度*mHeightRatio init { init(attrs) // 一定要有此代码 if (getDrawable() != null) { mDrawableSizeRatio = 1f * getDrawable().getIntrinsicWidth() / getDrawable().getIntrinsicHeight() } }// 虽然此处会调用setImageDrawable,但此时成员变量还未被正确初始化 /** * 初始化变量 */ private fun init(attrs: AttributeSet?) { val a = getContext().obtainStyledAttributes(attrs, R.styleable.RatioImageView) mIsWidthFitDrawableSizeRatio = a.getBoolean(R.styleable.RatioImageView_is_width_fix_drawable_size_ratio, mIsWidthFitDrawableSizeRatio) mIsHeightFitDrawableSizeRatio = a.getBoolean(R.styleable.RatioImageView_is_height_fix_drawable_size_ratio, mIsHeightFitDrawableSizeRatio) mHeightRatio = a.getFloat( R.styleable.RatioImageView_height_to_width_ratio, mHeightRatio) mWidthRatio = a.getFloat( R.styleable.RatioImageView_width_to_height_ratio, mWidthRatio) a.recycle() } override fun setImageResource(resId: Int) { super.setImageResource(resId) if (getDrawable() != null) { mDrawableSizeRatio = 1f * getDrawable().getIntrinsicWidth() / getDrawable().getIntrinsicHeight() if (mDrawableSizeRatio > 0 && (mIsWidthFitDrawableSizeRatio || mIsHeightFitDrawableSizeRatio)) { requestLayout() } } } override fun setImageDrawable(drawable: Drawable) { super.setImageDrawable(drawable) if (getDrawable() != null) { mDrawableSizeRatio = 1f * getDrawable().getIntrinsicWidth() / getDrawable().getIntrinsicHeight() if (mDrawableSizeRatio > 0 && (mIsWidthFitDrawableSizeRatio || mIsHeightFitDrawableSizeRatio)) { requestLayout() } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // 优先级从大到小: // mIsWidthFitDrawableSizeRatio mIsHeightFitDrawableSizeRatio // mWidthRatio mHeightRatio if (mDrawableSizeRatio > 0) { // 根据前景图宽高比例来测量view的大小 if (mIsWidthFitDrawableSizeRatio) { mWidthRatio = mDrawableSizeRatio } else if (mIsHeightFitDrawableSizeRatio) { mHeightRatio = 1 / mDrawableSizeRatio } } if (mHeightRatio > 0 && mWidthRatio > 0) { throw RuntimeException("高度和宽度不能同时设置百分比!!") } if (mWidthRatio > 0) { // 高度已知,根据比例,设置宽度 val height = MeasureSpec.getSize(heightMeasureSpec) super.onMeasure(MeasureSpec.makeMeasureSpec( (height * mWidthRatio).toInt(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)) } else if (mHeightRatio > 0) { // 宽度已知,根据比例,设置高度 val width = MeasureSpec.getSize(widthMeasureSpec) super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec( (width * mHeightRatio).toInt(), MeasureSpec.EXACTLY)) } else { // 系统默认测量 super.onMeasure(widthMeasureSpec, heightMeasureSpec) } } }
gpl-3.0
3be1b65aeb99bced17d3caa0ba11ffb4
38.716981
160
0.652649
4.110352
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSgv.kt
1
1171
package info.nightscout.androidaps.plugins.general.nsclient.data import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject /** * * {"mgdl":105,"mills":1455136282375,"device":"xDrip-BluetoothWixel","direction":"Flat","filtered":98272,"unfiltered":98272,"noise":1,"rssi":100} */ @Suppress("SpellCheckingInspection") class NSSgv(val data: JSONObject) { val mgdl: Int? get() = JsonHelper.safeGetIntAllowNull(data, "mgdl") val filtered: Int? get() = JsonHelper.safeGetIntAllowNull(data, "filtered") val unfiltered: Int? get() = JsonHelper.safeGetIntAllowNull(data, "unfiltered") val noise: Int? get() = JsonHelper.safeGetIntAllowNull(data, "noise") val rssi: Int? get() = JsonHelper.safeGetIntAllowNull(data, "rssi") val mills: Long? get() = JsonHelper.safeGetLongAllowNull(data, "mills") val device: String? get() = JsonHelper.safeGetStringAllowNull(data, "device", null) val direction: String? get() = JsonHelper.safeGetStringAllowNull(data, "direction", null) val id: String? get() = JsonHelper.safeGetStringAllowNull(data, "_id", null) }
agpl-3.0
647b42e8f1c9a33701db09fb81d436f6
35.625
145
0.685739
3.890365
false
false
false
false
hurricup/intellij-community
platform/configuration-store-impl/src/ComponentStoreImpl.kt
1
19303
/* * 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 com.intellij.configurationStore import com.intellij.notification.NotificationsManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runBatchUpdate import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.* import com.intellij.openapi.components.StateStorage.SaveSession import com.intellij.openapi.components.StateStorageChooserEx.Resolution import com.intellij.openapi.components.impl.ComponentManagerImpl import com.intellij.openapi.components.impl.stores.* import com.intellij.openapi.components.impl.stores.StateStorageManager.ExternalizationSession import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.util.InvalidDataException import com.intellij.openapi.util.JDOMExternalizable import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.NamedJDOMExternalizable import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.ui.AppUIUtil import com.intellij.util.ArrayUtilRt import com.intellij.util.SmartList import com.intellij.util.containers.SmartHashSet import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.messages.MessageBus import com.intellij.util.xmlb.JDOMXIncluder import gnu.trove.THashMap import io.netty.util.internal.SystemPropertyUtil import org.jdom.Element import org.jetbrains.annotations.TestOnly import java.io.IOException import java.nio.file.Paths import java.util.* import java.util.concurrent.CopyOnWriteArrayList import com.intellij.openapi.util.Pair as JBPair internal val LOG = Logger.getInstance(ComponentStoreImpl::class.java) internal val deprecatedComparator = Comparator<Storage> { o1, o2 -> val w1 = if (o1.deprecated) 1 else 0 val w2 = if (o2.deprecated) 1 else 0 w1 - w2 } abstract class ComponentStoreImpl : IComponentStore { private val components = Collections.synchronizedMap(THashMap<String, Any>()) private val settingsSavingComponents = CopyOnWriteArrayList<SettingsSavingComponent>() internal open val project: Project? get() = null open val loadPolicy: StateLoadPolicy get() = StateLoadPolicy.LOAD abstract val storageManager: StateStorageManager override final fun getStateStorageManager() = storageManager override final fun initComponent(component: Any, service: Boolean) { if (component is SettingsSavingComponent) { settingsSavingComponents.add(component) } var componentName = "" try { @Suppress("DEPRECATION") if (component is PersistentStateComponent<*>) { val stateSpec = StoreUtil.getStateSpec(component) componentName = stateSpec.name doAddComponent(componentName, component) if (initPersistentComponent(stateSpec, component, null, false) && service) { // if not service, so, component manager will check it later for all components project?.let { val app = ApplicationManager.getApplication() if (!app.isHeadlessEnvironment && !app.isUnitTestMode && it.isInitialized) { notifyUnknownMacros(this, it, componentName) } } } } else if (component is JDOMExternalizable) { componentName = ComponentManagerImpl.getComponentName(component) @Suppress("DEPRECATION") initJdomExternalizable(component, componentName) } } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { LOG.error("Cannot init ${componentName} component state", e) return } } override fun save(readonlyFiles: MutableList<JBPair<StateStorage.SaveSession, VirtualFile>>) { var errors: MutableList<Throwable>? = null val externalizationSession = if (components.isEmpty()) null else storageManager.startExternalization() if (externalizationSession != null) { val names = ArrayUtilRt.toStringArray(components.keys) Arrays.sort(names) val timeLogPrefix = "Saving" val timeLog = if (LOG.isDebugEnabled) StringBuilder(timeLogPrefix) else null for (name in names) { val start = if (timeLog == null) 0 else System.currentTimeMillis() try { commitComponent(externalizationSession, components.get(name)!!, name) } catch (e: Throwable) { if (errors == null) { errors = SmartList<Throwable>() } errors.add(Exception("Cannot get ${name} component state", e)) } timeLog?.let { val duration = System.currentTimeMillis() - start if (duration > 10) { it.append("\n").append(name).append(" took ").append(duration).append(" ms: ").append((duration / 60000)).append(" min ").append(((duration % 60000) / 1000)).append("sec") } } } if (timeLog != null && timeLog.length > timeLogPrefix.length) { LOG.debug(timeLog.toString()) } } for (settingsSavingComponent in settingsSavingComponents) { try { settingsSavingComponent.save() } catch (e: Throwable) { if (errors == null) { errors = SmartList<Throwable>() } errors.add(e) } } if (externalizationSession != null) { errors = doSave(externalizationSession.createSaveSessions(), readonlyFiles, errors) } CompoundRuntimeException.throwIfNotEmpty(errors) } override @TestOnly fun saveApplicationComponent(component: Any) { val externalizationSession = storageManager.startExternalization() ?: return commitComponent(externalizationSession, component, null) val sessions = externalizationSession.createSaveSessions() if (sessions.isEmpty()) { return } val absolutePath: String val state = StoreUtil.getStateSpec(component.javaClass) if (state != null) { absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(state.storages).path)).toAbsolutePath().toString() } else if (component is ExportableApplicationComponent && component is NamedJDOMExternalizable) { absolutePath = PathManager.getOptionsFile(component).absolutePath } else { throw AssertionError("${component.javaClass} doesn't have @State annotation and doesn't implement ExportableApplicationComponent") } runWriteAction { try { VfsRootAccess.allowRootAccess(absolutePath) CompoundRuntimeException.throwIfNotEmpty(doSave(sessions)) } finally { VfsRootAccess.disallowRootAccess(absolutePath) } } } private fun commitComponent(session: ExternalizationSession, component: Any, componentName: String?) { @Suppress("DEPRECATION") if (component is PersistentStateComponent<*>) { component.state?.let { val stateSpec = StoreUtil.getStateSpec(component) session.setState(getStorageSpecs(component, stateSpec, StateStorageOperation.WRITE), component, componentName ?: stateSpec.name, it) } } else if (component is JDOMExternalizable) { session.setStateInOldStorage(component, componentName ?: ComponentManagerImpl.getComponentName(component), component) } } protected open fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>> = arrayListOf(), prevErrors: MutableList<Throwable>? = null): MutableList<Throwable>? { var errors = prevErrors for (session in saveSessions) { errors = executeSave(session, readonlyFiles, prevErrors) } return errors } private fun initJdomExternalizable(@Suppress("DEPRECATION") component: JDOMExternalizable, componentName: String): String? { doAddComponent(componentName, component) if (loadPolicy != StateLoadPolicy.LOAD) { return null } try { getDefaultState(component, componentName, Element::class.java)?.let { component.readExternal(it) } } catch (e: Throwable) { LOG.error(e) } val element = storageManager.getOldStorage(component, componentName, StateStorageOperation.READ)?.getState(component, componentName, Element::class.java, null, false) ?: return null try { component.readExternal(element) } catch (e: InvalidDataException) { LOG.error(e) return null } return componentName } private fun doAddComponent(name: String, component: Any) { val existing = components.put(name, component) if (existing != null && existing !== component) { components.put(name, existing) LOG.error("Conflicting component name '$name': ${existing.javaClass} and ${component.javaClass}") } } private fun <T: Any> initPersistentComponent(stateSpec: State, component: PersistentStateComponent<T>, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean { if (loadPolicy == StateLoadPolicy.NOT_LOAD) { return false } val name = stateSpec.name val stateClass = ComponentSerializationUtil.getStateClass<T>(component.javaClass) if (!stateSpec.defaultStateAsResource && LOG.isDebugEnabled && getDefaultState(component, name, stateClass) != null) { LOG.error("$name has default state, but not marked to load it") } val defaultState = if (stateSpec.defaultStateAsResource) getDefaultState(component, name, stateClass) else null if (loadPolicy == StateLoadPolicy.LOAD) { val storageSpecs = getStorageSpecs(component, stateSpec, StateStorageOperation.READ) val storageChooser = component as? StateStorageChooserEx for (storageSpec in storageSpecs) { if (storageChooser?.getResolution(storageSpec, StateStorageOperation.READ) == Resolution.SKIP) { continue } val storage = storageManager.getStateStorage(storageSpec) // todo "ProjectModuleManager" investigate why after loadState we get empty state on getState, test CMakeWorkspaceContentRootsTest // use.loaded.state.as.existing used in upsource val stateGetter = if (isUseLoadedStateAsExisting(storage) && name != "AntConfiguration" && name != "ProjectModuleManager" && name != "DeprecatedModuleOptionManager" /* doesn't make sense to check it */ && SystemPropertyUtil.getBoolean("use.loaded.state.as.existing", true)) { (storage as? StorageBaseEx<*>)?.createGetSession(component, name, stateClass) } else { null } var state = if (stateGetter == null) storage.getState(component, name, stateClass, defaultState, reloadData) else stateGetter.getState(defaultState) if (state == null) { if (changedStorages != null && changedStorages.contains(storage)) { // state will be null if file deleted // we must create empty (initial) state to reinit component state = DefaultStateSerializer.deserializeState(Element("state"), stateClass, null)!! } else { continue } } try { component.loadState(state) } finally { stateGetter?.close() } return true } } // we load default state even if isLoadComponentState false - required for app components (for example, at least one color scheme must exists) if (defaultState != null) { component.loadState(defaultState) } return true } protected open fun isUseLoadedStateAsExisting(storage: StateStorage): Boolean = (storage as? XmlElementStorage)?.roamingType != RoamingType.DISABLED protected open fun getPathMacroManagerForDefaults(): PathMacroManager? = null private fun <T : Any> getDefaultState(component: Any, componentName: String, stateClass: Class<T>): T? { val url = DecodeDefaultsUtil.getDefaults(component, componentName) ?: return null try { val documentElement = JDOMXIncluder.resolve(JDOMUtil.loadDocument(url), url.toExternalForm()).detachRootElement() getPathMacroManagerForDefaults()?.expandPaths(documentElement) return DefaultStateSerializer.deserializeState(documentElement, stateClass, null) } catch (e: Throwable) { throw IOException("Error loading default state from $url", e) } } protected open fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): Array<out Storage> { val storages = stateSpec.storages if (storages.size == 1 || component is StateStorageChooserEx) { return storages } if (storages.isEmpty()) { if (stateSpec.defaultStateAsResource) { return storages } throw AssertionError("No storage specified") } return storages.sortByDeprecated() } override final fun isReloadPossible(componentNames: MutableSet<String>) = !componentNames.any { isNotReloadable(it) } private fun isNotReloadable(component: Any?) = component != null && (component !is PersistentStateComponent<*> || !StoreUtil.getStateSpec(component).reloadable) fun getNotReloadableComponents(componentNames: Collection<String>): Collection<String> { var notReloadableComponents: MutableSet<String>? = null for (componentName in componentNames) { if (isNotReloadable(components[componentName])) { if (notReloadableComponents == null) { notReloadableComponents = LinkedHashSet<String>() } notReloadableComponents.add(componentName) } } return notReloadableComponents ?: emptySet<String>() } override final fun reloadStates(componentNames: MutableSet<String>, messageBus: MessageBus) { runBatchUpdate(messageBus) { reinitComponents(componentNames) } } override final fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) { val stateSpec = StoreUtil.getStateSpecOrError(componentClass) @Suppress("UNCHECKED_CAST") val component = components[stateSpec.name] as PersistentStateComponent<Any>? if (component != null) { initPersistentComponent(stateSpec, component, emptySet(), true) } } private fun reloadState(componentName: String, changedStorages: Set<StateStorage>): Boolean { @Suppress("UNCHECKED_CAST") val component = components[componentName] as PersistentStateComponent<Any>? if (component == null) { return false } else { val changedStoragesEmpty = changedStorages.isEmpty() initPersistentComponent(StoreUtil.getStateSpec(component), component, if (changedStoragesEmpty) null else changedStorages, changedStoragesEmpty) return true } } /** * null if reloaded * empty list if nothing to reload * list of not reloadable components (reload is not performed) */ fun reload(changedStorages: Set<StateStorage>): Collection<String>? { if (changedStorages.isEmpty()) { return emptySet() } val componentNames = SmartHashSet<String>() for (storage in changedStorages) { try { // we must update (reload in-memory storage data) even if non-reloadable component will be detected later // not saved -> user does own modification -> new (on disk) state will be overwritten and not applied storage.analyzeExternalChangesAndUpdateIfNeed(componentNames) } catch (e: Throwable) { LOG.error(e) } } if (componentNames.isEmpty) { return emptySet() } val notReloadableComponents = getNotReloadableComponents(componentNames) reinitComponents(componentNames, changedStorages, notReloadableComponents) return if (notReloadableComponents.isEmpty()) null else notReloadableComponents } // used in settings repository plugin /** * You must call it in batch mode (use runBatchUpdate) */ fun reinitComponents(componentNames: Set<String>, changedStorages: Set<StateStorage> = emptySet(), notReloadableComponents: Collection<String> = emptySet()) { for (componentName in componentNames) { if (!notReloadableComponents.contains(componentName)) { reloadState(componentName, changedStorages) } } } @TestOnly fun removeComponent(name: String) { components.remove(name) } } internal fun executeSave(session: SaveSession, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>>, previousErrors: MutableList<Throwable>?): MutableList<Throwable>? { var errors = previousErrors try { session.save() } catch (e: ReadOnlyModificationException) { LOG.warn(e) readonlyFiles.add(JBPair.create<SaveSession, VirtualFile>(e.session ?: session, e.file)) } catch (e: Exception) { if (errors == null) { errors = SmartList<Throwable>() } errors.add(e) } return errors } private fun findNonDeprecated(storages: Array<Storage>): Storage { for (storage in storages) { if (!storage.deprecated) { return storage } } throw AssertionError("All storages are deprecated") } enum class StateLoadPolicy { LOAD, LOAD_ONLY_DEFAULT, NOT_LOAD } internal fun Array<Storage>.sortByDeprecated(): Array<out Storage> { if (isEmpty()) { return this } if (!this[0].deprecated) { var othersAreDeprecated = true for (i in 1..size - 1) { if (!this[i].deprecated) { othersAreDeprecated = false break } } if (othersAreDeprecated) { return this } } return sortedArrayWith(deprecatedComparator) } private fun notifyUnknownMacros(store: IComponentStore, project: Project, componentName: String) { val substitutor = store.stateStorageManager.macroSubstitutor ?: return val immutableMacros = substitutor.getUnknownMacros(componentName) if (immutableMacros.isEmpty()) { return } val macros = LinkedHashSet(immutableMacros) AppUIUtil.invokeOnEdt(Runnable { var notified: MutableList<String>? = null val manager = NotificationsManager.getNotificationsManager() for (notification in manager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) { if (notified == null) { notified = SmartList<String>() } notified.addAll(notification.macros) } if (!notified.isNullOrEmpty()) { macros.removeAll(notified!!) } if (macros.isEmpty()) { return@Runnable } LOG.debug("Reporting unknown path macros $macros in component $componentName") StorageUtil.doNotify(macros, project, Collections.singletonMap(substitutor, store)) }, project.disposed) }
apache-2.0
69e7ba7b4795a97824b9eb4f0b3bf037
35.769524
209
0.709372
4.959661
false
false
false
false
maurocchi/chesslave
backend/src/main/java/io/chesslave/model/Rules.kt
2
5596
package io.chesslave.model import io.chesslave.extensions.and import io.chesslave.extensions.defined import io.chesslave.extensions.exists import io.chesslave.extensions.undefined import io.chesslave.model.Move.Regular.Variation.EnPassant import io.chesslave.model.Piece.Type import io.vavr.collection.HashSet import io.vavr.collection.List import io.vavr.collection.Set import io.vavr.collection.Stream import io.vavr.kotlin.component1 import io.vavr.kotlin.component2 /** * TODO: Handle pawn promotion. * @return all the available moves (excluding castling) of the piece placed at the given square for the specified position. */ fun Position.moves(from: Square): Set<Move.Regular> = at(from) ?.let { piece -> val asRegular = { to: Square -> Move.Regular(from, to) } val isFreeOrWithOpponent = { move: Move.Regular -> at(move.to)?.let { piece.isOpponent(it) } ?: true } val isKingSafeAfterMove = { move: Move.Regular -> move.apply(this).isKingSafe(piece.color) } val isAvailable = isFreeOrWithOpponent and isKingSafeAfterMove when (piece.type) { Type.PAWN -> pawnMoves(from).filter(isKingSafeAfterMove) Type.KING -> from.kingSquares().map(asRegular).filter(isAvailable) Type.KNIGHT -> from.knightSquares().map(asRegular).filter(isAvailable) Type.BISHOP -> from.bishopSquaresIn(this).map(asRegular).filter(isAvailable) Type.ROOK -> from.rookSquaresIn(this).map(asRegular).filter(isAvailable) Type.QUEEN -> from.queenSquaresIn(this).map(asRegular).filter(isAvailable) } } ?: HashSet.empty() /** * @return all the moves available for the specified color. */ fun Position.allMoves(color: Color): Stream<Move.Regular> = this.toSet().toStream() .filter { (_, piece) -> piece.color == color } .flatMap { (square) -> moves(square) } /** * @return true if the king of the given color is not under attack in this position. */ fun Position.isKingSafe(color: Color): Boolean = !Square.all() .find { at(it) == Piece.kingOf(color) }.get() .isTargetForColor(this, color.opponent()) /** * @return true if this square is under attack or defence by pieces of the specified color. */ fun Square.isTargetForColor(position: Position, color: Color): Boolean = knightSquares().exists { position.at(it) == Piece.knightOf(color) } || bishopSquaresIn(position).exists { position.at(it) == Piece.bishopOf(color) } || rookSquaresIn(position).exists { position.at(it) == Piece.rookOf(color) } || queenSquaresIn(position).exists { position.at(it) == Piece.queenOf(color) } || kingSquares().exists { position.at(it) == Piece.kingOf(color) } || pawnCaptureSquares(color.opponent()).exists { position.at(it) == Piece.pawnOf(color) } /** * @return the pieces candidates to promotion if this piece is promotable in the given square, null otherwise */ fun Piece.candidatesForPromotion(square: Square): List<Piece>? { val promotionRow = if (color === Color.WHITE) 7 else 0 return if (type == Type.PAWN && square.row == promotionRow) List.of(Piece.queenOf(color), Piece.rookOf(color), Piece.knightOf(color), Piece.bishopOf(color)) else null } private fun Square.kingSquares() = translateAll( Pair(+0, +1), Pair(+1, +1), Pair(+1, +0), Pair(+1, -1), Pair(+0, -1), Pair(-1, -1), Pair(-1, +0), Pair(-1, +1)) private fun Square.knightSquares() = translateAll( Pair(+1, +2), Pair(+2, +1), Pair(+2, -1), Pair(+1, -2), Pair(-1, -2), Pair(-2, -1), Pair(-2, +1), Pair(-1, +2)) private fun Square.bishopSquaresIn(position: Position): Set<Square> = HashSet.of(walk(+1, +1), walk(+1, -1), walk(-1, -1), walk(-1, +1)) .flatMap(position::walkUntilPiece) private fun Square.rookSquaresIn(position: Position): Set<Square> = HashSet.of(walk(0, +1), walk(+1, 0), walk(0, -1), walk(-1, 0)) .flatMap(position::walkUntilPiece) private fun Square.queenSquaresIn(position: Position): Set<Square> = bishopSquaresIn(position).addAll(rookSquaresIn(position)) private fun Position.walkUntilPiece(walk: BoardPath): BoardPath = walk .splitAt { at(it).defined } .map({ it }, { it.headOption() }) .apply(BoardPath::appendAll) private fun Square.pawnCaptureSquares(color: Color): Set<Square> { val direction = Pawns.direction(color) return translateAll(Pair(-1, direction), Pair(+1, direction)) } private fun Position.pawnMoves(from: Square): Set<Move.Regular> { val piece = get(from) val direction = Pawns.direction(piece.color) val initialRow = if (piece.color === Color.WHITE) 1 else 6 val push = if (from.row == initialRow) 2 else 1 val forward = from.walk(0, direction) .takeWhile { at(it).undefined } .take(push) .map { to -> Move.Regular(from, to) } val captures = from.pawnCaptureSquares(piece.color) .filter { to -> at(to).exists { piece.isOpponent(it) } } .map { to -> Move.Regular(from, to) } val enPassantRow = if (piece.color === Color.WHITE) 4 else 3 val enPassantCaptures = if (from.row == enPassantRow) from.translateAll(Pair(-1, 0), Pair(+1, 0)) .filter { side -> at(side) == Piece.pawnOf(piece.color.opponent()) } .map { side -> side.translate(0, direction)!! } .filter { to -> at(to).undefined } .map { to -> Move.Regular(from, to, EnPassant()) } else HashSet.empty() return forward.appendAll(captures).appendAll(enPassantCaptures).toSet() }
gpl-2.0
baf4f72adc683f19635934572ceed456
38.695035
160
0.659578
3.397693
false
false
false
false
Maccimo/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/projectActions/ChangeProjectIconAction.kt
2
5547
// 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.openapi.wm.impl.welcomeScreen.projectActions import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.RecentProjectIconHelper import com.intellij.ide.RecentProjectIconHelper.Companion.createIcon import com.intellij.openapi.actionSystem.* import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeScreenUIManager import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.RecentProjectItem import com.intellij.ui.components.AnActionLink import com.intellij.ui.components.JBLabel import com.intellij.ui.components.dialog import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBUI import org.jetbrains.annotations.SystemIndependent import java.awt.BorderLayout import java.awt.Dimension import java.awt.Graphics import java.io.File import java.nio.file.Files import java.nio.file.Paths import javax.swing.JComponent import javax.swing.JPanel import kotlin.io.path.Path import com.intellij.ide.RecentProjectsManagerBase.Companion.instanceEx as ProjectIcon /** * @author Konstantin Bulenkov */ class ChangeProjectIconAction : RecentProjectsWelcomeScreenActionBase() { override fun actionPerformed(event: AnActionEvent) { val reopenProjectAction = getSelectedItem(event) as RecentProjectItem val projectPath = reopenProjectAction.projectPath val basePath = RecentProjectIconHelper.getDotIdeaPath(projectPath) ?: return val ui = ProjectIconUI(projectPath) val panel = panel { row { cell(IconPreviewPanel(ui.iconLabel)) panel { row { cell(ui.setIconActionLink) .gap(RightGap.SMALL) cell(ui.removeIcon.component) } row { text(IdeBundle.message("link.change.project.icon.description")).applyToComponent { foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND } } } } } if (dialog(IdeBundle.message("dialog.title.change.project.icon"), panel).showAndGet()) { val iconSvg = basePath.resolve("icon.svg").toFile() val iconPng = basePath.resolve("icon.png").toFile() if (ui.pathToIcon != null) { FileUtil.copy(File(ui.pathToIcon!!.path), iconSvg) VfsUtil.markDirtyAndRefresh(false, false, false, iconSvg) FileUtil.delete(iconPng) RecentProjectIconHelper.refreshProjectIcon(projectPath) } if (ui.iconRemoved) { FileUtil.delete(ui.pathToIcon()) RecentProjectIconHelper.refreshProjectIcon(projectPath) } } } override fun update(event: AnActionEvent) { val item = getSelectedItem(event) event.presentation.isEnabled = item is RecentProjectItem } } private class ChangeProjectIcon constructor(private val ui: ProjectIconUI) : AnAction() { override fun actionPerformed(e: AnActionEvent) { val files = FileChooserFactory.getInstance() .createFileChooser(FileChooserDescriptor(true, false, false, false, false, false).withFileFilter { file: VirtualFile -> "svg".equals(file.extension, ignoreCase = true) }, null, null).choose(null) if (files.size == 1) { try { val newIcon = createIcon(Paths.get(files[0].path)) ui.iconLabel.icon = newIcon ui.pathToIcon = files[0] ui.iconRemoved = false } catch (ignore: Exception) { } } } } class ProjectIconUI(val projectPath: @SystemIndependent String) { val setIconActionLink = AnActionLink(IdeBundle.message("link.change.project.icon"), ChangeProjectIcon(this)) val iconLabel = JBLabel(ProjectIcon.getProjectIcon(projectPath, false)) var pathToIcon: VirtualFile? = null val removeIcon = createToolbar() var iconRemoved = false private fun createToolbar(): ActionToolbar { val removeIconAction = object : DumbAwareAction(AllIcons.Actions.GC) { override fun actionPerformed(e: AnActionEvent) { iconRemoved = true iconLabel.icon = RecentProjectIconHelper.generateProjectIcon(projectPath) pathToIcon = null } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = pathToIcon != null || (Files.exists(pathToIcon()) && !iconRemoved) } } return ActionManager.getInstance().createActionToolbar("ProjectIconDialog", DefaultActionGroup(removeIconAction), true) .apply { targetComponent = iconLabel } } fun pathToIcon() = Path("${projectPath}/.idea/icon.svg") } private class IconPreviewPanel(component: JComponent) : JPanel(BorderLayout()) { val radius = 4 val size = 60 init { isOpaque = false background = WelcomeScreenUIManager.getMainAssociatedComponentBackground() preferredSize = Dimension(size, size) minimumSize = Dimension(size, size) add(component) } override fun paintComponent(g: Graphics) { g.color = background val config = GraphicsUtil.setupRoundedBorderAntialiasing(g) g.fillRoundRect(0, 0, width, height, 2 * radius, 2 * radius) config.restore() } }
apache-2.0
2afd145a8fe0d658606feb0f10bd1111
35.735099
127
0.726158
4.39889
false
false
false
false
Maccimo/intellij-community
python/src/com/jetbrains/python/namespacePackages/PyMarkAsNamespacePackageAction.kt
4
2657
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.namespacePackages import com.intellij.openapi.actionSystem.* import com.intellij.util.PlatformIcons import com.intellij.util.PlatformUtils import com.jetbrains.python.PyBundle import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher class PyMarkAsNamespacePackageAction : AnAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { val presentation = e.presentation presentation.isEnabled = false presentation.isVisible = false val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return if (virtualFiles.isEmpty()) return val project = e.project ?: return if (virtualFiles.any { PythonLanguageLevelPusher.getLanguageLevelForVirtualFile(project, it).isOlderThan(LanguageLevel.PYTHON34) }) { return } val module = e.getData(PlatformCoreDataKeys.MODULE) ?: return val service = PyNamespacePackagesService.getInstance(module) if (!PyNamespacePackagesService.isEnabled()) return presentation.isVisible = true presentation.icon = PlatformIcons.PACKAGE_ICON when { virtualFiles.all { service.canBeMarked(it) } -> { presentation.isEnabled = true presentation.text = if (PlatformUtils.isPyCharm()) { PyBundle.message("python.namespace.package.folder") } else { PyBundle.message("python.python.namespace.package.folder") } } virtualFiles.all { service.isMarked(it) } -> { presentation.isEnabled = true presentation.text = if (PlatformUtils.isPyCharm()) { PyBundle.message("python.unmark.as.namespace.package") } else { PyBundle.message("python.unmark.as.python.namespace.package") } } else -> { presentation.isEnabled = false presentation.text = if (PlatformUtils.isPyCharm()) { PyBundle.message("python.namespace.package.folder") } else { PyBundle.message("python.python.namespace.package.folder") } } } } override fun actionPerformed(e: AnActionEvent) { val module = e.getData(PlatformCoreDataKeys.MODULE) ?: return val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return val service = PyNamespacePackagesService.getInstance(module) virtualFiles.forEach { service.toggleMarkingAsNamespacePackage(it) } } }
apache-2.0
d07047b1a81e48da93acdf8db1f02958
36.43662
140
0.705683
4.661404
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/group/SystemMarks.kt
1
2484
/* * 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.group import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmark.BookmarksManager import com.intellij.ide.bookmark.LineBookmark import com.intellij.ide.bookmark.providers.LineBookmarkProvider import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.options.OptionScope.LOCAL import com.maddyhome.idea.vim.vimscript.services.IjVimOptionService class SystemMarks { companion object { @JvmStatic fun createOrGetSystemMark(ch: Char, line: Int, editor: Editor): LineBookmark? { if (!VimPlugin.getOptionService().isSet(LOCAL(IjVimEditor(editor)), IjVimOptionService.ideamarksName, IjVimOptionService.ideamarksName)) return null val project = editor.project ?: return null val type = BookmarkType.get(ch) if (type == BookmarkType.DEFAULT) return null val bookmarksManager = BookmarksManager.getInstance(project) ?: return null val foundBookmark = bookmarksManager.getBookmark(type) if (foundBookmark != null) { if (foundBookmark is LineBookmark && foundBookmark.line == line) { return foundBookmark } bookmarksManager.remove(foundBookmark) } return project.createLineBookmark(editor, line, ch) } } } internal fun Project.createLineBookmark(editor: Editor, line: Int, mnemonic: Char): LineBookmark? { val bookmarksManager = BookmarksManager.getInstance(this) ?: return null val lineBookmarkProvider = LineBookmarkProvider.find(this) ?: return null val bookmark = lineBookmarkProvider.createBookmark(editor, line) as LineBookmark? ?: return null val type = BookmarkType.get(mnemonic) if (type == BookmarkType.DEFAULT) return null val group = bookmarksManager.defaultGroup ?: bookmarksManager.getGroup("IdeaVim") ?: bookmarksManager.addGroup("IdeaVim", true) ?: return null if (group.canAdd(bookmark)) { group.add(bookmark, type) return bookmark } return null } internal fun Bookmark.mnemonic(project: Project?): Char { return BookmarksManager.getInstance(project)?.getType(this)!!.mnemonic }
mit
7331ea678b1d78bf49df7821ea1abe02
36.074627
154
0.754428
4.290155
false
false
false
false
SourceUtils/hl2-toolkit
src/main/kotlin/com/timepath/hl2/io/demo/LZSS.kt
1
2292
package com.timepath.hl2.io.demo import com.timepath.toUnsigned public class LZSS { class LZSSException(message: String) : Exception(message) companion object { fun readSwappedInteger(data: ByteArray, offset: Int) = (0 + (data[offset + 0].toUnsigned() shl 0) + (data[offset + 1].toUnsigned() shl 8) + (data[offset + 2].toUnsigned() shl 16) + (data[offset + 3].toUnsigned() shl 24) ) public val ID: String = "LZSS" private val LZSS_LOOKSHIFT = 4 throws(LZSSException::class) public fun inflate(input: ByteArray): ByteArray { // Pointers var pInput = 8 var pOutput = 0 // Header val id = String(input, 0, 4) val actualSize = readSwappedInteger(input, 4) if (ID != id || actualSize == 0) { throw LZSSException("Unrecognized header") } // Payload val output = ByteArray(actualSize) var totalBytes = 0 var cmdByte = 0 var getCmdByte = 0 while (true) { if (getCmdByte == 0) { cmdByte = input[pInput++].toInt() } getCmdByte = (getCmdByte + 1) and 7 if ((cmdByte and 1) == 1) { val position = (input[pInput++].toInt() shl LZSS_LOOKSHIFT) or (input[pInput].toInt() shr LZSS_LOOKSHIFT) val count = (input[pInput++].toInt() and 15) + 1 if (count == 1) { break } var pSource = pOutput - position - 1 for (i in 0..count - 1) { output[pOutput++] = output[pSource++] } totalBytes += count } else { output[pOutput++] = input[pInput++] totalBytes++ } cmdByte = cmdByte shr 1 } // Verify if (totalBytes != actualSize) { throw LZSSException("Unexpected failure: bytes read do not match expected size") } return output } } }
artistic-2.0
7d78bbd9b875e12e9ab1daa56a864c93
33.727273
125
0.457243
4.677551
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/utils/SpamCache.kt
1
1984
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.utils import gnu.trove.list.TLongList import gnu.trove.list.array.TLongArrayList import gnu.trove.map.hash.TLongObjectHashMap class SpamCache : TLongObjectHashMap<TLongList>() { @Throws(IllegalArgumentException::class) fun update(longs: LongArray, updateMode: Int = 0): SpamCache { when { updateMode == -1 && longs.size == 1 -> { this.remove(longs[0]) } longs.size == 2 -> { val msgIds: TLongList = if (!this.containsKey(longs[0])) { TLongArrayList() } else { this[longs[0]] as TLongArrayList } if (updateMode == 0) { msgIds.add(longs[1]) this.put(longs[0], msgIds) } else if (updateMode == 1) { msgIds.remove(longs[1]) this.put(longs[0], msgIds) } } else -> { throw IllegalArgumentException("Arguments don't match.") } } return this } }
agpl-3.0
bd4df2e91d3aec41a8c333a3fc3751a9
35.072727
104
0.583165
4.370044
false
false
false
false
TomsUsername/Phoenix
src/main/kotlin/phoenix/bot/pogo/nRnMK9r/util/data/PokemonData.kt
1
6007
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package phoenix.bot.pogo.nRnMK9r.util.data import POGOProtos.Enums.PokemonMoveOuterClass import com.google.common.geometry.S2CellId import com.google.common.geometry.S2LatLng import phoenix.bot.pogo.api.cache.BagPokemon import phoenix.bot.pogo.api.util.PokemonMoveMetaRegistry import phoenix.bot.pogo.nRnMK9r.util.pokemon.* import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.atomic.AtomicInteger data class PokemonData( var id: String? = null, var pokemonId: Int? = null, var name: String? = null, var nickname: String? = null, var pclass: String? = null, var type1: String? = null, var type2: String? = null, var cp: Int? = null, var iv: Int? = null, var stats: String? = null, var favorite: Boolean? = null, var cpMultiplier: Float? = null, var heightM: Float? = null, var weightKg: Float? = null, var individualStamina: Int? = null, var individualAttack: Int? = null, var individualDefense: Int? = null, var candy: Int? = null, var candiesToEvolve: Int? = null, var level: Float? = null, var move1: String? = null, var move1Type: String? = null, var move1Power: Int? = null, var move1Accuracy: Int? = null, var move1CritChance: Double? = null, var move1Time: Int? = null, var move1Energy: Int? = null, var move2: String? = null, var move2Type: String? = null, var move2Power: Int? = null, var move2Accuracy: Int? = null, var move2CritChance: Double? = null, var move2Time: Int? = null, var move2Energy: Int? = null, var deployedFortId: String? = null, var stamina: Int? = null, var maxStamina: Int? = null, var maxCp: Int? = null, var absMaxCp: Int? = null, var maxCpFullEvolveAndPowerup: Int? = null, var candyCostsForPowerup: Int? = null, var stardustCostsForPowerup: Int? = null, var creationTime: String? = null, var creationTimeMs: Long? = null, var creationLatDegrees: Double? = null, var creationLngDegrees: Double? = null, var baseCaptureRate: Double? = null, var baseFleeRate: Double? = null, var battlesAttacked: Int? = null, var battlesDefended: Int? = null, var isInjured: Boolean? = null, var isFainted: Boolean? = null, var cpAfterPowerup: Int? = null ) { fun buildFromPokemon(bagPokemon: BagPokemon): PokemonData { val pokemon = bagPokemon.pokemonData val latLng = S2LatLng(S2CellId(pokemon.capturedCellId).toPoint()) val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val pmeta = pokemon.meta val pmmeta1 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(pokemon.move1.number)) val pmmeta2 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(pokemon.move2.number)) this.id = pokemon.id.toString() this.pokemonId = pokemon.pokemonId.number this.name = pokemon.pokemonId.name this.nickname = pokemon.nickname this.pclass = pmeta.pokemonClass.name this.type1 = pmeta.type1.name this.type2 = pmeta.type2.name this.cp = pokemon.cp this.iv = pokemon.getIvPercentage() this.stats = pokemon.getStatsFormatted() this.favorite = pokemon.favorite > 0 this.cpMultiplier = pokemon.cpMultiplier this.heightM = pokemon.heightM this.weightKg = pokemon.weightKg this.individualStamina = pokemon.individualStamina this.individualAttack = pokemon.individualAttack this.individualDefense = pokemon.individualDefense this.candy = bagPokemon.poGoApi.inventory.candies.getOrPut(pmeta.family, { AtomicInteger(0) }).get() this.candiesToEvolve = pmeta.candyToEvolve this.level = pokemon.level this.move1 = pokemon.move1.name this.move1Type = pmmeta1.type.name this.move1Power = pmmeta1.power this.move1Accuracy = pmmeta1.accuracy this.move1CritChance = pmmeta1.critChance this.move1Time = pmmeta1.time this.move1Energy = pmmeta1.energy this.move2 = pokemon.move2.name this.move2Type = pmmeta2.type.name this.move2Power = pmmeta2.power this.move2Accuracy = pmmeta2.accuracy this.move2CritChance = pmmeta2.critChance this.move2Time = pmmeta2.time this.move2Energy = pmmeta2.energy this.deployedFortId = pokemon.deployedFortId this.stamina = pokemon.stamina this.maxStamina = pokemon.staminaMax this.maxCp = pokemon.maxCp this.absMaxCp = pokemon.absoluteMaxCp this.maxCpFullEvolveAndPowerup = pokemon.cpFullEvolveAndPowerup this.candyCostsForPowerup = pokemon.candyCostsForPowerup this.stardustCostsForPowerup = pokemon.stardustCostsForPowerup this.creationTime = dateFormatter.format(Date(pokemon.creationTimeMs)) this.creationTimeMs = pokemon.creationTimeMs this.creationLatDegrees = latLng.latDegrees() this.creationLngDegrees = latLng.lngDegrees() this.baseCaptureRate = pmeta.baseCaptureRate this.baseFleeRate = pmeta.baseFleeRate this.battlesAttacked = pokemon.battlesAttacked this.battlesDefended = pokemon.battlesDefended this.isInjured = pokemon.injured this.isFainted = pokemon.fainted this.cpAfterPowerup = pokemon.cpAfterPowerup return this } }
gpl-3.0
c9ea3f66b017ec0d629c11b8484a8ab9
38.519737
120
0.666889
3.965017
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/reader/savedposts/ReaderSavedPostsAnalyticsTracker.kt
1
1430
package org.wordpress.android.reader.savedposts import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.reader.savedposts.ReaderSavedPostsAnalyticsTracker.ErrorType.Companion.ERROR_TYPE import org.wordpress.android.reader.savedposts.ReaderSavedPostsAnalyticsTracker.ErrorType.Companion.EXPORTED_POSTS import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import javax.inject.Inject class ReaderSavedPostsAnalyticsTracker @Inject constructor( private val analyticsTracker: AnalyticsTrackerWrapper ) { fun trackStart() = analyticsTracker.track(Stat.READER_SAVED_POSTS_START) fun trackSuccess(numPosts: Int) = analyticsTracker.track( Stat.READER_SAVED_POSTS_SUCCESS, mapOf(EXPORTED_POSTS to numPosts) ) fun trackFailed(errorType: ErrorType) = analyticsTracker.track(Stat.READER_SAVED_POSTS_FAILED, mapOf(ERROR_TYPE to errorType.value)) sealed class ErrorType(open val value: String) { object QuerySavedPostsError : ErrorType("query_saved_posts_error") class GenericError(errorMessage: String?) : ErrorType( "generic_error: ${errorMessage?.take(EXCEPTION_MESSAGE_MAX_LENGTH) ?: ""}" ) companion object { const val ERROR_TYPE = "error_type" const val EXPORTED_POSTS = "exported_posts" const val EXCEPTION_MESSAGE_MAX_LENGTH = 100 } } }
gpl-2.0
f30c9bb0c6823d4962bd370c460f4edf
41.058824
114
0.73986
4.482759
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/comments/unified/UnifiedCommentsListDiffCallback.kt
1
1763
package org.wordpress.android.ui.comments.unified import android.os.Bundle import androidx.recyclerview.widget.DiffUtil import org.wordpress.android.ui.comments.unified.UnifiedCommentListItem.Comment import org.wordpress.android.ui.comments.unified.UnifiedCommentListItem.SubHeader class UnifiedCommentsListDiffCallback : DiffUtil.ItemCallback<UnifiedCommentListItem>() { override fun areItemsTheSame(oldItem: UnifiedCommentListItem, newItem: UnifiedCommentListItem): Boolean { return when { oldItem is SubHeader && newItem is SubHeader -> oldItem.id == newItem.id oldItem is Comment && newItem is Comment -> oldItem.id == newItem.id else -> false } } override fun areContentsTheSame(oldItem: UnifiedCommentListItem, newItem: UnifiedCommentListItem): Boolean { return oldItem == newItem } override fun getChangePayload(oldItem: UnifiedCommentListItem, newItem: UnifiedCommentListItem): Any { val bundle = Bundle() if (oldItem is Comment && newItem is Comment) { if (oldItem.isSelected != newItem.isSelected) { bundle.putBoolean(COMMENT_SELECTION_TOGGLED, newItem.isSelected) } if (oldItem.isPending != newItem.isPending) { bundle.putBoolean(COMMENT_PENDING_STATE_CHANGED, newItem.isPending) } } return bundle } companion object { const val COMMENT_SELECTION_TOGGLED = "COMMENT_SELECTION_TOGGLED" const val COMMENT_PENDING_STATE_CHANGED = "COMMENT_PENDING_STATE_CHANGED" const val COMMENT_CLICK_ACTION_CHANGED = "COMMENT_CLICK_ACTION_CHANGED" const val COMMENT_TOGGLE_ACTION_CHANGED = "COMMENT_TOGGLE_ACTION_CHANGED" } }
gpl-2.0
ece0f42388fb0aa4b8aeee7b55763f0a
40.97619
112
0.699943
4.752022
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/workers/notification/bloggingprompts/BloggingPromptsOnboardingNotificationHandlerTest.kt
1
1553
package org.wordpress.android.workers.notification.bloggingprompts import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.fluxc.store.AccountStore import org.wordpress.android.push.NotificationType.BLOGGING_PROMPTS_ONBOARDING import org.wordpress.android.ui.notifications.SystemNotificationsTracker class BloggingPromptsOnboardingNotificationHandlerTest { private val accountStore: AccountStore = mock() private val systemNotificationsTracker: SystemNotificationsTracker = mock() private val classToTest = BloggingPromptsOnboardingNotificationHandler(accountStore, systemNotificationsTracker) @Test fun `Should show notification if user has access token`() { whenever(accountStore.hasAccessToken()).thenReturn(true) val actual = classToTest.shouldShowNotification() val expected = true assertThat(actual).isEqualTo(expected) } @Test fun `Should NOT show notification if user has access token`() { whenever(accountStore.hasAccessToken()).thenReturn(false) val actual = classToTest.shouldShowNotification() val expected = false assertThat(actual).isEqualTo(expected) } @Test fun `Should track notification shown when onNotificationShown is called`() { classToTest.onNotificationShown() verify(systemNotificationsTracker).trackShownNotification(BLOGGING_PROMPTS_ONBOARDING) } }
gpl-2.0
95a81831471e1f13bed980169855e569
39.868421
116
0.773986
5.176667
false
true
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/recurrent/ran/RANLayerStructureSpec.kt
1
38884
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.recurrent.ran import com.kotlinnlp.simplednn.core.arrays.DistributionArray import com.kotlinnlp.simplednn.core.layers.models.recurrent.ran.RANLayerParameters import com.kotlinnlp.simplednn.core.functionalities.losses.MSECalculator import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow import com.kotlinnlp.simplednn.core.optimizer.getErrorsOf import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertFailsWith import kotlin.test.assertTrue /** * */ class RANLayerStructureSpec : Spek({ describe("a RANLayer") { context("forward") { context("without previous state context") { val layer = RANLayerStructureUtils.buildLayer(RANLayersWindow.Empty) layer.forward() it("should match the expected input gate") { assertTrue { layer.inputGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.39652, 0.25162, 0.5, 0.70475, 0.45264)), tolerance = 1.0e-05) } } it("should match the expected forget gate") { assertTrue { layer.forgetGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.85321, 0.43291, 0.11609, 0.51999, 0.24232)), tolerance = 1.0e-05) } } it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(1.02, -0.1, 0.1, 2.03, -1.41)), tolerance = 1.0e-05) } } it("should match the expected outputArray") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.38375, -0.02516, 0.04996, 0.8918, -0.56369)), tolerance = 1.0e-05) } } } context("with previous state context") { val layer = RANLayerStructureUtils.buildLayer(RANLayersWindow.Back) layer.forward() it("should match the expected input gate") { assertTrue { layer.inputGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.72312, 0.24974, 0.54983, 0.82054, 0.53494)), tolerance = 1.0e-05) } } it("should match the expected forget gate") { assertTrue { layer.forgetGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.91133, 0.18094, 0.04834, 0.67481, 0.38936)), tolerance = 1.0e-05) } } it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(1.02, -0.1, 0.1, 2.03, -1.41)), tolerance = 1.0e-05) } } it("should match the expected outputArray") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5045, 0.01121, 0.04046, 0.78504, -0.78786)), tolerance = 1.0e-05) } } } } context("forward with relevance") { context("without previous state context") { val layer = RANLayerStructureUtils.buildLayer(RANLayersWindow.Empty) val contributions = RANLayerParameters(inputSize = 4, outputSize = 5) layer.forward(contributions) it("should match the expected input gate") { assertTrue { layer.inputGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.39652, 0.25162, 0.5, 0.70475, 0.45264)), tolerance = 1.0e-05) } } it("should match the expected forget gate") { assertTrue { layer.forgetGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.85321, 0.43291, 0.11609, 0.51999, 0.24232)), tolerance = 1.0e-05) } } it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(1.02, -0.1, 0.1, 2.03, -1.41)), tolerance = 1.0e-05) } } it("should match the expected outputArray") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.38375, -0.02516, 0.04996, 0.8918, -0.56369)), tolerance = 1.0e-05) } } it("should match the expected contributions of the input gate") { val inputGateContrib: DenseNDArray = contributions.inputGate.weights.values assertTrue { inputGateContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.3, -0.44, 0.82, -0.5), doubleArrayOf(-0.56, 0.36, -0.09, -0.8), doubleArrayOf(-0.635, 0.555, -0.345, 0.425), doubleArrayOf(-0.44, 1.01, 0.2, 0.1), doubleArrayOf(-0.42, -1.0, 0.53, 0.7) )), tolerance = 1.0e-05) } } it("should match the expected contributions of the candidate") { val candidateContrib: DenseNDArray = contributions.candidate.weights.values assertTrue { candidateContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.85, -0.13, 0.05, 0.25), doubleArrayOf(0.56, -0.63, 0.27, -0.3), doubleArrayOf(-0.465, 0.315, -0.225, 0.475), doubleArrayOf(0.975, 0.715, -0.635, 0.975), doubleArrayOf(-0.475, -0.795, 0.735, -0.875) )), tolerance = 1.0e-05) } } layer.setOutputRelevance(DistributionArray.uniform(length = 5)) layer.propagateRelevanceToGates(contributions) layer.setInputRelevance(contributions) it("should match the expected input relevance") { val relevance: DenseNDArray = layer.inputArray.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-6.80494, 7.20431, -4.37039, 4.97103)), tolerance = 1.0e-05) } } it("should throw an Exception when calculating the recurrent relevance") { assertFailsWith <KotlinNullPointerException> { layer.setRecurrentRelevance(contributions) } } } context("with previous state context") { val prevStateLayer = RANLayersWindow.Back.getPrevState() val contextWindow = mock<LayersWindow>() val layer = RANLayerStructureUtils.buildLayer(contextWindow) val contributions = RANLayerParameters(inputSize = 4, outputSize = 5) whenever(contextWindow.getPrevState()).thenReturn(prevStateLayer) layer.forward(contributions) it("should match the expected input gate") { assertTrue { layer.inputGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.72312, 0.24974, 0.54983, 0.82054, 0.53494)), tolerance = 1.0e-05) } } it("should match the expected forget gate") { assertTrue { layer.forgetGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.91133, 0.18094, 0.04834, 0.67481, 0.38936)), tolerance = 1.0e-05) } } it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(1.02, -0.1, 0.1, 2.03, -1.41)), tolerance = 1.0e-05) } } it("should match the expected outputArray") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5045, 0.01121, 0.04046, 0.78504, -0.78786)), tolerance = 1.0e-05) } } it("should match the expected contributions of the input gate") { val inputGateContrib: DenseNDArray = contributions.inputGate.weights.values assertTrue { inputGateContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.35, -0.49, 0.77, -0.55), doubleArrayOf(-0.56, 0.36, -0.09, -0.8), doubleArrayOf(-0.5975, 0.5925, -0.3075, 0.4625), doubleArrayOf(-0.54, 0.91, 0.1, 0.0), doubleArrayOf(-0.37, -0.95, 0.58, 0.75) )), tolerance = 1.0e-05) } } it("should match the expected contributions of the forget gate") { val forgetGateContrib: DenseNDArray = contributions.forgetGate.weights.values assertTrue { forgetGateContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0325, -0.2475, 1.0125, 0.5125), doubleArrayOf(-0.5350, 0.2050, -0.0650, 0.025), doubleArrayOf(-0.6725, -0.8325, 0.3375, -0.4125), doubleArrayOf(0.7450, -0.7850, 0.2950, -0.275), doubleArrayOf(0.4475, -0.6525, 0.4275, -0.9125) )), tolerance = 1.0e-05) } } it("should match the expected contributions of the candidate") { val candidateContrib: DenseNDArray = contributions.candidate.weights.values assertTrue { candidateContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.85, -0.13, 0.05, 0.25), doubleArrayOf(0.56, -0.63, 0.27, -0.3), doubleArrayOf(-0.465, 0.315, -0.225, 0.475), doubleArrayOf(0.975, 0.715, -0.635, 0.975), doubleArrayOf(-0.475, -0.795, 0.735, -0.875) )), tolerance = 1.0e-05) } } it("should match the expected recurrent contributions of the input gate") { val inputGateContrib: DenseNDArray = contributions.inputGate.recurrentWeights.values assertTrue { inputGateContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.04, 0.2, -0.2, 0.94, 0.60), doubleArrayOf(0.14, -0.16, -0.06, 0.63, -0.56), doubleArrayOf(0.15, 0.15, -0.24, 0.42, -0.43), doubleArrayOf(0.08, 0.06, -0.07, 0.26, 0.72), doubleArrayOf(0.08, 0.08, -0.28, 0.05, 0.20) )), tolerance = 1.0e-05) } } it("should match the expected recurrent contributions of the forget gate") { val forgetGateContrib: DenseNDArray = contributions.forgetGate.recurrentWeights.values assertTrue { forgetGateContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.07, -0.03, 0.39, 0.18, 0.41), doubleArrayOf(-0.08, -0.16, 0.02, -0.7, -0.22), doubleArrayOf(-0.03, -0.27, -0.18, -0.99, 0.07), doubleArrayOf(-0.12, 0.06, -0.07, 0.38, 0.50), doubleArrayOf(-0.05, 0.01, -0.03, 0.72, -0.41) )), tolerance = 1.0e-05) } } layer.setOutputRelevance(DistributionArray.uniform(length = 5)) layer.propagateRelevanceToGates(contributions) layer.setInputRelevance(contributions) layer.setRecurrentRelevance(contributions) it("should match the expected relevance of the input gate") { val relevance: DenseNDArray = layer.inputGate.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.13434, -0.09416, 0.16398, 0.15841, 0.07058)), tolerance = 1.0e-05) } } it("should match the expected relevance of the forget gate") { val relevance: DenseNDArray = layer.forgetGate.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.03434, 0.19416, -0.06398, -0.05841, 0.02942)), tolerance = 1.0e-05) } } it("should match the expected relevance of the candidate") { val relevance: DenseNDArray = layer.candidate.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.13434, -0.09416, 0.16398, 0.15841, 0.07058)), tolerance = 1.0e-05) } } it("should match the expected input relevance") { val relevance: DenseNDArray = layer.inputArray.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.73699, 0.21761, -0.13861, 1.13203)), tolerance = 1.0e-05) } } it("should match the expected recurrent relevance") { val relevance: DenseNDArray = prevStateLayer.outputArray.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.15578, 0.3737, -0.40348, 0.45246, -0.05248)), tolerance = 1.0e-05) } } } } context("backward") { context("without previous and next state") { val layer = RANLayerStructureUtils.buildLayer(RANLayersWindow.Empty) layer.forward() val errors = MSECalculator().calculateErrors( output = layer.outputArray.values, outputGold = RANLayerStructureUtils.getOutputGold()) layer.outputArray.assignErrors(errors) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.15882, -0.77467, 0.19946, -0.15316, -0.69159)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate") { assertTrue { layer.inputGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.03877, 0.01459, 0.00499, -0.06469, 0.2416)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate") { assertTrue { layer.forgetGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.06298, -0.19492, 0.09973, -0.10794, -0.31304)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate biases") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.03877, 0.01459, 0.00499, -0.06469, 0.2416)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate biases") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.candidate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.06298, -0.19492, 0.09973, -0.10794, -0.31304)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.inputGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.03101, 0.03489, 0.03489, -0.03877), doubleArrayOf(-0.01167, -0.01313, -0.01313, 0.01459), doubleArrayOf(-0.00399, -0.00449, -0.00449, 0.00499), doubleArrayOf(0.05175, 0.05822, 0.05822, -0.06469), doubleArrayOf(-0.19328, -0.21744, -0.21744, 0.2416) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.forgetGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0) )), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate weights") { assertTrue { (paramsErrors.getErrorsOf(params.candidate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.05038, 0.05668, 0.05668, -0.06298), doubleArrayOf(0.15594, 0.17543, 0.17543, -0.19492), doubleArrayOf(-0.07978, -0.08976, -0.08976, 0.09973), doubleArrayOf(0.08635, 0.09714, 0.09714, -0.10794), doubleArrayOf(0.25044, 0.28174, 0.28174, -0.31304) )), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0) )), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.21996, -0.12731, 0.10792, 0.49361)), tolerance = 1.0e-05) } } } context("with previous state only") { val layer = RANLayerStructureUtils.buildLayer(RANLayersWindow.Back) layer.forward() val errors = MSECalculator().calculateErrors( output = layer.outputArray.values, outputGold = RANLayerStructureUtils.getOutputGold()) layer.outputArray.assignErrors(errors) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.04883, -0.73869, 0.19015, -0.32806, -0.46949)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate") { assertTrue { layer.inputGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.00997, 0.01384, 0.00471, -0.09807, 0.16469)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate") { assertTrue { layer.forgetGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.00078, -0.02161, -0.00255, 0.05157, 0.07412)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.03531, -0.18448, 0.10455, -0.26919, -0.25115)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate biases") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.00997, 0.01384, 0.00471, -0.09807, 0.16469)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate biases") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.00078, -0.02161, -0.00255, 0.05157, 0.07412)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.candidate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.03531, -0.18448, 0.10455, -0.26919, -0.25115)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.inputGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.00798, 0.00898, 0.00898, -0.00997), doubleArrayOf(-0.01107, -0.01246, -0.01246, 0.01384), doubleArrayOf(-0.00377, -0.00424, -0.00424, 0.00471), doubleArrayOf(0.07845, 0.08826, 0.08826, -0.09807), doubleArrayOf(-0.13175, -0.14822, -0.14822, 0.16469) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.forgetGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.00062, -0.0007, -0.0007, 0.00078), doubleArrayOf(0.01729, 0.01945, 0.01945, -0.02161), doubleArrayOf(0.00204, 0.00229, 0.00229, -0.00255), doubleArrayOf(-0.04125, -0.04641, -0.04641, 0.05157), doubleArrayOf(-0.0593, -0.06671, -0.06671, 0.07412) )), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate weights") { assertTrue { (paramsErrors.getErrorsOf(params.candidate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.02825, 0.03178, 0.03178, -0.03531), doubleArrayOf(0.14759, 0.16603, 0.16603, -0.18448), doubleArrayOf(-0.08364, -0.09409, -0.09409, 0.10455), doubleArrayOf(0.21535, 0.24227, 0.24227, -0.26919), doubleArrayOf(0.20092, 0.22604, 0.22604, -0.25115) )), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.00199, -0.00199, 0.00299, 0.00898, 0.00798), doubleArrayOf(-0.00277, 0.00277, -0.00415, -0.01246, -0.01107), doubleArrayOf(-0.00094, 0.00094, -0.00141, -0.00424, -0.00377), doubleArrayOf(0.01961, -0.01961, 0.02942, 0.08826, 0.07845), doubleArrayOf(-0.03294, 0.03294, -0.04941, -0.14822, -0.13175) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.00016, 0.00016, -0.00023, -0.0007, -0.00062), doubleArrayOf(0.00432, -0.00432, 0.00648, 0.01945, 0.01729), doubleArrayOf(0.00051, -0.00051, 0.00076, 0.00229, 0.00204), doubleArrayOf(-0.01031, 0.01031, -0.01547, -0.04641, -0.04125), doubleArrayOf(-0.01482, 0.01482, -0.02224, -0.06671, -0.0593) )), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.21972, 0.09327, -0.127, 0.17217)), tolerance = 1.0e-05) } } } context("with next state only") { val layer = RANLayerStructureUtils.buildLayer(RANLayersWindow.Front) layer.forward() val errors = MSECalculator().calculateErrors( output = layer.outputArray.values, outputGold = RANLayerStructureUtils.getOutputGold()) layer.outputArray.assignErrors(errors) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.30882, -0.42467, 0.59946, -1.00316, -0.88159)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate") { assertTrue { layer.inputGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.07538, 0.008, 0.01499, -0.42373, 0.30797)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate") { assertTrue { layer.forgetGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.12245, -0.10685, 0.29973, -0.70697, -0.39905)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate biases") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.07538, 0.008, 0.01499, -0.42373, 0.30797)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate biases") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.candidate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.12245, -0.10685, 0.29973, -0.70697, -0.39905)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.inputGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0603, 0.06784, 0.06784, -0.07538), doubleArrayOf(-0.0064, -0.0072, -0.0072, 0.00800), doubleArrayOf(-0.01199, -0.01349, -0.01349, 0.01499), doubleArrayOf(0.33899, 0.38136, 0.38136, -0.42373), doubleArrayOf(-0.24638, -0.27718, -0.27718, 0.30797) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.forgetGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0) )), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate weights") { assertTrue { (paramsErrors.getErrorsOf(params.candidate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.09796, 0.11021, 0.11021, -0.12245), doubleArrayOf(0.08548, 0.09617, 0.09617, -0.10685), doubleArrayOf(-0.23978, -0.26976, -0.26976, 0.29973), doubleArrayOf(0.56558, 0.63627, 0.63627, -0.70697), doubleArrayOf(0.31924, 0.35914, 0.35914, -0.39905) )), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0) )), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.55722, 0.45624, -0.39506, 0.30611)), tolerance = 1.0e-05) } } } context("with previous and next state") { val layer = RANLayerStructureUtils.buildLayer(RANLayersWindow.Bilateral) layer.forward() val errors = MSECalculator().calculateErrors( output = layer.outputArray.values, outputGold = RANLayerStructureUtils.getOutputGold()) layer.outputArray.assignErrors(errors) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.19883, -0.38869, 0.59015, -1.17806, -0.65949)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate") { assertTrue { layer.inputGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.04061, 0.00728, 0.01461, -0.35216, 0.23134)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate") { assertTrue { layer.forgetGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.00317, -0.01137, -0.00791, 0.18518, 0.10412)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.14378, -0.09707, 0.32448, -0.96664, -0.35279)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate biases") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.04061, 0.00728, 0.01461, -0.35216, 0.23134)), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate biases") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.00317, -0.01137, -0.00791, 0.18518, 0.10412)), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.candidate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.14378, -0.09707, 0.32448, -0.96664, -0.35279)), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.inputGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.03248, 0.03655, 0.03655, -0.04061), doubleArrayOf(-0.00583, -0.00655, -0.00655, 0.00728), doubleArrayOf(-0.01169, -0.01315, -0.01315, 0.01461), doubleArrayOf(0.28172, 0.31694, 0.31694, -0.35216), doubleArrayOf(-0.18507, -0.20820, -0.20820, 0.23134) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.forgetGate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.00254, -0.00285, -0.00285, 0.00317), doubleArrayOf(0.00910, 0.01023, 0.01023, -0.01137), doubleArrayOf(0.00633, 0.00712, 0.00712, -0.00791), doubleArrayOf(-0.14814, -0.16666, -0.16666, 0.18518), doubleArrayOf(-0.08330, -0.09371, -0.09371, 0.10412) )), tolerance = 1.0e-05) } } it("should match the expected errors of the candidate weights") { assertTrue { (paramsErrors.getErrorsOf(params.candidate.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.11502, 0.12940, 0.12940, -0.14378), doubleArrayOf(0.07766, 0.08737, 0.08737, -0.09707), doubleArrayOf(-0.25959, -0.29204, -0.29204, 0.32448), doubleArrayOf(0.77332, 0.86998, 0.86998, -0.96664), doubleArrayOf(0.28223, 0.31751, 0.31751, -0.35279) )), tolerance = 1.0e-05) } } it("should match the expected errors of the input gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.inputGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.00812, -0.00812, 0.01218, 0.03655, 0.03248), doubleArrayOf(-0.00146, 0.00146, -0.00218, -0.00655, -0.00583), doubleArrayOf(-0.00292, 0.00292, -0.00438, -0.01315, -0.01169), doubleArrayOf(0.07043, -0.07043, 0.10565, 0.31694, 0.28172), doubleArrayOf(-0.04627, 0.04627, -0.06940, -0.20820, -0.18507) )), tolerance = 1.0e-05) } } it("should match the expected errors of the forget gate recurrent weights") { assertTrue { paramsErrors.getErrorsOf(params.forgetGate.recurrentWeights)!!.values.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.00063, 0.00063, -0.00095, -0.00285, -0.00254), doubleArrayOf(0.00227, -0.00227, 0.00341, 0.01023, 0.00910), doubleArrayOf(0.00158, -0.00158, 0.00237, 0.00712, 0.00633), doubleArrayOf(-0.03704, 0.03704, -0.05555, -0.16666, -0.14814), doubleArrayOf(-0.02082, 0.02082, -0.03124, -0.09371, -0.08330) )), tolerance = 1.0e-05) } } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.65243, 0.74348, -0.76607, -0.15266)), tolerance = 1.0e-05) } } } } } })
mpl-2.0
8e9a668cbd246f49038c52e229d7bcc2
38.921971
106
0.562134
3.977496
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnlabeledReturnInsideLambdaInspection.kt
1
2086
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.quickfix.ChangeToLabeledReturnFix import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.returnExpressionVisitor import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class UnlabeledReturnInsideLambdaInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = returnExpressionVisitor(fun(returnExpression: KtReturnExpression) { if (returnExpression.labelQualifier != null) return val lambda = returnExpression.getParentOfType<KtLambdaExpression>(true, KtNamedFunction::class.java) ?: return val parentFunction = lambda.getStrictParentOfType<KtNamedFunction>() ?: return if (returnExpression.analyze().diagnostics.forElement(returnExpression).any { it.severity == Severity.ERROR }) return holder.registerProblem( returnExpression.returnKeyword, KotlinBundle.message("unlabeled.return.inside.lambda"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(ChangeToLabeledReturnFix(returnExpression, labeledReturn = "return@${parentFunction.name}")) ) }) }
apache-2.0
5266e289f326375d731128a0311aad44
56.972222
158
0.787632
5.176179
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/ricaricami/RicaricaMiLookup.kt
1
3620
/* * RicaricaMiLookup.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.ricaricami import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.multi.StringResource import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.transit.Station import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.transit.en1545.En1545LookupSTR import au.id.micolous.metrodroid.util.NumberUtils import au.id.micolous.metrodroid.util.StationTableReader object RicaricaMiLookup : En1545LookupSTR("ricaricami") { override fun parseCurrency(price: Int) = TransitCurrency.EUR(price) override val timeZone get() = TZ override fun getStation(station: Int, agency: Int?, transport: Int?): Station? { if (station == 0) return null return StationTableReader.getStation( mStr, station or ((transport ?: 0) shl 24), NumberUtils.intToHex(station)) } override fun getRouteName(routeNumber: Int?, routeVariant: Int?, agency: Int?, transport: Int?): FormattedString? { if (routeNumber == null) return null when(transport) { TRANSPORT_METRO -> { when (routeNumber) { 101 -> return FormattedString("M1") 104 -> return FormattedString("M2") 107 -> return FormattedString("M5") 301 -> return FormattedString("M3") } } TRANSPORT_TRENORD1, TRANSPORT_TRENORD2 -> { // Essentially a placeholder if (routeNumber == 1000) return null } TRANSPORT_TRAM -> { if (routeNumber == 60) return null } } if (routeVariant != null) { return FormattedString("$routeNumber/$routeVariant") } return FormattedString(routeNumber.toString()) } val TZ = MetroTimeZone.ROME const val TRANSPORT_METRO = 1 const val TRANSPORT_BUS = 2 const val TRANSPORT_TRAM = 4 const val TRANSPORT_TRENORD1 = 7 const val TRANSPORT_TRENORD2 = 9 const val TARIFF_URBAN_2X6 = 0x1b39 const val TARIFF_SINGLE_URBAN = 0xfff const val TARIFF_DAILY_URBAN = 0x100d const val TARIFF_YEARLY_URBAN = 45 const val TARIFF_MONTHLY_URBAN = 46 override val subscriptionMap: Map<Int, StringResource> = mapOf( TARIFF_SINGLE_URBAN to R.string.ricaricami_single_urban, TARIFF_DAILY_URBAN to R.string.ricaricami_daily_urban, TARIFF_URBAN_2X6 to R.string.ricaricami_urban_2x6, TARIFF_YEARLY_URBAN to R.string.ricaricami_yearly_urban, TARIFF_MONTHLY_URBAN to R.string.ricaricami_monthly_urban, 7095 to R.string.ricaricami_m1_3_ord_single ) }
gpl-3.0
fcdf8ec9a7bba5464c3b62c4da7f6f97
37.105263
119
0.651934
3.900862
false
false
false
false
GunoH/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/controlFlow/impl/FunctionalExpressionFlowUtil.kt
8
6501
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("FunctionalExpressionFlowUtil") package org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl import com.intellij.openapi.util.registry.Registry import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.parentOfType import org.jetbrains.annotations.NonNls import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.InvocationKind.* import org.jetbrains.plugins.groovy.lang.psi.util.skipParenthesesDownOrNull import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments /** * Invocation kinds for closures are __temporarily__ disabled. * * At first, I tried to solve the problem of handling side effects of functional expressions, such as * ``` * if (a instanceof A) { * with(1) { * // here a has type A * } * } * ``` * Not every closure should be inlined in that way, so it required kotlin-like distinction of types for closure invocation. * That is why this class was created. Unfortunately, it has some drawbacks: * it required enormous amount of computation power to determine the kind of closure, like resolve of the method, invoking the closure, * and some auxiliary precomputations before actually running type inference. Also, increased number of dependencies in control flow graph * implied more time spent in thread-local resolves. * It must be noted that most of the closures are actually [UNKNOWN] or [IN_PLACE_UNKNOWN], because amount of [IN_PLACE_ONCE] closures is very low. * Users do not have the ability to specify the kind of closure execution, and, considering groovy popularity, it's unlikely to appear. * Therefore, it makes little sense in [IN_PLACE_ONCE]. * * [UNKNOWN], on the other hand, is likely to be the most popular invocation kind. But correct handling of it is too complicated: we need to * track all side effects, happening in the unknown closure, and considering them at __every__ usage of side-effect-affected object. * * So at last I decided to remove the effects of [UNKNOWN] and [IN_PLACE_ONCE] in favor of [IN_PLACE_UNKNOWN], because its handling is relatively easy. * I do not completely lose my hope to distinguish different closures and reach the primary goal specified above, but the * low number of code parts that can benefit from these changes (in their current implementation) do not worth performance degradation. */ enum class InvocationKind { /** * Indicates that functional expressions will be invoked inplace and only one time. * Such functional expressions may be inlined in the place where they are defined. */ IN_PLACE_ONCE, /** * Indicates that functional expressions will be invoked inplace, but amount of their invocations is undefined. * Such functional expressions act like code blocks under some conditional statement. */ IN_PLACE_UNKNOWN, /** * Indicates that functional expressions does not provide any information: * neither if it is invoked inplace, nor about the amount of invocations. */ UNKNOWN } @NonNls private val trustedMethodsForExecutingOnce: Set<String> = setOf( "identity", "runAfter", "tap", "use", "with" ) @NonNls private val trustedMethodsForExecutingManyTimes: Set<String> = setOf( "any", "collect", "collectEntries", "collectMany", "collectNested", "combinations", "count", "countBy", "downto", "dropWhile", "each", "eachByte", "eachCombination", "eachPermutation", "eachWithIndex", "every", "find", "findAll", "findIndexOf", "findResult", "findResults", "flatten", "groupBy", "inject", "max", "min", "removeAll", "retainAll", "reverseEach", "sort", "split", "step", "sum", "takeWhile", "times", "toSorted", "toUnique", "unique", "upto" ) private val knownMethods = trustedMethodsForExecutingManyTimes union trustedMethodsForExecutingOnce fun GrFunctionalExpression?.getControlFlowOwner(): GrControlFlowOwner? = when (this) { is GrClosableBlock -> this is GrLambdaExpression -> body else -> null } /** * Most of the invocations should be with mayCache=true */ fun GrFunctionalExpression?.getInvocationKind(mayCache: Boolean = true): InvocationKind { if (this == null) { return UNKNOWN } if (mayCache) { return CachedValuesManager.getCachedValue(this) { CachedValueProvider.Result(computeInvocationKind(this), this) } } else { return computeInvocationKind(this) } } private fun computeInvocationKind(block: GrFunctionalExpression): InvocationKind { val call = block.parentOfType<GrMethodCall>() ?: return UNKNOWN if ((call.invokedExpression as? GrReferenceExpression)?.referenceName !in knownMethods) { return UNKNOWN } if (call.getArguments()?.none { (it as? ExpressionArgument)?.expression?.skipParenthesesDownOrNull() === block } == true) { return UNKNOWN } val method = call.multiResolve(false).firstOrNull()?.element as? GrGdkMethod val primaryInvocationKind = when (method?.name) { in trustedMethodsForExecutingOnce -> IN_PLACE_ONCE in trustedMethodsForExecutingManyTimes -> IN_PLACE_UNKNOWN else -> return UNKNOWN } return primaryInvocationKind.weakenIfUsesSafeNavigation(call) } private fun InvocationKind.weakenIfUsesSafeNavigation(call: GrMethodCall): InvocationKind = when (this) { IN_PLACE_ONCE -> { val refExpr = PsiTreeUtil.findChildOfType(call, GrReferenceExpression::class.java) if (refExpr != null && refExpr.dotToken?.text == "?.") { IN_PLACE_UNKNOWN } else { IN_PLACE_ONCE } } else -> this } private const val GROOVY_FLAT_DFA = "groovy.flat.dfa" internal fun isFlatDFAAllowed(): Boolean = Registry.`is`(GROOVY_FLAT_DFA, false)
apache-2.0
16d052c1fc2f76a14065bb09d985c4b3
35.318436
151
0.749423
4.146046
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveAnnotationFix.kt
2
2540
// 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 import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtFile class RemoveAnnotationFix(@Nls private val text: String, annotationEntry: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry) { override fun getText() = text override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.delete() } object JvmOverloads : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveAnnotationFix? { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null return RemoveAnnotationFix(KotlinBundle.message("remove.jvmoverloads.annotation"), annotationEntry) } } object JvmField : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveAnnotationFix? { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null return RemoveAnnotationFix(KotlinBundle.message("remove.jvmfield.annotation"), annotationEntry) } } object ExtensionFunctionType : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveAnnotationFix? { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null return RemoveAnnotationFix(KotlinBundle.message("remove.extension.function.type.annotation"), annotationEntry) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): RemoveAnnotationFix? { val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return null return RemoveAnnotationFix(KotlinBundle.message("fix.remove.annotation.text"), annotationEntry = annotationEntry) } } }
apache-2.0
c85b3b4921f65b7c49c7b737f475d9ec
46.943396
158
0.759449
5.545852
false
false
false
false
g1144146/sds_for_kotlin
src/main/kotlin/sds/classfile/attribute/Annotation.kt
1
1030
package sds.classfile.attribute import sds.classfile.ClassfileStream open class Annotation(data: ClassfileStream) { val type: Int = data.short() val pairs: Array<ElementValuePair> = (0 until data.short()).map { ElementValuePair(data) } .toTypedArray() } class ArrayValue(data: ClassfileStream) { val values: Array<ElementValue> = (0 until data.short()).map { ElementValue(data) } .toTypedArray() } class ElementValuePair(data: ClassfileStream) { val name: Int = data.short() val value: ElementValue = ElementValue(data) } class ElementValue(data: ClassfileStream) { val tag: Char = data.byte() as Char val value: Any = when(tag) { in 'B'..'D', 'F', 'I', 'J', 'S', 'Z', 'c', 's' -> data.short() 'e' -> EnumConstValue(data) '@' -> Annotation(data) '[' -> ArrayValue(data) else -> throw RuntimeException("unknown tag: $tag") } } class EnumConstValue(data: ClassfileStream) { val typeName: Int = data.short() val constName: Int = data.short() }
apache-2.0
cd7e0e1858134c49cfe65f95a67f080d
30.242424
110
0.646602
3.564014
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriApi.kt
2
7484
package eu.kanade.tachiyomi.data.track.shikimori import androidx.core.net.toUri import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.await import eu.kanade.tachiyomi.network.jsonMime import eu.kanade.tachiyomi.network.parseAs import eu.kanade.tachiyomi.util.lang.withIOContext import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.float import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.toRequestBody class ShikimoriApi(private val client: OkHttpClient, interceptor: ShikimoriInterceptor) { private val authClient = client.newBuilder().addInterceptor(interceptor).build() suspend fun addLibManga(track: Track, user_id: String): Track { return withIOContext { val payload = buildJsonObject { putJsonObject("user_rate") { put("user_id", user_id) put("target_id", track.media_id) put("target_type", "Manga") put("chapters", track.last_chapter_read.toInt()) put("score", track.score.toInt()) put("status", track.toShikimoriStatus()) } } authClient.newCall( POST( "$apiUrl/v2/user_rates", body = payload.toString().toRequestBody(jsonMime) ) ).await() track } } suspend fun updateLibManga(track: Track, user_id: String): Track = addLibManga(track, user_id) suspend fun search(search: String): List<TrackSearch> { return withIOContext { val url = "$apiUrl/mangas".toUri().buildUpon() .appendQueryParameter("order", "popularity") .appendQueryParameter("search", search) .appendQueryParameter("limit", "20") .build() authClient.newCall(GET(url.toString())) .await() .parseAs<JsonArray>() .let { response -> response.map { jsonToSearch(it.jsonObject) } } } } private fun jsonToSearch(obj: JsonObject): TrackSearch { return TrackSearch.create(TrackManager.SHIKIMORI).apply { media_id = obj["id"]!!.jsonPrimitive.int title = obj["name"]!!.jsonPrimitive.content total_chapters = obj["chapters"]!!.jsonPrimitive.int cover_url = baseUrl + obj["image"]!!.jsonObject["preview"]!!.jsonPrimitive.content summary = "" tracking_url = baseUrl + obj["url"]!!.jsonPrimitive.content publishing_status = obj["status"]!!.jsonPrimitive.content publishing_type = obj["kind"]!!.jsonPrimitive.content start_date = obj.get("aired_on")!!.jsonPrimitive.contentOrNull ?: "" } } private fun jsonToTrack(obj: JsonObject, mangas: JsonObject): Track { return Track.create(TrackManager.SHIKIMORI).apply { title = mangas["name"]!!.jsonPrimitive.content media_id = obj["id"]!!.jsonPrimitive.int total_chapters = mangas["chapters"]!!.jsonPrimitive.int last_chapter_read = obj["chapters"]!!.jsonPrimitive.float score = (obj["score"]!!.jsonPrimitive.int).toFloat() status = toTrackStatus(obj["status"]!!.jsonPrimitive.content) tracking_url = baseUrl + mangas["url"]!!.jsonPrimitive.content } } suspend fun findLibManga(track: Track, user_id: String): Track? { return withIOContext { val urlMangas = "$apiUrl/mangas".toUri().buildUpon() .appendPath(track.media_id.toString()) .build() val mangas = authClient.newCall(GET(urlMangas.toString())) .await() .parseAs<JsonObject>() val url = "$apiUrl/v2/user_rates".toUri().buildUpon() .appendQueryParameter("user_id", user_id) .appendQueryParameter("target_id", track.media_id.toString()) .appendQueryParameter("target_type", "Manga") .build() authClient.newCall(GET(url.toString())) .await() .parseAs<JsonArray>() .let { response -> if (response.size > 1) { throw Exception("Too much mangas in response") } val entry = response.map { jsonToTrack(it.jsonObject, mangas) } entry.firstOrNull() } } } fun getCurrentUser(): Int { return runBlocking { authClient.newCall(GET("$apiUrl/users/whoami")) .await() .parseAs<JsonObject>() .let { it["id"]!!.jsonPrimitive.int } } } suspend fun accessToken(code: String): OAuth { return withIOContext { client.newCall(accessTokenRequest(code)) .await() .parseAs() } } private fun accessTokenRequest(code: String) = POST( oauthUrl, body = FormBody.Builder() .add("grant_type", "authorization_code") .add("client_id", clientId) .add("client_secret", clientSecret) .add("code", code) .add("redirect_uri", redirectUrl) .build() ) companion object { private const val clientId = "1aaf4cf232372708e98b5abc813d795b539c5a916dbbfe9ac61bf02a360832cc" private const val clientSecret = "229942c742dd4cde803125d17d64501d91c0b12e14cb1e5120184d77d67024c0" private const val baseUrl = "https://shikimori.one" private const val apiUrl = "$baseUrl/api" private const val oauthUrl = "$baseUrl/oauth/token" private const val loginUrl = "$baseUrl/oauth/authorize" private const val redirectUrl = "tachiyomi://shikimori-auth" private const val baseMangaUrl = "$apiUrl/mangas" fun mangaUrl(remoteId: Int): String { return "$baseMangaUrl/$remoteId" } fun authUrl() = loginUrl.toUri().buildUpon() .appendQueryParameter("client_id", clientId) .appendQueryParameter("redirect_uri", redirectUrl) .appendQueryParameter("response_type", "code") .build() fun refreshTokenRequest(token: String) = POST( oauthUrl, body = FormBody.Builder() .add("grant_type", "refresh_token") .add("client_id", clientId) .add("client_secret", clientSecret) .add("refresh_token", token) .build() ) } }
apache-2.0
bd111d1e40e637428df757453028f854
37.979167
107
0.583645
4.785166
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/examples/advanced/VideoDecodingExample.kt
2
3686
package graphics.scenery.tests.examples.advanced import graphics.scenery.BufferUtils import graphics.scenery.DetachedHeadCamera import graphics.scenery.FullscreenObject import graphics.scenery.SceneryBase import graphics.scenery.backends.Renderer import graphics.scenery.textures.Texture import graphics.scenery.utils.VideoDecoder import org.joml.Quaternionf import org.joml.Vector3f import org.joml.Vector3i import java.io.FileNotFoundException import java.nio.ByteBuffer import kotlin.concurrent.thread import kotlin.test.assertTrue /** * Example to show programmatic video decoding. It also demonstrates how the [FullscreenObject] class and its associated shaders may * be used to display an image in full screen. * * @author Aryaman Gupta <[email protected]> */ class VideoDecodingExample : SceneryBase("VideoDecodingExample", 600, 600, wantREPL = false) { var buffer: ByteBuffer = ByteBuffer.allocateDirect(0) var decodedFrameCount: Int = 0 override fun init () { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val cam = DetachedHeadCamera() with(cam) { perspectiveCamera(50.0f, windowWidth, windowHeight) spatial { position = Vector3f(3.213f, 8.264E-1f, -9.844E-1f) rotation = Quaternionf(3.049E-2, 9.596E-1, -1.144E-1, -2.553E-1) } scene.addChild(this) } val plane = FullscreenObject() scene.addChild(plane) settings.set("Renderer.HDR.Exposure", 0.05f) val videoDecoder = VideoDecoder(this::class.java.getResource("SampleVideo.mp4")?.sanitizedPath() ?: throw FileNotFoundException("Could not find sample file.")) logger.info("video decoder object created") thread { while (!sceneInitialized()) { Thread.sleep(200) } decodedFrameCount = 1 while (videoDecoder.nextFrameExists) { val image = videoDecoder.decodeFrame() /* the decoded image is returned as a ByteArray, and can now be processed. Here, it is simply displayed in fullscreen */ if(image != null) { // image can be null, e.g. when the decoder encounters invalid information between frames drawFrame(image, videoDecoder.videoWidth, videoDecoder.videoHeight, plane, decodedFrameCount) decodedFrameCount++ } } decodedFrameCount -= 1 logger.info("Done decoding and displaying $decodedFrameCount frames.") } } private fun drawFrame(tex: ByteArray, width: Int, height: Int, plane: FullscreenObject, frameIndex: Int) { if(frameIndex % 100 == 0) { logger.info("Displaying frame $frameIndex") } if(buffer.capacity() == 0) { buffer = BufferUtils.allocateByteAndPut(tex) } else { buffer.put(tex).flip() } plane.material { textures["diffuse"] = Texture(Vector3i(width, height, 1), 4, contents = buffer, mipmap = true) } } override fun main() { // add assertions, these only get called when the example is called // as part of scenery's integration tests assertions[AssertionCheckPoint.AfterClose]?.add { assertTrue ( decodedFrameCount == 105, "All frames of the video were read and decoded" ) } super.main() } companion object { @JvmStatic fun main(args: Array<String>) { VideoDecodingExample().main() } } }
lgpl-3.0
52d1d456c5284c074b55f51fd10956c8
33.773585
167
0.636462
4.545006
false
false
false
false
neva-dev/javarel-framework
presentation/view/src/main/kotlin/com/neva/javarel/presentation/view/impl/MultiViewManager.kt
1
2104
package com.neva.javarel.presentation.view.impl import com.google.common.collect.Sets import com.neva.javarel.foundation.api.adapting.Adapter import com.neva.javarel.presentation.view.api.View import com.neva.javarel.presentation.view.api.ViewEngine import com.neva.javarel.presentation.view.api.ViewManager import com.neva.javarel.resource.api.Resource import com.neva.javarel.resource.api.ResourceAdapter import com.neva.javarel.resource.api.ResourceException import com.neva.javarel.resource.api.ResourceResolver import org.apache.felix.scr.annotations.* import kotlin.reflect.KClass @Component(immediate = true) @Service(ViewManager::class, Adapter::class) class MultiViewManager : ViewManager, ResourceAdapter<View>() { @Reference( referenceInterface = ViewEngine::class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY ) private val engines = Sets.newConcurrentHashSet<ViewEngine>() @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY) private lateinit var resourceResolver: ResourceResolver override val targetType: KClass<View> get() = View::class override fun adapt(adaptable: Resource): View { for (engine in engines) { if (engine.handles(adaptable.descriptor)) { return engine.make(adaptable) } } throw ResourceException("Cannot find a view engine for resource: '${adaptable.descriptor}'") } override fun make(resource: Resource): View { return adapt(resource) } override fun make(resourceUri: String): View { return make(resourceResolver.findOrFail(resourceUri)) } override fun make(template: String, extension: String): View { return make(ViewTemplateResource(template, extension, resourceResolver)) } protected fun bindViewEngine(engine: ViewEngine) { engines.add(engine) } protected fun unbindViewEngine(engine: ViewEngine) { engines.remove(engine) } }
apache-2.0
f53ae0291e325679abf018a537e26ad1
32.951613
100
0.721958
4.356108
false
false
false
false
kymjs/oschina-gam
app/src/main/java/org/kymjs/oschina/ui/fragment/FriendGroup.kt
1
2651
package org.kymjs.oschina.ui.fragment import android.graphics.Rect import android.os.Bundle import android.support.v7.widget.DefaultItemAnimator 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 org.kymjs.kjframe.http.HttpCallBack import org.kymjs.kjframe.ui.BindView import org.kymjs.oschina.R import org.kymjs.oschina.adapter.FriendGroupAdapter import org.kymjs.oschina.api.OSChinaApi import org.kymjs.oschina.ui.widget.CircleRefreshLayout /** * 好友动态列表界面 * @author kymjs (http://www.kymjs.com/) on 8/12/15. */ public class FriendGroup : BaseMainFragment() { @BindView(id = R.id.recyclerView) private val recyclerView: RecyclerView? = null @BindView(id = R.id.swiperefreshlayout) private val refreshLayout: CircleRefreshLayout? = null private var datas: MutableList<String>? = null override fun inflaterView(layoutInflater: LayoutInflater, viewGroup: ViewGroup, bundle: Bundle?): View? { val rootView: View = layoutInflater.inflate(R.layout.frag_main_friendgroup, null) return rootView } override fun initWidget(parentView: View?) { super.initWidget(parentView) setContentData(0) refreshLayout?.setOnRefreshListener(object : CircleRefreshLayout.OnCircleRefreshListener { override fun refreshing() { refreshLayout.finishRefreshing(); } override fun completeRefresh() { } }) recyclerView?.setLayoutManager(LinearLayoutManager(outsideAty)) recyclerView?.setItemAnimator(DefaultItemAnimator()) val itemDecoration: RecyclerView.ItemDecoration = DividerItemDecoration(); recyclerView?.addItemDecoration(itemDecoration); val adapter = FriendGroupAdapter() recyclerView?.setAdapter(adapter) } override fun onResume() { super.onResume() setTitle("好友动态") } /** * set RecyclerView divider height 20px */ inner class DividerItemDecoration : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state); outRect.set(0, 0, 0, 20);//每个item的底部偏移 } } fun setContentData(page: Int) { OSChinaApi.getFriendGroupList(page, object : HttpCallBack() { override fun onSuccess(t: String) { } }) } }
apache-2.0
5acc26a09d4ce5c3ec53eebfbe315a9a
30.865854
113
0.693456
4.451448
false
false
false
false
aerisweather/AerisAndroidSDK
Kotlin/AerisSdkDemo/app/src/androidTest/java/com/example/demoaerisproject/data/preferenceStore/PrefStoreRepositoryTest.kt
1
2747
package com.example.demoaerisproject.data.preferenceStore import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class PrefStoreRepositoryTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext Assert.assertEquals("com.example.demoaerisproject", appContext.packageName) } @Test fun happy_path_insert_retrieve_boolean() { val appContext = InstrumentationRegistry.getInstrumentation().targetContext val repo = PrefStoreRepository(appContext) CoroutineScope(Dispatchers.Default).launch { repo.getBoolean(PrefStoreRepository.NOTIFICATION_ENABLED_KEY).collect { Assert.assertEquals(true, it) } } runBlocking { repo.setBoolean(PrefStoreRepository.NOTIFICATION_ENABLED_KEY, true) } } @Test fun happy_path_insert_retrieve_reified_boolean() { val appContext = InstrumentationRegistry.getInstrumentation().targetContext val repo = PrefStoreRepository(appContext) repo.set(PrefStoreRepository.NOTIFICATION_ENABLED_KEY, true) val isNotificationEnabled = repo.get(PrefStoreRepository.NOTIFICATION_ENABLED_KEY, false) Assert.assertEquals(true, isNotificationEnabled) } @Test fun happy_path_insert_retrieve_reified_int() { val appContext = InstrumentationRegistry.getInstrumentation().targetContext val repo = PrefStoreRepository(appContext) repo.set(PrefStoreRepository.LAST_FRAGMENT_KEY, 22) val id = repo.get(PrefStoreRepository.LAST_FRAGMENT_KEY, 1) Assert.assertEquals(22, id) } @Test fun happy_path_insert_retrieve_reified_string() { val appContext = InstrumentationRegistry.getInstrumentation().targetContext val repo = PrefStoreRepository(appContext) repo.set(PrefStoreRepository.STRING_FLAG, "abc") val str = repo.get(PrefStoreRepository.STRING_FLAG, "a") Assert.assertEquals("abc", str) } @Test fun happy_path_insert_retrieve_reified_long() { val appContext = InstrumentationRegistry.getInstrumentation().targetContext val repo = PrefStoreRepository(appContext) repo.set(PrefStoreRepository.LONG_FLAG, 10L) val number = repo.get(PrefStoreRepository.LONG_FLAG, 1L) Assert.assertEquals(10L, number) } }
mit
8b2398a94ae13cab14e5e665fdbbe05e
36.135135
97
0.724791
4.827768
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/OptionalExpectationInspection.kt
2
4408
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.quickfix.expectactual.CreateActualClassFix import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.oldFashionedDescription import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.classOrObjectVisitor import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker.Companion.allStrongIncompatibilities import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.multiplatform.ExpectActualCompatibility import org.jetbrains.kotlin.resolve.multiplatform.ExpectedActualResolver import org.jetbrains.kotlin.resolve.multiplatform.OptionalAnnotationUtil import org.jetbrains.kotlin.resolve.multiplatform.onlyFromThisModule class OptionalExpectationInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return classOrObjectVisitor(fun(classOrObject: KtClassOrObject) { if (classOrObject !is KtClass || !classOrObject.isAnnotation()) return if (!classOrObject.hasExpectModifier()) return val descriptor = classOrObject.resolveToDescriptorIfAny() ?: return if (!descriptor.annotations.hasAnnotation(OptionalAnnotationUtil.OPTIONAL_EXPECTATION_FQ_NAME)) return // FIXME(dsavvinov): this is wrong in HMPP model, use logic similar to ExpectedActualDeclarationChecker val implementingModules = classOrObject.findModuleDescriptor().implementingDescriptors if (implementingModules.isEmpty()) return for (actualModuleDescriptor in implementingModules) { val compatibility = ExpectedActualResolver.findActualForExpected( descriptor, actualModuleDescriptor, onlyFromThisModule(actualModuleDescriptor) ) ?: continue if (!compatibility.allStrongIncompatibilities() && (ExpectActualCompatibility.Compatible in compatibility || !compatibility.values.flatMapTo( hashSetOf() ) { it }.all { actual -> val expectedOnes = ExpectedActualResolver.findExpectedForActual( actual, onlyFromThisModule(descriptor.module) ) expectedOnes != null && ExpectActualCompatibility.Compatible in expectedOnes.keys }) ) continue val platform = actualModuleDescriptor.platform ?: continue if (platform.isCommon()) continue val displayedName = actualModuleDescriptor.getCapability(ModuleInfo.Capability)?.displayedName ?: "" val actualModule = (actualModuleDescriptor.getCapability(ModuleInfo.Capability) as? ModuleSourceInfo)?.module ?: continue holder.registerProblem( classOrObject.nameIdentifier ?: classOrObject, KotlinBundle.message( "optionally.expected.annotation.has.no.actual.annotation.in.module.0.for.platform.1", displayedName, platform.oldFashionedDescription ), IntentionWrapper(CreateActualClassFix(classOrObject, actualModule, platform)) ) } }) } }
apache-2.0
2bdc01982c8e8ba695b3f408253af619
57.773333
158
0.711207
5.754569
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/training/environment/Locator.kt
1
6349
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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 de.dreier.mytargets.features.training.environment import android.Manifest.permission.ACCESS_COARSE_LOCATION import android.Manifest.permission.ACCESS_FINE_LOCATION import android.annotation.SuppressLint import android.content.Context import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import androidx.annotation.RequiresPermission import androidx.core.content.getSystemService import timber.log.Timber /** * Get device location using various methods * * @author emil http://stackoverflow.com/users/220710/emil */ class Locator(private val context: Context) : LocationListener { private val locationManager = context.getSystemService<LocationManager>()!! private var method: Locator.Method? = null private var callback: Locator.Listener? = null enum class Method { NETWORK, GPS, NETWORK_THEN_GPS } @SuppressLint("MissingPermission", "SupportAnnotationUsage") @RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION]) fun getLocation(method: Locator.Method, callback: Locator.Listener) { this.method = method this.callback = callback when (this.method) { Locator.Method.NETWORK, Locator.Method.NETWORK_THEN_GPS -> { val networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) if (networkLocation != null) { Timber.d( "Last known location found for network provider : %s", networkLocation .toString() ) this.callback!!.onLocationFound(networkLocation) } else { Timber.d("Request updates from network provider.") this.requestUpdates(LocationManager.NETWORK_PROVIDER) } } Locator.Method.GPS -> { val gpsLocation = this.locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER) if (gpsLocation != null) { Timber.d( "Last known location found for GPS provider : %s", gpsLocation .toString() ) this.callback!!.onLocationFound(gpsLocation) } else { Timber.d("Request updates from GPS provider.") this.requestUpdates(LocationManager.GPS_PROVIDER) } } } } @SuppressLint("MissingPermission", "SupportAnnotationUsage") @RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION]) private fun requestUpdates(provider: String) { if (locationManager.isProviderEnabled(provider)) { if (provider.contentEquals(LocationManager.NETWORK_PROVIDER) && Connectivity.isConnected( this.context ) ) { Timber.d("Network connected, start listening : %s", provider) locationManager .requestLocationUpdates( provider, TIME_INTERVAL.toLong(), DISTANCE_INTERVAL.toFloat(), this ) } else if (provider.contentEquals(LocationManager.GPS_PROVIDER) && Connectivity.isConnectedMobile( this.context ) ) { Timber.d("Mobile network connected, start listening : %s", provider) locationManager .requestLocationUpdates( provider, TIME_INTERVAL.toLong(), DISTANCE_INTERVAL.toFloat(), this ) } else { Timber.d("Proper network not connected for provider : %s", provider) onProviderDisabled(provider) } } else { onProviderDisabled(provider) } } fun cancel() { Timber.d("Locating canceled.") locationManager.removeUpdates(this) } override fun onLocationChanged(location: Location) { Timber.d( "Location found : %f, %f%s", location.latitude, location .longitude, if (location.hasAccuracy()) " : +- ${location.accuracy} meters" else "" ) locationManager.removeUpdates(this) callback!!.onLocationFound(location) } override fun onProviderDisabled(provider: String) { Timber.d("Provider disabled : %s", provider) if (this.method == Locator.Method.NETWORK_THEN_GPS && provider.contentEquals(LocationManager.NETWORK_PROVIDER)) { // Network provider disabled, try GPS Timber.d("Request updates from GPS provider, network provider disabled.") this.requestUpdates(LocationManager.GPS_PROVIDER) } else { this.locationManager.removeUpdates(this) this.callback!!.onLocationNotFound() } } override fun onProviderEnabled(provider: String) { Timber.d("Provider enabled : %s", provider) } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) { Timber.d("Provided status changed : $provider : status : $status") } interface Listener { fun onLocationFound(location: Location) fun onLocationNotFound() } companion object { private const val TIME_INTERVAL = 100 // minimum time between updates in milliseconds private const val DISTANCE_INTERVAL = 1 // minimum distance between updates in meters } }
gpl-2.0
802b1ab803ab527eae23bad46920af5f
37.017964
121
0.600095
5.389643
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/analysis/aggregation/cluster/Cluster.kt
1
1974
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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 de.dreier.mytargets.shared.analysis.aggregation.cluster import android.graphics.PointF import de.dreier.mytargets.shared.analysis.aggregation.average.Average import de.dreier.mytargets.shared.models.db.Shot import java.util.* class Cluster(private val totalNumber: Int) { val points = ArrayList<Shot>() private val centerOfGroup = PointF() private var isDirty = false private val weight = 0.0 var stdDev: Double = 0.toDouble() val size: Int get() = points.size init { isDirty = true } private fun compute() { if (!isDirty) { return } val average = Average() average.computeAverage(points) average.computeStdDevX(points) average.computeStdDevY(points) centerOfGroup.set(average.average) stdDev = average.stdDev isDirty = false } fun add(paramPointF: Shot) { points.add(paramPointF) isDirty = true } fun getCenterOfGroup(): PointF { compute() return centerOfGroup } fun getWeight(): Double { compute() return weight } override fun toString(): String { return "Cluster{" + "points=" + points + ", centerOfGroup=" + centerOfGroup + ", totalNumber=" + totalNumber + ", isDirty=" + isDirty + ", weight=" + weight + '}' } }
gpl-2.0
31c0f57ba3485db51e21d58e89285115
25.675676
70
0.622087
4.496583
false
false
false
false
MarkusAmshove/Kluent
jvm/src/main/kotlin/org/amshove/kluent/AssertionErrors.kt
1
2527
package org.amshove.kluent import org.junit.ComparisonFailure /** An error that bundles multiple other [Throwable]s together */ actual class MultiAssertionError actual constructor(errors: List<Throwable>) : AssertionError(createMessage(errors)) { companion object { private fun createMessage(errors: List<Throwable>) = buildString { append("The following ") if (errors.size == 1) { append("assertion") } else { append(errors.size).append(" assertions") } append(" failed:\n") if (errors.size == 1) { append(formatException(errors[0])) stacktraces.throwableLocation(errors[0])?.let { append("at ").append(it) } } else { for ((i, err) in errors.withIndex()) { append(formatException(err, i)) stacktraces.throwableLocation(err)?.let { append("at ").append(it).append(System.lineSeparator()) } } } } private fun formatException(error: Throwable, errorIndex: Int? = null): String { when (error) { is ComparisonFailure -> { return if (errorIndex == null) { "Are not equivalent:\nExpected:\n${error.expected}\nbut was:\n${error.actual}".trimMargin() } else { "${errorIndex + 1}) Are not equivalent:\nExpected:\n${error.expected}but was:\n${error.actual}".trimMargin() } } else -> { return if (errorIndex == null) { if (error.message == null) { "" } else { "${error.message!!}\n" } } else { "${errorIndex + 1}) ${error.message}\n" } } } } } } actual fun assertionError(error: Throwable): Throwable { val message = buildString { append("The following assertion failed:\n") append(error.message).append(System.lineSeparator()) stacktraces.throwableLocation(error)?.let { append("at ").append(it).append(System.lineSeparator()) } } val t = AssertionError(message) stacktraces.cleanStackTrace(t) return t }
mit
9e7191907856c1ed504d057fb03d12f0
34.591549
132
0.48239
5.136179
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/util/SingleAlarm.kt
1
3548
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState class SingleAlarm @JvmOverloads constructor(private val task: Runnable, private val delay: Int, parentDisposable: Disposable? = null, threadToUse: ThreadToUse = ThreadToUse.SWING_THREAD, private val modalityState: ModalityState? = computeDefaultModality(threadToUse)) : Alarm(threadToUse, parentDisposable) { constructor(task: Runnable, delay: Int, modalityState: ModalityState, parentDisposable: Disposable) : this(task, delay = delay, parentDisposable = parentDisposable, threadToUse = ThreadToUse.SWING_THREAD, modalityState = modalityState) constructor(task: Runnable, delay: Int, threadToUse: Alarm.ThreadToUse, parentDisposable: Disposable) : this(task, delay = delay, parentDisposable = parentDisposable, threadToUse = threadToUse, modalityState = computeDefaultModality(threadToUse)) init { if (threadToUse == ThreadToUse.SWING_THREAD && modalityState == null) { throw IllegalArgumentException("modalityState must be not null if threadToUse == ThreadToUse.SWING_THREAD") } } @JvmOverloads fun request(forceRun: Boolean = false, delay: Int = [email protected]) { if (isEmpty) { _addRequest(task, if (forceRun) 0 else delay.toLong(), modalityState) } } /** * Cancel doesn't interrupt already running task. */ fun cancel() { cancelAllRequests() } /** * Cancel doesn't interrupt already running task. */ @JvmOverloads fun cancelAndRequest(forceRun: Boolean = false) { if (!isDisposed) { cancelAllAndAddRequest(task, if (forceRun) 0 else delay, modalityState) } } fun getUnfinishedRequest(): Runnable? { val unfinishedTasks = unfinishedRequests if (unfinishedTasks.isEmpty()) { return null } LOG.assertTrue(unfinishedTasks.size == 1) return unfinishedTasks.first() } } fun pooledThreadSingleAlarm(delay: Int, parentDisposable: Disposable = ApplicationManager.getApplication(), task: () -> Unit): SingleAlarm { return SingleAlarm(Runnable(task), delay = delay, threadToUse = Alarm.ThreadToUse.POOLED_THREAD, parentDisposable = parentDisposable) } private fun computeDefaultModality(threadToUse: Alarm.ThreadToUse): ModalityState? { return when (threadToUse) { Alarm.ThreadToUse.SWING_THREAD -> ModalityState.NON_MODAL else -> null } }
apache-2.0
aab252dd19f87a71681e7d0405bc44bc
46.959459
165
0.54876
6.075342
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Friend.kt
1
1024
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.common.startsWith import org.objectweb.asm.Type.BOOLEAN_TYPE import org.objectweb.asm.Type.INT_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Method2 @DependsOn(Buddy::class) class Friend : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Buddy>() } .and { it.instanceFields.count { it.type == BOOLEAN_TYPE } == 2 } @MethodParameters("other") class compareTo00 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.arguments.startsWith(type<Friend>()) } } }
mit
ecbc6f0f956a2118b87b0da7b8a8e8fe
40
83
0.757813
3.968992
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/declarative/impl/InlayTags.kt
1
753
// 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.codeInsight.hints.declarative.impl object InlayTags { const val LIST_TAG: Byte = 0 const val TEXT_TAG: Byte = 1 const val ICON_TAG: Byte = 2 const val COLLAPSE_BUTTON_TAG: Byte = 3 const val COLLAPSIBLE_LIST_EXPANDED_BRANCH_TAG: Byte = 4 const val COLLAPSIBLE_LIST_COLLAPSED_BRANCH_TAG: Byte = 5 const val COLLAPSIBLE_LIST_EXPLICITLY_EXPANDED_TAG: Byte = 6 const val COLLAPSIBLE_LIST_IMPLICITLY_EXPANDED_TAG: Byte = 7 const val COLLAPSIBLE_LIST_EXPLICITLY_COLLAPSED_TAG: Byte = 8 const val COLLAPSIBLE_LIST_IMPLICITLY_COLLAPSED_TAG: Byte = 9 const val CLICK_HANDLER_SCOPE_TAG: Byte = 10 }
apache-2.0
b537ef30f9e74016a732703472562556
46.125
120
0.756972
3.585714
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/InlayHintsUtils.kt
1
11580
// 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.codeInsight.hints import com.intellij.codeInsight.hints.presentation.* import com.intellij.configurationStore.deserializeInto import com.intellij.configurationStore.serialize import com.intellij.lang.Language import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.application.invokeLater import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.markup.EffectType import com.intellij.openapi.editor.markup.TextAttributesEffectsBuilder import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import com.intellij.util.SmartList import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.Nls.Capitalization.Title import java.awt.Dimension import java.awt.Rectangle import java.util.function.Supplier class ProviderWithSettings<T: Any>( val info: ProviderInfo<T>, var settings: T ) { val configurable: ImmediateConfigurable by lazy { provider.createConfigurable(settings) } val provider: InlayHintsProvider<T> get() = info.provider val language: Language get() = info.language } fun <T : Any> ProviderWithSettings<T>.withSettingsCopy(): ProviderWithSettings<T> { val settingsCopy = copySettings(settings, provider) return ProviderWithSettings(info, settingsCopy) } fun <T : Any> ProviderWithSettings<T>.getCollectorWrapperFor(file: PsiFile, editor: Editor, language: Language): CollectorWithSettings<T>? { val key = provider.key val sink = InlayHintsSinkImpl(editor) val collector = provider.getCollectorFor(file, editor, settings, sink) ?: return null return CollectorWithSettings(collector, key, language, sink) } internal fun <T : Any> ProviderWithSettings<T>.getPlaceholdersCollectorFor(file: PsiFile, editor: Editor): CollectorWithSettings<T>? { val key = provider.key val sink = InlayHintsSinkImpl(editor) val collector = provider.getPlaceholdersCollectorFor(file, editor, settings, sink) ?: return null return CollectorWithSettings(collector, key, language, sink) } internal fun <T : Any> InlayHintsProvider<T>.withSettings(language: Language, config: InlayHintsSettings): ProviderWithSettings<T> { val settings = getActualSettings(config, language) return ProviderWithSettings(ProviderInfo(language, this), settings) } internal fun <T : Any> InlayHintsProvider<T>.getActualSettings(config: InlayHintsSettings, language: Language): T = config.findSettings(key, language) { createSettings() } internal fun <T : Any> copySettings(from: T, provider: InlayHintsProvider<T>): T { val settings = provider.createSettings() // Workaround to make a deep copy of settings. The other way is to parametrize T with something like // interface DeepCopyable<T> { fun deepCopy(from: T): T }, but there will be a lot of problems with recursive type bounds // That way was implemented and rejected serialize(from)?.deserializeInto(settings) return settings } internal fun strikeOutBuilder(editor: Editor): TextAttributesEffectsBuilder { val effectColor = editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.INLAY_DEFAULT).foregroundColor return TextAttributesEffectsBuilder.create().coverWith(EffectType.STRIKEOUT, effectColor) } class CollectorWithSettings<T : Any>( val collector: InlayHintsCollector, val key: SettingsKey<T>, val language: Language, val sink: InlayHintsSinkImpl ) { fun collectHints(element: PsiElement, editor: Editor): Boolean { return collector.collect(element, editor, sink) } /** * Collects hints from the file and apply them to editor. * Doesn't expect other hints in editor. * Use only for settings preview. */ fun collectTraversingAndApply(editor: Editor, file: PsiFile, enabled: Boolean) { val hintsBuffer = collectTraversing(editor, file, enabled) applyToEditor(file, editor, hintsBuffer) } /** * Same as [collectTraversingAndApply] but invoked on bg thread */ fun collectTraversingAndApplyOnEdt(editor: Editor, file: PsiFile, enabled: Boolean) { val hintsBuffer = collectTraversing(editor, file, true) if (!enabled) { val builder = strikeOutBuilder(editor) addStrikeout(hintsBuffer.inlineHints, builder) { root, constraints -> HorizontalConstrainedPresentation(root, constraints) } addStrikeout(hintsBuffer.blockAboveHints, builder) { root, constraints -> BlockConstrainedPresentation(root, constraints) } addStrikeout(hintsBuffer.blockBelowHints, builder) { root, constraints -> BlockConstrainedPresentation(root, constraints) } } invokeLater { applyToEditor(file, editor, hintsBuffer) } } fun collectTraversing(editor: Editor, file: PsiFile, enabled: Boolean): HintsBuffer { if (enabled) { val traverser = SyntaxTraverser.psiTraverser(file) traverser.forEach { collectHints(it, editor) } } return sink.complete() } fun applyToEditor(file: PsiFile, editor: Editor, hintsBuffer: HintsBuffer) { InlayHintsPass.applyCollected(hintsBuffer, file, editor) } } internal fun <T: Any> addStrikeout(inlineHints: Int2ObjectOpenHashMap<MutableList<ConstrainedPresentation<*, T>>>, builder: TextAttributesEffectsBuilder, factory: (RootInlayPresentation<*>, T?) -> ConstrainedPresentation<*, T> ) { inlineHints.forEach { it.value.replaceAll { presentation -> val transformer = AttributesTransformerPresentation(presentation.root) { builder.applyTo(it) } val rootPresentation = RecursivelyUpdatingRootPresentation(transformer) factory(rootPresentation, presentation.constraints) } } } fun InlayPresentation.fireContentChanged() { fireContentChanged(Rectangle(width, height)) } fun InlayPresentation.fireUpdateEvent(previousDimension: Dimension) { val current = dimension() if (previousDimension != current) { fireSizeChanged(previousDimension, current) } fireContentChanged() } fun InlayPresentation.dimension() = Dimension(width, height) private typealias ConstrPresent<C> = ConstrainedPresentation<*, C> @ApiStatus.Experimental fun InlayHintsSink.addCodeVisionElement(editor: Editor, offset: Int, priority: Int, presentation: InlayPresentation) { val line = editor.document.getLineNumber(offset) val column = offset - editor.document.getLineStartOffset(line) val root = RecursivelyUpdatingRootPresentation(presentation) val constraints = BlockConstraints(false, priority, InlayGroup.CODE_VISION_GROUP.ordinal, column) addBlockElement(line, true, root, constraints) } object InlayHintsUtils { fun getDefaultInlayHintsProviderPopupActions( providerKey: SettingsKey<*>, providerName: Supplier<@Nls(capitalization = Title) String> ): List<AnAction> = listOf( DisableInlayHintsProviderAction(providerKey, providerName, false), ConfigureInlayHintsProviderAction(providerKey) ) fun getDefaultInlayHintsProviderCasePopupActions( providerKey: SettingsKey<*>, providerName: Supplier<@Nls(capitalization = Title) String>, caseId: String, caseName: Supplier<@Nls(capitalization = Title) String> ): List<AnAction> = listOf( DisableInlayHintsProviderCaseAction(providerKey, providerName, caseId, caseName), DisableInlayHintsProviderAction(providerKey, providerName, true), ConfigureInlayHintsProviderAction(providerKey) ) /** * Function updates list of old presentations with new list, taking into account priorities. * Both lists must be sorted. * * @return list of updated constrained presentations */ fun <Constraint : Any> produceUpdatedRootList( new: List<ConstrPresent<Constraint>>, old: List<ConstrPresent<Constraint>>, comparator: Comparator<ConstrPresent<Constraint>>, editor: Editor, factory: InlayPresentationFactory ): List<ConstrPresent<Constraint>> { val updatedPresentations: MutableList<ConstrPresent<Constraint>> = SmartList() // TODO [roman.ivanov] // this function creates new list anyway, even if nothing from old presentations got updated, // which makes us update list of presentations on every update (which should be relatively rare!) // maybe I should really create new list only in case when anything get updated val oldSize = old.size val newSize = new.size var oldIndex = 0 var newIndex = 0 // Simultaneous bypass of both lists and merging them to new one with element update loop@ while (true) { val newEl = new[newIndex] val oldEl = old[oldIndex] val value = comparator.compare(newEl, oldEl) when { value > 0 -> { oldIndex++ if (oldIndex == oldSize) { break@loop } } value < 0 -> { updatedPresentations.add(newEl) newIndex++ if (newIndex == newSize) { break@loop } } else -> { val oldRoot = oldEl.root val newRoot = newEl.root if (newRoot.key == oldRoot.key) { oldRoot.updateIfSame(newRoot, editor, factory) updatedPresentations.add(oldEl) } else { updatedPresentations.add(newEl) } newIndex++ oldIndex++ if (newIndex == newSize || oldIndex == oldSize) { break@loop } } } } for (i in newIndex until newSize) { updatedPresentations.add(new[i]) } return updatedPresentations } /** * @return true iff updated */ private fun <Content : Any>RootInlayPresentation<Content>.updateIfSame( newPresentation: RootInlayPresentation<*>, editor: Editor, factory: InlayPresentationFactory ) : Boolean { if (key != newPresentation.key) return false @Suppress("UNCHECKED_CAST") return update(newPresentation.content as Content, editor, factory) } /** * Note that the range may still be invalid if document doesn't match PSI */ fun getTextRangeWithoutLeadingCommentsAndWhitespaces(element: PsiElement): TextRange { val start = SyntaxTraverser.psiApi().children(element).firstOrNull { it !is PsiComment && it !is PsiWhiteSpace } ?: element return TextRange.create(start.startOffset, element.endOffset) } @JvmStatic fun isFirstInLine(element: PsiElement): Boolean { var prevLeaf = PsiTreeUtil.prevLeaf(element, true) if (prevLeaf == null) { return true } while (prevLeaf is PsiWhiteSpace) { if (prevLeaf.textContains('\n') || prevLeaf.textRange.startOffset == 0) { return true } prevLeaf = PsiTreeUtil.prevLeaf(prevLeaf, true) } return false } private val TEXT_METRICS_STORAGE = Key.create<InlayTextMetricsStorage>("InlayTextMetricsStorage") internal fun getTextMetricStorage(editor: EditorImpl): InlayTextMetricsStorage { val storage = editor.getUserData(TEXT_METRICS_STORAGE) if (storage == null) { val newStorage = InlayTextMetricsStorage(editor) editor.putUserData(TEXT_METRICS_STORAGE, newStorage) return newStorage } return storage } }
apache-2.0
3421288b09ae8eda146e7477018016be
36.358065
140
0.731347
4.550098
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/OpenLinkInDefaultActivity.kt
1
2803
package com.nononsenseapps.feeder.ui import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Browser.EXTRA_CREATE_NEW_TAB import android.util.Log import android.widget.Toast import androidx.lifecycle.lifecycleScope import com.nononsenseapps.feeder.R import com.nononsenseapps.feeder.base.DIAwareComponentActivity import com.nononsenseapps.feeder.db.COL_LINK import com.nononsenseapps.feeder.db.room.ID_UNSET import com.nononsenseapps.feeder.model.cancelNotification import com.nononsenseapps.feeder.util.DEEP_LINK_HOST import kotlinx.coroutines.launch import org.kodein.di.instance /** * Proxy activity to mark item as read and notified in database as well as cancelling the * notification before performing a notification action such as opening in the browser. * * If link is null, then item is only marked as read and notified. */ class OpenLinkInDefaultActivity : DIAwareComponentActivity() { private val viewModel: OpenLinkInDefaultActivityViewModel by instance(arg = this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent?.let { intent -> val uri = intent.data if (uri?.host == DEEP_LINK_HOST && uri.lastPathSegment == "feed") { val feedItemIds = intent.getLongArrayExtra(EXTRA_FEEDITEMS_TO_MARK_AS_NOTIFIED) ?: longArrayOf() viewModel.markAsNotifiedInBackground(feedItemIds.toList()) startActivity( Intent( Intent.ACTION_VIEW, uri, this, MainActivity::class.java ) ) } else { handleNotificationActions(intent) } } // Terminate activity immediately finish() } private fun handleNotificationActions(intent: Intent) { val id: Long = intent.data?.lastPathSegment?.toLong() ?: ID_UNSET val link: String? = intent.data?.getQueryParameter(COL_LINK) lifecycleScope.launch { viewModel.markAsReadAndNotified(id) cancelNotification(this@OpenLinkInDefaultActivity, id) } if (link != null) { try { startActivity( Intent(Intent.ACTION_VIEW, Uri.parse(link)).also { intent.putExtra(EXTRA_CREATE_NEW_TAB, true) } ) } catch (e: Throwable) { e.printStackTrace() Toast.makeText(this, R.string.no_activity_for_link, Toast.LENGTH_SHORT).show() Log.e("FeederOpenInWebBrowser", "Failed to start browser", e) } } } }
gpl-3.0
a941036ebf6103519f1b799e916bfd18
34.0375
95
0.623618
4.783276
false
false
false
false
Iamironz/lightweight-fragments
src/main/java/com/implimentz/fragments/FragmentManager.kt
1
5652
@file:Suppress("unused") package com.implimentz.fragments import android.view.LayoutInflater import android.view.ViewGroup import java.io.Serializable import java.util.* /** * Created by ironz. * Date: 20.01.16, 9:32 * In Intellij IDEA 15.0.3 Ultimate * email: [email protected] * twitter: iamironz */ /** * Class that represent stack and base stack control with holding in App class */ class FragmentManager(private val container: ViewGroup, private val inflater: LayoutInflater, private val listener: StackChangeListener) { val stack = FragmentHolder.getStackById(container.id) init { FragmentHolder.register(container.id) } fun destroyStack() { stack.forEach { it.onPause() it.onDestroy() } FragmentHolder.unregister(container.id) } fun onPause() { if (stack.isEmpty()) { return } val fragment = stack.last() if (fragment.showing.not()) { return } fragment.onPause() } fun onResume() { if (stack.isEmpty()) { return } val fragment = stack.last() tryShow(fragment) } fun openFragment(name: String, fragment: Fragment<out Serializable>) { openFragment0(name, fragment) } fun openFragment(fragment: Fragment<out Serializable>) { openFragment0(fragment.javaClass.name, fragment) } private fun openFragment0(name: String, fragment: Fragment<out Serializable>) { if (stack.isEmpty().not()) { val last = stack.last() last.onPause() } fragment.name = name stack.add(fragment) tryShow(fragment) } fun popFragment(fragment: Fragment<out Serializable>): Boolean { return popFragment0(fragment.javaClass.name) } fun popFragment(fragment: Class<out Fragment<out Serializable>>): Boolean { return popFragment0(fragment.name) } fun popFragment(name: String): Boolean { return popFragment0(name) } private fun popFragment0(name: String): Boolean { if (stack.isEmpty()) { return false } for (i in stack.indices) { val fragment = stack[i] if (fragment.name == name) { closeFragmentRange(i.inc()) tryShow(fragment) return true } } return false } private fun closeFragmentRange(start: Int) { val forDeleting = ArrayList<Fragment<out Serializable>>() for (i in start..stack.lastIndex) { val fragment = stack[i] tryClose(fragment) forDeleting.add(fragment) } stack.removeAll(forDeleting) } fun closeLastFragment() { if (stack.isEmpty() || stack.size < 2) { return } val old = stack[stack.lastIndex] tryClose(old) stack.remove(old) tryRestoreLast() } fun onBackPressed() { if (stack.isEmpty() || stack.size < 2) { return } val item = stack.last() item.onBackPressed() } fun hasNotEndedActions(): Boolean { if (stack.isEmpty()) { return false } val fragment = stack.last() return fragment.hasNotEndedAction() } fun onActionEndRequired() { if (stack.isEmpty()) { return } val fragment = stack.last() if (fragment.hasNotEndedAction()) { fragment.onActionEndRequired() } } fun closeFragment(name: Fragment<out Serializable>) { closeFragment0(name.javaClass.name) } fun closeFragment(fragment: Class<out Fragment<out Serializable>>) { closeFragment0(fragment.name) } fun closeFragment(name: String) { closeFragment0(name) } private fun closeFragment0(name: String) { if (stack.isEmpty()) { return } val firstOrNull = stack.asReversed() .filter { it.name == name } .firstOrNull() firstOrNull?.let { tryClose(it) stack.remove(it) tryRestoreLast() } } private fun tryRestoreLast() { if (stack.isEmpty()) { return } val fragment = stack.last() tryShow(fragment) } private fun tryShow(fragment: Fragment<out Serializable>) { if (fragment.showing) { return } tryAddViewToFront(fragment) callStackListener(fragment) } private fun tryAddViewToFront(fragment: Fragment<out Serializable>) { val view = fragment.constructView(container, inflater) if (container.contains(view).not()) { container.addView(view) container.hidePrevious() } fragment.onResume() } private fun callStackListener(fragment: Fragment<out Serializable>) { listener.onStackChanged(fragment) } private fun tryClose(fragment: Fragment<out Serializable>) { val view = fragment.view if (container.contains(view).not()) { return } container.showPrevious() container.removeView(view) fragment.onPause() if (fragment.configurationChanged) { return } fragment.onDestroy() } fun getStackCount(): Int { return stack.size } fun stackIsEmpty(): Boolean { return stack.size < 2 } }
mit
dd50ed6ee8177ed1da43dad7304e0521
20.172285
83
0.563517
4.572816
false
false
false
false
leafclick/intellij-community
platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/libraries/libraries/LegacyBridgeModifiableBase.kt
1
1252
package com.intellij.workspace.legacyBridge.libraries.libraries import com.intellij.configurationStore.serialize import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.util.JDOMUtil import com.intellij.workspace.api.* abstract class LegacyBridgeModifiableBase(protected val diff: TypedEntityStorageBuilder) { protected val entityStoreOnDiff = EntityStoreOnBuilder(diff) private var committedOrDisposed = false protected var modelIsCommittedOrDisposed get() = committedOrDisposed set(value) { if (!value) error("Only 'true' value is accepted here") committedOrDisposed = true } protected fun assertModelIsLive() { if (committedOrDisposed) { error("${javaClass.simpleName} was already committed or disposed" ) } } internal fun serializeComponentAsString(rootElementName: String, component: PersistentStateComponent<*>?) : String? { val state = component?.state ?: return null val propertiesElement = serialize(state) ?: return null propertiesElement.name = rootElementName return JDOMUtil.writeElement(propertiesElement) } companion object { // TODO Some common mechanics? internal val assertChangesApplied get() = true } }
apache-2.0
20a6dbd21db1746123b4428df7b50570
31.947368
119
0.760383
5.173554
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/DynamicPlugins.kt
1
24273
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins import com.fasterxml.jackson.databind.type.TypeFactory import com.intellij.configurationStore.StoreUtil.Companion.saveDocumentsAndProjectsAndApp import com.intellij.configurationStore.jdomSerializer import com.intellij.configurationStore.runInAutoSaveDisabledMode import com.intellij.ide.IdeEventQueue import com.intellij.ide.SaveAndSyncHandler import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.ide.ui.UIThemeProvider import com.intellij.lang.Language import com.intellij.notification.NotificationDisplayType import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.impl.ActionManagerImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.extensions.ExtensionsArea import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.keymap.impl.BundledKeymapBean import com.intellij.openapi.keymap.impl.BundledKeymapProvider import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.util.PotemkinProgress import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.registry.Registry import com.intellij.psi.util.CachedValuesManager import com.intellij.serviceContainer.PlatformComponentManagerImpl import com.intellij.serviceContainer.PlatformComponentManagerImpl.DescriptorToLoad import com.intellij.util.ArrayUtil import com.intellij.util.CachedValuesManagerImpl import com.intellij.util.MemoryDumpHelper import com.intellij.util.SystemProperties import com.intellij.util.containers.ConcurrentFactoryMap import com.intellij.util.messages.Topic import com.intellij.util.messages.impl.MessageBusImpl import com.intellij.util.xmlb.BeanBinding import java.text.SimpleDateFormat import java.util.* import javax.swing.JComponent internal class CannotUnloadPluginException(value: String) : ProcessCanceledException(RuntimeException(value)) interface DynamicPluginListener { @JvmDefault fun beforePluginLoaded(pluginDescriptor: IdeaPluginDescriptor) { } @JvmDefault fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) { } /** * @param isUpdate true if the plugin is being unloaded as part of an update installation and a new version will be loaded afterwards */ @JvmDefault fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { } @JvmDefault fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { } /** * Checks if the plugin can be dynamically unloaded at this moment. * Method should throw {@link CannotUnloadPluginException} if it isn't possible by some reason */ @Throws(CannotUnloadPluginException::class) @JvmDefault fun checkUnloadPlugin(pluginDescriptor: IdeaPluginDescriptor) { } companion object { @JvmField val TOPIC = Topic.create("DynamicPluginListener", DynamicPluginListener::class.java) } } object DynamicPlugins { private val LOG = Logger.getInstance(DynamicPlugins::class.java) private val GROUP = NotificationGroup("Dynamic plugin installation", NotificationDisplayType.BALLOON, false) val pluginDisposables = ConcurrentFactoryMap.createWeakMap<PluginDescriptor, Disposable> { plugin -> Disposer.newDisposable("Plugin disposable [${plugin.name}]") } @JvmStatic @JvmOverloads fun allowLoadUnloadWithoutRestart(descriptor: IdeaPluginDescriptorImpl, baseDescriptor: IdeaPluginDescriptorImpl? = null): Boolean { val projectManager = ProjectManager.getInstance() val anyProject = projectManager.openProjects.firstOrNull() ?: projectManager.defaultProject val loadedPluginDescriptor = if (descriptor.pluginId != null) PluginManagerCore.getPlugin(descriptor.pluginId) as? IdeaPluginDescriptorImpl else null try { ApplicationManager.getApplication().messageBus.syncPublisher(DynamicPluginListener.TOPIC).checkUnloadPlugin(descriptor) } catch (e: CannotUnloadPluginException) { val localizedMessage = e.cause?.localizedMessage LOG.info(localizedMessage) return false } if (loadedPluginDescriptor != null && isPluginLoaded(loadedPluginDescriptor.pluginId)) { if (!descriptor.useIdeaClassLoader) { val pluginClassLoader = loadedPluginDescriptor.pluginClassLoader if (pluginClassLoader !is PluginClassLoader && !ApplicationManager.getApplication().isUnitTestMode) { val loader = baseDescriptor ?: descriptor LOG.info("Plugin ${loader.pluginId} is not unload-safe because of use of UrlClassLoader as the default class loader. " + "For example, the IDE is started from the sources with the plugin.") return false } } } val extensions = descriptor.extensions if (extensions != null) { for (epName in extensions.keys) { val pluginExtensionPoint = findPluginExtensionPoint(baseDescriptor ?: descriptor, epName) if (pluginExtensionPoint != null) { if (baseDescriptor != null && !pluginExtensionPoint.isDynamic) { LOG.info("Plugin ${baseDescriptor.pluginId} is not unload-safe because of use of non-dynamic EP $epName in optional dependencies on it") return false } continue } val ep = Extensions.getRootArea().getExtensionPointIfRegistered<Any>(epName) ?: anyProject.extensionArea.getExtensionPointIfRegistered<Any>(epName) if (ep != null) { if (!ep.isDynamic) { if (baseDescriptor != null) { LOG.info("Plugin ${baseDescriptor.pluginId} is not unload-safe because of use of non-dynamic EP $epName in optional dependencies on it") } else { LOG.info("Plugin ${descriptor.pluginId} is not unload-safe because of extension to non-dynamic EP $epName") } return false } continue } if (baseDescriptor != null) { val baseEP = findPluginExtensionPoint(baseDescriptor, epName) if (baseEP != null) { if (!baseEP.isDynamic) { LOG.info("Plugin ${baseDescriptor.pluginId} is not unload-safe because of use of non-dynamic EP $epName in optional dependencies on it") return false } continue } } LOG.info("Plugin ${descriptor.pluginId} is not unload-safe because of unresolved extension $epName") return false } } if (!hasNoComponents(descriptor)) return false if (!((ActionManager.getInstance() as ActionManagerImpl).canUnloadActions(descriptor))) return false descriptor.optionalConfigs?.forEach { (pluginId, optionalDescriptors) -> if (isPluginLoaded(pluginId) && optionalDescriptors.any { !allowLoadUnloadWithoutRestart(it, descriptor) }) return false } var canUnload = true processOptionalDependenciesOnPlugin(descriptor) { _, fullyLoadedDescriptor -> if (!allowLoadUnloadWithoutRestart(fullyLoadedDescriptor, descriptor)) { canUnload = false } canUnload } return canUnload } private fun processOptionalDependenciesOnPlugin(rootDescriptor: IdeaPluginDescriptorImpl, callback: (descriptor: IdeaPluginDescriptorImpl, fullyLoadedDescriptor: IdeaPluginDescriptorImpl) -> Boolean) { val pluginXmlFactory = PluginXmlFactory() val listContext = DescriptorListLoadingContext.createSingleDescriptorContext(PluginManagerCore.disabledPlugins()) for (descriptor in PluginManager.getPlugins()) { if (!descriptor.isEnabled) continue if (!descriptor.optionalDependentPluginIds.contains(rootDescriptor.pluginId)) { continue } descriptor as IdeaPluginDescriptorImpl val dependencyConfigFile = descriptor.findOptionalDependencyConfigFile(rootDescriptor.pluginId) ?: continue val pathResolver = PathBasedJdomXIncluder.DEFAULT_PATH_RESOLVER val element = try { pathResolver.resolvePath(descriptor.basePath, dependencyConfigFile, pluginXmlFactory) } catch (e: Exception) { LOG.info("Can't resolve optional dependency on plugin being loaded/unloaded: config file $dependencyConfigFile, error ${e.message}") continue } val fullyLoadedDescriptor = IdeaPluginDescriptorImpl(descriptor.pluginPath, false) val context = DescriptorLoadingContext(listContext, false, false, pathResolver) if (!fullyLoadedDescriptor.readExternal(element, descriptor.basePath, pathResolver, context, descriptor)) { LOG.info("Can't read descriptor $dependencyConfigFile for optional dependency of plugin being loaded/unloaded") continue } if (!callback(descriptor, fullyLoadedDescriptor)) { break } } } private fun findPluginExtensionPoint(pluginDescriptor: IdeaPluginDescriptorImpl, epName: String): ExtensionPointImpl<*>? { return findContainerExtensionPoint(pluginDescriptor.app, epName) ?: findContainerExtensionPoint(pluginDescriptor.project, epName) ?: findContainerExtensionPoint(pluginDescriptor.module, epName) } private fun findContainerExtensionPoint(containerDescriptor: ContainerDescriptor, epName: String): ExtensionPointImpl<*>? { val extensionPoints = containerDescriptor.extensionPoints ?: return null return extensionPoints.find { it.name == epName } } /** * Checks if the plugin can be loaded/unloaded immediately when the corresponding action is invoked in the * plugins settings, without pressing the Apply button. */ @JvmStatic fun allowLoadUnloadSynchronously(pluginDescriptor: IdeaPluginDescriptorImpl): Boolean { val extensions = pluginDescriptor.extensions if (extensions != null && !extensions.all { it.key == UIThemeProvider.EP_NAME.name || it.key == BundledKeymapBean.EP_NAME.name || it.key == BundledKeymapProvider.EP_NAME.name }) { return false } return hasNoComponents(pluginDescriptor) && pluginDescriptor.actionDescriptionElements.isNullOrEmpty() } private fun hasNoComponents(pluginDescriptor: IdeaPluginDescriptorImpl): Boolean { return isUnloadSafe(pluginDescriptor.appContainerDescriptor) && isUnloadSafe(pluginDescriptor.projectContainerDescriptor) && isUnloadSafe(pluginDescriptor.moduleContainerDescriptor) } private fun isUnloadSafe(containerDescriptor: ContainerDescriptor): Boolean { return containerDescriptor.components.isNullOrEmpty() } @JvmStatic @JvmOverloads fun unloadPluginWithProgress(parentComponent: JComponent?, pluginDescriptor: IdeaPluginDescriptorImpl, disable: Boolean = false, isUpdate: Boolean = false): Boolean { var result = false if (!allowLoadUnloadSynchronously(pluginDescriptor)) { runInAutoSaveDisabledMode { val saveAndSyncHandler = SaveAndSyncHandler.getInstance() saveAndSyncHandler.saveSettingsUnderModalProgress(ApplicationManager.getApplication()) for (openProject in ProjectManager.getInstance().openProjects) { saveAndSyncHandler.saveSettingsUnderModalProgress(openProject) } } } val indicator = PotemkinProgress("Unloading plugin ${pluginDescriptor.name}", null, parentComponent, null) indicator.runInSwingThread { result = unloadPlugin(pluginDescriptor, disable, isUpdate, save = false) } return result } @JvmStatic @JvmOverloads fun unloadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, disable: Boolean = false, isUpdate: Boolean = false, save: Boolean = true): Boolean { val application = ApplicationManager.getApplication() as ApplicationImpl // The descriptor passed to `unloadPlugin` is the full descriptor loaded from disk, it does not have a classloader. // We need to find the real plugin loaded into the current instance and unload its classloader. val loadedPluginDescriptor = PluginManagerCore.getPlugin(pluginDescriptor.pluginId) as? IdeaPluginDescriptorImpl ?: return false try { if (save) { saveDocumentsAndProjectsAndApp(true) } application.runWriteAction { try { application.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginUnload(pluginDescriptor, isUpdate) processOptionalDependenciesOnPlugin(pluginDescriptor) { _, dependencyDescriptor -> unloadPluginDescriptor(dependencyDescriptor, dependencyDescriptor) true } if (!pluginDescriptor.useIdeaClassLoader) { if (loadedPluginDescriptor.pluginClassLoader is PluginClassLoader) { IconLoader.detachClassLoader(loadedPluginDescriptor.pluginClassLoader) Language.unregisterLanguages(loadedPluginDescriptor.pluginClassLoader) } } pluginDescriptor.optionalConfigs?.forEach { (pluginId, optionalDescriptors) -> if (isPluginLoaded(pluginId)) { for (optionalDescriptor in optionalDescriptors) { unloadPluginDescriptor(optionalDescriptor, loadedPluginDescriptor) } } } unloadPluginDescriptor(pluginDescriptor, loadedPluginDescriptor) for (project in ProjectManager.getInstance().openProjects) { (CachedValuesManager.getManager(project) as CachedValuesManagerImpl).clearCachedValues() } jdomSerializer.clearSerializationCaches() BeanBinding.clearSerializationCaches() TypeFactory.defaultInstance().clearCache() Disposer.clearDisposalTraces() // ensure we don't have references to plugin classes in disposal backtraces if (disable) { // Update list of disabled plugins PluginManagerCore.setPlugins(PluginManagerCore.getPlugins()) } else { PluginManagerCore.setPlugins(ArrayUtil.remove(PluginManagerCore.getPlugins(), loadedPluginDescriptor)) } } finally { val disposable = pluginDisposables.remove(pluginDescriptor) if (disposable != null) { Disposer.dispose(disposable) } application.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginUnloaded(pluginDescriptor, isUpdate) } } } catch (e: Exception) { Logger.getInstance(DynamicPlugins.javaClass).error(e) } finally { IdeEventQueue.getInstance().flushQueue() if (ApplicationManager.getApplication().isUnitTestMode && !(loadedPluginDescriptor.pluginClassLoader is PluginClassLoader)) { return true } val classLoaderUnloaded = loadedPluginDescriptor.unloadClassLoader() if (!classLoaderUnloaded) { if (Registry.`is`("ide.plugins.snapshot.on.unload.fail") && MemoryDumpHelper.memoryDumpAvailable() && !ApplicationManager.getApplication().isUnitTestMode) { val snapshotFolder = System.getProperty("snapshots.path", SystemProperties.getUserHome()) val snapshotDate = SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(Date()) val snapshotPath = "$snapshotFolder/unload-${pluginDescriptor.pluginId}-$snapshotDate.hprof" MemoryDumpHelper.captureMemoryDump(snapshotPath) notify("Captured memory snapshot on plugin unload fail: $snapshotPath", NotificationType.WARNING) } LOG.info("Plugin ${pluginDescriptor.pluginId} is not unload-safe because class loader cannot be unloaded") } return classLoaderUnloaded } } internal fun notify(text: String, notificationType: NotificationType) { GROUP.createNotification(text, notificationType).notify(null) } private fun unloadPluginDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl, loadedPluginDescriptor: IdeaPluginDescriptorImpl) { val application = ApplicationManager.getApplication() as ApplicationImpl (ActionManager.getInstance() as ActionManagerImpl).unloadActions(pluginDescriptor) val openProjects = ProjectManager.getInstance().openProjects val unloadListeners = mutableListOf<Runnable>() pluginDescriptor.extensions?.let { extensions -> for ((epName, epExtensions) in extensions) { val appEp = Extensions.getRootArea().getExtensionPointIfRegistered<Any>(epName) as ExtensionPointImpl<*>? if (appEp != null) { appEp.unregisterExtensions(epExtensions, unloadListeners) } else { for (openProject in openProjects) { val projectEp = openProject.extensionArea.getExtensionPointIfRegistered<Any>(epName) as ExtensionPointImpl<*>? projectEp?.unregisterExtensions(epExtensions, unloadListeners) } } } } for (unloadListener in unloadListeners) { unloadListener.run() } processExtensionPoints(pluginDescriptor, openProjects) { areaInstance, name -> areaInstance.getExtensionPoint<Any>(name).reset() } processExtensionPoints(pluginDescriptor, openProjects) { areaInstance, name -> areaInstance.unregisterExtensionPoint(name) } pluginDescriptor.app.extensionPoints?.forEach(ExtensionPointImpl<*>::clearExtensionClass) pluginDescriptor.project.extensionPoints?.forEach(ExtensionPointImpl<*>::clearExtensionClass) loadedPluginDescriptor.app.extensionPoints?.forEach(ExtensionPointImpl<*>::clearExtensionClass) loadedPluginDescriptor.project.extensionPoints?.forEach(ExtensionPointImpl<*>::clearExtensionClass) val appServiceInstances = application.unloadServices(pluginDescriptor.app) for (appServiceInstance in appServiceInstances) { application.stateStore.unloadComponent(appServiceInstance) } (application.messageBus as MessageBusImpl).unsubscribePluginListeners(loadedPluginDescriptor) for (project in openProjects) { val projectServiceInstances = (project as ProjectImpl).unloadServices(pluginDescriptor.project) for (projectServiceInstance in projectServiceInstances) { project.stateStore.unloadComponent(projectServiceInstance) } for (module in ModuleManager.getInstance(project).modules) { val moduleServiceInstances = (module as PlatformComponentManagerImpl).unloadServices(pluginDescriptor.module) for (moduleServiceInstance in moduleServiceInstances) { module.stateStore.unloadComponent(moduleServiceInstance) } } (project.messageBus as MessageBusImpl).unsubscribePluginListeners(loadedPluginDescriptor) } } private fun processExtensionPoints(pluginDescriptor: IdeaPluginDescriptorImpl, openProjects: Array<Project>, callback: (ExtensionsArea, String) -> Unit) { pluginDescriptor.app.extensionPoints?.let { val rootArea = ApplicationManager.getApplication().extensionArea for (point in it) { callback(rootArea, point.name) } } pluginDescriptor.project.extensionPoints?.let { for (point in it) { val extensionPointName = point.name for (openProject in openProjects) { callback(openProject.extensionArea, extensionPointName) } } } } @JvmStatic fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, wasDisabled: Boolean) { if (!ApplicationManager.getApplication().isUnitTestMode) { PluginManagerCore.initClassLoader(pluginDescriptor) } val application = ApplicationManager.getApplication() as ApplicationImpl application.runWriteAction { application.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginLoaded(pluginDescriptor) try { loadPluginDescriptor(pluginDescriptor, pluginDescriptor) processOptionalDependenciesOnPlugin(pluginDescriptor) { descriptor, fullyLoadedDescriptor -> loadPluginDescriptor(descriptor, fullyLoadedDescriptor) true } for (openProject in ProjectManager.getInstance().openProjects) { (CachedValuesManager.getManager(openProject) as CachedValuesManagerImpl).clearCachedValues() } if (wasDisabled) { // Update list of disabled plugins (PluginManagerCore.getPlugin(pluginDescriptor.pluginId) as? IdeaPluginDescriptorImpl)?.setLoader( pluginDescriptor.pluginClassLoader) PluginManagerCore.setPlugins(PluginManagerCore.getPlugins()) } else { PluginManagerCore.setPlugins(ArrayUtil.mergeArrays(PluginManagerCore.getPlugins(), arrayOf(pluginDescriptor))) } } finally { application.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginLoaded(pluginDescriptor) } } } private fun loadPluginDescriptor(baseDescriptor: IdeaPluginDescriptorImpl, fullyLoadedBaseDescriptor: IdeaPluginDescriptorImpl) { val application = ApplicationManager.getApplication() as ApplicationImpl val listenerCallbacks = arrayListOf<Runnable>() val pluginsToLoad = mutableListOf(DescriptorToLoad(fullyLoadedBaseDescriptor, baseDescriptor)) fullyLoadedBaseDescriptor.optionalConfigs?.forEach { (pluginId, optionalDescriptors) -> if (isPluginLoaded(pluginId)) { optionalDescriptors.mapTo(pluginsToLoad) { DescriptorToLoad(it, baseDescriptor) } } } application.registerComponents(pluginsToLoad, listenerCallbacks) for (openProject in ProjectManager.getInstance().openProjects) { (openProject as ProjectImpl).registerComponents(pluginsToLoad, listenerCallbacks) for (module in ModuleManager.getInstance(openProject).modules) { (module as PlatformComponentManagerImpl).registerComponents(pluginsToLoad, listenerCallbacks) } } listenerCallbacks.forEach(Runnable::run) for (descriptorToLoad in pluginsToLoad) { (ActionManager.getInstance() as ActionManagerImpl).registerPluginActions(baseDescriptor, descriptorToLoad.descriptor.actionDescriptionElements, false) } } private fun isPluginLoaded(pluginId: PluginId?) = PluginManagerCore.getLoadedPlugins().any { it.pluginId == pluginId } @JvmStatic fun pluginDisposable(clazz: Class<*>): Disposable? { val classLoader = clazz.classLoader if (classLoader is PluginClassLoader) { val pluginDescriptor = classLoader.pluginDescriptor if (pluginDescriptor != null) { return pluginDisposables[pluginDescriptor] } } return null } @JvmStatic fun pluginDisposableWrapper(clazz: Class<*>, defaultValue: Disposable): Disposable { val pluginDisposable = pluginDisposable(clazz) if (pluginDisposable != null) { val result = Disposer.newDisposable() Disposer.register(pluginDisposable, result) Disposer.register(defaultValue, result) return result } return defaultValue } @JvmStatic fun onPluginUnload(parentDisposable: Disposable, callback: Runnable) { ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { callback.run() } }) } }
apache-2.0
a8d7e8074340b002d5d6b4831881ccbd
43.132727
164
0.732501
5.637018
false
false
false
false
rodm/teamcity-gradle-init-scripts-plugin
server/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/server/health/InvalidInitScriptsHealthReport.kt
1
4135
/* * Copyright 2017 Rod MacKenzie. * * 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.rodm.teamcity.gradle.scripts.server.health import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.FEATURE_TYPE import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME import jetbrains.buildServer.serverSide.BuildTypeSettings import jetbrains.buildServer.serverSide.healthStatus.HealthStatusItem import jetbrains.buildServer.serverSide.healthStatus.HealthStatusItemConsumer import jetbrains.buildServer.serverSide.healthStatus.HealthStatusReport import jetbrains.buildServer.serverSide.healthStatus.HealthStatusScope import jetbrains.buildServer.serverSide.healthStatus.ItemCategory import jetbrains.buildServer.serverSide.healthStatus.ItemSeverity.INFO import jetbrains.buildServer.web.openapi.PagePlaces import jetbrains.buildServer.web.openapi.PluginDescriptor import jetbrains.buildServer.web.openapi.healthStatus.HealthStatusItemPageExtension open class InvalidInitScriptsHealthReport(pagePlaces: PagePlaces, descriptor: PluginDescriptor) : HealthStatusReport() { private val TYPE = "InvalidInitScriptsReport" private val CATEGORY = ItemCategory("invalid_init_scripts", "Invalid Gradle init scripts configuration", INFO) init { val pageExtension = HealthStatusItemPageExtension(TYPE, pagePlaces) pageExtension.includeUrl = descriptor.getPluginResourcesPath("/health/invalidInitScripts.jsp") pageExtension.isVisibleOutsideAdminArea = true pageExtension.addCssFile("/css/admin/buildTypeForm.css") pageExtension.register() } override fun getType() = TYPE override fun getDisplayName() = "Invalid Gradle Init Scripts configuration" override fun getCategories() = listOf(CATEGORY) override fun canReportItemsFor(scope: HealthStatusScope) : Boolean { return scope.isItemWithSeverityAccepted(CATEGORY.severity) } override fun report(scope: HealthStatusScope, resultConsumer: HealthStatusItemConsumer) { for (buildType in scope.buildTypes) { for (feature in buildType.getBuildFeaturesOfType(FEATURE_TYPE)) { if (!hasGradleRunnerBuildStep(buildType)) { val scriptName = feature.parameters[INIT_SCRIPT_NAME] val data = mapOf("buildType" to buildType, "scriptName" to scriptName) val identity = CATEGORY.id + "_" + buildType.buildTypeId val statusItem = HealthStatusItem(identity, CATEGORY, data) resultConsumer.consumeForBuildType(buildType, statusItem) } } } for (buildTemplate in scope.buildTypeTemplates) { for (feature in buildTemplate.getBuildFeaturesOfType(FEATURE_TYPE)) { if (!hasGradleRunnerBuildStep(buildTemplate)) { val scriptName = feature.parameters[INIT_SCRIPT_NAME] val data = mapOf("buildTemplate" to buildTemplate, "scriptName" to scriptName) val identity = CATEGORY.id + "_" + buildTemplate.id val statusItem = HealthStatusItem(identity, CATEGORY, data) resultConsumer.consumeForTemplate(buildTemplate, statusItem) } } } } open fun hasGradleRunnerBuildStep(buildTypeSettings: BuildTypeSettings): Boolean { buildTypeSettings.buildRunners.forEach { runner -> if ("gradle-runner" == runner.runType.type) { return true } } return false } }
apache-2.0
e62431791091241b1418e7c785feee5e
45.460674
120
0.717291
4.946172
false
false
false
false
leafclick/intellij-community
platform/lang-api/src/com/intellij/codeInsight/hints/settings/ParameterNameHintsSettings.kt
1
6758
// 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.codeInsight.hints.settings import com.intellij.lang.Language import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.getAttributeBooleanValue import org.jdom.Element private object XmlTagHelper { const val BLACKLISTS = "blacklists" const val LANGUAGE_LIST = "blacklist" const val LANGUAGE = "language" const val ADDED = "added" const val REMOVED = "removed" const val PATTERN = "pattern" const val DISABLED_LANGUAGES = "disabledLanguages" const val DISABLED_LANGUAGE_ITEM = "language" const val DISABLED_LANGUAGE_ID = "id" } class Diff(val added: Set<String>, val removed: Set<String>) { fun applyOn(base: Set<String>): Set<String> { val baseSet = base.toMutableSet() added.forEach { baseSet.add(it) } removed.forEach { baseSet.remove(it) } return baseSet } companion object Builder { fun build(base: Set<String>, updated: Set<String>): Diff { val removed = base.toMutableSet() removed.removeAll(updated) val added = updated.toMutableSet() added.removeAll(base) return Diff(added, removed) } } } @State(name = "ParameterNameHintsSettings", storages = [(Storage("parameter.hints.xml"))]) class ParameterNameHintsSettings : PersistentStateComponent<Element> { private val removedPatterns = hashMapOf<String, Set<String>>() private val addedPatterns = hashMapOf<String, Set<String>>() private val options = hashMapOf<String, Boolean>() private val disabledLanguages = hashSetOf<String>() fun addIgnorePattern(language: Language, pattern: String) { val patternsBefore = getAddedPatterns(language) setAddedPatterns(language, patternsBefore + pattern) } fun getBlackListDiff(language: Language): Diff { val added = getAddedPatterns(language) val removed = getRemovedPatterns(language) return Diff(added, removed) } fun setBlackListDiff(language: Language, diff: Diff) { setAddedPatterns(language, diff.added) setRemovedPatterns(language, diff.removed) } override fun getState(): Element { val root = Element("settings") if (removedPatterns.isNotEmpty() || addedPatterns.isNotEmpty()) { val blacklists = Element(XmlTagHelper.BLACKLISTS) root.addContent(blacklists) val allLanguages = removedPatterns.keys + addedPatterns.keys allLanguages.forEach { val removed = removedPatterns[it] ?: emptySet() val added = addedPatterns[it] ?: emptySet() val languageBlacklist = Element(XmlTagHelper.LANGUAGE_LIST).apply { setAttribute(XmlTagHelper.LANGUAGE, it) val removedElements = removed.map { it.toPatternElement(XmlTagHelper.REMOVED) } val addedElements = added.map { it.toPatternElement(XmlTagHelper.ADDED) } addContent(addedElements + removedElements) } blacklists.addContent(languageBlacklist) } } options.forEach { (id, value) -> val element = Element("option") element.setAttribute("id", id) element.setAttribute("value", value.toString()) root.addContent(element) } if (disabledLanguages.isNotEmpty()) { val disabledLanguagesElement = Element(XmlTagHelper.DISABLED_LANGUAGES) disabledLanguagesElement.addContent(disabledLanguages.map { val element = Element(XmlTagHelper.DISABLED_LANGUAGE_ITEM) element.setAttribute(XmlTagHelper.DISABLED_LANGUAGE_ID, it) element }) root.addContent(disabledLanguagesElement) } return root } fun setIsEnabledForLanguage(enabled: Boolean, language: Language) { if (!enabled) { disabledLanguages.add(language.id) } else { disabledLanguages.remove(language.id) } } fun isEnabledForLanguage(language: Language): Boolean { return language.id !in disabledLanguages } override fun loadState(state: Element) { addedPatterns.clear() removedPatterns.clear() options.clear() disabledLanguages.clear() val allBlacklistElements = state.getChild(XmlTagHelper.BLACKLISTS) ?.getChildren(XmlTagHelper.LANGUAGE_LIST) ?: emptyList() allBlacklistElements.forEach { blacklistElement -> val language = blacklistElement.attributeValue(XmlTagHelper.LANGUAGE) ?: return@forEach val added = blacklistElement.extractPatterns(XmlTagHelper.ADDED) addedPatterns[language] = addedPatterns[language]?.plus(added) ?: added val removed = blacklistElement.extractPatterns(XmlTagHelper.REMOVED) removedPatterns[language] = removedPatterns[language]?.plus(removed) ?: removed } state.getChildren("option").forEach { val id = it.getAttributeValue("id") options[id] = it.getAttributeBooleanValue("value") } state.getChild(XmlTagHelper.DISABLED_LANGUAGES)?.apply { getChildren(XmlTagHelper.DISABLED_LANGUAGE_ITEM).forEach { val languageId = it.attributeValue(XmlTagHelper.DISABLED_LANGUAGE_ID) ?: return@forEach disabledLanguages.add(languageId) } } } companion object { @JvmStatic fun getInstance(): ParameterNameHintsSettings = ServiceManager.getService(ParameterNameHintsSettings::class.java) } fun getOption(optionId: String): Boolean? { return options[optionId] } fun setOption(optionId: String, value: Boolean?) { if (value == null) { options.remove(optionId) } else { options[optionId] = value } } private fun getAddedPatterns(language: Language): Set<String> { val key = language.displayName return addedPatterns[key] ?: emptySet() } private fun getRemovedPatterns(language: Language): Set<String> { val key = language.displayName return removedPatterns[key] ?: emptySet() } private fun setRemovedPatterns(language: Language, removed: Set<String>) { val key = language.displayName removedPatterns[key] = removed } private fun setAddedPatterns(language: Language, added: Set<String>) { val key = language.displayName addedPatterns[key] = added } } private fun Element.extractPatterns(tag: String): Set<String> { return getChildren(tag).mapNotNull { it.attributeValue(XmlTagHelper.PATTERN) }.toSet() } private fun Element.attributeValue(attr: String): String? = this.getAttribute(attr)?.value private fun String.toPatternElement(status: String): Element { val element = Element(status) element.setAttribute(XmlTagHelper.PATTERN, this) return element }
apache-2.0
5a6d5158d067361bc4a6c822545d3d40
31.339713
140
0.715448
4.411227
false
false
false
false
baz8080/folkets_android
app/src/test/kotlin/com/mbcdev/folkets/FolketsTextToSpeechTests.kt
1
9800
package com.mbcdev.folkets import android.speech.tts.TextToSpeech import com.crashlytics.android.answers.Answers import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.mockito.* import org.mockito.Mockito.* import java.util.* /** * Tests for [FolketsTextToSpeech] * * Created by barry on 09/07/2017. */ class FolketsTextToSpeechTests { @Captor lateinit var paramsCaptor : ArgumentCaptor<HashMap<String, String>> @Mock lateinit var mockedTts : TextToSpeech @Before fun setup() { MockitoAnnotations.initMocks(this) } @Test fun `speech does not work if the underlying TTS is null`() { val folketsTts = FolketsTextToSpeech(null, null, null) val ttsStatus = folketsTts.speak(null, null) assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_TTS_NULL) } @Test fun `speech does not work if the underying TTS has no onInit listener`() { val folketsTts = FolketsTextToSpeech(mockedTts, null, null) val ttsStatus = folketsTts.speak(null, null) assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_LISTENER_NULL) verifyZeroInteractions(mockedTts) } @Test fun `speech does not work if the onInit listener is not ready`() { val realListener = FolketsTextToSpeechInitListener() val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(null, null) assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_TTS_NOT_READY) verifyZeroInteractions(mockedTts) } @Test fun `speech does not work if the language and phrase are missing`() { val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(null, null) assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_LANGUAGE_OR_PHRASE_MISSING) verifyZeroInteractions(mockedTts) } @Test fun `speech does not work if the language is missing`() { val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(null, "foto") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_LANGUAGE_OR_PHRASE_MISSING) verifyZeroInteractions(mockedTts) } @Test fun `speech does not work if the phrase is missing`() { val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(Language.ENGLISH, "") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_LANGUAGE_OR_PHRASE_MISSING) verifyZeroInteractions(mockedTts) } @Test fun `speech does not work if the language is missing data`() { val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) `when`(mockedTts.isLanguageAvailable(ArgumentMatchers.any())).thenReturn(TextToSpeech.LANG_MISSING_DATA) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(Language.ENGLISH, "train") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_LANGUAGE_NOT_SUPPORTED) } @Test fun `speech does not work if the language is not supported`() { val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) `when`(mockedTts.isLanguageAvailable(ArgumentMatchers.any())).thenReturn(TextToSpeech.LANG_NOT_SUPPORTED) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(Language.SWEDISH, "tåg") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.ERROR_LANGUAGE_NOT_SUPPORTED) } @Test fun `speech takes language from input when its current language is null`() { `when`(mockedTts.language).thenReturn(null) val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(Language.ENGLISH, "Ireland") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.SUCCESS) val localeCaptor = ArgumentCaptor.forClass(Locale::class.java) verify(mockedTts, atMost(1)).language = localeCaptor.capture() val locale = localeCaptor.value assertThat(locale).isEqualTo(Language.ENGLISH.locale) } @Test fun `speech uses previous language when it matches the requested language`() { `when`(mockedTts.language).thenReturn(Language.SWEDISH.locale) val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(Language.SWEDISH, "Sverige") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.SUCCESS) verify(mockedTts, atMost(0)).language = ArgumentMatchers.any() } @Test fun `speech switches language when it does not match the requested language`() { `when`(mockedTts.language).thenReturn(Language.SWEDISH.locale) val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(Language.ENGLISH, "Dublin") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.SUCCESS) val localeCaptor = ArgumentCaptor.forClass(Locale::class.java) verify(mockedTts, atMost(1)).language = localeCaptor.capture() val locale = localeCaptor.value assertThat(locale).isEqualTo(Language.ENGLISH.locale) } @Test fun `speak is called with the correct arguments`() { `when`(mockedTts.language).thenReturn(Language.SWEDISH.locale) val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) val ttsStatus = folketsTts.speak(Language.SWEDISH, "Göteborg") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.SUCCESS) val phraseCaptor = ArgumentCaptor.forClass(String::class.java) val queueModeCaptor = ArgumentCaptor.forClass(Int::class.java) verify(mockedTts, atMost(1)).speak( phraseCaptor.capture(), queueModeCaptor.capture(), paramsCaptor.capture()) val phrase = phraseCaptor.value assertThat(phrase).isEqualTo("Göteborg") val queueMode = queueModeCaptor.value assertThat(queueMode).isEqualTo(TextToSpeech.QUEUE_FLUSH) val params = paramsCaptor.value assertThat(params).isNull() } @Test fun `fabric provider is null-safe when speech is successful`() { `when`(mockedTts.language).thenReturn(Language.SWEDISH.locale) val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, null) folketsTts.speak(Language.SWEDISH, "Göteborg") val ttsStatus = folketsTts.speak(Language.SWEDISH, "Göteborg") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.SUCCESS) } @Test fun `fabric provider is called when speech is a success`() { val answers = mock(Answers::class.java) val populator = mock(EventPopulator::class.java) val fabricProvider = spy(DefaultFabricProvider(answers, populator)) `when`(fabricProvider.isInitialised).thenReturn(true) `when`(mockedTts.language).thenReturn(Language.SWEDISH.locale) val realListener = FolketsTextToSpeechInitListener() realListener.onInit(TextToSpeech.SUCCESS) val folketsTts = FolketsTextToSpeech(mockedTts, realListener, fabricProvider) val ttsStatus = folketsTts.speak(Language.SWEDISH, "Göteborg") assertThat(ttsStatus).isNotNull() assertThat(ttsStatus).isEqualTo(FolketsTextToSpeech.SpeechStatus.SUCCESS) val languageCodeCaptor = ArgumentCaptor.forClass(String::class.java) val phraseCaptor = ArgumentCaptor.forClass(String::class.java) verify(fabricProvider).logTextToSpeechEvent( languageCodeCaptor.capture(), phraseCaptor.capture()) val languageCode = languageCodeCaptor.value val phrase = phraseCaptor.value assertThat(languageCode).isNotNull() assertThat(languageCode).isEqualTo("sv") assertThat(phrase).isNotNull() assertThat(phrase).isEqualTo("Göteborg") } }
apache-2.0
01d6e5e89198c6fd7621836be043a67c
36.098485
113
0.71306
4.24859
false
true
false
false
smmribeiro/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddSdkPanel.kt
2
7084
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.sdk.add import com.intellij.CommonBundle import com.intellij.ide.IdeBundle import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.text.StringUtil import com.jetbrains.python.PySdkBundle import com.jetbrains.python.newProject.steps.PyAddNewEnvironmentPanel import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.add.PyAddSdkDialogFlowAction.OK import com.jetbrains.python.sdk.configuration.PyProjectVirtualEnvConfiguration import com.jetbrains.python.sdk.flavors.MacPythonSdkFlavor import icons.PythonIcons import java.awt.Component import java.io.File import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel /** * @author vlan */ abstract class PyAddSdkPanel : JPanel(), PyAddSdkView { override val actions: Map<PyAddSdkDialogFlowAction, Boolean> get() = mapOf(OK.enabled()) override val component: Component get() = this /** * [component] is permanent. [PyAddSdkStateListener.onComponentChanged] won't * be called anyway. */ override fun addStateListener(stateListener: PyAddSdkStateListener): Unit = Unit override fun previous(): Nothing = throw UnsupportedOperationException() override fun next(): Nothing = throw UnsupportedOperationException() override fun complete(): Unit = Unit abstract override val panelName: String override val icon: Icon = PythonIcons.Python.Python open val sdk: Sdk? = null open val nameExtensionComponent: JComponent? = null open var newProjectPath: String? = null override fun getOrCreateSdk(): Sdk? = sdk override fun onSelected(): Unit = Unit override fun validateAll(): List<ValidationInfo> = emptyList() open fun addChangeListener(listener: Runnable) {} companion object { @JvmStatic fun validateEnvironmentDirectoryLocation(field: TextFieldWithBrowseButton): ValidationInfo? { val text = field.text val file = File(text) val message = when { StringUtil.isEmptyOrSpaces(text) -> PySdkBundle.message("python.venv.location.field.empty") file.exists() && !file.isDirectory -> PySdkBundle.message("python.venv.location.field.not.directory") file.isNotEmptyDirectory -> PySdkBundle.message("python.venv.location.directory.not.empty") else -> return null } return ValidationInfo(message, field) } /** Should be protected. Please, don't use outside the class. KT-48508 */ @JvmStatic @PublishedApi internal fun validateSdkComboBox(field: PySdkPathChoosingComboBox, view: PyAddSdkView): ValidationInfo? { return validateSdkComboBox(field, getDefaultButtonName(view)) } @JvmStatic fun validateSdkComboBox(field: PySdkPathChoosingComboBox, @NlsContexts.Button defaultButtonName: String): ValidationInfo? { return when (val sdk = field.selectedSdk) { null -> ValidationInfo(PySdkBundle.message("python.sdk.field.is.empty"), field) is PySdkToInstall -> { val message = sdk.getInstallationWarning(defaultButtonName) ValidationInfo(message).asWarning().withOKEnabled() } is PyDetectedSdk -> { if (SystemInfo.isMac) MacPythonSdkFlavor.checkDetectedPython(sdk) else null } else -> null } } @NlsContexts.Button private fun getDefaultButtonName(view: PyAddSdkView): String { return if (view.component.parent?.parent is PyAddNewEnvironmentPanel) { IdeBundle.message("new.dir.project.create") // ProjectSettingsStepBase.createActionButton } else { CommonBundle.getOkButtonText() // DialogWrapper.createDefaultActions } } } } /** * Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] on the EDT. */ fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox, sdkObtainer: () -> List<Sdk>) { addInterpretersAsync(sdkComboBox, sdkObtainer, {}) } /** * Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] and calls [onAdded] on the EDT. */ fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox, sdkObtainer: () -> List<Sdk>, onAdded: (List<Sdk>) -> Unit) { ApplicationManager.getApplication().executeOnPooledThread { val executor = AppUIExecutor.onUiThread(ModalityState.any()) executor.execute { sdkComboBox.setBusy(true) } var sdks = emptyList<Sdk>() try { sdks = sdkObtainer() } finally { executor.execute { sdkComboBox.setBusy(false) sdkComboBox.removeAllItems() sdks.forEach(sdkComboBox::addSdkItem) onAdded(sdks) } } } } /** * Keeps [NewPySdkComboBoxItem] if it is present in the combobox. */ private fun PySdkPathChoosingComboBox.removeAllItems() { if (childComponent.itemCount > 0 && childComponent.getItemAt(0) is NewPySdkComboBoxItem) { while (childComponent.itemCount > 1) { childComponent.removeItemAt(1) } } else { childComponent.removeAllItems() } } /** * Obtains a list of sdk to be used as a base for a virtual environment on a pool, * then fills the [sdkComboBox] on the EDT and chooses [PySdkSettings.preferredVirtualEnvBaseSdk] or prepends it. */ fun addBaseInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox, existingSdks: List<Sdk>, module: Module?, context: UserDataHolder, callback: () -> Unit = {}) { addInterpretersAsync( sdkComboBox, { findBaseSdks(existingSdks, module, context).takeIf { it.isNotEmpty() } ?: getSdksToInstall() }, { sdkComboBox.apply { val preferredSdk = PyProjectVirtualEnvConfiguration.findPreferredVirtualEnvBaseSdk(items) if (preferredSdk != null) { if (items.find { it.homePath == preferredSdk.homePath } == null) { addSdkItemOnTop(preferredSdk) } selectedSdk = preferredSdk } } callback() } ) }
apache-2.0
08a06f787636d5e6b1f8bbbe87df0c48
34.777778
127
0.711886
4.691391
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/CellBaseImpl.kt
7
1900
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.ui.dsl.builder.CellBase import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.ui.layout.* import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal internal sealed class CellBaseImpl<T : CellBase<T>> : CellBase<T> { var horizontalAlign = HorizontalAlign.LEFT private set var verticalAlign = VerticalAlign.CENTER private set var resizableColumn = false private set var rightGap: RightGap? = null private set var customGaps: Gaps? = null private set abstract fun visibleFromParent(parentVisible: Boolean) abstract fun enabledFromParent(parentEnabled: Boolean) override fun visibleIf(predicate: ComponentPredicate): CellBase<T> { visible(predicate()) predicate.addListener { visible(it) } return this } override fun enabledIf(predicate: ComponentPredicate): CellBase<T> { enabled(predicate()) predicate.addListener { enabled(it) } return this } override fun horizontalAlign(horizontalAlign: HorizontalAlign): CellBase<T> { this.horizontalAlign = horizontalAlign return this } override fun verticalAlign(verticalAlign: VerticalAlign): CellBase<T> { this.verticalAlign = verticalAlign return this } override fun resizableColumn(): CellBase<T> { this.resizableColumn = true return this } override fun gap(rightGap: RightGap): CellBase<T> { this.rightGap = rightGap return this } override fun customize(customGaps: Gaps): CellBase<T> { this.customGaps = customGaps return this } }
apache-2.0
bafec733462df7cb764cdc3133a4d3e9
26.142857
158
0.746316
4.357798
false
false
false
false
ThatsNoMoon/KDA
src/main/kotlin/com/thatsnomoon/kda/extensions/MemberExtensions.kt
1
3358
/* * Copyright 2018 Benjamin Scherer * 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.thatsnomoon.kda.extensions import kotlinx.coroutines.experimental.Deferred import net.dv8tion.jda.core.MessageBuilder import net.dv8tion.jda.core.entities.Member import net.dv8tion.jda.core.entities.Message import net.dv8tion.jda.core.entities.MessageEmbed import java.time.Duration /** * Bans this member. * * @param delDays Days to delete this Member's messages in * @param reason Reason to ban this Member, recorded in the Audit Log * @param delay [Duration] to wait before queueing this action * * @return Empty [Deferred] that resolves when this action is complete */ fun Member.ban(delDays: Int = 0, reason: String = "", delay: Duration = Duration.ZERO): Deferred<Unit> = this.guild.controller.ban(this, delDays, reason) after delay map { Unit } /** * Kicks this member. * * @param reason Reason to kick this Member, recorded in the Audit Log * @param delay [Duration] to wait before queueing this action * * @return Empty [Deferred] that resolves when this action is complete */ fun Member.kick(reason: String = "", delay: Duration = Duration.ZERO): Deferred<Unit> = this.guild.controller.kick(this, reason) after delay map { Unit } /** * Sends this member a direct message. * * @param text Message content to send * @param delay [Duration] to wait before queueing this action * * @return [Deferred] that resolves to the sent Message */ fun Member.send(text: String, delay: Duration = Duration.ZERO): Deferred<Message> = this.user.openPrivateChannel() flatMap { it.send(text, delay) } /** * Sends this member a direct message. * * @param message Message to send * @param delay [Duration] to wait before queueing this action * * @return [Deferred] that resolves to the sent Message */ fun Member.send(message: Message, delay: Duration = Duration.ZERO): Deferred<Message> = this.user.openPrivateChannel() flatMap { it.send(message, delay) } /** * Sends this member a direct message. * * @param init Function to "build" the message to send, i.e. set content and options * @param delay [Duration] to wait before queueing this action * * @return [Deferred] that resolves to the sent Message */ inline fun Member.send(delay: Duration = Duration.ZERO, init: MessageBuilder.() -> Unit): Deferred<Message> { val builder = MessageBuilder() builder.init() return this.send(builder.build(), delay) } /** * Sends this member a direct message. * * @param embed Embed to send * @param delay [Duration] to wait before queueing this action * * @return [Deferred] that resolves to the sent Message */ fun Member.send(embed: MessageEmbed, delay: Duration = Duration.ZERO): Deferred<Message> = this.user.openPrivateChannel() flatMap { it.send(embed, delay) }
apache-2.0
1648447d3378b9fefd4b8b27251288ca
35.107527
109
0.724538
3.846506
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/types/GroovyTypeHintsUtil.kt
11
2956
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.codeInsight.hint.types import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.codeInsight.hints.presentation.PresentationFactory import com.intellij.codeInsight.hints.presentation.SpacePresentation import com.intellij.psi.* internal fun PresentationFactory.buildRepresentation(type: PsiType): InlayPresentation { return type.accept(object : PsiTypeVisitor<InlayPresentation>() { private val visitor = this override fun visitClassType(classType: PsiClassType): InlayPresentation { val classParameters = if (classType.hasParameters()) { listOf(smallText("<"), *classType.parameters.map { it.accept(visitor) }.intersperse(smallText(", ")).toTypedArray(), smallText(">")) } else { emptyList() } val className: String = classType.className ?: classType.presentableText return seq( psiSingleReference(smallText(className)) { classType.resolve() }, *classParameters.toTypedArray() ) } override fun visitArrayType(arrayType: PsiArrayType): InlayPresentation { return seq( arrayType.componentType.accept(visitor), smallText("[]") ) } override fun visitWildcardType(wildcardType: PsiWildcardType): InlayPresentation { val boundRepresentation = wildcardType.bound?.accept(visitor) val boundKeywordRepresentation = when { wildcardType.isExtends -> seq(smallText(" extends "), boundRepresentation!!) wildcardType.isSuper -> seq(smallText(" super "), boundRepresentation!!) else -> SpacePresentation(0, 0) } return seq( smallText("?"), boundKeywordRepresentation ) } override fun visitPrimitiveType(primitiveType: PsiPrimitiveType): InlayPresentation { return smallText(primitiveType.name) } }) } private fun <T> Iterable<T>.intersperse(delimiter: T): List<T> { val collector = mutableListOf<T>() for (element in this) { if (collector.isNotEmpty()) { collector.add(delimiter) } collector.add(element) } return collector } internal fun PresentationFactory.buildRepresentation(typeParameterList: PsiTypeParameterList): InlayPresentation { return typeParameterList.typeParameters.map { typeParameter -> val name = typeParameter.name!! val bound = typeParameter.extendsListTypes.map { buildRepresentation(it) }.intersperse(smallText(" & ")) if (bound.isEmpty()) { smallText(name) } else { seq(smallText("$name extends "), seq(*bound.toTypedArray()) ) } }.intersperse(smallText(", ")) .run { seq(smallText("<"), *this.toTypedArray(), smallText(">")) } .let { roundWithBackground(it) } }
apache-2.0
a2b1b8c1a148c04fb45ef90776a54234
33.383721
140
0.684032
4.783172
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/highlighter/Labels.kt
13
997
// EXPECTED_DUPLICATED_HIGHLIGHTING fun <info descr="null">bar</info>(<info descr="null">block</info>: () -> <info descr="null">Int</info>) = <info descr="null"><info descr="null">block</info></info>() fun <info descr="null">foo</info>(): <info descr="null">Int</info> { <info descr="null"><info descr="null">bar</info></info> <info descr="null" textAttributesKey="KOTLIN_LABEL">label@</info> { return<info descr="null" textAttributesKey="KOTLIN_LABEL">@label</info> 2 } <info descr="null" textAttributesKey="KOTLIN_LABEL">loop@</info> for (<info descr="null">i</info> in 1..100) { break<info descr="null" textAttributesKey="KOTLIN_LABEL">@loop</info> } <info descr="null" textAttributesKey="KOTLIN_LABEL">loop2@</info> for (<info descr="null">i</info> in 1..100) { break<error descr="There should be no space or comments before '@' in label reference"> </error><info descr="null" textAttributesKey="KOTLIN_LABEL">@loop2</info> } return 1 }
apache-2.0
c3ec9928d0933d955907a84e79e42d8f
51.526316
169
0.658977
3.665441
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/project/ProjectUtils.kt
1
16054
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.project import com.intellij.ide.GeneralSettings import com.intellij.ide.RecentProjectListActionProvider import com.intellij.ide.RecentProjectsManager import com.intellij.ide.ReopenProjectAction import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.TrustedPaths import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.application.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.NOTIFICATIONS_SILENT_MODE import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.util.io.createDirectories import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.isDirectory import training.lang.LangManager import training.lang.LangSupport import training.learn.LearnBundle import training.util.featureTrainerVersion import training.util.iftNotificationGroup import java.io.File import java.io.FileFilter import java.io.IOException import java.io.PrintWriter import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.CompletableFuture import kotlin.io.path.getLastModifiedTime import kotlin.io.path.name object ProjectUtils { private const val LEARNING_PROJECT_MODIFICATION = "LEARNING_PROJECT_MODIFICATION" private const val FEATURE_TRAINER_VERSION = "feature-trainer-version.txt" private val LOG = logger<ProjectUtils>() val learningProjectsPath: Path get() = Paths.get(PathManager.getSystemPath(), "demo") /** * For example: * @projectPath = "/learnProjects/SimpleProject" * @projectName = "SimpleProject" * */ fun importOrOpenProject(langSupport: LangSupport, projectToClose: Project?, postInitCallback: (learnProject: Project) -> Unit) { runBackgroundableTask(LearnBundle.message("learn.project.initializing.process"), project = projectToClose) { val dest = getLearningInstallationContentRoot(langSupport) ?: return@runBackgroundableTask if (!isSameVersion(versionFile(dest))) { if (dest.exists()) { dest.delete() } langSupport.installAndOpenLearningProject(dest, projectToClose) { it.basePath?.let { path -> copyLearnProjectIcon(File(path)) } postInitCallback(it) } } else { val path = langSupport.getLearningProjectPath(dest).toAbsolutePath().toString() LangManager.getInstance().setLearningProjectPath(langSupport, path) openOrImportLearningProject(dest, OpenProjectTask(projectToClose = projectToClose), langSupport, postInitCallback) } } } private fun getLearningInstallationContentRoot(langSupport: LangSupport): Path? { val storedProjectPath = LangManager.getInstance().getLearningProjectPath(langSupport) val path = if (storedProjectPath != null) langSupport.getContentRootPath(Paths.get(storedProjectPath)) else null val canonicalPlace = learningProjectsPath.resolve(langSupport.contentRootDirectoryName) var useCanonical = true if (path != null) { if (path != canonicalPlace && path.isDirectory() && versionFile(path).exists()) { // Learning project was already installed to some directory if (createProjectDirectory(canonicalPlace)) { // Remove the old learning directory val rpProvider = RecentProjectListActionProvider.getInstance() val projectActions = rpProvider.getActions() for (action in projectActions) { val projectPath = (action as? ReopenProjectAction)?.projectPath if (projectPath != null && Paths.get(projectPath) == path) { RecentProjectsManager.getInstance().removePath(projectPath) } } path.delete(recursively = true) } else { useCanonical = false } } } return if (useCanonical) { if (createProjectDirectory(canonicalPlace)) canonicalPlace else invokeAndWaitIfNeeded { chooseParentDirectoryForLearningProject(langSupport) } ?: return null } else path!! } private fun createProjectDirectory(place: Path): Boolean { if (place.isDirectory()) return true try { place.createDirectories() } catch (e: IOException) { return false } return true } fun getProjectRoot(project: Project): VirtualFile { val roots = ProjectRootManager.getInstance(project).contentRoots if (roots.isNotEmpty()) { if (roots.size > 1) LOG.warn("Multiple content roots in project ${project.name}: ${roots.toList()}") return roots[0] } LOG.error("Not found content roots in project ${project.name}. " + "Base path: ${project.basePath}, project file path: ${project.projectFilePath}") throw error("Not found content roots for project") } fun simpleInstallAndOpenLearningProject(contentRoot: Path, langSupport: LangSupport, openProjectTask: OpenProjectTask, postInitCallback: (learnProject: Project) -> Unit) { val actualContentRoot = copyLearningProjectFiles(contentRoot, langSupport) if (actualContentRoot == null) return createVersionFile(actualContentRoot) openOrImportLearningProject(actualContentRoot, openProjectTask, langSupport) { updateLearningModificationTimestamp(it) postInitCallback(it) } } private fun updateLearningModificationTimestamp(it: Project) { PropertiesComponent.getInstance(it).setValue(LEARNING_PROJECT_MODIFICATION, System.currentTimeMillis().toString()) } private fun openOrImportLearningProject(contentRoot: Path, openProjectTask: OpenProjectTask, langSupport: LangSupport, postInitCallback: (learnProject: Project) -> Unit) { val projectDirectoryVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByNioFile( langSupport.getLearningProjectPath(contentRoot) ) ?: error("Copied Learn project folder is null") val task = openProjectTask.copy(beforeInit = { NOTIFICATIONS_SILENT_MODE.set(it, true) }) invokeLater { val nioPath = projectDirectoryVirtualFile.toNioPath() val confirmOpenNewProject = GeneralSettings.getInstance().confirmOpenNewProject if (confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) { GeneralSettings.getInstance().confirmOpenNewProject = GeneralSettings.OPEN_PROJECT_SAME_WINDOW } val project = try { ProjectUtil.openOrImport(nioPath, task) ?: error("Cannot create project for ${langSupport.primaryLanguage} at $nioPath") } finally { if (confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) { GeneralSettings.getInstance().confirmOpenNewProject = confirmOpenNewProject } } postInitCallback(project) } } /** * Returns [newContentDirectory] if learning project files successfully copied on the first try, * path to the directory chosen by user if learning project files successfully copied on the second try, * null if user closed the directory chooser. */ private fun copyLearningProjectFiles(newContentDirectory: Path, langSupport: LangSupport): Path? { var targetDirectory = newContentDirectory if (!langSupport.copyLearningProjectFiles(targetDirectory.toFile())) { targetDirectory = invokeAndWaitIfNeeded { chooseParentDirectoryForLearningProject(langSupport) } ?: return null if (!langSupport.copyLearningProjectFiles(targetDirectory.toFile())) { invokeLater { Messages.showInfoMessage(LearnBundle.message("learn.project.initializing.cannot.create.message"), LearnBundle.message("learn.project.initializing.cannot.create.title")) } error("Cannot create learning demo project. See LOG files for details.") } } val path = langSupport.getLearningProjectPath(targetDirectory) LangManager.getInstance().setLearningProjectPath(langSupport, path.toAbsolutePath().toString()) TrustedPaths.getInstance().setProjectPathTrusted(path, true) return targetDirectory } fun learningProjectUrl(langSupport: LangSupport) = langSupport.javaClass.classLoader.getResource(langSupport.projectResourcePath) ?: throw IllegalArgumentException("No project ${langSupport.projectResourcePath} in resources " + "for ${langSupport.primaryLanguage} IDE learning course") private fun chooseParentDirectoryForLearningProject(langSupport: LangSupport): Path? { val descriptor = FileChooserDescriptor(false, true, false, false, false, false) .withTitle(LearnBundle.message("learn.project.initializing.choose.place", langSupport.contentRootDirectoryName)) val dialog = FileChooserDialogImpl(descriptor, null) var result: List<VirtualFile>? = null dialog.choose(VfsUtil.getUserHomeDir(), Consumer { result = it }) val directories = result ?: return null if (directories.isEmpty()) error("No directory selected for the project") val chosen = directories.single() val canonicalPath = chosen.canonicalPath ?: error("No canonical path for $chosen") return File(canonicalPath, langSupport.contentRootDirectoryName).toPath() } private fun copyLearnProjectIcon(projectDir: File) { val iconPath = "learnProjects/.idea" val iconUrl = ProjectUtils::class.java.classLoader.getResource(iconPath) ?: throw IllegalArgumentException( "Unable to locate icon for learn project by path: $iconPath") val ideaDir = File(projectDir, ".idea") FileUtil.ensureExists(ideaDir) FileUtils.copyResourcesRecursively(iconUrl, ideaDir) } private fun createVersionFile(newProjectDirectory: Path) { PrintWriter(newProjectDirectory.resolve(FEATURE_TRAINER_VERSION).toFile(), "UTF-8").use { it.println(featureTrainerVersion) } } private fun isSameVersion(versionFile: Path): Boolean { if (!versionFile.exists()) return false val res = Files.lines(versionFile).findFirst() if (res.isPresent) { return featureTrainerVersion == res.get() } return false } private fun versionFile(dest: Path) = dest.resolve(FEATURE_TRAINER_VERSION) fun markDirectoryAsSourcesRoot(project: Project, pathToSources: String) { val modules = ModuleManager.getInstance(project).modules if (modules.size > 1) { thisLogger().error("The learning project has more than one module: ${modules.map { it.name }}") } val module = modules.first() val sourcesPath = project.basePath!! + '/' + pathToSources val sourcesRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(sourcesPath) if (sourcesRoot == null) { val status = when { !File(sourcesPath).exists() -> "does not exist" File(sourcesPath).isDirectory -> "existed directory" else -> "it is regular file" } error("Failed to find directory with source files: $sourcesPath ($status)") } val rootsModel = ModuleRootManager.getInstance(module).modifiableModel val contentEntry = rootsModel.contentEntries.find { val contentEntryFile = it.file contentEntryFile != null && VfsUtilCore.isAncestor(contentEntryFile, sourcesRoot, false) } ?: error("Failed to find content entry for file: ${sourcesRoot.name}") contentEntry.addSourceFolder(sourcesRoot, false) runWriteAction { rootsModel.commit() project.save() } } fun createSdkDownloadingNotification(): Notification { return iftNotificationGroup.createNotification(LearnBundle.message("learn.project.initializing.jdk.download.notification.title"), LearnBundle.message("learn.project.initializing.jdk.download.notification.message", ApplicationNamesInfo.getInstance().fullProductName), NotificationType.INFORMATION) } fun closeAllEditorsInProject(project: Project) { FileEditorManagerEx.getInstanceEx(project).windows.forEach { it.files.forEach { file -> it.closeFile(file) } } } fun restoreProject(languageSupport: LangSupport, project: Project) { val done = CompletableFuture<Boolean>() AppUIExecutor.onWriteThread().withDocumentsCommitted(project).submit { try { val stamp = PropertiesComponent.getInstance(project).getValue(LEARNING_PROJECT_MODIFICATION)?.toLong() ?: 0 val needReplace = mutableListOf<Path>() val validContent = mutableListOf<Path>() val directories = mutableListOf<Path>() val root = getProjectRoot(project) val contentRootPath = languageSupport.getContentRootPath(root.toNioPath()) for (path in Files.walk(contentRootPath)) { if (contentRootPath.relativize(path).any { file -> file.name == ".idea" || file.name == "git" || file.name == ".git" || file.name == ".gitignore" || file.name == "venv" || file.name == FEATURE_TRAINER_VERSION || file.name.endsWith(".iml") }) continue if (path.isDirectory()) { directories.add(path) } else { if (path.getLastModifiedTime().toMillis() > stamp) { needReplace.add(path) } else { validContent.add(path) } } } var modified = false for (path in needReplace) { path.delete() modified = true } val contentRoodDirectory = contentRootPath.toFile() languageSupport.copyLearningProjectFiles(contentRoodDirectory, FileFilter { val path = it.toPath() val needCopy = needReplace.contains(path) || !validContent.contains(path) modified = needCopy || modified needCopy }) for (path in directories) { if (isEmptyDir(path)) { modified = true path.delete() } } if (modified) { VfsUtil.markDirtyAndRefresh(false, true, true, root) PropertiesComponent.getInstance(project).setValue(LEARNING_PROJECT_MODIFICATION, System.currentTimeMillis().toString()) } done.complete(true) } catch (e: Exception) { done.complete(false) throw e } } val success = done.get() if (!success) { thisLogger().error("IFT Learning project files refresh failed") } } private fun isEmptyDir(path: Path): Boolean { if (Files.isDirectory(path)) { Files.newDirectoryStream(path).use { directory -> return !directory.iterator().hasNext() } } return false } }
apache-2.0
354d579019284b28e42c7f4d08d0d899
40.378866
140
0.691043
4.965667
false
false
false
false
mdaniel/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/requests/CreateMethodFromGroovyUsageRequest.kt
2
1792
// 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.groovy.codeInspection.untypedUnresolvedAccess.requests import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.CreateMethodRequest import com.intellij.lang.jvm.actions.ExpectedType import com.intellij.lang.jvm.actions.expectedType import com.intellij.lang.jvm.actions.expectedTypes import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments internal class CreateMethodFromGroovyUsageRequest( methodCall: GrMethodCall, modifiers: Collection<JvmModifier> ) : CreateExecutableFromGroovyUsageRequest<GrMethodCall>(methodCall, modifiers), CreateMethodRequest { override fun getArguments(): List<Argument>? { return call.getArguments() } override fun isValid() = super.isValid() && call.let { getRefExpression()?.referenceName != null } private fun getRefExpression() : GrReferenceExpression? = if (super.isValid()) call.invokedExpression as? GrReferenceExpression else null override fun getMethodName() = getRefExpression()?.referenceName!! override fun getReturnType() : List<ExpectedType> { val expected = GroovyExpectedTypesProvider.getDefaultExpectedTypes(call) if (expected.isEmpty()) { return expectedTypes(PsiType.VOID) } return expected.map { expectedType(it, ExpectedType.Kind.EXACT) } } }
apache-2.0
aa9d458fb1628a454895c669f0db89fa
43.8
139
0.804688
4.502513
false
false
false
false
WycliffeAssociates/translationRecorder
translationRecorder/app/src/main/java/org/wycliffeassociates/translationrecorder/login/LoginActivity.kt
1
3015
package org.wycliffeassociates.translationrecorder.login import android.content.Intent import android.os.Bundle import com.door43.login.TermsOfUseActivity import org.wycliffeassociates.translationrecorder.R import org.wycliffeassociates.translationrecorder.login.fragments.FragmentCreateProfile import org.wycliffeassociates.translationrecorder.login.fragments.FragmentReviewProfile import org.wycliffeassociates.translationrecorder.login.interfaces.OnProfileCreatedListener import org.wycliffeassociates.translationrecorder.login.interfaces.OnRedoListener import org.wycliffeassociates.translationrecorder.permissions.PermissionActivity import org.wycliffeassociates.translationrecorder.wav.WavFile import java.io.File /** * Created by sarabiaj on 3/9/2018. */ class LoginActivity : PermissionActivity(), OnProfileCreatedListener, OnRedoListener { override fun onPermissionsAccepted() {} private lateinit var mFragmentCreateProfile: FragmentCreateProfile private var mFragmentReviewProfile: FragmentReviewProfile? = null private lateinit var profilesDirectory: File public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) Screen.lockOrientation(this) if (savedInstanceState == null) { startActivityForResult(Intent(this, TermsOfUseActivity::class.java), 42) profilesDirectory = File(externalCacheDir, "profiles") initializeFragments() addFragments() } } private fun initializeFragments() { mFragmentCreateProfile = FragmentCreateProfile.newInstance( profilesDirectory, this ) mFragmentCreateProfile.retainInstance = true } private fun addFragments() { fragmentManager.beginTransaction() .add(R.id.fragment_container, mFragmentCreateProfile) .commit() } override fun onProfileCreated(wav: WavFile, audio: File, hash: String) { mFragmentReviewProfile = FragmentReviewProfile.newInstance(wav, audio, hash, this) fragmentManager.beginTransaction() .replace(R.id.fragment_container, mFragmentReviewProfile) .commit() } override fun onRedo() { mFragmentCreateProfile = FragmentCreateProfile.newInstance( profilesDirectory, this ) fragmentManager.beginTransaction() .replace(R.id.fragment_container, mFragmentCreateProfile) .commit() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 42 && resultCode != TermsOfUseActivity.RESULT_OK) { finish() } } override fun onBackPressed() { super.onBackPressed() startActivity(Intent(this, UserActivity::class.java)) finish() } }
mit
c7f7934837a2eb53b48837e056078a33
35.768293
91
0.709121
4.785714
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/projectView/KtDeclarationTreeNode.kt
1
3967
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.projectView import com.intellij.ide.projectView.PresentationData import com.intellij.ide.projectView.ViewSettings import com.intellij.ide.projectView.impl.nodes.AbstractPsiBasedNode import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.psi.* internal class KtDeclarationTreeNode( project: Project?, ktDeclaration: KtDeclaration?, viewSettings: ViewSettings? ) : AbstractPsiBasedNode<KtDeclaration?>(project, ktDeclaration!!, viewSettings) { override fun extractPsiFromValue(): PsiElement? = value override fun getChildrenImpl(): Collection<AbstractTreeNode<*>> = emptyList() override fun updateImpl(data: PresentationData) { val declaration = value ?: return data.presentableText = tryGetRepresentableText(declaration) } override fun isDeprecated(): Boolean = value?.let { KtPsiUtil.isDeprecated(it) } ?: false companion object { private val CLASS_INITIALIZER = "<" + KotlinBundle.message("project.view.class.initializer") + ">" private val ERROR_NAME = "<" + KotlinBundle.message("project.view.class.error.name") + ">" private fun String?.orErrorName() = if (!isNullOrBlank()) this else ERROR_NAME fun tryGetRepresentableText(declaration: KtDeclaration): String? { val settings = declaration.containingKtFile.kotlinCustomSettings fun StringBuilder.appendColon() { if (settings.SPACE_BEFORE_TYPE_COLON) append(" ") append(":") if (settings.SPACE_AFTER_TYPE_COLON) append(" ") } fun KtProperty.presentableText() = buildString { append(name.orErrorName()) typeReference?.text?.let { reference -> appendColon() append(reference) } } fun KtFunction.presentableText() = buildString { receiverTypeReference?.text?.let { receiverReference -> append(receiverReference) append('.') } append(name.orErrorName()) append("(") val valueParameters = valueParameters valueParameters.forEachIndexed { index, parameter -> parameter.name?.let { parameterName -> append(parameterName) appendColon() } parameter.typeReference?.text?.let { typeReference -> append(typeReference) } if (index != valueParameters.size - 1) { append(", ") } } append(")") typeReference?.text?.let { returnTypeReference -> appendColon() append(returnTypeReference) } } fun KtObjectDeclaration.presentableText(): String? = buildString { if (isCompanion()) { append("companion object") } else { append(name.orErrorName()) } } return when (declaration) { is KtProperty -> declaration.presentableText() is KtFunction -> declaration.presentableText() is KtObjectDeclaration -> declaration.presentableText() is KtAnonymousInitializer -> CLASS_INITIALIZER else -> declaration.name.orErrorName() } } } }
apache-2.0
5c93359f57dc7d20ec6038777a88845f
39.070707
158
0.586337
5.782799
false
false
false
false
550609334/Twobbble
app/src/main/java/com/twobbble/view/adapter/CommentAdapter.kt
1
6273
package com.twobbble.view.adapter import android.support.v7.widget.RecyclerView import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.twobbble.R import com.twobbble.entity.Comment import com.twobbble.entity.Shot import com.twobbble.tools.Constant import com.twobbble.tools.ImageLoad import com.twobbble.tools.Utils import com.twobbble.tools.ctx import com.zhy.view.flowlayout.FlowLayout import com.zhy.view.flowlayout.TagAdapter import kotlinx.android.synthetic.main.count_info_layout.view.* import kotlinx.android.synthetic.main.details_user.view.* import kotlinx.android.synthetic.main.item_comment.view.* import kotlinx.android.synthetic.main.item_comment_load.view.* import kotlinx.android.synthetic.main.item_details_head.view.* @Suppress("DEPRECATION") /** * Created by liuzipeng on 2017/3/1. */ class CommentAdapter(private val mShot: Shot, private val mComments: MutableList<Comment>, val likeClick: (View, Int) -> Unit, val userClick: (View, Int) -> Unit, val authorClick: () -> Unit, val commentHintClick: () -> Unit, val countClick: (Int) -> Unit, val tagClick: (Int) -> Unit) : RecyclerView.Adapter<CommentAdapter.ViewHolder>() { companion object { private val HEAD = 1 private val COMMENT = 2 } private var mFirstHolder: ViewHolder? = null override fun onBindViewHolder(holder: ViewHolder, position: Int) { if (position != 0) { holder.bindComment(mComments[position]) bindCommentEvent(holder, position) } else { holder.bindShotInfo(mShot) mShot.tags?.let { if (mShot.tags!!.isNotEmpty()) { mountTags(mShot.tags!!, holder) } } mFirstHolder = holder } } fun showProgress() { mFirstHolder?.itemView?.mCommentProgress?.visibility = View.VISIBLE } fun hideCommentHint() { mFirstHolder?.itemView?.mCommentHintText?.visibility = View.GONE } fun hideProgress() { mFirstHolder?.itemView?.mCommentProgress?.visibility = View.GONE } fun showCommentHint(msgResId: Int) { mFirstHolder?.let { it.itemView.mCommentHintText.visibility = View.VISIBLE it.itemView.mCommentHintText.setText(msgResId) } } fun addItem(position: Int, comment: Comment) { mComments.add(comment) notifyItemInserted(position) } fun addItems(comments: MutableList<Comment>) { val position = 1 mComments.addAll(comments) notifyItemInserted(position) } /** * 绑定标签数据 */ private fun mountTags(tags: List<String>, holder: ViewHolder) { holder.itemView.mTagLayout.visibility = View.VISIBLE holder.itemView.mTags.adapter = object : TagAdapter<String>(tags) { override fun getView(parent: FlowLayout, position: Int, t: String?): View { val mTagBtn = LayoutInflater.from(parent.ctx).inflate(R.layout.tag_layout, holder.itemView.mTags, false) as TextView if (position != tags.size - 1) mTagBtn.text = "$t," else mTagBtn.text = t mTagBtn.setOnClickListener { tagClick(position) } return mTagBtn } } } private fun bindCommentEvent(holder: ViewHolder, position: Int) { holder.itemView.mCommentAvatarImg.setOnClickListener { userClick(it, position) } holder.itemView.mCommentLikeBtn.setOnClickListener { likeClick(holder.itemView.mLikeImg, position) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { if (viewType == COMMENT) { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_comment, parent, false)) } else { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_details_head, parent, false)) } } override fun getItemCount(): Int = mComments.size override fun getItemViewType(position: Int): Int = if (position == 0) HEAD else COMMENT inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindComment(comment: Comment) { with(comment) { ImageLoad.frescoLoadCircle(itemView.mCommentAvatarImg, user?.avatar_url.toString()) itemView.mCommentText.text = Html.fromHtml(body) itemView.mNameText.text = user?.name itemView.mCommentLikeCount.text = likes_count.toString() itemView.mTimeText.text = Utils.formatDateUseCh(Utils.parseISO8601(created_at!!)) } } fun bindShotInfo(shot: Shot) { with(shot) { itemView.mTitleText.text = title itemView.mAuthorText.text = user?.name if (description != null && !description.equals("")) { itemView.mDescriptionText.text = Html.fromHtml(description) } ImageLoad.frescoLoadCircle(itemView.mAvatarImg, user?.avatar_url.toString()) itemView.mLikeCountText.text = likes_count.toString() itemView.mBucketCountText.text = buckets_count.toString() itemView.mViewsCountText.text = views_count.toString() itemView.mCommentCountText.text = comments_count.toString() itemView.mAttachmentCountText.text = attachments_count.toString() } itemView.mCommentHintText.setOnClickListener { commentHintClick() } itemView.mAuthorLayout.setOnClickListener { authorClick() } itemView.mLikeCountBtn.setOnClickListener { countClick(Constant.DETAILS_EVENT_LIKE_COUNT) } itemView.mAttachmentCountBtn.setOnClickListener { countClick(Constant.DETAILS_EVENT_ATTACHMENT_COUNT) } itemView.mBucketCountBtn.setOnClickListener { countClick(Constant.DETAILS_EVENT_BUCKET_COUNT) } } } }
apache-2.0
93a2b446f1af63fcb72b0d2428a27e6f
37.654321
132
0.638556
4.465763
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinAwareMoveFilesOrDirectoriesDialog.kt
1
10589
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.TextComponentAccessor import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.PsiManager import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.copy.CopyFilesOrDirectoriesDialog import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.MoveHandler import com.intellij.ui.NonFocusableCheckBox import com.intellij.ui.RecentsManager import com.intellij.ui.TextFieldWithHistoryWithBrowseButton import com.intellij.ui.components.JBLabelDecorator import com.intellij.util.ui.FormBuilder import com.intellij.util.ui.UIUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit import org.jetbrains.kotlin.idea.core.util.onTextChange import org.jetbrains.kotlin.idea.refactoring.isInKotlinAwareSourceRoot import org.jetbrains.kotlin.idea.refactoring.move.logFusForMoveRefactoring import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.psi.KtFile import javax.swing.JComponent class KotlinAwareMoveFilesOrDirectoriesDialog( private val project: Project, private val initialDirectory: PsiDirectory?, private val psiElements: List<PsiFileSystemItem>, private val callback: MoveCallback? ) : DialogWrapper(project, true) { companion object { private const val RECENT_KEYS = "MoveFile.RECENT_KEYS" private const val MOVE_FILES_OPEN_IN_EDITOR = "MoveFile.OpenInEditor" private const val MOVE_FILES_SEARCH_REFERENCES = "MoveFile.SearchReferences" private const val HELP_ID = "refactoring.moveFile" private fun setConfigurationValue(id: String, value: Boolean, defaultValue: Boolean) { if (!ApplicationManager.getApplication().isUnitTestMode) { PropertiesComponent.getInstance().setValue(id, value, defaultValue) } } private fun getConfigurationValue(id: String, defaultValue: Boolean) = !ApplicationManager.getApplication().isUnitTestMode && PropertiesComponent.getInstance().getBoolean(id, defaultValue) } private data class CheckboxesState( val searchReferences: Boolean, val openInEditor: Boolean, val updatePackageDirective: Boolean ) private val nameLabel = JBLabelDecorator.createJBLabelDecorator().setBold(true) private val targetDirectoryField = TextFieldWithHistoryWithBrowseButton() private val searchReferencesCb = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.search.references")).apply { isSelected = true } private val openInEditorCb = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.open.moved.files.in.editor")) private val updatePackageDirectiveCb = NonFocusableCheckBox() private val initializedCheckBoxesState: CheckboxesState override fun getHelpId() = HELP_ID init { title = RefactoringBundle.message("move.title") init() initializeData() initializedCheckBoxesState = getCheckboxesState(applyDefaults = true) } private fun getCheckboxesState(applyDefaults: Boolean) = CheckboxesState( searchReferences = applyDefaults || searchReferencesCb.isSelected, //searchReferencesCb is true by default openInEditor = !applyDefaults && openInEditorCb.isSelected, //openInEditorCb is false by default updatePackageDirective = updatePackageDirectiveCb.isSelected ) override fun createActions() = arrayOf(okAction, cancelAction, helpAction) override fun getPreferredFocusedComponent() = targetDirectoryField.childComponent override fun createCenterPanel(): JComponent? = null override fun createNorthPanel(): JComponent { RecentsManager.getInstance(project).getRecentEntries(RECENT_KEYS)?.let { targetDirectoryField.childComponent.history = it } val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() targetDirectoryField.addBrowseFolderListener( RefactoringBundle.message("select.target.directory"), RefactoringBundle.message("the.file.will.be.moved.to.this.directory"), project, descriptor, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT ) val textField = targetDirectoryField.childComponent.textEditor FileChooserFactory.getInstance().installFileCompletion(textField, descriptor, true, disposable) textField.onTextChange { validateOKButton() } targetDirectoryField.setTextFieldPreferredWidth(CopyFilesOrDirectoriesDialog.MAX_PATH_LENGTH) Disposer.register(disposable, targetDirectoryField) openInEditorCb.isSelected = getConfigurationValue(id = MOVE_FILES_OPEN_IN_EDITOR, defaultValue = false) searchReferencesCb.isSelected = getConfigurationValue(id = MOVE_FILES_SEARCH_REFERENCES, defaultValue = true) val shortcutText = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_CODE_COMPLETION)) return FormBuilder.createFormBuilder() .addComponent(nameLabel) .addLabeledComponent(RefactoringBundle.message("move.files.to.directory.label"), targetDirectoryField, UIUtil.LARGE_VGAP) .addTooltip(RefactoringBundle.message("path.completion.shortcut", shortcutText)) .addComponentToRightColumn(searchReferencesCb, UIUtil.LARGE_VGAP) .addComponentToRightColumn(openInEditorCb, UIUtil.LARGE_VGAP) .addComponentToRightColumn(updatePackageDirectiveCb, UIUtil.LARGE_VGAP) .panel } private fun initializeData() { val psiElement = psiElements.singleOrNull() if (psiElement != null) { val shortenedPath = CopyFilesOrDirectoriesDialog.shortenPath(psiElement.virtualFile) nameLabel.text = when (psiElement) { is PsiFile -> RefactoringBundle.message("move.file.0", shortenedPath) else -> RefactoringBundle.message("move.directory.0", shortenedPath) } } else { val isFile = psiElements.all { it is PsiFile } val isDirectory = psiElements.all { it is PsiDirectory } nameLabel.text = when { isFile -> RefactoringBundle.message("move.specified.files") isDirectory -> RefactoringBundle.message("move.specified.directories") else -> RefactoringBundle.message("move.specified.elements") } } targetDirectoryField.childComponent.text = initialDirectory?.virtualFile?.presentableUrl ?: "" validateOKButton() with(updatePackageDirectiveCb) { val ktFiles = psiElements.filterIsInstance<KtFile>().filter(KtFile::isInKotlinAwareSourceRoot) if (ktFiles.isEmpty()) { parent.remove(updatePackageDirectiveCb) return } val singleFile = ktFiles.singleOrNull() isSelected = singleFile == null || singleFile.packageMatchesDirectoryOrImplicit() text = KotlinBundle.message("checkbox.text.update.package.directive") } } private fun validateOKButton() { isOKActionEnabled = targetDirectoryField.childComponent.text.isNotEmpty() } private val selectedDirectoryName: String get() = targetDirectoryField.childComponent.text.let { when { it.startsWith(".") -> (initialDirectory?.virtualFile?.path ?: "") + "/" + it else -> it } } private fun getModel(): Model { val directory = LocalFileSystem.getInstance().findFileByPath(selectedDirectoryName)?.let { PsiManager.getInstance(project).findDirectory(it) } val elementsToMove = directory?.let { existentDirectory -> val choice = if (psiElements.size > 1 || psiElements[0] is PsiDirectory) intArrayOf(-1) else null psiElements.filterNot { it is PsiFile && CopyFilesOrDirectoriesHandler.checkFileExist(existentDirectory, choice, it, it.name, title) } } ?: psiElements.toList() return KotlinAwareMoveFilesOrDirectoriesModel( project, elementsToMove, selectedDirectoryName, updatePackageDirectiveCb.isSelected, searchReferencesCb.isSelected, callback ) } override fun doOKAction() { val modelResult: ModelResultWithFUSData try { modelResult = getModel().computeModelResult() } catch (e: ConfigurationException) { setErrorText(e.message) return } project.executeCommand(MoveHandler.getRefactoringName()) { with(modelResult) { logFusForMoveRefactoring( numberOfEntities = elementsCount, entity = entityToMove, destination = destination, isDefault = getCheckboxesState(applyDefaults = false) == initializedCheckBoxesState, body = processor ) } } setConfigurationValue(id = MOVE_FILES_SEARCH_REFERENCES, value = searchReferencesCb.isSelected, defaultValue = true) setConfigurationValue(id = MOVE_FILES_OPEN_IN_EDITOR, value = openInEditorCb.isSelected, defaultValue = false) RecentsManager.getInstance(project).registerRecentEntry(RECENT_KEYS, targetDirectoryField.childComponent.text) close(OK_EXIT_CODE, /* isOk = */ true) } }
apache-2.0
efb487d29c2a510c0442b4c9636ab349
44.450644
158
0.716782
5.278664
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/OverrideIconForOverloadMethodBug.kt
8
1122
interface <lineMarker descr="*">SkipSupport</lineMarker> { fun <lineMarker descr="<html><body>Is implemented in <br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportImpl<br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportWithDefaults</body></html>">skip</lineMarker>(why: String) fun <lineMarker descr="<html><body>Is implemented in <br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportWithDefaults</body></html>">skip</lineMarker>() } public interface <lineMarker descr="*">SkipSupportWithDefaults</lineMarker> : SkipSupport { override fun <lineMarker descr="<html><body>Is overridden in <br>&nbsp;&nbsp;&nbsp;&nbsp;SkipSupportImpl</body></html>"><lineMarker descr="Implements function in 'SkipSupport'">skip</lineMarker></lineMarker>(why: String) {} override fun <lineMarker descr="Implements function in 'SkipSupport'">skip</lineMarker>() { skip("not given") } } open class SkipSupportImpl: SkipSupportWithDefaults { override fun <lineMarker descr="Overrides function in 'SkipSupportWithDefaults'">skip</lineMarker>(why: String) = throw RuntimeException(why) } // KT-4428 Incorrect override icon shown for overloaded methods
apache-2.0
722bb44b0948b367c04ab48b8f484786
61.388889
227
0.743316
4.417323
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt
1
13506
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature import com.intellij.psi.PsiReference import com.intellij.refactoring.changeSignature.ParameterInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.core.setDefaultValue import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.util.isPrimaryConstructorOfDataClass import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.addRemoveModifier.setModifierList import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.descriptorUtil.isAnnotationConstructor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.AbstractTypeChecker import org.jetbrains.kotlin.types.TypeCheckerState import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.checker.ClassicTypeSystemContext import org.jetbrains.kotlin.types.checker.createClassicTypeCheckerState import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.model.TypeConstructorMarker class KotlinParameterInfo( val callableDescriptor: CallableDescriptor, val originalIndex: Int = -1, private var name: String, val originalTypeInfo: KotlinTypeInfo = KotlinTypeInfo(false), var defaultValueForCall: KtExpression? = null, var defaultValueAsDefaultParameter: Boolean = false, var valOrVar: KotlinValVar = defaultValOrVar(callableDescriptor), val modifierList: KtModifierList? = null, ) : ParameterInfo { private var _defaultValueForParameter: KtExpression? = null fun setDefaultValueForParameter(expression: KtExpression?) { _defaultValueForParameter = expression } val defaultValue: KtExpression? get() = defaultValueForCall?.takeIf { defaultValueAsDefaultParameter } ?: _defaultValueForParameter var currentTypeInfo: KotlinTypeInfo = originalTypeInfo val defaultValueParameterReferences: Map<PsiReference, DeclarationDescriptor> by lazy { collectDefaultValueParameterReferences(defaultValueForCall) } private fun collectDefaultValueParameterReferences(defaultValueForCall: KtExpression?): Map<PsiReference, DeclarationDescriptor> { val file = defaultValueForCall?.containingFile as? KtFile ?: return emptyMap() if (!file.isPhysical && file.analysisContext == null) return emptyMap() return CollectParameterRefsVisitor(callableDescriptor, defaultValueForCall).run() } override fun getOldIndex(): Int = originalIndex val isNewParameter: Boolean get() = originalIndex == -1 override fun getDefaultValue(): String? = null override fun getName(): String = name override fun setName(name: String?) { this.name = name ?: "" } override fun getTypeText(): String = currentTypeInfo.render() val isTypeChanged: Boolean get() = !currentTypeInfo.isEquivalentTo(originalTypeInfo) override fun isUseAnySingleVariable(): Boolean = false override fun setUseAnySingleVariable(b: Boolean) { throw UnsupportedOperationException() } fun renderType(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val defaultRendering = currentTypeInfo.render() val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering val parameter = currentBaseFunction.valueParameters[parameterIndex] if (parameter.isVararg) return defaultRendering val parameterType = parameter.type if (parameterType.isError) return defaultRendering val originalType = inheritedCallable.originalCallableDescriptor.valueParameters.getOrNull(originalIndex)?.type val typeToRender = originalType?.takeIf { val checker = OverridingTypeCheckerContext.createChecker(inheritedCallable.originalCallableDescriptor, currentBaseFunction) AbstractTypeChecker.equalTypes(checker, originalType.unwrap(), parameterType.unwrap()) } ?: parameterType return typeToRender.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, true) } fun getInheritedName(inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val name = this.name.quoteIfNeeded() if (!inheritedCallable.isInherited) return name val baseFunction = inheritedCallable.baseFunction val baseFunctionDescriptor = baseFunction.originalCallableDescriptor val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor val inheritedParameterDescriptors = inheritedFunctionDescriptor.valueParameters if (originalIndex < 0 || originalIndex >= baseFunctionDescriptor.valueParameters.size || originalIndex >= inheritedParameterDescriptors.size ) return name val inheritedParamName = inheritedParameterDescriptors[originalIndex].name.render() val oldParamName = baseFunctionDescriptor.valueParameters[originalIndex].name.render() return when { oldParamName == inheritedParamName && inheritedFunctionDescriptor !is AnonymousFunctionDescriptor -> name else -> inheritedParamName } } fun requiresExplicitType(inheritedCallable: KotlinCallableDefinitionUsage<*>): Boolean { val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor if (inheritedFunctionDescriptor !is AnonymousFunctionDescriptor) return true if (originalIndex < 0) return !inheritedCallable.hasExpectedType val inheritedParameterDescriptor = inheritedFunctionDescriptor.valueParameters[originalIndex] val parameter = DescriptorToSourceUtils.descriptorToDeclaration(inheritedParameterDescriptor) as? KtParameter ?: return false return parameter.typeReference != null } private fun getOriginalParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter? { return (inheritedCallable.declaration as? KtFunction)?.valueParameters?.getOrNull(originalIndex) } private fun buildNewParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>, parameterIndex: Int): KtParameter { val psiFactory = KtPsiFactory(inheritedCallable.project) val buffer = StringBuilder() if (modifierList != null) { buffer.append(modifierList.text).append(' ') } if (valOrVar != KotlinValVar.None) { buffer.append(valOrVar).append(' ') } buffer.append(getInheritedName(inheritedCallable)) if (requiresExplicitType(inheritedCallable)) { buffer.append(": ").append(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { buffer.append(" = ").append(it.text) } } return psiFactory.createParameter(buffer.toString()) } fun getDeclarationSignature(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter { val originalParameter = getOriginalParameter(inheritedCallable) ?: return buildNewParameter(inheritedCallable, parameterIndex) val psiFactory = KtPsiFactory(originalParameter) val newParameter = originalParameter.copied() modifierList?.let { newParameter.setModifierList(it) } if (valOrVar != newParameter.valOrVarKeyword.toValVar()) { newParameter.setValOrVar(valOrVar) } val newName = getInheritedName(inheritedCallable) if (newParameter.name != newName) { newParameter.setName(newName.quoteIfNeeded()) } if (newParameter.typeReference != null || requiresExplicitType(inheritedCallable)) { newParameter.typeReference = psiFactory.createType(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { newParameter.setDefaultValue(it) } } return newParameter } private class CollectParameterRefsVisitor( private val callableDescriptor: CallableDescriptor, private val expressionToProcess: KtExpression ) : KtTreeVisitorVoid() { private val refs = LinkedHashMap<PsiReference, DeclarationDescriptor>() private val bindingContext = expressionToProcess.analyze(BodyResolveMode.PARTIAL) private val project = expressionToProcess.project fun run(): Map<PsiReference, DeclarationDescriptor> { expressionToProcess.accept(this) return refs } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val ref = expression.mainReference val descriptor = targetToCollect(expression, ref) ?: return refs[ref] = descriptor } private fun targetToCollect(expression: KtSimpleNameExpression, ref: KtReference): DeclarationDescriptor? { val descriptor = ref.resolveToDescriptors(bindingContext).singleOrNull() if (descriptor is ValueParameterDescriptor) { return takeIfOurParameter(descriptor) } if (descriptor is PropertyDescriptor && callableDescriptor is ConstructorDescriptor) { val parameter = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) if (parameter is KtParameter) { return takeIfOurParameter(bindingContext[BindingContext.VALUE_PARAMETER, parameter]) } } val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null (resolvedCall.resultingDescriptor as? ReceiverParameterDescriptor)?.let { return if (takeIfOurReceiver(it.containingDeclaration) != null) it else null } takeIfOurReceiver(resolvedCall.extensionReceiver as? ImplicitReceiver)?.let { return it } takeIfOurReceiver(resolvedCall.dispatchReceiver as? ImplicitReceiver)?.let { return it } return null } private fun compareDescriptors(currentDescriptor: DeclarationDescriptor?, originalDescriptor: DeclarationDescriptor?): Boolean { return compareDescriptors(project, currentDescriptor, originalDescriptor) } private fun takeIfOurParameter(parameter: DeclarationDescriptor?): ValueParameterDescriptor? { return (parameter as? ValueParameterDescriptor) ?.takeIf { compareDescriptors(it.containingDeclaration, callableDescriptor) } } private fun takeIfOurReceiver(receiverDescriptor: DeclarationDescriptor?): DeclarationDescriptor? { return receiverDescriptor?.takeIf { compareDescriptors(it, callableDescriptor.extensionReceiverParameter?.containingDeclaration) || compareDescriptors(it, callableDescriptor.dispatchReceiverParameter?.containingDeclaration) } } private fun takeIfOurReceiver(receiver: ImplicitReceiver?): DeclarationDescriptor? { return takeIfOurReceiver(receiver?.declarationDescriptor) } } } private fun defaultValOrVar(callableDescriptor: CallableDescriptor): KotlinValVar = if (callableDescriptor.isAnnotationConstructor() || callableDescriptor.isPrimaryConstructorOfDataClass) KotlinValVar.Val else KotlinValVar.None private class OverridingTypeCheckerContext(private val matchingTypeConstructors: Map<TypeConstructorMarker, TypeConstructor>) : ClassicTypeSystemContext { override fun areEqualTypeConstructors(c1: TypeConstructorMarker, c2: TypeConstructorMarker): Boolean { return super.areEqualTypeConstructors(c1, c2) || run { val img1 = matchingTypeConstructors[c1] val img2 = matchingTypeConstructors[c2] img1 != null && img1 == c2 || img2 != null && img2 == c1 } } companion object { fun createChecker(superDescriptor: CallableDescriptor, subDescriptor: CallableDescriptor): TypeCheckerState { val context = OverridingTypeCheckerContext(subDescriptor.typeParameters.zip(superDescriptor.typeParameters).associate { it.first.typeConstructor to it.second.typeConstructor }) return createClassicTypeCheckerState(isErrorTypeEqualsToAnything = false, typeSystemContext = context) } } }
apache-2.0
85ed4cef397e1a31876df465e8a51b16
45.253425
158
0.739967
6.206801
false
false
false
false
jwren/intellij-community
platform/util/concurrency/org/jetbrains/concurrency/AsyncPromise.kt
3
5312
// 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.concurrency import com.intellij.openapi.diagnostic.Logger import com.intellij.util.ExceptionUtilRt import com.intellij.util.Function import org.jetbrains.concurrency.Promise.State import java.util.concurrent.* import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer private val CANCELED = object: CancellationException() { override fun fillInStackTrace(): Throwable = this } open class AsyncPromise<T> private constructor(f: CompletableFuture<T>, private val hasErrorHandler: AtomicBoolean, addExceptionHandler: Boolean) : CancellablePromise<T>, CompletablePromise<T> { internal val f: CompletableFuture<T> constructor() : this(CompletableFuture(), AtomicBoolean(), addExceptionHandler = false) init { // cannot be performed outside AsyncPromise constructor because this instance `hasErrorHandler` must be checked this.f = when { addExceptionHandler -> { f.exceptionally { originalError -> val error = (originalError as? CompletionException)?.cause ?: originalError if (shouldLogErrors()) { Logger.getInstance(AsyncPromise::class.java).errorIfNotMessage((error as? CompletionException)?.cause ?: error) } throw error } } else -> f } } override fun isDone(): Boolean = f.isDone override fun get(): T? = nullizeCancelled { f.get() } override fun get(timeout: Long, unit: TimeUnit): T? = nullizeCancelled { f.get(timeout, unit) } // because of the contract: get() should return null for canceled promise private inline fun nullizeCancelled(value: () -> T?): T? { if (isCancelled) { return null } return try { value() } catch (e: CancellationException) { null } } override fun isCancelled(): Boolean = f.isCancelled // because of the unorthodox contract: "double cancel must return false" override fun cancel(mayInterruptIfRunning: Boolean): Boolean = !isCancelled && f.completeExceptionally(CANCELED) override fun cancel() { cancel(true) } override fun getState(): State { return when { !f.isDone -> State.PENDING f.isCompletedExceptionally -> State.REJECTED else -> State.SUCCEEDED } } override fun onSuccess(handler: Consumer<in T>): AsyncPromise<T> { return AsyncPromise(f.whenComplete { value, error -> if (error != null) { throw error } if (!isHandlerObsolete(handler)) { handler.accept(value) } }, hasErrorHandler, addExceptionHandler = true) } override fun onError(rejected: Consumer<in Throwable>): AsyncPromise<T> { hasErrorHandler.set(true) return AsyncPromise(f.whenComplete { _, exception -> if (exception != null) { if (!isHandlerObsolete(rejected)) { rejected.accept((exception as? CompletionException)?.cause ?: exception) } } }, hasErrorHandler, addExceptionHandler = false) } override fun onProcessed(processed: Consumer<in T?>): AsyncPromise<T> { return AsyncPromise(f.whenComplete { value, _ -> if (!isHandlerObsolete(processed)) { processed.accept(value) } }, hasErrorHandler, addExceptionHandler = true) } @Throws(TimeoutException::class) override fun blockingGet(timeout: Int, timeUnit: TimeUnit): T? { try { return get(timeout.toLong(), timeUnit) } catch (e: ExecutionException) { val cause = e.cause ?: throw e // checked exceptions must be not thrown as is - API should conform to Java standards ExceptionUtilRt.rethrowUnchecked(cause) throw e } } override fun <SUB_RESULT : Any?> then(done: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { return AsyncPromise(f.thenApply { done.`fun`(it) }, hasErrorHandler, addExceptionHandler = true) } override fun <SUB_RESULT : Any?> thenAsync(doneF: Function<in T, out Promise<SUB_RESULT>>): Promise<SUB_RESULT> { return AsyncPromise(f.thenCompose { val promise = doneF.`fun`(it) val future = CompletableFuture<SUB_RESULT>() promise .onSuccess { value -> future.complete(value) } .onError { error -> future.completeExceptionally(error) } future }, hasErrorHandler, addExceptionHandler = true) } override fun processed(child: Promise<in T>): Promise<T> { if (child !is AsyncPromise) { return this } return onSuccess { child.setResult(it) } .onError { child.setError(it) } } override fun setResult(t: T?) { f.complete(t) } override fun setError(error: Throwable): Boolean { if (!f.completeExceptionally(error)) { return false } if (shouldLogErrors()) { Logger.getInstance(AsyncPromise::class.java).errorIfNotMessage(error) } return true } protected open fun shouldLogErrors() = !hasErrorHandler.get() fun setError(error: String) = setError(createError(error)) } inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? { return try { runnable() } catch (e: Throwable) { setError(e) null } }
apache-2.0
19e44ab0faa40a357784975d7ce6bc3a
29.705202
125
0.661709
4.408299
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/interop/objc/tests/kt42482.kt
3
762
import kotlin.native.ref.WeakReference import kotlinx.cinterop.* import kotlin.test.* import objcTests.* @Test fun testKT42482() { // Attempt to make the state predictable: kotlin.native.internal.GC.collect() kt42482Deallocated = false assertFalse(kt42482Deallocated); { assertEquals(41, KT42482().fortyTwo()) val obj: KT42482 = KT42482Impl() assertEquals(42, obj.fortyTwo()) kt42482Swizzle(obj) assertEquals(43, obj.fortyTwo()) // Test retain and release on swizzled object: kt42482Global = obj kt42482Global = null }() kotlin.native.internal.GC.collect() assertTrue(kt42482Deallocated) } class KT42482Impl : KT42482() { override fun fortyTwo() = 42 }
apache-2.0
e4745dc62a19b79ea8087db554b6044e
20.771429
54
0.665354
3.753695
false
true
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/persistence/manager/impl/EmbeddedPersistenceManager.kt
1
23007
package com.onyx.persistence.manager.impl import com.onyx.exception.* import com.onyx.extension.* import com.onyx.extension.common.instance import com.onyx.interactors.query.QueryCollector import com.onyx.interactors.query.impl.DefaultQueryInteractor import com.onyx.interactors.record.data.Reference import com.onyx.persistence.* import com.onyx.persistence.collections.LazyQueryCollection import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.manager.PersistenceManager import com.onyx.persistence.query.Query import com.onyx.interactors.relationship.data.RelationshipTransaction import com.onyx.interactors.relationship.data.RelationshipReference import com.onyx.persistence.query.QueryListenerEvent import com.onyx.persistence.stream.QueryMapStream import com.onyx.persistence.stream.QueryStream import java.util.* /** * Persistence manager supplies a public API for performing database persistence and querying operations. This specifically is used for an embedded database. * * @author Tim Osborn * @see com.onyx.persistence.manager.PersistenceManager * * @since 1.0.0 * * * PersistenceManagerFactory factory = new EmbeddedPersistenceManagerFactory(); * factory.setCredentials("username", "password"); * factory.setLocation("/MyDatabaseLocation") * factory.initialize(); * * PersistenceManager manager = factory.getPersistenceManager(); // Get the Persistence manager from the persistence manager factory * * factory.close(); //Close the in memory database * */ open class EmbeddedPersistenceManager(context: SchemaContext) : PersistenceManager { override var context: SchemaContext = context set(value) { field = value value.systemPersistenceManager = this } var isJournalingEnabled: Boolean = false /** * Save entity. Persists a single entity for update or insert. This method will cascade relationships and persist indexes. * * @param entity Managed Entity to Save * @return Saved Managed Entity * @throws OnyxException Exception occurred while persisting an entity * @since 1.0.0 */ @Throws(OnyxException::class) override fun <E : IManagedEntity> saveEntity(entity: E): E { context.checkForKillSwitch() if(entity.isValid(context)) { val putResult = entity.save(context) journal { context.transactionInteractor.writeSave(entity) } entity.saveIndexes(context, if(putResult.isInsert) 0L else putResult.recordId, putResult.recordId) entity.saveRelationships(context) // Update Cached queries context.queryCacheInteractor.updateCachedQueryResultsForEntity(entity, entity.descriptor(context), entity.reference(putResult.recordId, context), if (putResult.isInsert) QueryListenerEvent.INSERT else QueryListenerEvent.UPDATE) } return entity } /** * Batch saves a list of entities. * * * The entities must all be of the same type * * @param entities List of entities * @throws OnyxException Exception occurred while saving an entity within the list. This will not roll back preceding saves if error occurs. * @since 1.0.0 */ @Throws(OnyxException::class) override fun saveEntities(entities: List<IManagedEntity>) { context.checkForKillSwitch() if (entities.isEmpty()) return try { entities.forEach { if (it.isValid(context)) { saveEntity(it) } } } catch (e:ClassCastException) { throw EntityClassNotFoundException(EntityClassNotFoundException.ENTITY_NOT_FOUND) } } /** * Deletes a single entity * * * The entity must exist otherwise it will throw an exception. This will cascade delete relationships and remove index references. * * @param entity Managed Entity to delete * @return Flag indicating it was deleted * @throws OnyxException Error occurred while deleting * @since 1.0.0 */ @Throws(OnyxException::class) override fun deleteEntity(entity: IManagedEntity): Boolean { context.checkForKillSwitch() val descriptor = context.getDescriptorForEntity(entity) val previousReferenceId = entity.referenceId(context, descriptor) if(previousReferenceId > 0) { journal { context.transactionInteractor.writeDelete(entity) } entity.deleteAllIndexes(context, previousReferenceId, descriptor) entity.deleteRelationships(context) entity.recordInteractor(context, descriptor).delete(entity) } return previousReferenceId > 0 } /** * Execute query and delete entities returned in the results * * @param query Query used to filter entities with criteria * @return Number of entities deleted * @throws OnyxException Exception occurred while executing delete query * @since 1.0.0 */ @Throws(OnyxException::class) override fun executeDelete(query: Query): Int { context.checkForKillSwitch() // We want to lock the index controller so that it does not do background indexing val descriptor = context.getDescriptorForEntity(query.entityType, query.partition) query.isUpdateOrDelete = true query.validate(context, descriptor) val queryController = DefaultQueryInteractor(descriptor, this, context) val results:QueryCollector<IManagedEntity> = queryController.getReferencesForQuery(query) query.resultsCount = results.getNumberOfResults() journal { context.transactionInteractor.writeDeleteQuery(query) } return queryController.deleteRecordsWithReferences(results.references, query) } /** * Updates all rows returned by a given query * * The query#updates list must not be null or empty * * @param query Query used to filter entities with criteria * @return Number of entities updated * @throws OnyxException Exception occurred while executing update query * @since 1.0.0 */ @Throws(OnyxException::class) override fun executeUpdate(query: Query): Int { context.checkForKillSwitch() // We want to lock the index controller so that it does not do background indexing val descriptor = context.getDescriptorForEntity(query.entityType, query.partition) query.isUpdateOrDelete = true query.validate(context, descriptor) val queryController = DefaultQueryInteractor(descriptor, this, context) val results:QueryCollector<IManagedEntity> = queryController.getReferencesForQuery(query) query.resultsCount = results.getNumberOfResults() journal { context.transactionInteractor.writeQueryUpdate(query) } return queryController.updateRecordsWithReferences(query, results.references) } /** * Execute query with criteria and optional row limitations * * @param query Query containing criteria * @return Query Results * @throws OnyxException Error while executing query * @since 1.0.0 */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <E> executeQuery(query: Query): List<E> { context.checkForKillSwitch() val descriptor = context.getDescriptorForEntity(query.entityType, query.partition) query.validate(context, descriptor) val queryController = DefaultQueryInteractor(descriptor, this, context) val results:QueryCollector<E> = if(!query.cache) queryController.getReferencesForQuery(query) else cache(query) { queryController.getReferencesForQuery(query) } return results.results as List<E> } /** * Execute query with criteria and optional row limitations. Specify lazy instantiation of query results. * * @param query Query containing criteria * @return LazyQueryCollection lazy loaded results * @throws OnyxException Error while executing query * @since 1.0.0 */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <E : IManagedEntity> executeLazyQuery(query: Query): List<E> { context.checkForKillSwitch() query.isLazy = true val descriptor = context.getDescriptorForEntity(query.entityType, query.partition) query.validate(context, descriptor) val queryController = DefaultQueryInteractor(descriptor, this, context) val results:QueryCollector<E> = if(!query.cache) queryController.getReferencesForQuery(query) else cache(query) { queryController.getReferencesForQuery(query) } return LazyQueryCollection<IManagedEntity>(descriptor, results.getLimitedReferences(), context) as List<E> } /** * Hydrates an instantiated entity. The instantiated entity must have the primary key defined and partition key if the data is partitioned. * All relationships are hydrated based on their fetch policy. * The entity must also not be null. * * @param entity Entity to hydrate. * @return Managed Entity * @throws OnyxException Error when hydrating entity * @since 1.0.0 */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <E : IManagedEntity> find(entity: IManagedEntity): E { context.checkForKillSwitch() val results = entity.recordInteractor(context)[entity] ?: throw NoResultsException() results.hydrateRelationships(context) entity.copy(results, context) return entity as E } /** * Find Entity By Class and ID. * * * All relationships are hydrated based on their fetch policy. This does not take into account the partition. * * @param clazz Managed Entity Type. This must be a cast of IManagedEntity * @param id Primary Key of entity * @return Managed Entity * @throws OnyxException Error when finding entity * @since 1.0.0 */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <E : IManagedEntity> findById(clazz: Class<*>, id: Any): E? { context.checkForKillSwitch() var entity: IManagedEntity? = clazz.createNewEntity() // Find the object entity = entity!!.recordInteractor(context).getWithId(id) entity?.hydrateRelationships(context) return entity as E? } /** * Find Entity By Class and ID. * * * All relationships are hydrated based on their fetch policy. This does not take into account the partition. * * @param clazz Managed Entity Type. This must be a cast of IManagedEntity * @param id Primary Key of entity * @param partitionId Partition key for entity * @return Managed Entity * @throws OnyxException Error when finding entity within partition specified * @since 1.0.0 */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <E : IManagedEntity> findByIdInPartition(clazz: Class<*>, id: Any, partitionId: Any): E? { context.checkForKillSwitch() var entity: IManagedEntity? = clazz.createNewEntity() entity?.setPartitionValue(context = context, value = partitionId) // Find the object entity = entity!!.recordInteractor(context).getWithId(id) entity?.hydrateRelationships(context) return entity as E? } /** * Determines if the entity exists within the database. * * * It is determined by the primary id and partition key * * @param entity Managed Entity to check * @return Returns true if the entity primary key exists. Otherwise it returns false * @throws OnyxException Error when finding entity within partition specified * @since 1.0.0 */ @Throws(OnyxException::class) override fun exists(entity: IManagedEntity): Boolean { context.checkForKillSwitch() return entity.recordInteractor(context).exists(entity) } /** * Determines if the entity exists within the database. * * * It is determined by the primary id and partition key * * @param entity Managed Entity to check * @param partitionId Partition Value for entity * @return Returns true if the entity primary key exists. Otherwise it returns false * @throws OnyxException Error when finding entity within partition specified * @since 1.0.0 */ @Throws(OnyxException::class) override fun exists(entity: IManagedEntity, partitionId: Any): Boolean { context.checkForKillSwitch() val descriptor = context.getDescriptorForEntity(entity, partitionId) val recordInteractor = context.getRecordInteractor(descriptor) return recordInteractor.exists(entity) } /** * Force Hydrate relationship based on attribute name * * @param entity Managed Entity to attach relationship values * @param attribute String representation of relationship attribute * @throws OnyxException Error when hydrating relationship. The attribute must exist and be a relationship. * @since 1.0.0 */ @Throws(OnyxException::class) override fun initialize(entity: IManagedEntity, attribute: String) { context.checkForKillSwitch() val descriptor = context.getDescriptorForEntity(entity) val relationshipDescriptor = descriptor.relationships[attribute] ?: throw RelationshipNotFoundException(RelationshipNotFoundException.RELATIONSHIP_NOT_FOUND, attribute, entity.javaClass.name) val relationshipInteractor = context.getRelationshipInteractor(relationshipDescriptor) relationshipInteractor.hydrateRelationshipForEntity(entity, RelationshipTransaction(), true) } /** * This is a way to batch save all relationships for an entity. This does not retain any existing relationships and will * overwrite all existing with the set you are sending in. This is useful to optimize batch saving entities with relationships. * * @param entity Parent Managed Entity * @param relationship Relationship attribute * @param relationshipIdentifiers Existing relationship identifiers * @throws OnyxException Error occurred while saving relationship. * @since 1.0.0 */ @Throws(OnyxException::class) override fun saveRelationshipsForEntity(entity: IManagedEntity, relationship: String, relationshipIdentifiers: Set<Any>) { context.checkForKillSwitch() val relationships = context.getDescriptorForEntity(entity).relationships val relationshipDescriptor = relationships[relationship] ?: throw RelationshipNotFoundException(RelationshipNotFoundException.RELATIONSHIP_NOT_FOUND, relationship, entity.javaClass.name) val references = HashSet<RelationshipReference>() relationshipIdentifiers.forEach { if (it is RelationshipReference) { references.add(it) } else { references.add(RelationshipReference(it, 0)) } } val relationshipInteractor = context.getRelationshipInteractor(relationshipDescriptor) relationshipInteractor.updateAll(entity, references) } /** * Get an entity by its partition reference. This is the same as the method above but for objects that have * a reference as part of a partition. An example usage would be in LazyQueryCollection so that it may * hydrate objects in random partitions. * * @param entityType Type of managed entity * @param reference Partition reference holding both the partition id and reference id * @param <E> The managed entity implementation class * @return Managed Entity * @throws OnyxException The reference does not exist for that type */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <E : IManagedEntity> getWithReference(entityType: Class<*>, reference: Reference): E? { context.checkForKillSwitch() val managedEntity = reference.toManagedEntity(context, entityType) managedEntity?.hydrateRelationships(context) return managedEntity as E } /** * Retrieves an entity using the primaryKey and partition * * @param clazz Entity Type * @param id Entity Primary Key * @param partitionId - Partition Identifier. Not to be confused with partition key. This is a unique id within the partition System table * @return Managed Entity * @throws OnyxException error occurred while attempting to retrieve entity. * @since 1.0.0 */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <E : IManagedEntity?> findByIdWithPartitionId(clazz: Class<*>, id: Any, partitionId: Long): E { context.checkForKillSwitch() val entity = RelationshipReference(identifier = id, partitionId = partitionId).toManagedEntity(context, clazz) entity?.hydrateRelationships(context) return entity as E } /** * Get Map representation of an entity with reference id * * @param entityType Original type of entity * @param reference Reference location within a data structure * @return Map of key key pair of the entity. Key being the attribute name. */ @Throws(OnyxException::class) override fun getMapWithReferenceId(entityType: Class<*>, reference: Reference): Map<String, *>? { context.checkForKillSwitch() return reference.recordInteractor(context, entityType).getMapWithReferenceId(reference.reference) } /** * Retrieve the quantity of entities that match the query criteria. * * * usage: * * * Query myQuery = new Query(); * myQuery.setClass(SystemEntity.class); * long numberOfSystemEntities = persistenceManager.countForQuery(myQuery); * * * or: * * * Query myQuery = new Query(SystemEntity.class, new QueryCriteria("primaryKey", QueryCriteriaOperator.GREATER_THAN, 3)); * long numberOfSystemEntitiesWithIdGt3 = persistenceManager.countForQuery(myQuery); * * @param query The query to apply to the count operation * @return The number of entities that meet the query criteria * @throws OnyxException Error during query. * @since 1.3.0 Implemented with feature request #71 */ @Throws(OnyxException::class) override fun countForQuery(query: Query): Long { context.checkForKillSwitch() val clazz = query.entityType // We want to lock the index controller so that it does not do background indexing val descriptor = context.getDescriptorForEntity(clazz, query.partition) query.validate(context, descriptor) val cachedResults = context.queryCacheInteractor.getCachedQueryResults(query) if (cachedResults?.references != null) return cachedResults.references!!.size.toLong() val queryController = DefaultQueryInteractor(descriptor, this, context) return queryController.getCountForQuery(query) } /** * This method is used for bulk streaming data entities. An example of bulk streaming is for analytics or bulk updates included but not limited to model changes. * * @param query Query to execute and stream * @param streamer Instance of the streamer to use to stream the data * @since 1.0.0 */ @Throws(OnyxException::class) @Suppress("UNCHECKED_CAST") override fun <T : Any> stream(query: Query, streamer: QueryStream<T>) { context.checkForKillSwitch() val entityList = this.executeLazyQuery<IManagedEntity>(query) as LazyQueryCollection<IManagedEntity> entityList.forEachIndexed { index, iManagedEntity -> if (streamer is QueryMapStream) { (streamer as QueryStream<Map<String, Any?>>).accept(entityList.getDict(index) as Map<String, Any?>, this) } else { streamer.accept(iManagedEntity as T, this) } } } /** * This method is used for bulk streaming. An example of bulk streaming is for analytics or bulk updates included but not limited to model changes. * * @param query Query to execute and stream * @param queryStreamClass Class instance of the database stream * @since 1.0.0 */ @Throws(OnyxException::class) override fun stream(query: Query, queryStreamClass: Class<*>) { context.checkForKillSwitch() val streamer:QueryStream<*> = try { queryStreamClass.instance() } catch (e: InstantiationException) { throw StreamException(StreamException.CANNOT_INSTANTIATE_STREAM) } catch (e: IllegalAccessException) { throw StreamException(StreamException.CANNOT_INSTANTIATE_STREAM) } this.stream(query, streamer) } /** * Un-register a query listener. This will remove the listener from observing changes for that query. * If you do not un-register queries, they will not expire nor will they be de-registered automatically. * This could cause performance degradation if removing the registration is neglected. * * @param query Query with a listener attached * * @throws OnyxException Un expected error when attempting to unregister listener * * @since 1.3.0 Added query subscribers as an enhancement. */ @Throws(OnyxException::class) override fun removeChangeListener(query: Query): Boolean { query.validate(context) return context.queryCacheInteractor.unSubscribe(query) } /** * Listen to a query and register its subscriber * * @param query Query with query listener * @since 1.3.1 */ @Throws(OnyxException::class) override fun listen(query: Query) { query.cache = true context.checkForKillSwitch() query.validate(context) context.queryCacheInteractor.subscribe(query) } /** * Run Journaling code if it is enabled * * @since 2.0.0 Added as a fancy unit */ private fun journal(body:() -> Unit) { if(isJournalingEnabled) body.invoke() } /** * Cache query results from the closure. If the query has already been cached, return the results * of the cache. * * @param query Query results to cache * @param body Closure to execute to retrieve the results of the query * * @since 2.0.0 */ private fun <E> cache(query: Query, body: () -> QueryCollector<E>) = context.queryCacheInteractor.cache(query, body) }
agpl-3.0
f8ef43445e0e1fa8d25cc143048bfcae
37.409015
239
0.68301
4.869206
false
false
false
false
Abdel-RhmanAli/Inventory-App
app/src/main/java/com/example/android/inventory/ui/SwipeToDeleteTouchHelper.kt
1
2506
package com.example.android.inventory.ui import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper class SwipeToDeleteCallBack(dragDirection: Int, swipeDirection: Int, val body: (Int) -> Unit) : ItemTouchHelper.SimpleCallback(dragDirection, swipeDirection) { override fun onMove(recyclerView: RecyclerView, holder1: RecyclerView.ViewHolder, holder2: RecyclerView.ViewHolder): Boolean { return false } override fun onSwiped(holder: RecyclerView.ViewHolder, p1: Int) { body(holder.adapterPosition) } override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { // Get RecyclerView item from the ViewHolder val itemView = viewHolder.itemView val p = Paint() p.color = Color.RED if (dX > 0) { //RIGHT c.drawRect( itemView.left.toFloat(), itemView.top.toFloat(), dX, itemView.bottom.toFloat(), p ) p.color = Color.WHITE p.textSize = 36F c.drawText( "Delete", dX / 4, (itemView.top.toFloat() + itemView.bottom.toFloat()) / 2, p ) } else { //LEFT c.drawRect( itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat(), p ) p.color = Color.WHITE p.textSize = 36F c.drawText( "Delete", itemView.right.toFloat() + dX / 4, (itemView.top.toFloat() + itemView.bottom.toFloat()) / 2, p ) } super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } } }
apache-2.0
817e58f625523396a41465fec3a7019f
34.882353
174
0.494413
5.377682
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/JKMemberData.kt
2
2826
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.externalCodeProcessing import com.intellij.psi.PsiField import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.isPrivate interface JKMemberData { var kotlinElementPointer: SmartPsiElementPointer<KtNamedDeclaration>? var isStatic: Boolean val fqName: FqName? var name: String val kotlinElement get() = kotlinElementPointer?.element val searchInJavaFiles: Boolean get() = true val searchInKotlinFiles: Boolean get() = true val searchingNeeded get() = kotlinElement?.isPrivate() != true && (searchInJavaFiles || searchInKotlinFiles) } interface JKMemberDataCameFromJava<J : PsiMember> : JKMemberData { val javaElement: J override val fqName get() = javaElement.kotlinFqName } interface JKFieldData : JKMemberData data class JKFakeFieldData( override var isStatic: Boolean, override var kotlinElementPointer: SmartPsiElementPointer<KtNamedDeclaration>? = null, override val fqName: FqName?, override var name: String ) : JKFieldData { override val searchInJavaFiles: Boolean get() = false override val searchInKotlinFiles: Boolean get() = false } data class JKFieldDataFromJava( override val javaElement: PsiField, override var isStatic: Boolean = false, override var kotlinElementPointer: SmartPsiElementPointer<KtNamedDeclaration>? = null, override var name: String = javaElement.name ) : JKMemberDataCameFromJava<PsiField>, JKFieldData { override val searchInKotlinFiles: Boolean get() = wasRenamed val wasRenamed: Boolean get() = javaElement.name != name } interface JKMethodData : JKMemberDataCameFromJava<PsiMethod> { var usedAsAccessorOfProperty: JKFieldData? } data class JKPhysicalMethodData( override val javaElement: PsiMethod, override var isStatic: Boolean = false, override var kotlinElementPointer: SmartPsiElementPointer<KtNamedDeclaration>? = null, override var usedAsAccessorOfProperty: JKFieldData? = null ) : JKMethodData { override var name: String = javaElement.name } data class JKLightMethodData( override val javaElement: PsiMethod, override var isStatic: Boolean = false, override var kotlinElementPointer: SmartPsiElementPointer<KtNamedDeclaration>? = null, override var usedAsAccessorOfProperty: JKFieldData? = null ) : JKMethodData { override var name: String = javaElement.name }
apache-2.0
3c3120e46e664e185c241b88c66c4a9d
31.860465
120
0.755485
4.940559
false
false
false
false
jwren/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/intentions/PackageSearchUnresolvedReferenceQuickFix.kt
2
1894
package com.jetbrains.packagesearch.intellij.plugin.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Iconable import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.jetbrains.packagesearch.PackageSearchIcons import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.util.uiStateModifier import java.util.regex.Pattern class PackageSearchUnresolvedReferenceQuickFix(private val ref: PsiReference) : IntentionAction, LowPriorityAction, Iconable { private val classnamePattern = Pattern.compile("(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)*\\p{Lu}\\p{javaJavaIdentifierPart}+") override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { PackageSearchToolWindowFactory.activateToolWindow(project) { project.uiStateModifier.setSearchQuery(ref.canonicalText) } } override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = ref.element.run { isValid && classnamePattern.matcher(text).matches() } @Suppress("DialogTitleCapitalization") // It's the Package Search plugin name... override fun getText() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.action") @Suppress("DialogTitleCapitalization") // It's the Package Search plugin name... override fun getFamilyName() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.family") override fun getIcon(flags: Int) = PackageSearchIcons.Package override fun startInWriteAction() = false }
apache-2.0
0ad737e53653da1d5cd060edd38300f2
46.35
126
0.792503
5.023873
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/PropertyUsageReplacementStrategy.kt
4
1234
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInliner import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.references.ReferenceAccess class PropertyUsageReplacementStrategy(readReplacement: CodeToInline?, writeReplacement: CodeToInline?) : UsageReplacementStrategy { private val readReplacementStrategy = readReplacement?.let { CallableUsageReplacementStrategy(it, inlineSetter = false) } private val writeReplacementStrategy = writeReplacement?.let { CallableUsageReplacementStrategy(it, inlineSetter = true) } override fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)? { return when (usage.readWriteAccess(useResolveForReadWrite = true)) { ReferenceAccess.READ -> readReplacementStrategy?.createReplacer(usage) ReferenceAccess.WRITE -> writeReplacementStrategy?.createReplacer(usage) ReferenceAccess.READ_WRITE -> null } } }
apache-2.0
db4c405fa376e85db095bf4e862418ff
46.461538
158
0.765802
5.251064
false
false
false
false
jwren/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/references/OneToAbstractMany.kt
2
2379
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl.references import com.intellij.workspaceModel.storage.impl.* import com.intellij.workspaceModel.storage.impl.ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * This reference has a special behaviour. During addDIff it doesn't try to merge added and remove children, but just replaces all children. * This behaviour should be updated if you want a version of this reference that merges children */ class OneToAbstractMany<Parent : WorkspaceEntityBase, Child : WorkspaceEntityBase>(private val childClass: Class<Child>) : ReadOnlyProperty<Parent, Sequence<Child>> { private var connectionId: ConnectionId? = null override fun getValue(thisRef: Parent, property: KProperty<*>): Sequence<Child> { if (connectionId == null) { connectionId = ConnectionId.create(thisRef.javaClass, childClass, ONE_TO_ABSTRACT_MANY, true) } return thisRef.snapshot.extractOneToAbstractManyChildren(connectionId!!, thisRef.id.asParent()) } } class MutableOneToAbstractMany<Parent : WorkspaceEntityBase, Child : WorkspaceEntityBase, ModifParent : ModifiableWorkspaceEntityBase<Parent>>( private val parentClass: Class<Parent>, private val childClass: Class<Child> ) : ReadWriteProperty<ModifParent, Sequence<Child>> { private var connectionId: ConnectionId? = null override fun getValue(thisRef: ModifParent, property: KProperty<*>): Sequence<Child> { if (connectionId == null) { connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ABSTRACT_MANY, true) } return thisRef.diff.extractOneToAbstractManyChildren(connectionId!!, thisRef) } override fun setValue(thisRef: ModifParent, property: KProperty<*>, value: Sequence<Child>) { if (!thisRef.modifiable.get()) { throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!") } if (connectionId == null) { connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ABSTRACT_MANY, true) } thisRef.diff.updateOneToAbstractManyChildrenOfParent(connectionId!!, thisRef, value) } }
apache-2.0
fdad71293aa90b95022354a8dc207b3a
47.55102
166
0.770912
4.777108
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/scopes/KtFirStarImportingScope.kt
2
5493
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.frontend.api.fir.scopes import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.fir.scopes.getContainingCallableNamesIfPresent import org.jetbrains.kotlin.fir.scopes.getContainingClassifierNamesIfPresent import org.jetbrains.kotlin.fir.scopes.impl.FirAbstractStarImportingScope import org.jetbrains.kotlin.fir.scopes.impl.FirDefaultStarImportingScope import org.jetbrains.kotlin.idea.frontend.api.ValidityTokenOwner import org.jetbrains.kotlin.idea.frontend.api.ValidityToken import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder import org.jetbrains.kotlin.idea.frontend.api.fir.utils.cached import org.jetbrains.kotlin.idea.frontend.api.fir.utils.weakRef import org.jetbrains.kotlin.idea.frontend.api.scopes.* import org.jetbrains.kotlin.idea.frontend.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.idea.frontend.api.symbols.KtClassifierSymbol import org.jetbrains.kotlin.idea.frontend.api.symbols.KtConstructorSymbol import org.jetbrains.kotlin.idea.frontend.api.withValidityAssertion import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelClassByPackageIndex import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelFunctionByPackageIndex import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelPropertyByPackageIndex import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassOrObject internal class KtFirStarImportingScope( firScope: FirAbstractStarImportingScope, private val builder: KtSymbolByFirBuilder, project: Project, override val token: ValidityToken, ) : KtStarImportingScope, ValidityTokenOwner { private val firScope: FirAbstractStarImportingScope by weakRef(firScope) override val isDefaultImportingScope: Boolean = withValidityAssertion { firScope is FirDefaultStarImportingScope } private val packageHelper = PackageIndexHelper(project) override val imports: List<StarImport> by cached { firScope.starImports.map { import -> StarImport( import.packageFqName, import.relativeClassName, import.resolvedClassId ) } } override fun getCallableSymbols(nameFilter: KtScopeNameFilter): Sequence<KtCallableSymbol> = withValidityAssertion { firScope.getCallableSymbols(getCallableNames().filter(nameFilter), builder) } override fun getClassifierSymbols(nameFilter: KtScopeNameFilter): Sequence<KtClassifierSymbol> = withValidityAssertion { firScope.getClassifierSymbols(getClassifierNames().filter(nameFilter), builder) } override fun getConstructors(): Sequence<KtConstructorSymbol> = emptySequence() // todo cache? @OptIn(ExperimentalStdlibApi::class) override fun getCallableNames(): Set<Name> = withValidityAssertion { imports.flatMapTo(hashSetOf()) { import: Import -> if (import.relativeClassName == null) { // top level callable packageHelper.getPackageTopLevelCallables(import.packageFqName) } else { //member val classId = import.resolvedClassId ?: error("Class id should not be null as relativeClassName is not null") firScope.getStaticsScope(classId)?.getContainingCallableNamesIfPresent().orEmpty() } } } override fun getClassifierNames(): Set<Name> = withValidityAssertion { imports.flatMapTo(hashSetOf()) { import -> if (import.relativeClassName == null) { packageHelper.getPackageTopLevelClassifiers(import.packageFqName) } else { val classId = import.resolvedClassId ?: error("Class id should not be null as relativeClassName is not null") firScope.getStaticsScope(classId)?.getContainingClassifierNamesIfPresent().orEmpty() } } } } private class PackageIndexHelper(private val project: Project) { //todo use more concrete scope private val searchScope = GlobalSearchScope.allScope(project) private val functionByPackageIndex = KotlinTopLevelFunctionByPackageIndex.getInstance() private val propertyByPackageIndex = KotlinTopLevelPropertyByPackageIndex.getInstance() private val classByPackageIndex = KotlinTopLevelClassByPackageIndex.getInstance() fun getPackageTopLevelCallables(packageFqName: FqName): Set<Name> { return getTopLevelCallables(packageFqName).mapTo(hashSetOf()) { it.nameAsSafeName } } fun getPackageTopLevelClassifiers(packageFqName: FqName): Set<Name> { return getTopLevelClassifiers(packageFqName).mapTo(hashSetOf()) { it.nameAsSafeName } } private fun getTopLevelClassifiers(packageFqName: FqName): MutableCollection<KtClassOrObject> = classByPackageIndex.get(packageFqName.asString(), project, searchScope) private fun getTopLevelCallables(packageFqName: FqName): Sequence<KtCallableDeclaration> = sequence<KtCallableDeclaration> { yieldAll(functionByPackageIndex.get(packageFqName.asString(), project, searchScope)) yieldAll(propertyByPackageIndex.get(packageFqName.asString(), project, searchScope)) } }
apache-2.0
968427c037473f3e9924ba1e4aa4d8ae
48.053571
128
0.76643
4.913238
false
false
false
false
smmribeiro/intellij-community
platform/elevation/common/src/com/intellij/execution/process/mediator/grpc/ExceptionAsStatus.kt
5
7201
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.process.mediator.grpc import com.intellij.execution.process.mediator.daemon.QuotaExceededException import io.grpc.Status import io.grpc.Status.Code.* import io.grpc.StatusException import io.grpc.StatusRuntimeException import org.jetbrains.annotations.VisibleForTesting import java.io.EOFException import java.io.FileNotFoundException import java.io.IOException import java.util.concurrent.CancellationException import kotlin.reflect.KClass @Suppress("DataClassPrivateConstructor") data class ExceptionAsStatus private constructor(val status: Status, val exceptionDescriptor: ExceptionDescriptor<*>) { data class ExceptionDescriptor<T : Throwable> internal constructor( val type: KClass<out T>, val constructor: (String?, Throwable?) -> T ) { companion object { internal inline fun <reified T : Throwable> withThrowable( noinline constructor: (String?, Throwable?) -> T ) = ExceptionDescriptor(T::class, constructor) internal inline fun <reified T : Throwable> withInitCause( noinline constructor: (String?) -> T ) = ExceptionDescriptor(T::class) { s, cause -> constructor(s).initCause(cause) } } } companion object { private inline operator fun <reified T : Throwable> invoke( status: Status, noinline exceptionConstructor: (String?, Throwable?) -> T ) = ExceptionAsStatus(status, ExceptionDescriptor.withThrowable(exceptionConstructor)) // @formatter:off @VisibleForTesting internal val KNOWN_EXCEPTIONS: LinkedHashMap<Class<out Throwable>, ExceptionAsStatus> = listOf( // the order matters! should be from the most generic down to more specific ExceptionDescriptor(Throwable::class, ::RuntimeException) asStatus DATA_LOSS, ExceptionDescriptor.withThrowable(::Exception) asStatus DATA_LOSS, ExceptionDescriptor.withThrowable(::RuntimeException) asStatus DATA_LOSS, ExceptionDescriptor.withThrowable(::Error) asStatus DATA_LOSS, ExceptionDescriptor.withThrowable(::AssertionError) asStatus DATA_LOSS, ExceptionDescriptor.withInitCause(::NoClassDefFoundError) asStatus DATA_LOSS, ExceptionDescriptor.withInitCause(::ClassCastException) asStatus DATA_LOSS, ExceptionDescriptor.withInitCause(::NullPointerException) asStatus DATA_LOSS, ExceptionDescriptor.withInitCause(::KotlinNullPointerException) asStatus DATA_LOSS, ExceptionDescriptor.withThrowable(::ConcurrentModificationException) asStatus DATA_LOSS, ExceptionDescriptor.withThrowable(::UnsupportedOperationException) asStatus UNIMPLEMENTED, ExceptionDescriptor.withInitCause(::NoSuchElementException) asStatus OUT_OF_RANGE, ExceptionDescriptor.withInitCause(::IndexOutOfBoundsException) asStatus OUT_OF_RANGE, ExceptionDescriptor.withInitCause(::StringIndexOutOfBoundsException) asStatus OUT_OF_RANGE, ExceptionDescriptor.withInitCause(::ArrayIndexOutOfBoundsException) asStatus OUT_OF_RANGE, ExceptionDescriptor.withThrowable(::IllegalStateException) asStatus FAILED_PRECONDITION, ExceptionDescriptor.withInitCause(::CancellationException) asStatus CANCELLED, ExceptionDescriptor.withInitCause(::QuotaExceededException) asStatus RESOURCE_EXHAUSTED, ExceptionDescriptor.withThrowable(::IllegalArgumentException) asStatus INVALID_ARGUMENT, ExceptionDescriptor.withInitCause(::IllegalThreadStateException) asStatus INVALID_ARGUMENT, ExceptionDescriptor.withInitCause(::NumberFormatException) asStatus INVALID_ARGUMENT, ExceptionDescriptor.withThrowable(::IOException) asStatus NOT_FOUND, ExceptionDescriptor.withInitCause(::EOFException) asStatus NOT_FOUND, ExceptionDescriptor.withInitCause(::FileNotFoundException) asStatus NOT_FOUND, ).associateByTo(LinkedHashMap()) { it.exceptionDescriptor.type.java }.also { map -> val definedSupertypes = mutableSetOf<Class<*>>() for (throwableClass in map.keys) { check(throwableClass !in definedSupertypes) { "KNOWN_EXCEPTIONS should be from the most generic down to more specific" } definedSupertypes.addAll(throwableClass.superclassChain()) } } // @formatter:on private infix fun <T : Throwable> ExceptionDescriptor<T>.asStatus(statusCode: Status.Code) = ExceptionAsStatus(statusCode.toStatus(), this) fun forThrowableClass(throwableClass: Class<*>): ExceptionAsStatus? { return throwableClass.superclassChain() .mapNotNull { KNOWN_EXCEPTIONS[it] } .firstOrNull() } private fun Class<*>.superclassChain() = generateSequence(this) { it.superclass } fun forStatusCode(statusCode: Status.Code): ExceptionAsStatus? { return KNOWN_EXCEPTIONS.values.firstOrNull { it.status.code == statusCode } } const val CLASS_NAME_START = "#" const val CLASS_NAME_DELIMITER = ": " inline fun <R> wrap(block: () -> R): R { return try { block() } catch (t: Throwable) { when (t) { is StatusException -> throw t is StatusRuntimeException -> throw t } val exceptionAsStatus = forThrowableClass(t.javaClass) ?: throw t throw exceptionAsStatus.status .withDescription(CLASS_NAME_START + t.javaClass.name + (t.message?.let { CLASS_NAME_DELIMITER + it } ?: "")) .withCause(t) .asException() } } inline fun <R> unwrap(block: () -> R): R { return try { block() } catch (e: Exception) { val status = when (e) { is StatusException -> e.status is StatusRuntimeException -> e.status else -> throw e } val code = status.code @Suppress("NON_EXHAUSTIVE_WHEN") when (code) { OK, UNKNOWN, INTERNAL, UNAUTHENTICATED -> throw e } val description = status.description val throwableClass = if (description != null && description.startsWith(CLASS_NAME_START)) { val className = description.substringAfter(CLASS_NAME_START).substringBefore(CLASS_NAME_DELIMITER) kotlin.runCatching { Class.forName(className, false, ExceptionAsStatus::class.java.classLoader) }.getOrNull() } else null val message = when { description == null -> code.toString() throwableClass == null -> description description.contains(CLASS_NAME_DELIMITER) -> description.substringAfter(CLASS_NAME_DELIMITER) else -> null } val exceptionAsStatus = throwableClass?.let { forThrowableClass(it) } ?: forStatusCode(code) ?: throw e throw exceptionAsStatus.exceptionDescriptor.constructor(message, e) } } } }
apache-2.0
098f8e48bea9e37ba1757e3393e782d7
43.450617
140
0.681989
4.901974
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/settings/ESP.kt
1
3700
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * 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.charlatano.settings import com.charlatano.game.Color /////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// --- ESP Types --- /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /** * Whether or not to use skeleton ESP. */ var SKELETON_ESP = false /** * Whether or not to use box ESP. */ var BOX_ESP = false /** * Whether or not to use the within-game glow ESP. * * This ESP **CANNOT** be hidden from game capture for streaming. */ var GLOW_ESP = true /** * Whether or not to enable radar reveal. */ var RADAR = false /** * This gets rid of glow ESP "flicker", and more importantly reduces CPU usage. */ var FLICKER_FREE_GLOW = true /** * Whether or not to use model ESP. * This esp makes the model itself glow a certain color. * This esp is currently tied to GLOW_ESP, and GLOW_ESP must be true * This esp does not show enemies through walls, it only highlights and makes them extremely visible when on screen */ var MODEL_ESP = true /** * Whether or not to change model colors */ var CHAMS = false /** * Brightness of CHAMS */ var CHAMS_BRIGHTNESS = 100 /////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////// --- TOGGLES --- //////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /** * Whether or not to highlight your team mates. */ var SHOW_TEAM = true /** * Whether or not to highlight enemies. */ var SHOW_ENEMIES = true /** * Whether or not to highlight "dormant" (unknown-location) players. * * Enabling this can allow you to see players at a further distance, * but you may see some "ghost" players which are really not there. */ var SHOW_DORMANT = false /** * Whether or not to highlight the bomb. */ var SHOW_BOMB = true /** * Whether or not to highlight weapons. */ var SHOW_WEAPONS = false /** * Whether or not to highlight grenades. */ var SHOW_GRENADES = false /////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////// --- COLORS --- /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /** * The color to highlight your team mates. */ var TEAM_COLOR = Color(0, 0, 255, 1.0) /** * The color to highlight your enemies. */ var ENEMY_COLOR = Color(255, 0, 0, 1.0) /** * The color to highlight the bomb. */ var BOMB_COLOR = Color(255, 255, 0, 1.0) /** * The color to highlight weapons. */ var WEAPON_COLOR = Color(0, 255, 0, 0.5) /** * The color to highlight grenades. */ var GRENADE_COLOR = Color(0, 255, 0, 1.0)
agpl-3.0
9109bda935acbb71b250f7f7f6c3bd6a
25.811594
115
0.534054
4.07489
false
false
false
false
GoogleContainerTools/google-container-tools-intellij
skaffold-editing/src/main/kotlin/com/google/container/tools/skaffold/editing/SkaffoldContextType.kt
1
1353
/* * Copyright 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.container.tools.skaffold.editing import com.intellij.codeInsight.template.TemplateContextType import com.intellij.psi.PsiFile import org.jetbrains.yaml.YAMLFileType private const val SKAFFOLD_TEMPLATE_ID = "SKAFFOLD" private const val SKAFFOLD_TEMPLATE_NAME = "Skaffold" /** * Defines the [TemplateContextType] for Skaffold files. */ class SkaffoldContextType( id: String = SKAFFOLD_TEMPLATE_ID, presentableName: String = SKAFFOLD_TEMPLATE_NAME ) : TemplateContextType(id, presentableName) { /** * A file is in context for Skaffold live templates if it is a yaml file. */ override fun isInContext(file: PsiFile, offset: Int): Boolean = file.fileType == YAMLFileType.YML }
apache-2.0
5a8a0809b77f3a72656452e1587315f4
32.825
77
0.741316
4.026786
false
false
false
false
kevinmost/koolbelt
extensions-android/src/main/java/com/kevinmost/koolbelt/extension/android/ContextUtil.kt
2
931
package com.kevinmost.koolbelt.extension.android import android.content.Context import android.support.annotation.PluralsRes fun Context.getPlural(@PluralsRes id: Int, quantity: Int, vararg args: Any = arrayOf(quantity)) : CharSequence { return resources.getQuantityString(id, quantity, *args) } inline fun Context.dimensions(block: DimensionsContext.() -> Unit) { DimensionsContext(this).apply(block) } class DimensionsContext(private val context: Context) { val Int.dp: Int get() = (this * density).toInt() val Int.sp: Int get() = (this * scaledDensity).toInt() val Int.px2Dp: Float get() = (this.toFloat() / density).toFloat() val Int.px2Sp: Float get() = (this.toFloat() / scaledDensity).toFloat() private val density: Float get() = context.resources.displayMetrics.density private val scaledDensity: Float get() = context.resources.displayMetrics.scaledDensity }
apache-2.0
27c91443da8eb0c3f163cc65c71c8d8d
24.162162
68
0.71536
3.92827
false
false
false
false
seventhroot/elysium
bukkit/rpk-travel-bukkit/src/main/kotlin/com/rpkit/travel/bukkit/command/SetWarpCommand.kt
1
1750
package com.rpkit.travel.bukkit.command import com.rpkit.travel.bukkit.RPKTravelBukkit import com.rpkit.travel.bukkit.warp.RPKWarpImpl import com.rpkit.warp.bukkit.warp.RPKWarpProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class SetWarpCommand(private val plugin: RPKTravelBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (!sender.hasPermission("rpkit.travel.command.setwarp")) { sender.sendMessage(plugin.messages["no-permission-set-warp"]) return true } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } if (!args.isNotEmpty()) { sender.sendMessage(plugin.messages["set-warp-usage"]) return true } val warpProvider = plugin.core.serviceManager.getServiceProvider(RPKWarpProvider::class) if (warpProvider.getWarp(args[0]) != null) { sender.sendMessage(plugin.messages["set-warp-invalid-name-already-in-use"]) return true } val warp = RPKWarpImpl(name = args[0], location = sender.location) warpProvider.addWarp(warp) sender.sendMessage(plugin.messages["set-warp-valid", mapOf( Pair("warp", warp.name), Pair("world", warp.location.world?.name ?: ""), Pair("x", warp.location.blockX.toString()), Pair("y", warp.location.blockY.toString()), Pair("z", warp.location.blockZ.toString()) )]) return true } }
apache-2.0
5742b5b0292ca4eaf0240c425bb4ae3d
39.697674
114
0.646286
4.137116
false
false
false
false
hazuki0x0/YuzuBrowser
browser/src/main/java/jp/hazuki/yuzubrowser/browser/view/GestureFrameLayout.kt
1
3002
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.browser.view import android.content.Context import android.gesture.GestureOverlayView import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.widget.FrameLayout import com.google.android.material.appbar.AppBarLayout import jp.hazuki.yuzubrowser.browser.R class GestureFrameLayout(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) { private var viewOffset = 0 private val gestureOverlay: CustomGestureOverlayView by bind(R.id.webGestureOverlayViewInner) fun setWebFrame(appBarLayout: AppBarLayout) { appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset -> viewOffset = verticalOffset + appBarLayout.totalScrollRange gestureOverlay.translationY = -viewOffset.toFloat() }) } override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { val event = MotionEvent.obtain(ev) val offsetX = scrollX - gestureOverlay.left val offsetY = scrollY - gestureOverlay.top + viewOffset event.offsetLocation(offsetX.toFloat(), offsetY.toFloat()) return gestureOverlay.preDispatchTouchEvent(event) or super.dispatchTouchEvent(ev) } fun setGestureVisible(visible: Boolean) { gestureOverlay.isGestureVisible = visible } fun removeAllOnGestureListeners() { gestureOverlay.removeAllOnGestureListeners() } fun removeAllOnGesturePerformedListeners() { gestureOverlay.removeAllOnGesturePerformedListeners() } fun addOnGestureListener(listener: GestureOverlayView.OnGestureListener?) { gestureOverlay.addOnGestureListener(listener) } fun addOnGesturePerformedListener(listener: GestureOverlayView.OnGesturePerformedListener?) { gestureOverlay.addOnGesturePerformedListener(listener) } override fun setOnTouchListener(l: View.OnTouchListener?) { gestureOverlay.setOnTouchListener(l) } override fun isEnabled(): Boolean { return gestureOverlay.isEnabled } override fun setEnabled(enabled: Boolean) { gestureOverlay.isEnabled = enabled super.setEnabled(enabled) } private fun <T : View> bind(idRes: Int): Lazy<T> { @Suppress("UNCHECKED_CAST") return lazy(LazyThreadSafetyMode.NONE) { findViewById<T>(idRes) } } }
apache-2.0
24d4bf933ba23da1e4c2efb207498529
34.738095
107
0.736509
4.810897
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/readitlater/ReadItLater.kt
1
2119
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.readitlater import android.content.ContentResolver import android.content.ContentValues import android.content.Context import android.widget.Toast import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.utils.extensions.browserApplicationContext import jp.hazuki.yuzubrowser.ui.provider.IReadItLaterProvider import jp.hazuki.yuzubrowser.webview.CustomWebView fun readItLater(context: Context, resolver: ContentResolver, url: String?, webView: CustomWebView) { val page = url ?: webView.url if (page.isNullOrEmpty()) { Toast.makeText(context, R.string.failed, Toast.LENGTH_SHORT).show() return } val provider = context.browserApplicationContext.providerManager.readItLaterProvider val uri = resolver.insert(provider.editUri, ContentValues().apply { put(IReadItLaterProvider.URL, page) put(IReadItLaterProvider.TITLE, webView.title ?: page) }) if (uri == null) { Toast.makeText(context, R.string.failed, Toast.LENGTH_SHORT).show() return } val cursor = resolver.query(uri, null, null, null, null) if (cursor != null) { cursor.moveToFirst() val path = cursor.getString(0) cursor.close() if (webView.saveWebArchiveMethod(path)) { Toast.makeText(context, context.getString(R.string.saved_file) + webView.title, Toast.LENGTH_SHORT).show() return } } resolver.delete(provider.convertToEdit(uri), null, null) }
apache-2.0
385c763fb5dfee229f714214e38d2444
38.259259
118
0.721095
4.059387
false
false
false
false
square/sqldelight
runtime/src/commonMain/kotlin/com/squareup/sqldelight/db/SqlDriver.kt
1
4314
/* * Copyright (C) 2018 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 com.squareup.sqldelight.db import com.squareup.sqldelight.Transacter /** * Maintains connections to an underlying SQL database and provides APIs for managing transactions * and executing SQL statements. */ interface SqlDriver : Closeable { /** * Execute a SQL statement and return a [SqlCursor] that iterates the result set. * * @param [identifier] An opaque, unique value that can be used to implement any driver-side * caching of prepared statements. If [identifier] is null, a fresh statement is required. * @param [sql] The SQL string to be executed. * @param [parameters] The number of bindable parameters [sql] contains. * @param [binders] A lambda which is called before execution to bind any parameters to the SQL * statement. */ fun executeQuery( identifier: Int?, sql: String, parameters: Int, binders: (SqlPreparedStatement.() -> Unit)? = null ): SqlCursor /** * Execute a SQL statement. * * @param [identifier] An opaque, unique value that can be used to implement any driver-side * caching of prepared statements. If [identifier] is null, a fresh statement is required. * @param [sql] The SQL string to be executed. * @param [parameters] The number of bindable parameters [sql] contains. * @param [binders] A lambda which is called before execution to bind any parameters to the SQL * statement. */ fun execute( identifier: Int?, sql: String, parameters: Int, binders: (SqlPreparedStatement.() -> Unit)? = null ) /** * Start a new [Transacter.Transaction] on the database. * * It's up to the implementor how this method behaves for different connection/threading patterns. */ fun newTransaction(): Transacter.Transaction /** * The currently open [Transacter.Transaction] on the database. * * It's up to the implementor how this method behaves for different connection/threading patterns. */ fun currentTransaction(): Transacter.Transaction? /** * API for creating and migrating a SQL database. */ interface Schema { /** * The version of this schema. */ val version: Int /** * Use [driver] to create the schema from scratch. Assumes no existing database state. */ fun create(driver: SqlDriver) /** * Use [driver] to migrate from schema [oldVersion] to [newVersion]. */ fun migrate(driver: SqlDriver, oldVersion: Int, newVersion: Int) } } /** * Represents a block of code [block] that should be executed during a migration after the migration * has finished migrating to [afterVersion]. */ class AfterVersion( internal val afterVersion: Int, internal val block: () -> Unit ) /** * Run [SqlDriver.Schema.migrate] normally but execute [callbacks] during the migration whenever * the it finished upgrading to a version specified by [AfterVersion.afterVersion]. */ fun SqlDriver.Schema.migrateWithCallbacks( driver: SqlDriver, oldVersion: Int, newVersion: Int, vararg callbacks: AfterVersion ) { var lastVersion = oldVersion // For each callback within the [oldVersion..newVersion) range, alternate between migrating // the schema and invoking each callback. callbacks.filter { it.afterVersion in oldVersion until newVersion } .sortedBy { it.afterVersion } .forEach { callback -> migrate(driver, oldVersion = lastVersion, newVersion = callback.afterVersion + 1) callback.block() lastVersion = callback.afterVersion + 1 } // If there were no callbacks, or the newVersion is higher than the highest callback, // complete the migration. if (lastVersion < newVersion) { migrate(driver, lastVersion, newVersion) } }
apache-2.0
5ca04e612052877b5df664a6f705a1be
32.184615
100
0.704219
4.415558
false
false
false
false
ucpdh23/Servant
src/main/kotlin/es/xan/servantv3/network/NetworkVerticle.kt
1
4013
package es.xan.servantv3.network import es.xan.servantv3.AbstractServantVerticle import es.xan.servantv3.Constant import es.xan.servantv3.Action import es.xan.servantv3.messages.UpdateState import es.xan.servantv3.messages.Configure import io.vertx.core.eventbus.Message import es.xan.servantv3.SSHUtils import es.xan.servantv3.MessageBuilder import io.vertx.core.logging.LoggerFactory import es.xan.servantv3.messages.Device import es.xan.servantv3.messages.DeviceStatus import java.util.Date import java.util.concurrent.TimeUnit import es.xan.servantv3.Events import es.xan.servantv3.MessageBuilder.ReplyBuilder import es.xan.servantv3.JsonUtils /** * Home network manager. Store information about the devices connected to the network, * creating events when devices come in or out. * According to the changes in the devices' status, this Verticle publishes two events: Events.REM_NETWORK_DEVICES_MESSAGE and Events.REW_NETWORK_DEVICES_MESSAGE. * Devices status info must be provided by external sensors through the REST API defined into the controller DevicesController. */ class NetworkVerticle : AbstractServantVerticle(Constant.NETWORK_VERTICLE) { companion object { val LOG = LoggerFactory.getLogger(NetworkVerticle::class.java.name) val TTL = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES); } init { supportedActions(Actions::class.java) } override fun start() { super.start(); vertx.setPeriodic(300000, { id -> publishAction(Actions.CHECK_STATUS); }); } // *********** Verticle state info var storedStatus: MutableMap<String, Device> = HashMap(); // *********** Supported actions enum class Actions(val clazz : Class<*>? ) : Action { /** * Updates the status of the passing device */ UPDATE_DEVICE_STATUS(Device::class.java), /** * Checks the current status the all the available devices */ CHECK_STATUS(null), /** * Returns a list with the current devices status */ LIST(null); } fun update_device_status(input: Device) { if (input.status == DeviceStatus.DOWN) input.status = DeviceStatus.QUARANTINE; val stored = storedStatus.getOrPut(input.mac) {Device(input.user, input.mac, DeviceStatus.NEW, 0)} updateStatus(stored, input.timestamp, input.status) } fun check_status() { LOG.debug("check network status"); val currTimeStamp = Date().getTime() storedStatus .filterValues { dev -> dev.status == DeviceStatus.QUARANTINE && dev.timestamp < currTimeStamp - TTL} .forEach { _, dev -> updateStatus(dev, currTimeStamp, DeviceStatus.DOWN)}; } fun list(message: Message<Any>) { val devices = storedStatus.values.map{device -> JsonUtils.toJson(device)}; val builder = MessageBuilder.createReply().apply { setResult(devices); setOk() } message.reply(builder.build()); } // ********* Private methos private fun updateStatus(dev : Device, timestamp : Long, status : DeviceStatus) { if (dev.status == status) return; val step = DeviceWorkflow.resolve(dev.status, status); if (step == null) return; dev.timestamp = timestamp; dev.status = status; if (step.event != null) { LOG.debug("publishing event [{}] for device [{}]", step.event, dev.mac) publishEvent(step.event, dev); } } public enum class DeviceWorkflow(val from: DeviceStatus, val to: DeviceStatus, val event: Events? = null) { NEW_UP(DeviceStatus.NEW, DeviceStatus.UP, Events.NEW_NETWORK_DEVICES_MESSAGE), NEW_QUARANTINE(DeviceStatus.NEW, DeviceStatus.QUARANTINE), UP_QUARANTINE(DeviceStatus.UP, DeviceStatus.QUARANTINE), QUARANTINE_UP(DeviceStatus.QUARANTINE, DeviceStatus.UP), QUARANTINE_DOWN(DeviceStatus.QUARANTINE, DeviceStatus.DOWN, Events.REM_NETWORK_DEVICES_MESSAGE), DOWN_UP(DeviceStatus.DOWN, DeviceStatus.UP, Events.NEW_NETWORK_DEVICES_MESSAGE); companion object { fun resolve(curr: DeviceStatus, new: DeviceStatus) = DeviceWorkflow.values().firstOrNull { it.from == curr && it.to == new }; } } }
mit
e86c72adea993b825ead651a99ab349c
28.955224
162
0.723399
3.444635
false
false
false
false