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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JordyLangen/vaultbox | app/src/main/java/com/jlangen/vaultbox/vaults/VaultRepository.kt | 1 | 1118 | package com.jlangen.vaultbox.vaults
import android.os.Environment
import com.jlangen.vaultbox.vaults.Vault
import io.reactivex.Observable
import java.io.File
class VaultRepository {
companion object {
const val KEEPASS_DATABASE_EXTENSION = ".kdbx"
}
private fun search(directory: File, extension: String): List<Vault> {
val databaseFiles = mutableListOf<Vault>()
val files = directory.listFiles()
if (files == null || files.isEmpty()) {
return databaseFiles
}
for (entry in files) {
if (entry.isDirectory) {
databaseFiles.addAll(search(entry, extension))
}
if (entry.isFile && entry.path.endsWith(extension)) {
databaseFiles.add(Vault(entry.name, entry.absolutePath))
}
}
return databaseFiles
}
fun findAll(): Observable<List<Vault>> {
return Observable.fromCallable {
val externalStorage = Environment.getExternalStorageDirectory()
search(externalStorage, KEEPASS_DATABASE_EXTENSION)
}
}
} | apache-2.0 | e872218bf62880cc80592e70d6cb852d | 26.975 | 75 | 0.62254 | 4.757447 | false | false | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/database/NotesTransactions.kt | 1 | 2076 | package me.aberrantfox.hotbot.database
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import org.joda.time.DateTime
data class NoteRecord(val id: Int,
val moderator: String,
val member: String,
val note: String,
val dateTime: DateTime)
fun insertNote(member: String, moderator: String, note: String) =
transaction {
Notes.insert {
it[Notes.member] = member
it[Notes.moderator] = moderator
it[Notes.note] = note
it[Notes.date] = DateTime.now()
}
}
fun replaceNote(id: Int, note: String, moderator: String) =
transaction {
Notes.update({Notes.id eq id}) {
it[Notes.moderator] = moderator
it[Notes.note] = note
it[Notes.date] = DateTime.now()
}
}
fun getNotesByUser(userId: String) =
transaction {
val notes = mutableListOf<NoteRecord>()
val selectedNotes = Notes.select {
Notes.member eq userId
}
selectedNotes.forEach {
notes.add(NoteRecord(it[Notes.id],
it[Notes.moderator],
it[Notes.member],
it[Notes.note],
it[Notes.date]))
}
notes
}
fun removeNoteById(noteId: Int) =
transaction {
val numberDeleted = Notes.deleteWhere {
Notes.id eq noteId
}
numberDeleted
}
fun removeAllNotesByUser(userId: String) =
transaction {
val numberDeleted = Notes.deleteWhere {
Notes.member eq userId
}
numberDeleted
} | mit | 4d4e74aacda602df3e21254d4638de5f | 27.847222 | 65 | 0.535645 | 4.839161 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/player/profile/ProfileViewController.kt | 1 | 13682 | package io.ipoli.android.player.profile
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.annotation.ColorInt
import android.support.design.widget.TabLayout
import android.support.v4.graphics.drawable.DrawableCompat
import android.view.*
import android.widget.ProgressBar
import android.widget.TextView
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import io.ipoli.android.R
import io.ipoli.android.common.ViewUtils
import io.ipoli.android.common.redux.android.ReduxViewController
import io.ipoli.android.common.text.LongFormatter
import io.ipoli.android.common.view.*
import io.ipoli.android.player.data.AndroidAttribute
import io.ipoli.android.player.data.AndroidAvatar
import io.ipoli.android.player.data.AndroidRank
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.profile.ProfileViewState.StateType.LOADING
import io.ipoli.android.player.profile.ProfileViewState.StateType.PROFILE_DATA_LOADED
import kotlinx.android.synthetic.main.controller_profile.view.*
import kotlinx.android.synthetic.main.profile_charisma_attribute.view.*
import kotlinx.android.synthetic.main.profile_expertise_attribute.view.*
import kotlinx.android.synthetic.main.profile_intelligence_attribute.view.*
import kotlinx.android.synthetic.main.profile_strength_attribute.view.*
import kotlinx.android.synthetic.main.profile_wellbeing_attribute.view.*
import kotlinx.android.synthetic.main.profile_willpower_attribute.view.*
import kotlinx.android.synthetic.main.view_loader.view.*
class ProfileViewController(args: Bundle? = null) :
ReduxViewController<ProfileAction, ProfileViewState, ProfileReducer>(args) {
override val reducer = ProfileReducer(ProfileReducer.PROFILE_KEY)
override var helpConfig: HelpConfig? =
HelpConfig(
io.ipoli.android.R.string.help_dialog_profile_title,
io.ipoli.android.R.string.help_dialog_profile_message
)
private var isEdit: Boolean = false
private val tabListener = object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
}
override fun onTabSelected(tab: TabLayout.Tab) {
showPageAtPosition(view, tab.position)
}
}
private fun showPageAtPosition(view: View?, position: Int) {
view?.let {
val childRouter = getChildRouter(it.profileTabContainer)
childRouter.setRoot(RouterTransaction.with(getViewControllerForPage(position)))
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
setHasOptionsMenu(true)
val view = container.inflate(io.ipoli.android.R.layout.controller_profile)
setToolbar(view.toolbar)
val collapsingToolbar = view.collapsingToolbarContainer
collapsingToolbar.isTitleEnabled = false
view.toolbar.title = stringRes(io.ipoli.android.R.string.controller_profile_title)
view.toolbar.setBackgroundColor(attrData(R.attr.colorPrimary))
var coloredBackground = view.coloredBackground.background.mutate()
coloredBackground = DrawableCompat.wrap(coloredBackground)
DrawableCompat.setTint(coloredBackground, attrData(R.attr.colorPrimary))
DrawableCompat.setTintMode(coloredBackground, PorterDuff.Mode.SRC_IN)
val avatarBackground = view.playerAvatar.background as GradientDrawable
avatarBackground.setColor(attrData(android.R.attr.colorBackground))
view.post {
view.requestFocus()
}
return view
}
override fun onAttach(view: View) {
super.onAttach(view)
showBackButton()
view.tabLayout.addOnTabSelectedListener(tabListener)
view.tabLayout.getTabAt(0)!!.select()
showPageAtPosition(view, 0)
}
override fun onDetach(view: View) {
view.tabLayout.removeOnTabSelectedListener(tabListener)
resetDecorView()
super.onDetach(view)
}
private fun resetDecorView() {
activity?.let {
it.window.decorView.systemUiVisibility = 0
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(io.ipoli.android.R.menu.profile_menu, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
val editAction = menu.findItem(io.ipoli.android.R.id.actionEdit)
editAction.isVisible = !isEdit
super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home ->
return router.handleBack()
io.ipoli.android.R.id.actionEdit ->
navigate().toEditProfile()
}
return super.onOptionsItemSelected(item)
}
override fun onCreateLoadAction() = ProfileAction.Load(null)
override fun render(state: ProfileViewState, view: View) {
when (state.type) {
LOADING -> {
view.profileContainer.gone()
view.loader.visible()
}
PROFILE_DATA_LOADED -> {
isEdit = false
activity!!.invalidateOptionsMenu()
view.loader.gone()
view.profileContainer.visible()
renderInfo(state, view)
renderAvatar(state, view)
renderMembershipStatus(state, view)
renderAttributes(state, view)
renderLevelProgress(state, view)
renderHealth(state, view)
renderCoinsAndGems(state, view)
renderRank(state, view)
}
else -> {
}
}
}
private fun renderRank(state: ProfileViewState, view: View) {
view.rank.text = state.rankText
view.nextRank.text = state.nextRankText
}
private fun renderAttributes(state: ProfileViewState, view: View) {
view.moreAttributes.onDebounceClick {
navigateFromRoot().toAttributes()
}
val vms = state.attributeViewModels
renderAttribute(
vms[Player.AttributeType.STRENGTH]!!,
view.strengthProgress,
view.strengthLevel,
view.strengthProgressText,
view.strengthContainer
)
renderAttribute(
vms[Player.AttributeType.INTELLIGENCE]!!,
view.intelligenceProgress,
view.intelligenceLevel,
view.intelligenceProgressText,
view.intelligenceContainer
)
renderAttribute(
vms[Player.AttributeType.CHARISMA]!!,
view.charismaProgress,
view.charismaLevel,
view.charismaProgressText,
view.charismaContainer
)
renderAttribute(
vms[Player.AttributeType.EXPERTISE]!!,
view.expertiseProgress,
view.expertiseLevel,
view.expertiseProgressText,
view.expertiseContainer
)
renderAttribute(
vms[Player.AttributeType.WELL_BEING]!!,
view.wellbeingProgress,
view.wellbeingLevel,
view.wellbeingProgressText,
view.wellbeingContainer
)
renderAttribute(
vms[Player.AttributeType.WILLPOWER]!!,
view.willpowerProgress,
view.willpowerLevel,
view.willpowerProgressText,
view.willpowerContainer
)
}
private fun renderAttribute(
attribute: AttributeViewModel,
progressView: ProgressBar,
levelView: TextView,
levelProgressView: TextView,
container: View
) {
progressView.progress = attribute.progress
progressView.max = attribute.max
progressView.progressTintList =
ColorStateList.valueOf(attribute.progressColor)
progressView.secondaryProgressTintList =
ColorStateList.valueOf(attribute.secondaryColor)
container.onDebounceClick {
navigateFromRoot().toAttributes(attribute.type)
}
levelView.text = attribute.level
levelProgressView.text = attribute.progressText
}
private fun renderMembershipStatus(state: ProfileViewState, view: View) {
if (state.isMember!!) {
view.membershipStatus.visible()
view.membershipStatusIcon.visible()
val background = view.membershipStatus.background as GradientDrawable
background.setStroke(
ViewUtils.dpToPx(2f, view.context).toInt(),
attrData(io.ipoli.android.R.attr.colorPrimary)
)
} else {
view.membershipStatus.gone()
view.membershipStatusIcon.gone()
}
}
private fun renderCoinsAndGems(state: ProfileViewState, view: View) {
view.coins.text = state.lifeCoinsText
view.gems.text = state.gemsText
}
private fun renderInfo(state: ProfileViewState, view: View) {
view.profileDisplayName.text = state.displayNameText
if (state.username.isNullOrBlank()) {
view.username.gone()
} else {
view.username.visible()
@SuppressLint("SetTextI18n")
view.username.text = "@${state.username}"
}
}
private fun renderAvatar(state: ProfileViewState, view: View) {
Glide.with(view.context).load(state.avatarImage)
.apply(RequestOptions.circleCropTransform())
.into(view.playerAvatar)
val background = view.playerAvatar.background as GradientDrawable
background.setColor(colorRes(AndroidAvatar.valueOf(state.avatar.name).backgroundColor))
view.playerAvatar.onDebounceClick {
navigateFromRoot().toAvatarStore(HorizontalChangeHandler())
}
}
private fun renderHealth(state: ProfileViewState, view: View) {
view.healthProgress.max = state.maxHealth
view.healthProgress.animateProgressFromZero(state.health)
view.healthProgressText.text = state.healthProgressText
}
private fun renderLevelProgress(state: ProfileViewState, view: View) {
view.levelProgress.max = state.levelXpMaxProgress
view.levelProgress.animateProgressFromZero(state.levelXpProgress)
view.level.text = state.levelText
view.levelProgressText.text = state.levelProgressText
}
private val ProfileViewState.avatarImage
get() = AndroidAvatar.valueOf(avatar.name).image
private val ProfileViewState.displayNameText
get() = if (displayName.isNullOrBlank())
stringRes(io.ipoli.android.R.string.unknown_hero)
else
displayName
private val ProfileViewState.levelText
get() = "$level"
private val ProfileViewState.levelProgressText
get() = "$levelXpProgress / $levelXpMaxProgress"
private val ProfileViewState.healthProgressText
get() = "$health / $maxHealth"
private val ProfileViewState.gemsText
get() = LongFormatter.format(activity!!, gems.toLong())
private val ProfileViewState.lifeCoinsText
get() = LongFormatter.format(activity!!, coins.toLong())
private val ProfileViewState.rankText
get() = stringRes(AndroidRank.valueOf(rank!!.name).title)
private val ProfileViewState.nextRankText
get() = stringRes(
R.string.next_rank,
stringRes(AndroidRank.valueOf(nextRank!!.name).title)
)
private fun getViewControllerForPage(position: Int): Controller {
return when (position) {
0 -> ProfileInfoViewController(reducer.stateKey)
1 -> ProfilePostListViewController(reducer.stateKey, null)
2 -> ProfilePlayerListViewController(
reducerKey = reducer.stateKey,
showFollowers = false
)
3 -> ProfilePlayerListViewController(
reducerKey = reducer.stateKey,
showFollowers = true
)
4 -> ProfileChallengeListViewController(reducer.stateKey, null)
else -> throw IllegalArgumentException("Unknown controller position $position")
}
}
data class AttributeViewModel(
val type: Player.AttributeType,
val level: String,
val progress: Int,
val max: Int,
val progressText: String,
@ColorInt val secondaryColor: Int,
@ColorInt val progressColor: Int
)
private val ProfileViewState.attributeViewModels: Map<Player.AttributeType, AttributeViewModel>
get() = attributes!!.map {
val attr = AndroidAttribute.valueOf(it.type.name)
it.type to AttributeViewModel(
type = it.type,
level = "Lvl ${it.level}",
progress = ((it.progressForLevel * 100f) / it.progressForNextLevel).toInt(),
max = 100,
progressText = "${it.progressForLevel}/${it.progressForNextLevel}",
secondaryColor = colorRes(attr.colorPrimary),
progressColor = colorRes(attr.colorPrimaryDark)
)
}.toMap()
} | gpl-3.0 | a21802ce4b17a7a9f65f74d5317179de | 34.448187 | 99 | 0.661307 | 4.89517 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/RemoveSingleExpressionStringTemplateInspection.kt | 3 | 2715 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.inspections
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.*
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.createExpressionByPattern
class RemoveSingleExpressionStringTemplateInspection() :
AbstractKotlinApplicatorBasedInspection<KtStringTemplateExpression, RemoveSingleExpressionStringTemplateInspection.Input>(
KtStringTemplateExpression::class
) {
data class Input(val isString: Boolean) : KotlinApplicatorInput
override fun getApplicator(): KotlinApplicator<KtStringTemplateExpression, Input> = applicator {
familyAndActionName(KotlinBundle.lazyMessage("remove.single.expression.string.template"))
isApplicableByPsi { stringTemplateExpression: KtStringTemplateExpression ->
stringTemplateExpression.singleExpressionOrNull() != null
}
applyTo { stringTemplateExpression, input ->
// Note that we do not reuse the result of `stringTemplateExpression.singleExpressionOrNull()`
// from `getInputProvider()` method because PsiElement may become invalidated between read actions
// e.g., it may be reparsed and recreated and old reference will become stale and invalid.
val expression = stringTemplateExpression.singleExpressionOrNull() ?: return@applyTo
val newElement = if (input.isString) {
expression
} else {
KtPsiFactory(stringTemplateExpression).createExpressionByPattern(
pattern = "$0.$1()", expression, "toString"
)
}
stringTemplateExpression.replace(newElement)
}
}
override fun getApplicabilityRange(): KotlinApplicabilityRange<KtStringTemplateExpression> = ApplicabilityRanges.SELF
override fun getInputProvider(): KotlinApplicatorInputProvider<KtStringTemplateExpression, Input> =
inputProvider { stringTemplateExpression: KtStringTemplateExpression ->
val expression = stringTemplateExpression.singleExpressionOrNull() ?: return@inputProvider null
Input(expression.getKtType()?.isString == true)
}
private fun KtStringTemplateExpression.singleExpressionOrNull() = children.singleOrNull()?.children?.firstOrNull() as? KtExpression
} | apache-2.0 | 97ad2a93c17d7702c1bfa872a4a15652 | 54.428571 | 135 | 0.747698 | 5.993377 | false | false | false | false |
brianwernick/PlaylistCore | library/src/main/kotlin/com/devbrackets/android/playlistcore/components/playlisthandler/DefaultPlaylistHandler.kt | 1 | 18096 | package com.devbrackets.android.playlistcore.components.playlisthandler
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import com.devbrackets.android.playlistcore.R
import com.devbrackets.android.playlistcore.api.MediaPlayerApi
import com.devbrackets.android.playlistcore.api.PlaylistItem
import com.devbrackets.android.playlistcore.components.audiofocus.AudioFocusProvider
import com.devbrackets.android.playlistcore.components.audiofocus.DefaultAudioFocusProvider
import com.devbrackets.android.playlistcore.components.image.ImageProvider
import com.devbrackets.android.playlistcore.components.mediacontrols.DefaultMediaControlsProvider
import com.devbrackets.android.playlistcore.components.mediacontrols.MediaControlsProvider
import com.devbrackets.android.playlistcore.components.mediasession.DefaultMediaSessionProvider
import com.devbrackets.android.playlistcore.components.mediasession.MediaSessionProvider
import com.devbrackets.android.playlistcore.components.notification.DefaultPlaylistNotificationProvider
import com.devbrackets.android.playlistcore.components.notification.PlaylistNotificationProvider
import com.devbrackets.android.playlistcore.data.MediaInfo
import com.devbrackets.android.playlistcore.data.MediaProgress
import com.devbrackets.android.playlistcore.data.PlaybackState
import com.devbrackets.android.playlistcore.data.PlaylistItemChange
import com.devbrackets.android.playlistcore.listener.MediaStatusListener
import com.devbrackets.android.playlistcore.listener.ProgressListener
import com.devbrackets.android.playlistcore.listener.ServiceCallbacks
import com.devbrackets.android.playlistcore.manager.BasePlaylistManager
import com.devbrackets.android.playlistcore.util.MediaProgressPoll
import com.devbrackets.android.playlistcore.util.SafeWifiLock
@Suppress("MemberVisibilityCanBePrivate")
open class DefaultPlaylistHandler<I : PlaylistItem, out M : BasePlaylistManager<I>> protected constructor(
protected val context: Context,
protected val serviceClass: Class<out Service>,
protected val playlistManager: M,
protected val imageProvider: ImageProvider<I>,
protected val notificationProvider: PlaylistNotificationProvider,
protected val mediaSessionProvider: MediaSessionProvider,
protected val mediaControlsProvider: MediaControlsProvider,
protected val audioFocusProvider: AudioFocusProvider<I>,
var listener: Listener<I>?
) : PlaylistHandler<I>(playlistManager.mediaPlayers), ProgressListener, MediaStatusListener<I> {
companion object {
const val TAG = "DefaultPlaylistHandler"
}
interface Listener<I : PlaylistItem> {
fun onMediaPlayerChanged(oldPlayer: MediaPlayerApi<I>?, newPlayer: MediaPlayerApi<I>?)
fun onItemSkipped(item: I)
}
protected val mediaInfo = MediaInfo()
protected val wifiLock = SafeWifiLock(context)
protected var mediaProgressPoll = MediaProgressPoll<I>()
protected val notificationManager: NotificationManager by lazy {
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
protected lateinit var serviceCallbacks: ServiceCallbacks
/**
* Retrieves the ID to use for the notification and registering this
* service as Foreground when media is playing
*/
protected open val notificationId: Int
get() = R.id.playlistcore_default_notification_id
/**
* Determines if media is currently playing
*/
protected open val isPlaying: Boolean
get() = currentMediaPlayer?.isPlaying ?: false
protected open val isLoading: Boolean
get() {
return currentPlaybackState == PlaybackState.RETRIEVING ||
currentPlaybackState == PlaybackState.PREPARING ||
currentPlaybackState == PlaybackState.SEEKING
}
var currentPlaylistItem: I? = null
protected var pausedForSeek = false
protected var playingBeforeSeek = false
protected var startPaused = false
protected var seekToPosition: Long = -1
protected var sequentialErrors: Int = 0
init {
audioFocusProvider.setPlaylistHandler(this)
}
override fun setup(serviceCallbacks: ServiceCallbacks) {
this.serviceCallbacks = serviceCallbacks
mediaProgressPoll.progressListener = this
playlistManager.playlistHandler = this
}
override fun tearDown() {
setPlaybackState(PlaybackState.STOPPED)
relaxResources()
playlistManager.playlistHandler = null
mediaInfo.clear()
}
override fun play() {
if (!isPlaying) {
currentMediaPlayer?.play()
}
mediaProgressPoll.start()
setPlaybackState(PlaybackState.PLAYING)
setupForeground()
audioFocusProvider.requestFocus()
}
override fun pause(transient: Boolean) {
if (isPlaying) {
currentMediaPlayer?.pause()
}
mediaProgressPoll.stop()
setPlaybackState(PlaybackState.PAUSED)
serviceCallbacks.endForeground(false)
if (!transient) {
audioFocusProvider.abandonFocus()
}
}
override fun togglePlayPause() {
if (isPlaying) {
pause(false)
} else {
play()
}
}
override fun stop() {
currentMediaPlayer?.stop()
setPlaybackState(PlaybackState.STOPPED)
currentPlaylistItem?.let {
playlistManager.playbackStatusListener?.onItemPlaybackEnded(it)
}
// let go of all resources
relaxResources()
playlistManager.reset()
serviceCallbacks.stop()
}
override fun next() {
playlistManager.next()
startItemPlayback(0, !isPlaying)
}
override fun previous() {
playlistManager.previous()
startItemPlayback(0, !isPlaying)
}
override fun startSeek() {
if (isPlaying) {
pausedForSeek = true
pause(true)
}
}
override fun seek(positionMillis: Long) {
performSeek(positionMillis)
}
override fun onPrepared(mediaPlayer: MediaPlayerApi<I>) {
startMediaPlayer(mediaPlayer)
sequentialErrors = 0
}
override fun onBufferingUpdate(mediaPlayer: MediaPlayerApi<I>, percent: Int) {
// Makes sure to update listeners of buffer updates even when playback is paused
if (!mediaPlayer.isPlaying && currentMediaProgress.bufferPercent != percent) {
currentMediaProgress.update(mediaPlayer.currentPosition, percent, mediaPlayer.duration)
onProgressUpdated(currentMediaProgress)
}
}
override fun onSeekComplete(mediaPlayer: MediaPlayerApi<I>) {
if (pausedForSeek || playingBeforeSeek) {
play()
pausedForSeek = false
playingBeforeSeek = false
} else {
pause(false)
}
}
override fun onCompletion(mediaPlayer: MediaPlayerApi<I>) {
// Handles moving to the next playable item
next()
startPaused = false
}
override fun onError(mediaPlayer: MediaPlayerApi<I>): Boolean {
// Unless we've had 3 or more errors without an item successfully playing we will move to the next item
if (++sequentialErrors <= 3) {
next()
return false
}
setPlaybackState(PlaybackState.ERROR)
serviceCallbacks.endForeground(true)
wifiLock.release()
mediaProgressPoll.stop()
audioFocusProvider.abandonFocus()
return false
}
/**
* When the current media progress is updated we call through the
* [BasePlaylistManager] to inform any listeners of the change
*/
override fun onProgressUpdated(mediaProgress: MediaProgress): Boolean {
currentMediaProgress = mediaProgress
return playlistManager.onProgressUpdated(mediaProgress)
}
protected open fun setupForeground() {
val notification = notificationProvider.buildNotification(mediaInfo, mediaSessionProvider.get(), serviceClass)
serviceCallbacks.runAsForeground(notificationId, notification)
}
/**
* Performs the functionality to seek the current media item
* to the specified position. This should only be called directly
* when performing the initial setup of playback position. For
* normal seeking process use the [performSeekStarted] in
* conjunction with [performSeekEnded]
*
* @param position The position to seek to in milliseconds
* @param updatePlaybackState True if the playback state should be updated
*/
protected open fun performSeek(position: Long, updatePlaybackState: Boolean = true) {
playingBeforeSeek = isPlaying
currentMediaPlayer?.seekTo(position)
if (updatePlaybackState) {
setPlaybackState(PlaybackState.SEEKING)
}
}
protected open fun initializeMediaPlayer(mediaPlayer: MediaPlayerApi<I>) {
mediaPlayer.apply {
reset()
setMediaStatusListener(this@DefaultPlaylistHandler)
}
mediaProgressPoll.update(mediaPlayer)
mediaProgressPoll.reset()
}
protected open fun updateMediaInfo() {
// Generate the notification state
mediaInfo.mediaState.isPlaying = isPlaying
mediaInfo.mediaState.isLoading = isLoading
mediaInfo.mediaState.isNextEnabled = playlistManager.isNextAvailable
mediaInfo.mediaState.isPreviousEnabled = playlistManager.isPreviousAvailable
// Updates the notification information
mediaInfo.notificationId = notificationId
mediaInfo.playlistItem = currentPlaylistItem
mediaInfo.appIcon = imageProvider.notificationIconRes
mediaInfo.artwork = imageProvider.remoteViewArtwork
mediaInfo.largeNotificationIcon = imageProvider.largeNotificationImage
mediaInfo.playbackPositionMs = currentMediaPlayer?.currentPosition ?: PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN
mediaInfo.playbackDurationMs = currentMediaPlayer?.duration ?: -1
}
override fun updateMediaControls() {
if (currentPlaylistItem == null) {
return
}
updateMediaInfo()
mediaSessionProvider.update(mediaInfo)
mediaControlsProvider.update(mediaInfo, mediaSessionProvider.get())
// Updates the notification
val notification = notificationProvider.buildNotification(mediaInfo, mediaSessionProvider.get(), serviceClass)
notificationManager.notify(mediaInfo.notificationId, notification)
}
override fun refreshCurrentMediaPlayer() {
refreshCurrentMediaPlayer(currentMediaPlayer?.currentPosition ?: seekToPosition, !isPlaying)
}
protected open fun refreshCurrentMediaPlayer(seekPosition: Long, startPaused: Boolean) {
currentPlaylistItem.let {
seekToPosition = seekPosition
this.startPaused = startPaused
updateCurrentMediaPlayer(it)
if (!play(currentMediaPlayer, it)) {
next()
}
}
}
override fun onRemoteMediaPlayerConnectionChange(mediaPlayer: MediaPlayerApi<I>, state: MediaPlayerApi.RemoteConnectionState) {
// If the mediaPlayer that changed state is of lower priority than the current one we ignore the change
currentMediaPlayer?.let {
if (mediaPlayers.indexOf(it) < mediaPlayers.indexOf(mediaPlayer)) {
Log.d(TAG, "Ignoring remote connection state change for $mediaPlayer because it is of lower priority than the current MediaPlayer")
return
}
}
when (state) {
MediaPlayerApi.RemoteConnectionState.CONNECTING -> {
if (mediaPlayer != currentMediaPlayer) {
val resumePlayback = isPlaying
pause(true)
seekToPosition = currentMediaPlayer?.currentPosition ?: seekToPosition
startPaused = !resumePlayback
}
return
}
MediaPlayerApi.RemoteConnectionState.CONNECTED -> {
if (mediaPlayer != currentMediaPlayer) {
refreshCurrentMediaPlayer(currentMediaProgress.position, startPaused)
}
}
MediaPlayerApi.RemoteConnectionState.NOT_CONNECTED -> {
if (mediaPlayer == currentMediaPlayer) {
refreshCurrentMediaPlayer(currentMediaProgress.position, startPaused)
}
}
}
}
/**
* Releases resources used by the service for playback. This includes the "foreground service"
* status and notification, the wake locks, and the audioPlayer if requested
*/
protected open fun relaxResources() {
mediaProgressPoll.release()
currentMediaPlayer = null
audioFocusProvider.abandonFocus()
wifiLock.release()
serviceCallbacks.endForeground(true)
notificationManager.cancel(notificationId)
mediaSessionProvider.get().release()
}
override fun startItemPlayback(positionMillis: Long, startPaused: Boolean) {
this.seekToPosition = positionMillis
this.startPaused = startPaused
playlistManager.playbackStatusListener?.onItemPlaybackEnded(currentPlaylistItem)
currentPlaylistItem = getNextPlayableItem()
currentPlaylistItem.let {
updateCurrentMediaPlayer(it)
mediaItemChanged(it)
if (play(currentMediaPlayer, it)) {
return
}
}
// If the playback wasn't handled, attempt to seek to the next playable item, otherwise stop the service
if (playlistManager.isNextAvailable) {
next()
} else {
stop()
}
}
protected open fun updateCurrentMediaPlayer(item: I?) {
if (mediaPlayers.isEmpty()) {
Log.d(TAG, "No media players available, stopping service")
stop()
}
val newMediaPlayer = item?.let { getMediaPlayerForItem(it) }
if (newMediaPlayer != currentMediaPlayer) {
listener?.onMediaPlayerChanged(currentMediaPlayer, newMediaPlayer)
currentMediaPlayer?.stop()
}
currentMediaPlayer = newMediaPlayer
}
protected open fun getMediaPlayerForItem(item: I): MediaPlayerApi<I>? {
// We prioritize players higher in the list over the currentMediaPlayer
return mediaPlayers.firstOrNull { it.handlesItem(item) }
}
/**
* Starts the actual playback of the specified audio item.
*
* @return True if the item playback was correctly handled
*/
protected open fun play(mediaPlayer: MediaPlayerApi<I>?, item: I?): Boolean {
if (mediaPlayer == null || item == null) {
return false
}
initializeMediaPlayer(mediaPlayer)
audioFocusProvider.requestFocus()
mediaPlayer.playItem(item)
setupForeground()
setPlaybackState(PlaybackState.PREPARING)
wifiLock.update(!(currentPlaylistItem?.downloaded ?: true))
return true
}
/**
* Reconfigures the mediaPlayerApi according to audio focus settings and starts/restarts it. This
* method starts/restarts the mediaPlayerApi respecting the current audio focus state. So if
* we have focus, it will play normally; if we don't have focus, it will either leave the
* mediaPlayerApi paused or set it to a low volume, depending on what is allowed by the
* current focus settings.
*/
protected open fun startMediaPlayer(mediaPlayer: MediaPlayerApi<I>) {
// Seek to the correct position
val seekRequested = seekToPosition > 0
if (seekRequested) {
performSeek(seekToPosition, false)
seekToPosition = -1
}
// Start the playback only if requested, otherwise update the state to paused
mediaProgressPoll.start()
if (!mediaPlayer.isPlaying && !startPaused) {
pausedForSeek = seekRequested
play()
playlistManager.playbackStatusListener?.onMediaPlaybackStarted(currentPlaylistItem!!, mediaPlayer.currentPosition, mediaPlayer.duration)
} else {
setPlaybackState(PlaybackState.PAUSED)
}
audioFocusProvider.refreshFocus()
}
/**
* Iterates through the playList, starting with the current item, until we reach an item we can play.
* Normally this will be the current item, however if they don't have network then
* it will be the next downloaded item.
*/
protected open fun getNextPlayableItem(): I? {
var item = playlistManager.currentItem
while (item != null && getMediaPlayerForItem(item) == null) {
listener?.onItemSkipped(item)
item = playlistManager.next()
}
//If we are unable to get a next playable item, inform the listener we are at the end of the playlist
item ?: playlistManager.playbackStatusListener?.onPlaylistEnded()
return item
}
/**
* Called when the current media item has changed, this will update the notification and
* media control values.
*/
protected open fun mediaItemChanged(item: I?) {
// Validates that the currentPlaylistItem is for the currentItem
if (!playlistManager.isPlayingItem(item)) {
Log.d(TAG, "forcing currentPlaylistItem update")
currentPlaylistItem = playlistManager.currentItem
}
item?.let {
imageProvider.updateImages(it)
}
currentItemChange = PlaylistItemChange(item, playlistManager.isPreviousAvailable, playlistManager.isNextAvailable).apply {
playlistManager.onPlaylistItemChanged(currentItem, hasNext, hasPrevious)
}
}
/**
* Updates the current PlaybackState and informs any listening classes.
*
* @param state The new PlaybackState
*/
protected open fun setPlaybackState(state: PlaybackState) {
currentPlaybackState = state
playlistManager.onPlaybackStateChanged(state)
// Makes sure the Media Controls are up-to-date
if (state != PlaybackState.STOPPED && state != PlaybackState.ERROR) {
updateMediaControls()
}
}
open class Builder<I : PlaylistItem, out M : BasePlaylistManager<I>>(
protected val context: Context,
protected val serviceClass: Class<out Service>,
protected val playlistManager: M,
protected val imageProvider: ImageProvider<I>
) {
var notificationProvider: PlaylistNotificationProvider? = null
var mediaSessionProvider: MediaSessionProvider? = null
var mediaControlsProvider: MediaControlsProvider? = null
var audioFocusProvider: AudioFocusProvider<I>? = null
var listener: Listener<I>? = null
fun build(): DefaultPlaylistHandler<I, M> {
return DefaultPlaylistHandler(
context,
serviceClass,
playlistManager,
imageProvider,
notificationProvider ?: DefaultPlaylistNotificationProvider(context),
mediaSessionProvider ?: DefaultMediaSessionProvider(context, serviceClass),
mediaControlsProvider ?: DefaultMediaControlsProvider(context),
audioFocusProvider ?: DefaultAudioFocusProvider(context),
listener
)
}
}
} | apache-2.0 | 2feca7b230766d2448cc07519c1a4c2a | 32.389299 | 142 | 0.741877 | 4.985124 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAdvancedController.kt | 1 | 10916 | package eu.kanade.tachiyomi.ui.setting
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.provider.Settings
import androidx.core.net.toUri
import androidx.preference.PreferenceScreen
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.data.library.LibraryUpdateService.Target
import eu.kanade.tachiyomi.data.preference.PreferenceValues
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.PREF_DOH_ADGUARD
import eu.kanade.tachiyomi.network.PREF_DOH_CLOUDFLARE
import eu.kanade.tachiyomi.network.PREF_DOH_GOOGLE
import eu.kanade.tachiyomi.network.PREF_DOH_QUAD9
import eu.kanade.tachiyomi.ui.base.controller.openInBrowser
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.setting.database.ClearDatabaseController
import eu.kanade.tachiyomi.util.CrashLogUtil
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.withUIContext
import eu.kanade.tachiyomi.util.preference.bindTo
import eu.kanade.tachiyomi.util.preference.defaultValue
import eu.kanade.tachiyomi.util.preference.entriesRes
import eu.kanade.tachiyomi.util.preference.intListPreference
import eu.kanade.tachiyomi.util.preference.listPreference
import eu.kanade.tachiyomi.util.preference.onChange
import eu.kanade.tachiyomi.util.preference.onClick
import eu.kanade.tachiyomi.util.preference.preference
import eu.kanade.tachiyomi.util.preference.preferenceCategory
import eu.kanade.tachiyomi.util.preference.summaryRes
import eu.kanade.tachiyomi.util.preference.switchPreference
import eu.kanade.tachiyomi.util.preference.titleRes
import eu.kanade.tachiyomi.util.system.DeviceUtil
import eu.kanade.tachiyomi.util.system.isPackageInstalled
import eu.kanade.tachiyomi.util.system.powerManager
import eu.kanade.tachiyomi.util.system.toast
import rikka.sui.Sui
import uy.kohesive.injekt.injectLazy
import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys
class SettingsAdvancedController : SettingsController() {
private val network: NetworkHelper by injectLazy()
private val chapterCache: ChapterCache by injectLazy()
private val db: DatabaseHelper by injectLazy()
@SuppressLint("BatteryLife")
override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply {
titleRes = R.string.pref_category_advanced
if (BuildConfig.FLAVOR != "dev") {
switchPreference {
key = "acra.enable"
titleRes = R.string.pref_enable_acra
summaryRes = R.string.pref_acra_summary
defaultValue = true
}
}
preference {
key = "dump_crash_logs"
titleRes = R.string.pref_dump_crash_logs
summaryRes = R.string.pref_dump_crash_logs_summary
onClick {
CrashLogUtil(context).dumpLogs()
}
}
switchPreference {
key = Keys.verboseLogging
titleRes = R.string.pref_verbose_logging
summaryRes = R.string.pref_verbose_logging_summary
defaultValue = false
onChange {
activity?.toast(R.string.requires_app_restart)
true
}
}
preferenceCategory {
titleRes = R.string.label_background_activity
preference {
key = "pref_disable_battery_optimization"
titleRes = R.string.pref_disable_battery_optimization
summaryRes = R.string.pref_disable_battery_optimization_summary
onClick {
val packageName: String = context.packageName
if (!context.powerManager.isIgnoringBatteryOptimizations(packageName)) {
try {
val intent = Intent().apply {
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
data = "package:$packageName".toUri()
}
startActivity(intent)
} catch (e: ActivityNotFoundException) {
context.toast(R.string.battery_optimization_setting_activity_not_found)
}
} else {
context.toast(R.string.battery_optimization_disabled)
}
}
}
preference {
key = "pref_dont_kill_my_app"
title = "Don't kill my app!"
summaryRes = R.string.about_dont_kill_my_app
onClick {
openInBrowser("https://dontkillmyapp.com/")
}
}
}
preferenceCategory {
titleRes = R.string.label_data
preference {
key = CLEAR_CACHE_KEY
titleRes = R.string.pref_clear_chapter_cache
summary = context.getString(R.string.used_cache, chapterCache.readableSize)
onClick { clearChapterCache() }
}
switchPreference {
key = Keys.autoClearChapterCache
titleRes = R.string.pref_auto_clear_chapter_cache
defaultValue = false
}
preference {
key = "pref_clear_database"
titleRes = R.string.pref_clear_database
summaryRes = R.string.pref_clear_database_summary
onClick {
router.pushController(ClearDatabaseController().withFadeTransaction())
}
}
}
preferenceCategory {
titleRes = R.string.label_network
preference {
key = "pref_clear_cookies"
titleRes = R.string.pref_clear_cookies
onClick {
network.cookieManager.removeAll()
activity?.toast(R.string.cookies_cleared)
}
}
intListPreference {
key = Keys.dohProvider
titleRes = R.string.pref_dns_over_https
entries = arrayOf(
context.getString(R.string.disabled),
"Cloudflare",
"Google",
"AdGuard",
"Quad9",
)
entryValues = arrayOf(
"-1",
PREF_DOH_CLOUDFLARE.toString(),
PREF_DOH_GOOGLE.toString(),
PREF_DOH_ADGUARD.toString(),
PREF_DOH_QUAD9.toString(),
)
defaultValue = "-1"
summary = "%s"
onChange {
activity?.toast(R.string.requires_app_restart)
true
}
}
}
preferenceCategory {
titleRes = R.string.label_library
preference {
key = "pref_refresh_library_covers"
titleRes = R.string.pref_refresh_library_covers
onClick { LibraryUpdateService.start(context, target = Target.COVERS) }
}
preference {
key = "pref_refresh_library_tracking"
titleRes = R.string.pref_refresh_library_tracking
summaryRes = R.string.pref_refresh_library_tracking_summary
onClick { LibraryUpdateService.start(context, target = Target.TRACKING) }
}
}
preferenceCategory {
titleRes = R.string.label_extensions
listPreference {
bindTo(preferences.extensionInstaller())
titleRes = R.string.ext_installer_pref
summary = "%s"
// PackageInstaller doesn't work on MIUI properly for non-allowlisted apps
val values = if (DeviceUtil.isMiui) {
PreferenceValues.ExtensionInstaller.values()
.filter { it != PreferenceValues.ExtensionInstaller.PACKAGEINSTALLER }
} else {
PreferenceValues.ExtensionInstaller.values().toList()
}
entriesRes = values.map { it.titleResId }.toTypedArray()
entryValues = values.map { it.name }.toTypedArray()
onChange {
if (it == PreferenceValues.ExtensionInstaller.SHIZUKU.name &&
!(context.isPackageInstalled("moe.shizuku.privileged.api") || Sui.isSui())
) {
MaterialAlertDialogBuilder(context)
.setTitle(R.string.ext_installer_shizuku)
.setMessage(R.string.ext_installer_shizuku_unavailable_dialog)
.setPositiveButton(android.R.string.ok) { _, _ ->
openInBrowser("https://shizuku.rikka.app/download")
}
.setNegativeButton(android.R.string.cancel, null)
.show()
false
} else {
true
}
}
}
}
preferenceCategory {
titleRes = R.string.pref_category_display
listPreference {
bindTo(preferences.tabletUiMode())
titleRes = R.string.pref_tablet_ui_mode
summary = "%s"
entriesRes = PreferenceValues.TabletUiMode.values().map { it.titleResId }.toTypedArray()
entryValues = PreferenceValues.TabletUiMode.values().map { it.name }.toTypedArray()
onChange {
activity?.toast(R.string.requires_app_restart)
true
}
}
}
}
private fun clearChapterCache() {
if (activity == null) return
launchIO {
try {
val deletedFiles = chapterCache.clear()
withUIContext {
activity?.toast(resources?.getString(R.string.cache_deleted, deletedFiles))
findPreference(CLEAR_CACHE_KEY)?.summary =
resources?.getString(R.string.used_cache, chapterCache.readableSize)
}
} catch (e: Throwable) {
withUIContext { activity?.toast(R.string.cache_delete_error) }
}
}
}
}
private const val CLEAR_CACHE_KEY = "pref_clear_cache_key"
| apache-2.0 | dca1503f05aef4432d745f639a27dd2d | 37.572438 | 104 | 0.572554 | 5.072491 | false | false | false | false |
cfieber/orca | orca-kayenta/src/main/kotlin/com/netflix/spinnaker/orca/kayenta/model/Deployments.kt | 1 | 2767 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.kayenta.model
import com.netflix.spinnaker.moniker.Moniker
import com.netflix.spinnaker.orca.ext.mapTo
import com.netflix.spinnaker.orca.kayenta.pipeline.DeployCanaryClustersStage
import com.netflix.spinnaker.orca.kayenta.pipeline.KayentaCanaryStage
import com.netflix.spinnaker.orca.pipeline.model.Stage
import java.time.Duration
/**
* Defines the deployment context for canary control and experiment clusters.
*/
internal data class Deployments(
val baseline: Baseline,
val control: ClusterSpec,
val experiment: ClusterSpec,
val delayBeforeCleanup: Duration = Duration.ofHours(1)
)
/**
* Gets the set of regions from the canary cluster specs. Can be specified
* just as `region` or as `availabilityZones` which is a map of region to
* zones.
*/
internal val Deployments.regions: Set<String>
get() = if (experiment.availabilityZones.isNotEmpty()) {
experiment.availabilityZones.keys + control.availabilityZones.keys
} else {
setOf(experiment.region, control.region).filterNotNull().toSet()
}
/**
* The source cluster for the canary control.
*/
internal data class Baseline(
val cloudProvider: String?,
val application: String,
val account: String,
val cluster: String
)
/**
* The deployment context for a single cluster.
*/
internal data class ClusterSpec(
val cloudProvider: String,
val account: String,
val moniker: Moniker,
val availabilityZones: Map<String, Set<String>>,
val region: String?
)
/**
* Gets [Deployments] from the parent canary stage of this stage.
*/
internal val Stage.deployments: Deployments
get() = canaryStage.mapTo("/deployments")
/**
* Gets the parent canary stage of this stage. Throws an exception if it's
* missing or the wrong type.
*/
internal val Stage.canaryStage: Stage
get() = parent?.apply {
if (type != KayentaCanaryStage.STAGE_TYPE) {
throw IllegalStateException("${DeployCanaryClustersStage.STAGE_TYPE} should be the child of a ${KayentaCanaryStage.STAGE_TYPE} stage")
}
}
?: throw IllegalStateException("${DeployCanaryClustersStage.STAGE_TYPE} should be the child of a ${KayentaCanaryStage.STAGE_TYPE} stage")
| apache-2.0 | f1b9358e779cf7f09443a2f15d007ac9 | 31.552941 | 141 | 0.749548 | 4.051245 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MemberVisibilityCanBePrivateInspection.kt | 1 | 8118 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.ex.EntryPointsManager
import com.intellij.codeInspection.ex.EntryPointsManagerBase
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.Processor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.descriptors.EffectiveVisibility
import org.jetbrains.kotlin.descriptors.effectiveVisibility
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.canBePrivate
import org.jetbrains.kotlin.idea.core.isInheritable
import org.jetbrains.kotlin.idea.core.isOverridable
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.quickfix.AddModifierFixFE10
import org.jetbrains.kotlin.idea.refactoring.isConstructorDeclaredProperty
import org.jetbrains.kotlin.idea.search.isCheapEnoughToSearchConsideringOperators
import org.jetbrains.kotlin.idea.search.usagesSearch.dataClassComponentFunction
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.util.hasNonSuppressAnnotation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
class MemberVisibilityCanBePrivateInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitProperty(property: KtProperty) {
super.visitProperty(property)
if (!property.isLocal && canBePrivate(property)) {
registerProblem(holder, property)
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (canBePrivate(function)) {
registerProblem(holder, function)
}
}
override fun visitParameter(parameter: KtParameter) {
super.visitParameter(parameter)
if (parameter.isConstructorDeclaredProperty() && canBePrivate(parameter)) {
registerProblem(holder, parameter)
}
}
}
}
private fun canBePrivate(declaration: KtNamedDeclaration): Boolean {
if (declaration.hasModifier(KtTokens.PRIVATE_KEYWORD) || declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
if (declaration.hasNonSuppressAnnotation) return false
val classOrObject = declaration.containingClassOrObject ?: return false
val inheritable = classOrObject is KtClass && classOrObject.isInheritable()
if (!inheritable && declaration.hasModifier(KtTokens.PROTECTED_KEYWORD)) return false //reported by ProtectedInFinalInspection
if (declaration.isOverridable()) return false
val descriptor = (declaration.toDescriptor() as? DeclarationDescriptorWithVisibility) ?: return false
when (descriptor.effectiveVisibility()) {
EffectiveVisibility.PrivateInClass, EffectiveVisibility.PrivateInFile, EffectiveVisibility.Local -> return false
else -> {}
}
val entryPointsManager = EntryPointsManager.getInstance(declaration.project) as EntryPointsManagerBase
if (UnusedSymbolInspection.checkAnnotatedUsingPatterns(
declaration,
with(entryPointsManager) {
additionalAnnotations + ADDITIONAL_ANNOTATIONS
}
)
) return false
if (!declaration.canBePrivate()) return false
// properties can be referred by component1/component2, which is too expensive to search, don't analyze them
if (declaration is KtParameter && declaration.dataClassComponentFunction() != null) return false
val psiSearchHelper = PsiSearchHelper.getInstance(declaration.project)
val useScope = declaration.useScope
val name = declaration.name ?: return false
val restrictedScope = if (useScope is GlobalSearchScope) {
when (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(name, useScope, null, null)) {
PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES -> return false
PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES -> return false
PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES -> KotlinSourceFilterScope.projectSources(useScope, declaration.project)
}
} else useScope
var otherUsageFound = false
var inClassUsageFound = false
ReferencesSearch.search(declaration, restrictedScope).forEach(Processor {
val usage = it.element
if (usage.isOutside(classOrObject)) {
otherUsageFound = true
return@Processor false
}
val classOrObjectDescriptor = classOrObject.descriptor as? ClassDescriptor
if (classOrObjectDescriptor != null) {
val receiverType = (usage as? KtElement)?.resolveToCall()?.dispatchReceiver?.type
val receiverDescriptor = receiverType?.constructor?.declarationDescriptor
if (receiverDescriptor != null && receiverDescriptor != classOrObjectDescriptor) {
otherUsageFound = true
return@Processor false
}
}
val function = usage.getParentOfTypesAndPredicate<KtDeclarationWithBody>(
true, KtNamedFunction::class.java, KtPropertyAccessor::class.java
) { true }
val insideInlineFun = function.insideInline() || (function as? KtPropertyAccessor)?.property.insideInline()
if (insideInlineFun) {
otherUsageFound = true
false
} else {
inClassUsageFound = true
true
}
})
return inClassUsageFound && !otherUsageFound
}
private fun PsiElement.isOutside(classOrObject: KtClassOrObject): Boolean {
if (classOrObject != getParentOfType<KtClassOrObject>(false)) return true
val annotationEntry = getStrictParentOfType<KtAnnotationEntry>() ?: return false
return classOrObject.annotationEntries.any { it == annotationEntry }
}
private fun KtModifierListOwner?.insideInline() = this?.let { it.hasModifier(KtTokens.INLINE_KEYWORD) && !it.isPrivate() } ?: false
private fun registerProblem(holder: ProblemsHolder, declaration: KtDeclaration) {
val modifierListOwner = declaration.getParentOfType<KtModifierListOwner>(false) ?: return
val member = when (declaration) {
is KtNamedFunction -> KotlinBundle.message("text.Function")
else -> KotlinBundle.message("text.Property")
}
val nameElement = (declaration as? PsiNameIdentifierOwner)?.nameIdentifier ?: return
holder.registerProblem(
declaration.visibilityModifier() ?: nameElement,
KotlinBundle.message("0.1.could.be.private", member, declaration.getName().toString()),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(AddModifierFixFE10(modifierListOwner, KtTokens.PRIVATE_KEYWORD))
)
}
}
| apache-2.0 | fd16f99e5c5130e7d5c33dc18aa92c22 | 49.111111 | 137 | 0.709411 | 5.704849 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SelfLinkedEntityImpl.kt | 2 | 7761 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.referrersx
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SelfLinkedEntityImpl: SelfLinkedEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SelfLinkedEntity::class.java, SelfLinkedEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: SelfLinkedEntity?
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SelfLinkedEntityData?): ModifiableWorkspaceEntityBase<SelfLinkedEntity>(), SelfLinkedEntity.Builder {
constructor(): this(SelfLinkedEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SelfLinkedEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field SelfLinkedEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentEntity: SelfLinkedEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SelfLinkedEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SelfLinkedEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): SelfLinkedEntityData = result ?: super.getEntityData() as SelfLinkedEntityData
override fun getEntityClass(): Class<SelfLinkedEntity> = SelfLinkedEntity::class.java
}
}
class SelfLinkedEntityData : WorkspaceEntityData<SelfLinkedEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SelfLinkedEntity> {
val modifiable = SelfLinkedEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SelfLinkedEntity {
val entity = SelfLinkedEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SelfLinkedEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SelfLinkedEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SelfLinkedEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
} | apache-2.0 | 3568ac59c6c069d814c3316d3c9afb20 | 40.287234 | 190 | 0.641799 | 5.804787 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/testSources/com/intellij/util/PackageHtmlGenerator.kt | 12 | 4937 | // 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.util
import com.intellij.codeEditor.printing.HTMLTextPainter
import com.intellij.codeEditor.printing.HtmlStyleManager
import com.intellij.lang.Language
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.ProjectManager
import com.intellij.psi.PsiFileFactory
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.io.inputStream
import com.intellij.util.io.outputStream
import com.vladsch.flexmark.ast.FencedCodeBlock
import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.html.HtmlWriter
import com.vladsch.flexmark.html.renderer.CoreNodeRenderer
import com.vladsch.flexmark.html.renderer.NodeRendererContext
import com.vladsch.flexmark.html.renderer.NodeRenderingHandler
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.util.data.DataHolder
import com.vladsch.flexmark.util.data.MutableDataSet
import org.junit.ClassRule
import org.junit.Test
import java.io.StringWriter
import java.nio.file.Paths
//private class MyApp : CommandLineApplication(true, false, true)
val packages = arrayOf(
"platform/platform-api/src/com/intellij/util/io",
"platform/util/src/com/intellij/util/xmlb/annotations"
)
class PackageDocGenerator {
companion object {
@ClassRule
@JvmField
val appRule = ProjectRule()
}
@Test
fun convert() {
if (UsefulTestCase.IS_UNDER_TEAMCITY) {
return
}
main(PlatformTestUtil.getCommunityPath())
}
}
private fun main(communityPath: String) {
// PlatformTestCase.doAutodetectPlatformPrefix()
// IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(true)
// MyApp()
// PluginManagerCore.getPlugins()
// ApplicationManagerEx.getApplicationEx().load(null)
val options = MutableDataSet()
val htmlStyleManager = HtmlStyleManager(isInline = true)
val parser = Parser.builder(options).build()
val renderer = HtmlRenderer.builder(options)
.nodeRendererFactory { IntelliJNodeRenderer(options, htmlStyleManager) }
.build()
// see generatePackageHtmlJavaDoc - head.style cannot be used to define styles, so, we use inline style
for (dir in packages) {
val document = Paths.get(communityPath, dir, "readme.md").inputStream().reader().use { parser.parseReader(it) }
Paths.get(communityPath, dir, "package.html").outputStream().bufferedWriter().use { writer ->
if (htmlStyleManager.isInline) {
renderer.render(document, writer)
}
else {
val data = renderer.render(document)
writer.append("<html>\n<head>\n")
htmlStyleManager.writeStyleTag(writer, isUseLineNumberStyle = false)
writer.append("</head>\n<body>\n")
writer.write(data)
writer.append("</body>\n</html>")
}
}
}
// System.exit(0)
}
private class IntelliJNodeRenderer(options: DataHolder, private val htmlStyleManager: HtmlStyleManager) : CoreNodeRenderer(options) {
override fun getNodeRenderingHandlers(): MutableSet<NodeRenderingHandler<*>> {
val set = LinkedHashSet<NodeRenderingHandler<*>>()
set.add(NodeRenderingHandler(FencedCodeBlock::class.java) { node, context, html -> renderCode(node, context, html) })
set.addAll(super.getNodeRenderingHandlers()?.filter { it.nodeType != FencedCodeBlock::class.java } ?: emptyList())
return set
}
fun renderCode(node: FencedCodeBlock, context: NodeRendererContext, html: HtmlWriter) {
html.line()
// html.srcPosWithTrailingEOL(node.chars).withAttr().tag("pre").openPre()
// html.srcPosWithEOL(node.contentChars).withAttr(CODE_CONTENT).tag("code")
val writer = StringWriter()
val project = ProjectManager.getInstance().defaultProject
val psiFileFactory = PsiFileFactory.getInstance(project)
runReadAction {
val psiFile = psiFileFactory.createFileFromText(getLanguage(node), node.contentChars.normalizeEOL())
val htmlTextPainter = HTMLTextPainter(psiFile, project, htmlStyleManager, false, false)
writer.use {
htmlTextPainter.paint(null, writer, false)
}
}
html.rawIndentedPre(writer.buffer)
// html.tag("/code")
// html.tag("/pre").closePre()
html.lineIf(context.htmlOptions.htmlBlockCloseTagEol)
}
}
fun getLanguage(node: FencedCodeBlock): Language {
val info = node.info
if (info.isNotNull && !info.isBlank) run {
val space = info.indexOf(' ')
val language = (if (space == -1) info else info.subSequence(0, space)).unescape()
val languageId = if (language == "kotlin") language else language.toUpperCase()
return Language.findLanguageByID(languageId) ?: throw Exception("Cannot find language ${language}")
}
throw Exception("Please specify code block language")
} | apache-2.0 | a2e69b4f253de51fcfab0326b3b69669 | 36.694656 | 140 | 0.747012 | 4.086921 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionPanel.kt | 5 | 1387 | // 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.memberInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.refactoring.ui.AbstractMemberSelectionPanel
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SeparatorFactory
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import java.awt.BorderLayout
class KotlinMemberSelectionPanel(
@NlsContexts.DialogTitle title: String,
memberInfo: List<KotlinMemberInfo>,
@Nls abstractColumnHeader: String? = null
) : AbstractMemberSelectionPanel<KtNamedDeclaration, KotlinMemberInfo>() {
private val table = createMemberSelectionTable(memberInfo, abstractColumnHeader)
init {
layout = BorderLayout()
val scrollPane = ScrollPaneFactory.createScrollPane(table)
add(SeparatorFactory.createSeparator(title, table), BorderLayout.NORTH)
add(scrollPane, BorderLayout.CENTER)
}
private fun createMemberSelectionTable(
memberInfo: List<KotlinMemberInfo>,
@Nls abstractColumnHeader: String?
): KotlinMemberSelectionTable {
return KotlinMemberSelectionTable(memberInfo, null, abstractColumnHeader)
}
override fun getTable() = table
} | apache-2.0 | 8369af4b25edfe2f9c3f3fd02dc33a24 | 37.555556 | 158 | 0.777938 | 4.91844 | false | false | false | false |
chrhsmt/Sishen | app/src/main/java/com/chrhsmt/sisheng/AudioService.kt | 1 | 13080 | package com.chrhsmt.sisheng
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.AudioTrack
import android.util.Log
import be.tarsos.dsp.AudioDispatcher
import be.tarsos.dsp.AudioEvent
import be.tarsos.dsp.AudioProcessor
import be.tarsos.dsp.io.TarsosDSPAudioFormat
import be.tarsos.dsp.io.android.AndroidAudioPlayer
import be.tarsos.dsp.io.android.AndroidFFMPEGLocator
import be.tarsos.dsp.io.android.AudioDispatcherFactory
import be.tarsos.dsp.pitch.PitchDetectionHandler
import be.tarsos.dsp.pitch.PitchDetectionResult
import be.tarsos.dsp.pitch.PitchProcessor
import be.tarsos.dsp.writer.WriterProcessor
import com.chrhsmt.sisheng.exception.AudioServiceException
import com.chrhsmt.sisheng.persistence.ExternalMedia
import com.chrhsmt.sisheng.point.Point
import com.chrhsmt.sisheng.point.PointCalculator
import com.chrhsmt.sisheng.point.SimplePointCalculator
import com.chrhsmt.sisheng.ui.Chart
import com.github.mikephil.charting.utils.ColorTemplate
import kotlinx.android.synthetic.main.content_main.*
import java.io.File
import java.io.RandomAccessFile
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by chihiro on 2017/08/22.
*/
class AudioService : AudioServiceInterface {
companion object {
// val SAMPLING_RATE: Int = 22050 // 44100
val AUDIO_FILE_SAMPLING_RATE: Int = 44100
// 録音時に指定秒数の空白時間後に録音停止
val STOP_RECORDING_AFTER_SECOND: Int = 2
val BUFFER_SIZE: Int = 1024
val MAX_FREQ_THRESHOLD = 500f
val MICROPHONE_DATA_SET_LABEL_NAME = "Microphone"
}
private val TAG: String = "AudioService"
private val activity: Activity
private var chart: Chart? = null
private var audioDispatcher: AudioDispatcher? = null
private var analyzeThread: Thread? = null
private var isRunning: Boolean = false
private var frequencies: MutableList<Float> = ArrayList<Float>()
private var testFrequencies: MutableList<Float> = ArrayList<Float>()
constructor(chart: Chart?, activity: Activity) {
this.activity = activity
this.chart = chart
// Setting ffmpeg
AndroidFFMPEGLocator(this.activity)
}
override fun startAudioRecord() {
// 既存データをクリア
this.frequencies.clear()
this.chart?.clearDateSet(MICROPHONE_DATA_SET_LABEL_NAME)
// マイクロフォンバッファサイズの計算
val microphoneBufferSize = AudioRecord.getMinBufferSize(
Settings.samplingRate!!,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT) / 2
this.startRecord(
AudioDispatcherFactory.fromDefaultMicrophone(Settings.samplingRate!!, microphoneBufferSize, 0),
targetList = this.frequencies,
labelName = MICROPHONE_DATA_SET_LABEL_NAME,
color = Color.rgb(10, 240, 10),
shouldRecord = true
)
}
@SuppressLint("WrongConstant")
override fun testPlay(fileName: String, path: String?, playback: Boolean, callback: Runnable?, async: Boolean, labelName: String) {
this.testFrequencies.clear()
this.chart?.clear()
val run = Runnable {
val audioPath: String = if (path == null) {
this.copyAudioFile(fileName)
} else {
path
}
this.startRecord(
AudioDispatcherFactory.fromPipe(
audioPath,
AUDIO_FILE_SAMPLING_RATE,
BUFFER_SIZE,
0
),
false,
playback = playback,
samplingRate = AUDIO_FILE_SAMPLING_RATE,
targetList = this.testFrequencies,
labelName = labelName,
callback = callback
)
}
if (async) {
Thread(run).start()
} else {
run.run()
}
}
@SuppressLint("WrongConstant")
override fun debugTestPlay(fileName: String, path: String, playback: Boolean, callback: Runnable?) {
Thread(Runnable {
this.startRecord(
AudioDispatcherFactory.fromPipe(
path,
AUDIO_FILE_SAMPLING_RATE,
BUFFER_SIZE,
0
),
false,
playback = playback,
samplingRate = AUDIO_FILE_SAMPLING_RATE,
targetList = this.frequencies,
labelName = "RecordedSampleAudio",
callback = callback,
color = Color.rgb(255, 10, 10)
)
}).start()
}
@SuppressLint("WrongConstant")
override fun attemptPlay(fileName: String) {
AndroidFFMPEGLocator(this.activity)
Thread(Runnable {
val path = this.copyAudioFile(fileName)
this.startRecord(
AudioDispatcherFactory.fromPipe(
path,
AUDIO_FILE_SAMPLING_RATE,
BUFFER_SIZE,
0
),
false,
playback = true,
samplingRate = AUDIO_FILE_SAMPLING_RATE,
targetList = this.frequencies,
labelName = "RecordedSampleAudio",
color = Color.rgb(255, 10, 10)
)
}).start()
}
override fun stop() {
this.stopRecord()
}
@Throws(AudioServiceException::class)
override fun analyze() : Point {
return analyze(SimplePointCalculator::class.qualifiedName!!)
}
@Throws(AudioServiceException::class)
override fun analyze(klassName: String) : Point {
val calculator: PointCalculator = Class.forName(klassName).newInstance() as PointCalculator
val point = calculator.calc(this.frequencies, this.testFrequencies)
if (point.base <= this.testFrequencies.size) {
// 録音が失敗している場合
throw AudioServiceException("不好意思,我听不懂")
}
return point
}
@Throws(AudioServiceException::class)
fun analyze(calculator: PointCalculator) : Point {
val point = calculator.calc(this.frequencies, this.testFrequencies)
if (point.base <= this.testFrequencies.size) {
// 録音が失敗している場合
throw AudioServiceException("不好意思,我听不懂")
}
return point
}
override fun clearTestFrequencies() {
this.testFrequencies.clear()
}
override fun clearFrequencies() {
this.frequencies.clear()
}
override fun clear() {
this.frequencies.clear()
this.testFrequencies.clear()
}
private fun startRecord(dispatcher: AudioDispatcher,
onAnotherThread: Boolean = true,
playback: Boolean = false,
samplingRate: Int = Settings.samplingRate!!,
targetList: MutableList<Float>,
labelName: String = "Default",
color: Int = ColorTemplate.getHoloBlue(),
callback: Runnable? = null,
shouldRecord: Boolean = false) {
val pdh: PitchDetectionHandler = object: PitchDetectionHandler {
private var silinceBegin: Long = -1
override fun handlePitch(result: PitchDetectionResult?, event: AudioEvent?) {
val pitch:Float = result!!.pitch
Log.d(TAG, String.format("pitch is %f, probability: %f", pitch, result!!.probability))
if ([email protected] && pitch > 0) {
// 音声検出し始め
[email protected] = true
}
// [email protected] = false
if ([email protected]) {
// 稼働中はピッチを保存
if (pitch > MAX_FREQ_THRESHOLD) {
// targetList.add(targetList.last())
} else {
targetList.add(pitch)
}
if (pitch < 0) {
// 無音の場合無音開始時間をセット
if (this.silinceBegin == -1L) {
this.silinceBegin = System.currentTimeMillis()
}
// N秒以上無音なら停止
if ((System.currentTimeMillis() - this.silinceBegin) >= STOP_RECORDING_AFTER_SECOND * 1000) {
[email protected]()
}
} else {
// 無音開始時間をクリア
this.silinceBegin = -1
}
}
[email protected] {
chart?.addEntry(pitch, name = labelName, color = color)
}
}
}
val processor: AudioProcessor = object : PitchProcessor(Settings.algorithm, samplingRate.toFloat(), BUFFER_SIZE, pdh) {
override fun processingFinished() {
super.processingFinished()
[email protected] = false
callback?.let { block ->
block.run()
}
}
}
dispatcher.addAudioProcessor(processor)
if (shouldRecord) {
ExternalMedia.saveDir?.takeIf { it -> it.canWrite() }?.let { it ->
val dateString = SimpleDateFormat("yyyy-MM-dd").format(Date())
val directory = File(it, dateString)
if (!directory.isDirectory) {
directory.mkdir()
}
val dateTimeString = SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format(Date())
val id = Regex("^mfsz/(\\d+)_[f|m].wav$").find(Settings.sampleAudioFileName!!)?.groups?.last()?.value
val sex = Settings.sex!!.first().toLowerCase()
val newFile = File(directory, String.format("%s-%s-%s.wav", dateTimeString, id, sex))
val format = TarsosDSPAudioFormat(AUDIO_FILE_SAMPLING_RATE.toFloat(), 16, 1, true, false)
val writeProcessor: AudioProcessor = WriterProcessor(format, RandomAccessFile(newFile, "rw"))
dispatcher.addAudioProcessor(writeProcessor)
}
}
if (playback) {
val bufferSize = AudioTrack.getMinBufferSize(dispatcher.format.sampleRate.toInt(), AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
dispatcher.addAudioProcessor(AndroidAudioPlayer(dispatcher.getFormat(), bufferSize, AudioManager.STREAM_MUSIC))
}
this.audioDispatcher = dispatcher
if (onAnotherThread) {
// TODO: Handlerにすべき?
this.analyzeThread = Thread(dispatcher, "AudioDispatcher")
this.analyzeThread!!.start()
} else {
dispatcher.run()
}
}
private fun stopRecord() {
this.audioDispatcher?.stop()
this.analyzeThread?.interrupt()
this.isRunning = false
[email protected] {
this.activity.button?.text = "開始"
}
}
override fun isRunning(): Boolean {
return this.isRunning
}
@SuppressLint("WrongConstant")
private fun copyAudioFile(fileName: String): String {
// ファイル移動
var dataName = fileName
if (fileName.contains("/")) {
dataName = fileName.replace("/", "_")
}
val path = String.format("/data/data/%s/files/%s", this.activity.packageName, dataName)
val input = this.activity.assets.open(fileName)
val output = this.activity.openFileOutput(dataName, Context.MODE_ENABLE_WRITE_AHEAD_LOGGING)
val DEFAULT_BUFFER_SIZE = 1024 * 4
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var n = 0
while (true) {
n = input.read(buffer)
if (n == -1) break
output.write(buffer, 0, n)
}
output.close()
input.close()
return path
}
fun getTestFreq(): MutableList<Float> {
return this.testFrequencies
}
fun addOtherChart(freqs: MutableList<Float>?, labelName: String, color: Int) {
freqs?.forEach { fl ->
chart?.addEntry(fl, name = labelName, color = color)
}
}
}
| mit | d1315dcc3effda8c74f580ec1cb3ca73 | 34.407202 | 156 | 0.565092 | 4.637881 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/vo/internship/apply/InternshipCompanyVo.kt | 1 | 1826 | package top.zbeboy.isy.web.vo.internship.apply
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2017-12-23 .
**/
open class InternshipCompanyVo {
var internshipCompanyId: String? = null
@NotNull
var studentId: Int? = null
@NotNull
var studentUsername: String? = null
@NotNull
@Size(max = 100)
var internshipReleaseId: String? = null
@NotNull
@Size(max = 15)
var studentName: String? = null
@NotNull
@Size(max = 50)
var collegeClass: String? = null
@NotNull
@Size(max = 2)
var studentSex: String? = null
@NotNull
@Size(max = 20)
var studentNumber: String? = null
@NotNull
@Size(max = 15)
var phoneNumber: String? = null
@NotNull
@Size(max = 100)
var qqMailbox: String? = null
@NotNull
@Size(max = 20)
var parentalContact: String? = null
@NotNull
var headmaster: String? = null
var headmasterContact: String? = null
@NotNull
@Size(max = 200)
var internshipCompanyName: String? = null
@NotNull
@Size(max = 500)
var internshipCompanyAddress: String? = null
@NotNull
@Size(max = 10)
var internshipCompanyContacts: String? = null
@NotNull
@Size(max = 20)
var internshipCompanyTel: String? = null
@NotNull
var schoolGuidanceTeacher: String? = null
var schoolGuidanceTeacherTel: String? = null
@NotNull
var startTime: String? = null
@NotNull
var endTime: String? = null
var commitmentBook: Byte? = null
var safetyResponsibilityBook: Byte? = null
var practiceAgreement: Byte? = null
var internshipApplication: Byte? = null
var practiceReceiving: Byte? = null
var securityEducationAgreement: Byte? = null
var parentalConsent: Byte? = null
} | mit | 71985c8d14af2608daf9928e1760f756 | 25.867647 | 49 | 0.659365 | 3.918455 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/vo/data/college/CollegeVo.kt | 1 | 570 | package top.zbeboy.isy.web.vo.data.college
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2017-12-01 .
**/
open class CollegeVo {
var collegeId: Int? = null
@NotNull
@Size(max = 200)
var collegeName: String? = null
var collegeIsDel: Byte? = null
@NotNull
@Min(1)
var schoolId: Int? = null
@NotNull
@Size(max = 500)
var collegeAddress: String? = null
@NotNull
@Size(max = 20)
var collegeCode: String? = null
} | mit | ec3a206d35fcdce718d2118f1927f3bb | 21.84 | 43 | 0.670175 | 3.540373 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovyColorSettingsPage.kt | 6 | 8790 | /*
* 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 org.jetbrains.plugins.groovy.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import icons.JetgroovyIcons
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter.*
import javax.swing.Icon
class GroovyColorSettingsPage : ColorSettingsPage {
private companion object {
val attributes = mapOf(
"Annotations//Annotation attribute name" to ANNOTATION_ATTRIBUTE_NAME,
"Annotations//Annotation name" to ANNOTATION,
"Braces and Operators//Braces" to BRACES,
"Braces and Operators//Brackets" to BRACKETS,
"Braces and Operators//Parentheses" to PARENTHESES,
"Braces and Operators//Operator sign" to OPERATION_SIGN,
"Comments//Line comment" to LINE_COMMENT,
"Comments//Block comment" to BLOCK_COMMENT,
"Comments//Groovydoc//Text" to DOC_COMMENT_CONTENT,
"Comments//Groovydoc//Tag" to DOC_COMMENT_TAG,
"Classes and Interfaces//Class" to CLASS_REFERENCE,
"Classes and Interfaces//Abstract class" to ABSTRACT_CLASS_NAME,
"Classes and Interfaces//Anonymous class" to ANONYMOUS_CLASS_NAME,
"Classes and Interfaces//Interface" to INTERFACE_NAME,
"Classes and Interfaces//Trait" to TRAIT_NAME,
"Classes and Interfaces//Enum" to ENUM_NAME,
"Classes and Interfaces//Type parameter" to TYPE_PARAMETER,
"Methods//Method declaration" to METHOD_DECLARATION,
"Methods//Constructor declaration" to CONSTRUCTOR_DECLARATION,
"Methods//Instance method call" to METHOD_CALL,
"Methods//Static method call" to STATIC_METHOD_ACCESS,
"Methods//Constructor call" to CONSTRUCTOR_CALL,
"Fields//Instance field" to INSTANCE_FIELD,
"Fields//Static field" to STATIC_FIELD,
"Variables and Parameters//Local variable" to LOCAL_VARIABLE,
"Variables and Parameters//Reassigned local variable" to REASSIGNED_LOCAL_VARIABLE,
"Variables and Parameters//Parameter" to PARAMETER,
"Variables and Parameters//Reassigned parameter" to REASSIGNED_PARAMETER,
"References//Instance property reference" to INSTANCE_PROPERTY_REFERENCE,
"References//Static property reference" to STATIC_PROPERTY_REFERENCE,
"References//Unresolved reference" to UNRESOLVED_ACCESS,
"Strings//String" to STRING,
"Strings//GString" to GSTRING,
"Strings//Valid string escape" to VALID_STRING_ESCAPE,
"Strings//Invalid string escape" to INVALID_STRING_ESCAPE,
"Keyword" to KEYWORD,
"Number" to NUMBER,
"Bad character" to BAD_CHARACTER,
"List/map to object conversion" to LITERAL_CONVERSION,
"Map key/Named argument" to MAP_KEY,
"Label" to LABEL
).map { AttributesDescriptor(it.key, it.value) }.toTypedArray()
val additionalTags = mapOf(
"annotation" to ANNOTATION,
"annotationAttribute" to ANNOTATION_ATTRIBUTE_NAME,
"groovydoc" to DOC_COMMENT_CONTENT,
"groovydocTag" to DOC_COMMENT_TAG,
"class" to CLASS_REFERENCE,
"abstractClass" to ABSTRACT_CLASS_NAME,
"anonymousClass" to ANONYMOUS_CLASS_NAME,
"interface" to INTERFACE_NAME,
"trait" to TRAIT_NAME,
"enum" to ENUM_NAME,
"typeParameter" to TYPE_PARAMETER,
"method" to METHOD_DECLARATION,
"constructor" to CONSTRUCTOR_DECLARATION,
"instanceMethodCall" to METHOD_CALL,
"staticMethodCall" to STATIC_METHOD_ACCESS,
"constructorCall" to CONSTRUCTOR_CALL,
"instanceField" to INSTANCE_FIELD,
"staticField" to STATIC_FIELD,
"localVariable" to LOCAL_VARIABLE,
"reassignedVariable" to REASSIGNED_LOCAL_VARIABLE,
"parameter" to PARAMETER,
"reassignedParameter" to REASSIGNED_PARAMETER,
"instanceProperty" to INSTANCE_PROPERTY_REFERENCE,
"staticProperty" to STATIC_PROPERTY_REFERENCE,
"unresolved" to UNRESOLVED_ACCESS,
"keyword" to KEYWORD,
"literalConstructor" to LITERAL_CONVERSION,
"mapKey" to MAP_KEY,
"label" to LABEL,
"validEscape" to VALID_STRING_ESCAPE,
"invalidEscape" to INVALID_STRING_ESCAPE
)
}
override fun getDisplayName(): String = "Groovy"
override fun getIcon(): Icon? = JetgroovyIcons.Groovy.Groovy_16x16
override fun getAttributeDescriptors(): Array<AttributesDescriptor> = attributes
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter(): GroovySyntaxHighlighter = GroovySyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> = additionalTags
@NonNls
override fun getDemoText(): String = """<keyword>package</keyword> highlighting
###
<groovydoc>/**
* This is Groovydoc comment
* <groovydocTag>@see</groovydocTag> java.lang.String#equals
*/</groovydoc>
<annotation>@Annotation</annotation>(<annotationAttribute>parameter</annotationAttribute> = 'value')
<keyword>class</keyword> <class>C</class> {
<keyword>def</keyword> <instanceField>property</instanceField> = <keyword>new</keyword> <anonymousClass>I</anonymousClass>() {}
<keyword>static</keyword> <keyword>def</keyword> <staticField>staticProperty</staticField> = []
<constructor>C</constructor>() {}
<keyword>def</keyword> <<typeParameter>T</typeParameter>> <typeParameter>T</typeParameter> <method>instanceMethod</method>(T <parameter>parameter</parameter>, <reassignedParameter>reassignedParameter</reassignedParameter>) {
<reassignedParameter>reassignedParameter</reassignedParameter> = 1
//This is a line comment
<keyword>return</keyword> <parameter>parameter</parameter>
}
<keyword>def</keyword> <method>getStuff</method>() { 42 }
<keyword>static</keyword> <keyword>boolean</keyword> <method>isStaticStuff</method>() { true }
<keyword>static</keyword> <keyword>def</keyword> <method>staticMethod</method>(<keyword>int</keyword> <parameter>i</parameter>) {
/* This is a block comment */
<interface>Map</interface> <localVariable>map</localVariable> = [<mapKey>key1</mapKey>: 1, <mapKey>key2</mapKey>: 2, (22): 33]
<class>File</class> <localVariable>f</localVariable> = <literalConstructor>[</literalConstructor>'path'<literalConstructor>]</literalConstructor>
<keyword>def</keyword> <reassignedVariable>a</reassignedVariable> = 'JetBrains'.<instanceMethodCall>matches</instanceMethodCall>(/Jw+Bw+/)
<label>label</label>:
<keyword>for</keyword> (<localVariable>entry</localVariable> <keyword>in</keyword> <localVariable>map</localVariable>) {
<keyword>if</keyword> (<localVariable>entry</localVariable>.value > 1 && <parameter>i</parameter> < 2) {
<reassignedVariable>a</reassignedVariable> = <unresolved>unresolvedReference</unresolved>
<keyword>continue</keyword> label
} <keyword>else</keyword> {
<reassignedVariable>a</reassignedVariable> = <localVariable>entry</localVariable>
}
}
<instanceMethodCall>print</instanceMethodCall> <localVariable>map</localVariable>.<mapKey>key1</mapKey>
}
}
<keyword>def</keyword> <localVariable>c</localVariable> = <keyword>new</keyword> <constructorCall>C</constructorCall>()
<localVariable>c</localVariable>.<instanceMethodCall>instanceMethod</instanceMethodCall>("Hello<validEscape>\n</validEscape>", 'world<invalidEscape>\x</invalidEscape>')
<instanceMethodCall>println</instanceMethodCall> <localVariable>c</localVariable>.<instanceProperty>stuff</instanceProperty>
<class>C</class>.<staticMethodCall>staticMethod</staticMethodCall>(<mapKey>namedArg</mapKey>: 1)
<class>C</class>.<staticProperty>staticStuff</staticProperty>
<keyword>abstract</keyword> <keyword>class</keyword> <abstractClass>AbstractClass</abstractClass> {}
<keyword>interface</keyword> <interface>I</interface> {}
<keyword>trait</keyword> <trait>T</trait> {}
<keyword>enum</keyword> <enum>E</enum> {}
@<keyword>interface</keyword> <annotation>Annotation</annotation> {
<class>String</class> <method>parameter</method>()
}
"""
}
| apache-2.0 | 7795711c5bd7219f73c5c10dc5a47eba | 43.170854 | 226 | 0.73083 | 4.327917 | false | false | false | false |
deso88/TinyGit | src/main/kotlin/hamburg/remme/tinygit/domain/Tag.kt | 1 | 523 | package hamburg.remme.tinygit.domain
class Tag(val name: String, val id: String) : Comparable<Tag> {
override fun toString() = name
override fun compareTo(other: Tag) = name.compareTo(other.name)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Tag
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
}
| bsd-3-clause | 183fc254d195dd80cbe461999c2e4ab5 | 20.791667 | 67 | 0.621415 | 4.217742 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/bungeecord/util/BungeeCordConstants.kt | 1 | 614 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bungeecord.util
object BungeeCordConstants {
const val HANDLER_ANNOTATION = "net.md_5.bungee.event.EventHandler"
const val EVENT_PRIORITY_CLASS = "net.md_5.bungee.event.EventPriority"
const val LISTENER_CLASS = "net.md_5.bungee.api.plugin.Listener"
const val CHAT_COLOR_CLASS = "net.md_5.bungee.api.ChatColor"
const val EVENT_CLASS = "net.md_5.bungee.api.plugin.Event"
const val PLUGIN = "net.md_5.bungee.api.plugin.Plugin"
}
| mit | b235b6288fdcee65972f7e3331e8957c | 28.238095 | 74 | 0.716612 | 3.283422 | false | false | false | false |
youdonghai/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.kt | 1 | 6320 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.tools.util.base
import com.intellij.diff.util.DiffPlaces
import com.intellij.diff.util.DiffUtil
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.openapi.util.Key
import com.intellij.util.xmlb.annotations.MapAnnotation
import java.util.*
@State(
name = "TextDiffSettings",
storages = arrayOf(Storage(value = DiffUtil.DIFF_CONFIG))
)
class TextDiffSettingsHolder : PersistentStateComponent<TextDiffSettingsHolder.State> {
companion object {
@JvmField val KEY: Key<TextDiffSettings> = Key.create("TextDiffSettings")
@JvmField val CONTEXT_RANGE_MODES: IntArray = intArrayOf(1, 2, 4, 8, -1)
@JvmField val CONTEXT_RANGE_MODE_LABELS: Array<String> = arrayOf("1", "2", "4", "8", "Disable")
@JvmStatic
fun getInstance(): TextDiffSettingsHolder {
return ServiceManager.getService(TextDiffSettingsHolder::class.java)
}
}
internal data class SharedSettings(
// Fragments settings
var CONTEXT_RANGE: Int = 4,
var MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES: Boolean = false,
var MERGE_LST_GUTTER_MARKERS: Boolean = true
)
internal data class PlaceSettings(
// Diff settings
var HIGHLIGHT_POLICY: HighlightPolicy = HighlightPolicy.BY_WORD,
var IGNORE_POLICY: IgnorePolicy = IgnorePolicy.DEFAULT,
// Presentation settings
var ENABLE_SYNC_SCROLL: Boolean = true,
// Editor settings
var SHOW_WHITESPACES: Boolean = false,
var SHOW_LINE_NUMBERS: Boolean = true,
var SHOW_INDENT_LINES: Boolean = false,
var USE_SOFT_WRAPS: Boolean = false,
var HIGHLIGHTING_LEVEL: HighlightingLevel = HighlightingLevel.INSPECTIONS,
var READ_ONLY_LOCK: Boolean = true,
// Fragments settings
var EXPAND_BY_DEFAULT: Boolean = true
)
class TextDiffSettings internal constructor(val SHARED_SETTINGS: SharedSettings,
val PLACE_SETTINGS: PlaceSettings) {
constructor() : this(SharedSettings(), PlaceSettings())
// Presentation settings
var isEnableSyncScroll: Boolean
get() = PLACE_SETTINGS.ENABLE_SYNC_SCROLL
set(value) { PLACE_SETTINGS.ENABLE_SYNC_SCROLL = value }
// Diff settings
var highlightPolicy: HighlightPolicy
get() = PLACE_SETTINGS.HIGHLIGHT_POLICY
set(value) { PLACE_SETTINGS.HIGHLIGHT_POLICY = value }
var ignorePolicy: IgnorePolicy
get() = PLACE_SETTINGS.IGNORE_POLICY
set(value) { PLACE_SETTINGS.IGNORE_POLICY = value }
//
// Merge
//
var isAutoApplyNonConflictedChanges: Boolean
get() = SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES
set(value) { SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES = value }
var isEnableLstGutterMarkersInMerge: Boolean
get() = SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS
set(value) { SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS = value }
// Editor settings
var isShowLineNumbers: Boolean
get() = PLACE_SETTINGS.SHOW_LINE_NUMBERS
set(value) { PLACE_SETTINGS.SHOW_LINE_NUMBERS = value }
var isShowWhitespaces: Boolean
get() = PLACE_SETTINGS.SHOW_WHITESPACES
set(value) { PLACE_SETTINGS.SHOW_WHITESPACES = value }
var isShowIndentLines: Boolean
get() = PLACE_SETTINGS.SHOW_INDENT_LINES
set(value) { PLACE_SETTINGS.SHOW_INDENT_LINES = value }
var isUseSoftWraps: Boolean
get() = PLACE_SETTINGS.USE_SOFT_WRAPS
set(value) { PLACE_SETTINGS.USE_SOFT_WRAPS = value }
var highlightingLevel: HighlightingLevel
get() = PLACE_SETTINGS.HIGHLIGHTING_LEVEL
set(value) { PLACE_SETTINGS.HIGHLIGHTING_LEVEL = value }
var contextRange: Int
get() = SHARED_SETTINGS.CONTEXT_RANGE
set(value) { SHARED_SETTINGS.CONTEXT_RANGE = value }
var isExpandByDefault: Boolean
get() = PLACE_SETTINGS.EXPAND_BY_DEFAULT
set(value) { PLACE_SETTINGS.EXPAND_BY_DEFAULT = value }
var isReadOnlyLock: Boolean
get() = PLACE_SETTINGS.READ_ONLY_LOCK
set(value) { PLACE_SETTINGS.READ_ONLY_LOCK = value }
//
// Impl
//
companion object {
@JvmStatic
fun getSettings(): TextDiffSettings {
return getSettings(null)
}
@JvmStatic
fun getSettings(place: String?): TextDiffSettings {
return getInstance().getSettings(place)
}
}
}
fun getSettings(place: String?): TextDiffSettings {
val placeSettings = myState.PLACES_MAP.getOrPut(place ?: DiffPlaces.DEFAULT, { PlaceSettings() })
return TextDiffSettings(myState.SHARED_SETTINGS, placeSettings)
}
class State {
@MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false)
internal var PLACES_MAP: TreeMap<String, PlaceSettings> = defaultPlaceSettings()
internal var SHARED_SETTINGS = SharedSettings()
companion object {
private fun defaultPlaceSettings(): TreeMap<String, PlaceSettings> {
val map = TreeMap<String, PlaceSettings>()
val changes = PlaceSettings()
changes.EXPAND_BY_DEFAULT = false
val commit = PlaceSettings()
commit.EXPAND_BY_DEFAULT = false
map.put(DiffPlaces.DEFAULT, PlaceSettings())
map.put(DiffPlaces.CHANGES_VIEW, changes)
map.put(DiffPlaces.COMMIT_DIALOG, commit)
return map
}
}
}
private var myState: State = State()
override fun getState(): State {
return myState
}
override fun loadState(state: State) {
myState = state
}
} | apache-2.0 | 89e594046346229014b54be870f3b4fc | 31.751295 | 101 | 0.692405 | 4.388889 | false | false | false | false |
ursjoss/sipamato | core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/launcher/UnsynchronizedEntitiesWarner.kt | 2 | 2141 | package ch.difty.scipamato.core.sync.launcher
import ch.difty.scipamato.core.db.tables.Newsletter
import ch.difty.scipamato.core.db.tables.Paper
import ch.difty.scipamato.core.db.tables.PaperCode
import ch.difty.scipamato.core.db.tables.PaperNewsletter
import org.jooq.DSLContext
import org.jooq.impl.DSL
import org.springframework.beans.factory.annotation.Qualifier
class UnsynchronizedEntitiesWarner @JvmOverloads constructor(
@Qualifier("dslContext") jooqCore: DSLContext,
val paperProvider: () -> List<Long> = { retrievePaperRecords(jooqCore) },
val newsletterPaperProvider: () -> List<String> = { retrieveNewsletterPaperRecords(jooqCore) },
) : Warner {
override fun findUnsynchronizedPapers(): String? {
val numbers = paperProvider()
return if (numbers.isEmpty()) null
else "Papers not synchronized due to missing codes: Number " +
numbers.joinToString(", ", postfix = ".")
}
override fun findNewsletterswithUnsynchronizedPapers(): String? {
val issues = newsletterPaperProvider()
return if (issues.isEmpty()) null
else "Incomplete Newsletters due to papers with missing codes - Papers: " +
issues.joinToString(", ", postfix = ".")
}
}
internal fun retrievePaperRecords(jooqCore: DSLContext): List<Long> = jooqCore
.select(Paper.PAPER.NUMBER)
.from(Paper.PAPER)
.where(Paper.PAPER.ID.notIn(DSL
.select(PaperCode.PAPER_CODE.PAPER_ID)
.from(PaperCode.PAPER_CODE)))
.fetchInto(Long::class.java)
internal fun retrieveNewsletterPaperRecords(jooqCore: DSLContext): List<String> = jooqCore
.select(Paper.PAPER.NUMBER.concat(" (").concat(Newsletter.NEWSLETTER.ISSUE).concat(")"))
.from(Newsletter.NEWSLETTER)
.innerJoin(PaperNewsletter.PAPER_NEWSLETTER)
.on(Newsletter.NEWSLETTER.ID.eq(PaperNewsletter.PAPER_NEWSLETTER.NEWSLETTER_ID))
.innerJoin(Paper.PAPER)
.on(PaperNewsletter.PAPER_NEWSLETTER.PAPER_ID.eq(Paper.PAPER.ID))
.where(Paper.PAPER.ID.notIn(DSL
.select(PaperCode.PAPER_CODE.PAPER_ID)
.from(PaperCode.PAPER_CODE)))
.fetchInto(String::class.java)
| gpl-3.0 | 7908c61e6b42aa50ee41edf55e34dbec | 41.82 | 99 | 0.721625 | 3.899818 | false | false | false | false |
allotria/intellij-community | plugins/devkit/devkit-core/src/actions/updateFromSources/UpdateIdeFromSourcesAction.kt | 2 | 24003 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.actions.updateFromSources
import com.intellij.CommonBundle
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.ide.plugins.PluginInstaller
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.notification.*
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.task.ProjectTaskManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.PathUtil
import com.intellij.util.Restarter
import com.intellij.util.TimeoutUtil
import com.intellij.util.io.inputStream
import com.intellij.util.io.isFile
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.util.PsiUtil
import java.io.File
import java.nio.file.Paths
import java.util.*
import kotlin.collections.LinkedHashSet
private val LOG = logger<UpdateIdeFromSourcesAction>()
private val notificationGroup by lazy {
NotificationGroup(displayId = "Update from Sources", displayType = NotificationDisplayType.STICKY_BALLOON)
}
internal open class UpdateIdeFromSourcesAction
@JvmOverloads constructor(private val forceShowSettings: Boolean = false)
: AnAction(if (forceShowSettings) DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.show.settings.text")
else DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.text"),
DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.description"), null), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (forceShowSettings || UpdateFromSourcesSettings.getState().showSettings) {
val oldWorkIdePath = UpdateFromSourcesSettings.getState().actualIdePath
val ok = UpdateFromSourcesDialog(project, forceShowSettings).showAndGet()
if (!ok) return
val updatedState = UpdateFromSourcesSettings.getState()
if (oldWorkIdePath != updatedState.actualIdePath) {
updatedState.workIdePathsHistory.remove(oldWorkIdePath)
updatedState.workIdePathsHistory.remove(updatedState.actualIdePath)
updatedState.workIdePathsHistory.add(0, updatedState.actualIdePath)
updatedState.workIdePathsHistory.add(0, oldWorkIdePath)
}
}
fun error(@NlsContexts.DialogMessage message : String) {
Messages.showErrorDialog(project, message, CommonBundle.getErrorTitle())
}
val state = UpdateFromSourcesSettings.getState()
val devIdeaHome = project.basePath ?: return
val workIdeHome = state.actualIdePath
val restartAutomatically = state.restartAutomatically
if (!ApplicationManager.getApplication().isRestartCapable && FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.ide.cannot.restart"))
}
val notIdeHomeMessage = checkIdeHome(workIdeHome)
if (notIdeHomeMessage != null) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home",
workIdeHome, notIdeHomeMessage))
}
if (FileUtil.isAncestor(workIdeHome, PathManager.getConfigPath(), false)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_CONFIG_PATH))
}
if (FileUtil.isAncestor(workIdeHome, PathManager.getSystemPath(), false)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.config.or.system.directory.under.home", workIdeHome, PathManager.PROPERTY_SYSTEM_PATH))
}
val scriptFile = File(devIdeaHome, "build/scripts/idea_ultimate.gant")
if (!scriptFile.exists()) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.build.scripts.not.exists", scriptFile))
}
if (!scriptFile.readText().contains(includeBinAndRuntimeProperty)) {
return error(DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.build.scripts.out.of.date"))
}
val bundledPluginDirsToSkip: List<String>
val nonBundledPluginDirsToInclude: List<String>
val buildEnabledPluginsOnly = !state.buildDisabledPlugins
if (buildEnabledPluginsOnly) {
val pluginDirectoriesToSkip = LinkedHashSet(state.pluginDirectoriesForDisabledPlugins)
pluginDirectoriesToSkip.removeAll(PluginManagerCore.getLoadedPlugins().asSequence().filter { it.isBundled }.map { it.path }.filter { it.isDirectory }.map { it.name })
PluginManagerCore.getPlugins().filter { it.isBundled && !it.isEnabled }.map { it.path }.filter { it.isDirectory }.mapTo(pluginDirectoriesToSkip) { it.name }
val list = pluginDirectoriesToSkip.toMutableList()
state.pluginDirectoriesForDisabledPlugins = list
bundledPluginDirsToSkip = list
nonBundledPluginDirsToInclude = PluginManagerCore.getPlugins().filter {
!it.isBundled && it.isEnabled && it.version != null && it.version.contains("SNAPSHOT")
}.map { it.path }.filter { it.isDirectory }.map { it.name }
}
else {
bundledPluginDirsToSkip = emptyList()
nonBundledPluginDirsToInclude = emptyList()
}
val deployDir = "$devIdeaHome/out/deploy" // NON-NLS
val distRelativePath = "dist" // NON-NLS
val backupDir = "$devIdeaHome/out/backup-before-update-from-sources" // NON-NLS
val params = createScriptJavaParameters(devIdeaHome, project, deployDir, distRelativePath, scriptFile,
buildEnabledPluginsOnly, bundledPluginDirsToSkip, nonBundledPluginDirsToInclude) ?: return
ProjectTaskManager.getInstance(project)
.buildAllModules()
.onSuccess {
if (!it.isAborted && !it.hasErrors()) {
runUpdateScript(params, project, workIdeHome, deployDir, distRelativePath, backupDir, restartAutomatically)
}
}
}
private fun checkIdeHome(workIdeHome: String): String? {
val homeDir = File(workIdeHome)
if (!homeDir.exists()) return null
if (homeDir.isFile) return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.directory")
val buildTxt = if (SystemInfo.isMac) "Resources/build.txt" else "build.txt" // NON-NLS
for (name in listOf("bin", buildTxt)) {
if (!File(homeDir, name).exists()) {
return DevKitBundle.message("action.UpdateIdeFromSourcesAction.error.work.home.not.valid.ide.home.not.exists", name)
}
}
return null
}
private fun runUpdateScript(params: JavaParameters,
project: Project,
workIdeHome: String,
deployDirPath: String,
distRelativePath: String,
backupDir: String,
restartAutomatically: Boolean) {
val builtDistPath = "$deployDirPath/$distRelativePath"
object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.text")
backupImportantFilesIfNeeded(workIdeHome, backupDir, indicator)
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.delete", builtDistPath)
FileUtil.delete(File(builtDistPath))
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.update.progress.start.gant.script")
val commandLine = params.toCommandLine()
commandLine.isRedirectErrorStream = true
val scriptHandler = OSProcessHandler(commandLine)
val output = Collections.synchronizedList(ArrayList<@NlsSafe String>())
scriptHandler.addProcessListener(object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
output.add(event.text)
if (outputType == ProcessOutputTypes.STDOUT) {
indicator.text2 = event.text
}
}
override fun processTerminated(event: ProcessEvent) {
if (indicator.isCanceled) {
return
}
if (event.exitCode != 0) {
notificationGroup.createNotification(title = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.title"),
content = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.failed.content",
event.exitCode),
type = NotificationType.ERROR)
.addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.output")) {
FileEditorManager.getInstance(project).openFile(LightVirtualFile("output.txt", output.joinToString("")), true)
})
.addAction(NotificationAction.createSimple(DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.action.view.debug.log")) {
val logFile = LocalFileSystem.getInstance().refreshAndFindFileByPath("$deployDirPath/log/debug.log") ?: return@createSimple // NON-NLS
logFile.refresh(true, false)
FileEditorManager.getInstance(project).openFile(logFile, true)
})
.notify(project)
return
}
if (!FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
startCopyingFiles(builtDistPath, workIdeHome, project)
return
}
val command = generateUpdateCommand(builtDistPath, workIdeHome)
if (restartAutomatically) {
ApplicationManager.getApplication().invokeLater { scheduleRestart(command, deployDirPath, project) }
}
else {
showRestartNotification(command, deployDirPath, project)
}
}
})
scriptHandler.startNotify()
while (!scriptHandler.isProcessTerminated) {
scriptHandler.waitFor(300)
indicator.checkCanceled()
}
}
}.queue()
}
private fun showRestartNotification(command: Array<String>, deployDirPath: String, project: Project) {
notificationGroup.createNotification(title = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"),
content = DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.content"),
listener = NotificationListener { _, _ -> restartWithCommand(command, deployDirPath) }).notify(project)
}
private fun scheduleRestart(command: Array<String>, deployDirPath: String, project: Project) {
object : Task.Modal(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.success.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
var progress = 0
for (i in 10 downTo 1) {
indicator.text = DevKitBundle.message(
"action.UpdateIdeFromSourcesAction.progress.text.new.installation.prepared.ide.will.restart", i)
repeat(10) {
indicator.fraction = 0.01 * progress++
indicator.checkCanceled()
TimeoutUtil.sleep(100)
}
}
restartWithCommand(command, deployDirPath)
}
override fun onCancel() {
showRestartNotification(command, deployDirPath, project)
}
}.setCancelText(DevKitBundle.message("action.UpdateIdeFromSourcesAction.button.postpone")).queue()
}
private fun backupImportantFilesIfNeeded(workIdeHome: String,
backupDirPath: String,
indicator: ProgressIndicator) {
val backupDir = File(backupDirPath)
if (backupDir.exists()) {
LOG.debug("$backupDir already exists, skipping backup")
return
}
LOG.debug("Backing up files from $workIdeHome to $backupDir")
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.backup.progress.text")
FileUtil.createDirectory(backupDir)
File(workIdeHome, "bin").listFiles()
?.filter { it.name !in safeToDeleteFilesInBin && it.extension !in safeToDeleteExtensions }
?.forEach { FileUtil.copy(it, File(backupDir, "bin/${it.name}")) }
File(workIdeHome).listFiles()
?.filter { it.name !in safeToDeleteFilesInHome }
?.forEach { FileUtil.copyFileOrDir(it, File(backupDir, it.name)) }
}
private fun startCopyingFiles(builtDistPath: String, workIdeHome: String, project: Project) {
object : Task.Backgroundable(project, DevKitBundle.message("action.UpdateIdeFromSourcesAction.task.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.progress.text")
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.delete.old.files.text")
FileUtil.delete(File(workIdeHome))
indicator.checkCanceled()
indicator.text2 = DevKitBundle.message("action.UpdateIdeFromSourcesAction.copy.copy.new.files.text")
FileUtil.copyDir(File(builtDistPath), File(workIdeHome))
indicator.checkCanceled()
Notification("Update from Sources", DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.title"),
DevKitBundle.message("action.UpdateIdeFromSourcesAction.notification.content", workIdeHome),
NotificationType.INFORMATION).notify(project)
}
}.queue()
}
@Suppress("HardCodedStringLiteral")
private fun generateUpdateCommand(builtDistPath: String, workIdeHome: String): Array<String> {
if (SystemInfo.isWindows) {
val restartLogFile = File(PathManager.getLogPath(), "update-from-sources.log")
val updateScript = FileUtil.createTempFile("update", ".cmd", false)
val workHomePath = File(workIdeHome).absolutePath
/* deletion of the IDE files may fail to delete some executable files because they are still used by the IDE process,
so the script wait for some time and try to delete again;
'ping' command is used instead of 'timeout' because the latter doesn't work from batch files;
removal of the script file is performed in separate process to avoid errors while executing the script */
FileUtil.writeToFile(updateScript, """
@echo off
SET count=20
SET time_to_wait=1
:DELETE_DIR
RMDIR /Q /S "$workHomePath"
IF EXIST "$workHomePath" (
IF %count% GEQ 0 (
ECHO "$workHomePath" still exists, wait %time_to_wait%s and try delete again
SET /A time_to_wait=%time_to_wait%+1
PING 127.0.0.1 -n %time_to_wait% >NUL
SET /A count=%count%-1
ECHO %count% attempts remain
GOTO DELETE_DIR
)
ECHO Failed to delete "$workHomePath", IDE wasn't updated. You may delete it manually and copy files from "${File(builtDistPath).absolutePath}" by hand
GOTO CLEANUP_AND_EXIT
)
XCOPY "${File(builtDistPath).absolutePath}" "$workHomePath"\ /Q /E /Y
:CLEANUP_AND_EXIT
START /b "" cmd /c DEL /Q /F "${updateScript.absolutePath}" & EXIT /b
""".trimIndent())
return arrayOf("cmd", "/c", updateScript.absolutePath, ">${restartLogFile.absolutePath}", "2>&1")
}
val command = arrayOf(
"rm -rf \"$workIdeHome\"/*",
"cp -R \"$builtDistPath\"/* \"$workIdeHome\""
)
return arrayOf("/bin/sh", "-c", command.joinToString(" && "))
}
private fun restartWithCommand(command: Array<String>, deployDirPath: String) {
updatePlugins(deployDirPath)
Restarter.doNotLockInstallFolderOnRestart()
(ApplicationManager.getApplication() as ApplicationImpl).restart(ApplicationEx.FORCE_EXIT or ApplicationEx.EXIT_CONFIRMED or ApplicationEx.SAVE, command)
}
private fun updatePlugins(deployDirPath: String) {
val pluginsDir = Paths.get(deployDirPath).resolve("artifacts/${ApplicationInfo.getInstance().build.productCode}-plugins")
val pluginsXml = pluginsDir.resolve("plugins.xml")
if (!pluginsXml.isFile()) {
LOG.warn("Cannot read non-bundled plugins from $pluginsXml, they won't be updated")
return
}
val plugins = try {
pluginsXml.inputStream().reader().use {
MarketplaceRequests.parsePluginList(it)
}
}
catch (e: Exception) {
LOG.error("Failed to parse $pluginsXml", e)
return
}
val existingCustomPlugins =
PluginManagerCore.getLoadedPlugins().asSequence().filter { !it.isBundled }.associateBy { it.pluginId.idString }
LOG.debug("Existing custom plugins: $existingCustomPlugins")
val pluginsToUpdate =
plugins.mapNotNull { node -> existingCustomPlugins[node.pluginId.idString]?.let { it to node } }
for ((existing, update) in pluginsToUpdate) {
val pluginFile = pluginsDir.resolve(update.downloadUrl)
LOG.debug("Adding update command: ${existing.pluginPath} to $pluginFile")
PluginInstaller.installAfterRestart(pluginFile, false, existing.pluginPath, update)
}
}
private fun createScriptJavaParameters(devIdeaHome: String,
project: Project,
deployDir: String,
@Suppress("SameParameterValue") distRelativePath: String,
scriptFile: File,
buildEnabledPluginsOnly: Boolean,
bundledPluginDirsToSkip: List<String>,
nonBundledPluginDirsToInclude: List<String>): JavaParameters? {
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk == null) {
LOG.warn("Project SDK is not defined")
return null
}
val params = JavaParameters()
params.isUseClasspathJar = true
params.setDefaultCharset(project)
params.jdk = sdk
params.mainClass = "org.codehaus.groovy.tools.GroovyStarter"
params.programParametersList.add("--classpath")
val buildScriptsModuleName = "intellij.idea.ultimate.build"
val buildScriptsModule = ModuleManager.getInstance(project).findModuleByName(buildScriptsModuleName)
if (buildScriptsModule == null) {
LOG.warn("Build scripts module $buildScriptsModuleName is not found in the project")
return null
}
val classpath = OrderEnumerator.orderEntries(buildScriptsModule)
.recursively().withoutSdk().runtimeOnly().productionOnly().classes().pathsList
val classesFromCoreJars = listOf(
params.mainClass,
"org.apache.tools.ant.BuildException", //ant
"org.apache.tools.ant.launch.AntMain", //ant-launcher
"org.apache.commons.cli.ParseException", //commons-cli
"groovy.util.CliBuilder" //groovy-cli-commons
)
val coreClassPath = classpath.rootDirs.filter { root ->
classesFromCoreJars.any { LibraryUtil.isClassAvailableInLibrary(listOf(root), it) }
}.mapNotNull { PathUtil.getLocalPath(it) }
params.classPath.addAll(coreClassPath)
coreClassPath.forEach { classpath.remove(FileUtil.toSystemDependentName(it)) }
params.programParametersList.add(classpath.pathsString)
params.programParametersList.add("--main")
params.programParametersList.add("gant.Gant")
params.programParametersList.add("--debug")
params.programParametersList.add("-Dsome_unique_string_42_239")
params.programParametersList.add("--file")
params.programParametersList.add(scriptFile.absolutePath)
params.programParametersList.add("update-from-sources")
params.vmParametersList.add("-D$includeBinAndRuntimeProperty=true")
params.vmParametersList.add("-Dintellij.build.bundled.jre.prefix=jbrsdk-")
if (buildEnabledPluginsOnly) {
if (bundledPluginDirsToSkip.isNotEmpty()) {
params.vmParametersList.add("-Dintellij.build.bundled.plugin.dirs.to.skip=${bundledPluginDirsToSkip.joinToString(",")}")
}
val nonBundled = if (nonBundledPluginDirsToInclude.isNotEmpty()) nonBundledPluginDirsToInclude.joinToString(",") else "none"
params.vmParametersList.add("-Dintellij.build.non.bundled.plugin.dirs.to.include=$nonBundled")
}
if (!buildEnabledPluginsOnly || nonBundledPluginDirsToInclude.isNotEmpty()) {
params.vmParametersList.add("-Dintellij.build.local.plugins.repository=true")
}
params.vmParametersList.add("-Dintellij.build.output.root=$deployDir")
params.vmParametersList.add("-DdistOutputRelativePath=$distRelativePath")
return params
}
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabledAndVisible = project != null && isIdeaProject(project)
}
private fun isIdeaProject(project: Project) = try {
DumbService.getInstance(project).computeWithAlternativeResolveEnabled<Boolean, RuntimeException> { PsiUtil.isIdeaProject(project) }
}
catch (e: IndexNotReadyException) {
false
}
}
private const val includeBinAndRuntimeProperty = "intellij.build.generate.bin.and.runtime.for.unpacked.dist"
internal class UpdateIdeFromSourcesSettingsAction : UpdateIdeFromSourcesAction(true)
@NonNls
private val safeToDeleteFilesInHome = setOf(
"bin", "help", "jre", "jre64", "jbr", "lib", "license", "plugins", "redist", "MacOS", "Resources",
"build.txt", "product-info.json", "Install-Linux-tar.txt", "Install-Windows-zip.txt", "ipr.reg"
)
@NonNls
private val safeToDeleteFilesInBin = setOf(
"append.bat", "appletviewer.policy", "format.sh", "format.bat",
"fsnotifier", "fsnotifier64",
"inspect.bat", "inspect.sh",
"restarter"
/*
"idea.properties",
"idea.sh",
"idea.bat",
"idea.exe.vmoptions",
"idea64.exe.vmoptions",
"idea.vmoptions",
"idea64.vmoptions",
"log.xml",
*/
)
@NonNls
private val safeToDeleteExtensions = setOf("exe", "dll", "dylib", "so", "ico", "svg", "png", "py") | apache-2.0 | cd46855a67838f7b52e76065c78fc7a3 | 48.087935 | 172 | 0.701412 | 4.942957 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/service/NotificationService.kt | 1 | 5435 | package no.skatteetaten.aurora.boober.service
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import no.skatteetaten.aurora.boober.feature.envName
import no.skatteetaten.aurora.boober.feature.name
import no.skatteetaten.aurora.boober.feature.releaseTo
import no.skatteetaten.aurora.boober.feature.version
import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeployment
import no.skatteetaten.aurora.boober.model.openshift.Notification
import no.skatteetaten.aurora.boober.model.openshift.NotificationType
import no.skatteetaten.aurora.boober.utils.findResourceByType
import no.skatteetaten.aurora.boober.utils.toMultiMap
@Service
class NotificationService(
val mattermostService: MattermostService,
val userDetailsProvider: UserDetailsProvider,
@Value("\${openshift.cluster}") val cluster: String,
@Value("\${integrations.openshift.url}") val openshiftUrl: String
) {
fun sendDeployNotifications(
deployResults: List<AuroraDeployResult>
): List<AuroraDeployResult> {
val deployResultsWithNotifications = deployResults
.createNotificationsForDeployResults()
.toMultiMap()
.filterKeys {
it.type == NotificationType.Mattermost
}
.sendMattermostNotification()
val deployResultWithoutNotifications = deployResults
.filter {
val notifications = it.findApplicationDeploymentSpec().notifications ?: emptySet()
notifications.isEmpty()
}
return deployResultWithoutNotifications + deployResultsWithNotifications
}
private fun List<AuroraDeployResult>.asBulletlistOfDeploys(isSuccessful: Boolean): String {
return this.joinToString(separator = "\n") { deployResult ->
val adSpec = deployResult.findApplicationDeploymentSpec()
val message = if (deployResult.success) adSpec.message else deployResult.reason ?: "Unknown error"
val messageFormatted = message?.let { " *message*=$it" } ?: ""
val adc = deployResult.auroraDeploymentSpecInternal
val releaseTo = adc.releaseTo?.let { " *releaseTo*=$it " } ?: ""
val deployId = if (!isSuccessful) "*deployId*=${deployResult.deployId} " else ""
val replicas = adc.fields["replicas"]?.let { " *replicas*=${it.value} " } ?: ""
"* **${adc.envName}/${adc.name}** *version*=${adc.version} $replicas $releaseTo $deployId $messageFormatted"
}
}
private fun Map<Notification, List<AuroraDeployResult>>.sendMattermostNotification(): List<AuroraDeployResult> {
val user = userDetailsProvider.getAuthenticatedUser().username
val headerMessage = "@$user has applied application(s) to cluster [$cluster]($openshiftUrl)"
return this.flatMap { (notification, deployResults) ->
val attachments = deployResults.createMattermostMessage()
val exceptionOrNull = mattermostService.sendMessage(
channelId = notification.notificationLocation,
message = headerMessage,
attachments = attachments
)
handleMattermostException(exceptionOrNull, deployResults, notification.notificationLocation)
}.distinctBy { it.deployId }
}
private fun List<AuroraDeployResult>.createDeployResultMessage(isSuccessful: Boolean): Attachment? {
if (this.isEmpty()) return null
val listOfDeploys = this.asBulletlistOfDeploys(isSuccessful = isSuccessful)
val headerMessage =
if (isSuccessful) "Applied application(s) to cluster" else "Failed to apply application(s) to cluster \n For more information run `ao inspect <deployId>` in cli"
val color = if (isSuccessful) AttachmentColor.Green else AttachmentColor.Red
val text = """
|#### $headerMessage
|$listOfDeploys
""".trimMargin()
return Attachment(
color = color.hex,
text = text
)
}
private fun List<AuroraDeployResult>.createMattermostMessage(): List<Attachment> {
val listOfSuccessDeploys = this.filter { it.success }.createDeployResultMessage(isSuccessful = true)
val listOfFailedDeploys = this.filter { !it.success }.createDeployResultMessage(isSuccessful = false)
return listOfNotNull(
listOfSuccessDeploys,
listOfFailedDeploys
)
}
private fun handleMattermostException(
exceptionOrNull: Exception?,
deployResults: List<AuroraDeployResult>,
notificationLocation: String
) = if (exceptionOrNull != null) {
deployResults.map {
it.copy(reason = it.reason + "Failed to send notification to mattermost channel_id=$notificationLocation")
}
} else {
deployResults
}
private fun AuroraDeployResult.findApplicationDeploymentSpec() = this.deployCommand
.resources
.findResourceByType<ApplicationDeployment>()
.spec
private fun List<AuroraDeployResult>.createNotificationsForDeployResults(): List<Pair<Notification, AuroraDeployResult>> =
this.flatMap { result ->
val notifications = result.findApplicationDeploymentSpec().notifications ?: emptySet()
notifications.map {
it to result
}
}
}
| apache-2.0 | dc689788123c4cf8f3951671ccef8b3d | 41.460938 | 173 | 0.681325 | 5.009217 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/fragment/content/transfer/PrepareIndexFragment.kt | 1 | 7675 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.fragment.content.transfer
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import com.genonbeta.android.framework.io.DocumentFile
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.content.App
import org.monora.uprotocol.client.android.content.Image
import org.monora.uprotocol.client.android.content.Song
import org.monora.uprotocol.client.android.content.Video
import org.monora.uprotocol.client.android.data.SelectionRepository
import org.monora.uprotocol.client.android.database.model.UTransferItem
import org.monora.uprotocol.client.android.fragment.ContentBrowserViewModel
import org.monora.uprotocol.client.android.model.FileModel
import org.monora.uprotocol.client.android.util.Progress
import org.monora.uprotocol.client.android.util.Transfers
import org.monora.uprotocol.core.protocol.Direction
import java.io.File
import javax.inject.Inject
import kotlin.random.Random
@AndroidEntryPoint
class PrepareIndexFragment : BottomSheetDialogFragment() {
private val viewModel: PrepareIndexViewModel by viewModels()
private val contentBrowserViewModel: ContentBrowserViewModel by activityViewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.layout_prepare_index, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.state.observe(viewLifecycleOwner) {
when (it) {
is PreparationState.Preparing -> {
}
is PreparationState.Ready -> {
contentBrowserViewModel.items = it.groupId to it.list
findNavController().navigate(
PrepareIndexFragmentDirections.actionPrepareIndexFragmentToNavPickClient()
)
}
}
}
}
}
@HiltViewModel
class PrepareIndexViewModel @Inject internal constructor(
@ApplicationContext context: Context,
private val selectionRepository: SelectionRepository,
) : ViewModel() {
private val _state = MutableLiveData<PreparationState>()
val state = liveData {
emitSource(_state)
}
init {
viewModelScope.launch(Dispatchers.IO) {
_state.postValue(PreparationState.Preparing)
val list = selectionRepository.getSelections()
val groupId = Random.nextLong()
val items = mutableListOf<UTransferItem>()
val progress = Progress(list.size)
val direction = Direction.Outgoing
list.forEach {
if (it is FileModel) {
Transfers.createStructure(context, items, progress, groupId, it.file) { _, _ ->
}
} else if (it is App) {
val base = DocumentFile.fromFile(File(it.info.sourceDir))
val hasSplit = Build.VERSION.SDK_INT >= 21 && it.info.splitSourceDirs != null
val name = "${it.label}_${it.versionName}"
val baseName = if (hasSplit) base.getName() else "$name.apk"
val directory = if (hasSplit) name else null
progress.index += 1
items.add(
UTransferItem(
progress.index.toLong(),
groupId,
baseName,
base.getType(),
base.getLength(),
directory,
base.getUri().toString(),
direction,
)
)
if (Build.VERSION.SDK_INT >= 21 && hasSplit) {
it.info.splitSourceDirs?.forEach { splitPath ->
progress.index += 1
val split = DocumentFile.fromFile(File(splitPath))
val id = progress.index.toLong()
items.add(
UTransferItem(
id,
groupId,
split.getName(),
split.getType(),
split.getLength(),
directory,
split.getUri().toString(),
direction,
)
)
}
}
} else {
progress.index += 1
val id = progress.index.toLong()
val item = when (it) {
is Song -> UTransferItem(
id, groupId, it.displayName, it.mimeType, it.size, null, it.uri.toString(), direction
)
is Image -> UTransferItem(
id, groupId, it.displayName, it.mimeType, it.size, null, it.uri.toString(), direction
)
is Video -> UTransferItem(
id, groupId, it.displayName, it.mimeType, it.size, null, it.uri.toString(), direction
)
else -> {
progress.index -= 1
Log.e(TAG, "Unknown object type was given ${it.javaClass.simpleName}")
return@forEach
}
}
items.add(item)
}
}
_state.postValue(PreparationState.Ready(groupId, items))
}
}
companion object {
private const val TAG = "PrepareIndexViewModel"
}
}
sealed class PreparationState {
object Preparing : PreparationState()
class Ready(val groupId: Long, val list: List<UTransferItem>) : PreparationState()
}
| gpl-2.0 | 1c5356ebbd246dac54b62d11b2870bfe | 39.17801 | 116 | 0.585874 | 5.362683 | false | false | false | false |
leafclick/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/uploader/EventLogExternalUploader.kt | 1 | 5373 | // 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.internal.statistic.eventLog.uploader
import com.intellij.internal.statistic.eventLog.*
import com.intellij.internal.statistic.uploader.EventLogUploaderOptions.*
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ArrayUtil
import com.intellij.util.io.exists
import java.io.File
import java.nio.file.Paths
object EventLogExternalUploader {
private val LOG = Logger.getInstance(EventLogExternalUploader.javaClass)
private const val UPLOADER_MAIN_CLASS = "com.intellij.internal.statistic.uploader.EventLogUploader"
fun startExternalUpload(recorderId: String, isTest: Boolean) {
val recorder = EventLogInternalRecorderConfig(recorderId)
if (!recorder.isSendEnabled()) {
LOG.info("Don't start external process because sending logs is disabled")
return
}
val device = DeviceConfiguration(EventLogConfiguration.deviceId, EventLogConfiguration.bucket)
val application = EventLogInternalApplicationInfo(isTest)
try {
val command = prepareUploadCommand(device, recorder, application)
Runtime.getRuntime().exec(command)
LOG.info("Started external process for uploading event log")
}
catch (e: EventLogUploadException) {
LOG.info(e)
}
}
private fun prepareUploadCommand(device: DeviceConfiguration,
recorder: EventLogRecorderConfig,
applicationInfo: EventLogApplicationInfo): Array<out String> {
val logFiles = logsToSend(recorder)
if (logFiles.isEmpty()) {
throw EventLogUploadException("No available logs to send")
}
val tempDir = getTempDir()
val uploader = findUploader()
val libs = findLibsByPrefixes(
"kotlin-stdlib", "gson", "commons-logging", "log4j.jar", "httpclient", "httpcore", "httpmime", "jdom.jar", "annotations.jar"
)
val libPaths = libs.map { it.path }
val classpath = joinAsClasspath(libPaths, uploader)
val args = arrayListOf<String>()
val java = findJavaHome()
args += File(java, if (SystemInfo.isWindows) "bin\\java.exe" else "bin/java").path
addArgument(args, "-cp", classpath)
args += "-Djava.io.tmpdir=${tempDir.path}"
args += UPLOADER_MAIN_CLASS
addArgument(args, IDE_TOKEN, Paths.get(PathManager.getSystemPath(), "token").toAbsolutePath().toString())
addArgument(args, RECORDER_OPTION, recorder.getRecorderId())
addArgument(args, LOGS_OPTION, logFiles.joinToString(separator = File.pathSeparator))
addArgument(args, DEVICE_OPTION, device.deviceId)
addArgument(args, BUCKET_OPTION, device.bucket.toString())
addArgument(args, URL_OPTION, applicationInfo.templateUrl)
addArgument(args, PRODUCT_OPTION, applicationInfo.productCode)
addArgument(args, USER_AGENT_OPTION, applicationInfo.userAgent)
if (applicationInfo.isInternal) {
args += INTERNAL_OPTION
}
if (applicationInfo.isTest) {
args += TEST_OPTION
}
return ArrayUtil.toStringArray(args)
}
private fun addArgument(args: ArrayList<String>, name: String, value: String) {
args += name
args += value
}
private fun logsToSend(recorder: EventLogRecorderConfig): List<String> {
val dir = recorder.getLogFilesProvider().getLogFilesDir()
if (dir != null && dir.exists()) {
return dir.toFile().listFiles()?.take(5)?.map { it.absolutePath } ?: emptyList()
}
return emptyList()
}
private fun joinAsClasspath(libCopies: List<String>, uploaderCopy: File): String {
if (libCopies.isEmpty()) {
return uploaderCopy.path
}
val libClassPath = libCopies.joinToString(separator = File.pathSeparator)
return "$libClassPath${File.pathSeparator}${uploaderCopy.path}"
}
private fun findUploader(): File {
val uploader = File(PathManager.getLibPath(), "platform-statistics-uploader.jar")
if (uploader.exists() && !uploader.isDirectory) {
return uploader
}
//consider local debug IDE case
val localBuild = File(PathManager.getHomePath(), "out/artifacts/statistics-uploader.jar")
if (localBuild.exists() && !localBuild.isDirectory) {
return localBuild
}
throw EventLogUploadException("Cannot find uploader jar")
}
private fun findJavaHome(): String {
return System.getProperty("java.home")
}
private fun findLibsByPrefixes(vararg prefixes: String): Array<File> {
val lib = PathManager.getLibPath()
val libFiles = File(lib).listFiles { file -> startsWithAny(file.name, prefixes) }
if (libFiles == null || libFiles.isEmpty()) {
throw EventLogUploadException("Cannot find libraries from dependency for event log uploader")
}
return libFiles
}
private fun startsWithAny(str: String, prefixes: Array<out String>): Boolean {
for (prefix in prefixes) {
if (str.startsWith(prefix)) return true
}
return false
}
private fun getTempDir(): File {
val tempDir = File(PathManager.getTempPath(), "statistics-uploader")
if (!(tempDir.exists() || tempDir.mkdirs())) {
throw EventLogUploadException("Cannot create temp directory: $tempDir")
}
return tempDir
}
}
| apache-2.0 | 7f5a576042dfb60aae71d492633d0d3c | 36.3125 | 140 | 0.709473 | 4.364744 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-serialization/src/main/kotlin/slatekit/serialization/deserializer/Deserializers.kt | 1 | 6633 | package slatekit.serialization.deserializer
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import slatekit.common.convert.Conversions
import slatekit.common.crypto.*
import slatekit.requests.Request
import slatekit.meta.*
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KType
class Deserializers(conversion: Conversion, enc: Encryptor?, decoders:Map<String, JSONTransformer<*>>) {
val basic = BasicDeserializer(conversion, enc)
val lists = ListDeserializer(conversion, enc)
val maps = MapDeserializer(conversion, enc)
val enums = EnumDeserializer(conversion, enc)
val smart = SmartValueDeserializer(conversion, enc)
val objs = ObjectDeserializer(conversion, enc)
val custom = CustomDeserializer(conversion, enc, decoders)
}
class BasicDeserializer(override val conversion: Conversion,
override val enc: Encryptor?) : DeserializerPart, DeserializeSupport {
override fun deserialize(context:Any, parent:Any, paramValue:Any?, paramName:String, paramType: KType):Any? {
val result = when (paramType.classifier) {
// Basic
KTypes.KStringType.classifier -> paramValue?.let { Conversions.handleString(it) }
KTypes.KBoolType.classifier -> paramValue?.toString()?.toBoolean()
KTypes.KShortType.classifier -> paramValue?.toString()?.toShort()
KTypes.KIntType.classifier -> paramValue?.toString()?.toInt()
KTypes.KLongType.classifier -> paramValue?.toString()?.toLong()
KTypes.KFloatType.classifier -> paramValue?.toString()?.toFloat()
KTypes.KDoubleType.classifier -> paramValue?.toString()?.toDouble()
// Dates
KTypes.KLocalDateType.classifier -> paramValue?.let { Conversions.toLocalDate(it as String) }
KTypes.KLocalTimeType.classifier -> paramValue?.let { Conversions.toLocalTime(it as String) }
KTypes.KLocalDateTimeType.classifier -> paramValue?.let { Conversions.toLocalDateTime(it as String) }
KTypes.KZonedDateTimeType.classifier -> paramValue?.let { Conversions.toZonedDateTime(it as String) }
KTypes.KDateTimeType.classifier -> paramValue?.let { Conversions.toDateTime(it as String) }
// Encrypted
KTypes.KDecIntType.classifier -> enc?.let { e -> EncInt(paramValue as String, e.decrypt(paramValue).toInt()) } ?: EncInt("", 0)
KTypes.KDecLongType.classifier -> enc?.let { e -> EncLong(paramValue as String, e.decrypt(paramValue).toLong()) } ?: EncLong("", 0L)
KTypes.KDecDoubleType.classifier -> enc?.let { e -> EncDouble(paramValue as String, e.decrypt(paramValue).toDouble()) } ?: EncDouble("", 0.0)
KTypes.KDecStringType.classifier -> enc?.let { e -> EncString(paramValue as String, e.decrypt(paramValue)) } ?: EncString("", "")
// Slate Kit
KTypes.KVarsType.classifier -> paramValue?.let { Conversions.toVars(it) }
KTypes.KDocType.classifier -> conversion.toDoc(context as Request, paramName)
KTypes.KUUIDType.classifier -> UUID.fromString(paramValue.toString())
else -> null
}
return result
}
}
class ListDeserializer(override val conversion: Conversion,
override val enc: Encryptor?) : DeserializerPart, DeserializeSupport {
override fun deserialize(context:Any, parent:Any, paramValue:Any?, paramName:String, paramType: KType):Any? {
val listType = paramType.arguments[0]!!.type!!
return when (paramValue) {
is JSONArray -> conversion.toList(paramValue, paramName, listType)
else -> handle(paramValue, listOf<Any>()) { listOf<Any>() } as List<*>
}
}
}
class MapDeserializer(override val conversion: Conversion,
override val enc: Encryptor?) : DeserializerPart, DeserializeSupport {
override fun deserialize(context:Any, parent:Any, paramValue:Any?, paramName:String, paramType: KType):Any? {
val tpeKey = paramType.arguments[0].type!!
val tpeVal = paramType.arguments[1].type!!
val emptyMap = mapOf<Any, Any>()
val items = when (paramValue) {
is JSONObject -> conversion.toMap(paramValue, paramName, tpeKey, tpeVal)
else -> handle(paramValue, emptyMap) { emptyMap } as Map<*, *>
}
return items
}
}
class EnumDeserializer(override val conversion: Conversion,
override val enc: Encryptor?) : DeserializerPart, DeserializeSupport {
override fun deserialize(context:Any, parent:Any, paramValue:Any?, paramName:String, paramType: KType):Any? {
val cls = paramType.classifier as KClass<*>
val result = Reflector.getEnumValue(cls, paramValue)
return result
}
}
class SmartValueDeserializer(override val conversion: Conversion,
override val enc: Encryptor?) : DeserializerPart, DeserializeSupport {
override fun deserialize(context:Any, parent:Any, paramValue:Any?, paramName:String, paramType: KType):Any? {
val result = handle(paramValue, null) { conversion.toSmartValue(paramValue?.toString() ?: "", paramName, paramType) }
return result
}
}
class ObjectDeserializer(override val conversion: Conversion,
override val enc: Encryptor?) : DeserializerPart, DeserializeSupport {
override fun deserialize(context:Any, parent:Any, paramValue:Any?, paramName:String, paramType: KType):Any? {
return when (paramValue) {
is JSONObject -> conversion.toObject(paramValue, paramName, paramType)
else -> handle(paramValue, null) { null }
}
}
}
class CustomDeserializer(override val conversion: Conversion,
override val enc: Encryptor?,
val decoders: Map<String, JSONTransformer<*>> = mapOf()) : DeserializerPart, DeserializeSupport {
override fun deserialize(context:Any, parent:Any, paramValue:Any?, paramName:String, paramType: KType):Any? {
val cls = paramType.classifier as KClass<*>
val fullName = cls.qualifiedName
val decoder = decoders[fullName]
val json = when(paramValue) {
is JSONObject -> paramValue
else -> parent as JSONObject
}
val result = when(decoder) {
is JSONRestoreWithContext<*> -> {
decoder.restore(context, json, paramName)
}
else -> {
decoder?.restore(json)
}
}
return result
}
} | apache-2.0 | 8757c7d6f75719eb32d2c722374d45eb | 43.52349 | 153 | 0.656867 | 4.6223 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Results.kt | 1 | 18294 | /**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
//</doc:import_required>
//<doc:import_examples>
import slatekit.common.checks.Checks
import slatekit.examples.common.User
import slatekit.results.*
import slatekit.results.Try
import slatekit.results.Success
import slatekit.results.Failure
import slatekit.results.builders.Notices
import slatekit.results.builders.OutcomeBuilder
import slatekit.results.builders.Outcomes
import slatekit.results.builders.Tries
import java.util.*
//</doc:import_examples>
class Example_Results : Command("results"), OutcomeBuilder {
//<doc:examples>
fun usage() {
// Create success explicitly
val start: Result<Int, Err> = Success(10)
// Properties
println(start.success) // true
println(start.status.code) // Codes.SUCCESS.code
println(start.status.desc) // Codes.SUCCESS.msg
// Safely operate on values with map/flatMap
val addResult = start.map { it + 1 }
val subResult = start.flatMap { Success(it - 1) }
// Check values
println(addResult.contains(11))
println(addResult.exists { it == 11 })
// Get values
println(addResult.getOrNull())
println(addResult.getOrElse { 0 })
// On conditions
subResult.onSuccess { println(it) } // 9
subResult.onFailure { println(it) } // N/A
// Pattern match on branches ( Success / Failure )
when (addResult) {
is Success -> println("Value is : ${addResult.value}") // 11
is Failure -> println("Error is : ${addResult.error}") // N/A
}
// Pattern match on status
when (addResult.status) {
is Passed.Succeeded -> println(addResult.desc)
is Passed.Pending -> println(addResult.desc)
is Failed.Denied -> println(addResult.desc)
is Failed.Invalid -> println(addResult.desc)
is Failed.Ignored -> println(addResult.desc)
is Failed.Errored -> println(addResult.desc)
is Failed.Unknown -> println(addResult.desc)
}
}
fun creation() {
// Success: Straight-forward
val result = Success(42)
// Success referenced as base type Result<Int, Err>
val result1a: Result<Int, Err> = Success(42)
// Success created with status codes / messages
val result1b = Success(42, status = Codes.SUCCESS)
val result1c = Success(42, msg = "Successfully processed")
val result1d = Success(42, msg = "Successfully processed", code = 200)
// Failure
val result1e = Failure(Err.of("Invalid email"))
// Failure referenced as base type Result<Int, Err>
val result1f: Result<Int, Err> = Failure(Err.of("Invalid email"))
// Failure created with status codes / messages
val result1g = Failure(Err.of("Invalid email"), Codes.INVALID)
val result1h = Failure(Err.of("Invalid email"), msg = "Invalid inputs")
val result1i = Failure(Err.of("Invalid email"), msg = "Invalid inputs", code = Codes.INVALID.code)
}
fun get() {
// Create
val result:Result<Int, Err> = Success(42)
// Get value or default to null
val value1:Int? = result.getOrNull()
// Get value or default with value provided
val value2:Int = result.getOrElse { 0 }
// Map over the value
val op1 = result.map { it + 1 }
// Flat Map over the value
val op2 = result.flatMap { Success(it + 1 ) }
// Fold to transform both the success / failure into something else ( e.g. string here )
val value3:String = result.fold({ "Succeeded : $it" }, {err -> "Failed : ${err.msg}" })
// Get value if success
result.onSuccess { println("Number = $it") }
// Get error if failure
result.onFailure { println("Error is ${it.msg}") }
// Pattern match
when(result) {
is Success -> println(result.value) // 42
is Failure -> println(result.error) // Err
}
}
fun check(){
val result:Result<Int,Err> = Success(42)
// Check if the value matches the criteria
result.exists { it == 42 } // true
// Check if the value matches the one provided
result.contains(2) // false
// Pattern match 1: "Top-Level" on Success/Failure (Binary true / false )
when(result) {
is Success -> println(result.value) // 42
is Failure -> println(result.error) // Err
}
// Pattern match 2: "Mid-level" on Status ( 7 logical groups )
// NOTE: The status property is available on both the Success/Failure branches
when(result.status) {
is Passed.Succeeded -> println(result.desc) // Success!
is Passed.Pending -> println(result.desc) // Success, but in progress
is Failed.Denied -> println(result.desc) // Security related
is Failed.Invalid -> println(result.desc) // Bad inputs / data
is Failed.Ignored -> println(result.desc) // Ignored for processing
is Failed.Errored -> println(result.desc) // Expected errors
is Failed.Unknown -> println(result.desc) // Unexpected errors
}
// Pattern match 3: "Low-Level" on numeric code
when(result.status.code) {
Codes.SUCCESS.code -> println("OK")
Codes.QUEUED.code -> println("Pending")
Codes.UPDATED.code -> println("User updated")
Codes.DENIED.code -> println("Log in again")
Codes.DEPRECATED.code -> println("No longer supported")
Codes.CONFLICT.code -> println("Email already exists")
else -> println("Other!!")
}
}
fun errors() {
// Build Err from various sources using convenience methods
// From simple string
val err1 = Err.of("Invalid email")
// From Exception
val err2 = Err.ex(Exception("Invalid email"))
// From field name / value
val err3 = Err.on("email", "abc123@", "Invalid email")
// From status code
val err4 = Err.code(Codes.INVALID)
// From list of error strings
val err5 = Err.list(listOf(
"username must be at least 8 chars",
"username must have 1 UPPERCASE letter"),
"Username is invalid")
// From list of Err types
val err6 = Err.ErrorList(listOf(
Err.on("email", "abc123 is not a valid email", "Invalid email"),
Err.on("phone", "123-456-789 is not a valid U.S. phone", "Invalid phone")
), "Please correct the errors")
// Create the Failure branch from the errors
val result:Result<UUID, Err> = Failure(err6)
}
fun aliases1(){
val result:Try<Int> = Success( "1".toInt() )
println(result)
}
fun aliases(){
// Build results ( imagine this is some user registration flow )
// Try<T> = Result<T, Exception>
val tried1 = Tries.success( User() )
val tried2 = Tries.denied<User>("Phone exists")
val tried3 = Tries.invalid<User>("Email required")
// Outcome<T> = Result<T, Err>
val outcome1 = Outcomes.success( User() )
val outcome2 = Outcomes.denied<User>("Phone exists")
val outcome3 = Outcomes.invalid<User>("Email required" )
// Notice<T> = Result<T, String>
val notice1 = Notices.success( User() )
val notice2 = Notices.denied<User>("Phone exists")
val notice3 = Notices.invalid<User>("Email required" )
// Validated<T> = Result<T, ErrorList>
val res4:Validated<String> = Failure(Err.ErrorList(listOf(
Err.on("email", "abc123 is not a valid email", "Invalid email"),
Err.on("phone", "123-456-789 is not a valid U.S. phone", "Invalid phone")
), "Please correct the errors"))
}
fun builders(){
// Outcome<Int> = Result<Int, Err>
val res1 = Outcomes.success(1, "Created User with id 1")
val res2 = Outcomes.denied<Int>("Not authorized to send alerts")
val res3 = Outcomes.ignored<Int>("Not a beta tester")
val res4 = Outcomes.invalid<Int>("Email is invalid")
val res5 = Outcomes.conflict<Int>("Duplicate email found")
val res6 = Outcomes.errored<Int>("Phone is invalid")
val res7 = Outcomes.unexpected<Int>("Unable to send confirmation code")
}
fun tries(){
// Try<Long> = Result<Long, Exception>
val converted1:Try<Long> = Tries.of { "1".toLong() }
// DeniedException will checked and converted to Status.Denied
val converted2:Try<Long> = Tries.of<Long> {
throw DeniedException("Token invalid")
}
}
fun validated(){
// Model to validate
val user = User(0, "batman_gotham", "batman", "", true, 34)
// Validated<User> = Result<User, Err.ErrorList>
val validated = Checks.collect<User,String, Err>(user) {
listOf(
isNotEmpty(user.firstName),
isNotEmpty(user.lastName),
isEmail(user.email)
)
}
// Print first error
when(validated) {
is Success -> println("User model is valid")
is Failure -> println("User model failed with : " + validated.error.errors.first().msg)
}
}
fun http(){
// Simulate a denied exception ( Security related )
val denied:Outcome<Long> = Outcomes.denied("Access token has expired")
// Convert it to HTTP
// This returns back the HTTP code + original Status
val code:Pair<Int, Status> = Codes.toHttp(denied.status)
println(code.first) // 401
}
//</doc:examples>
override fun execute(request: CommandRequest): Try<Any> {
//<doc:examples>
// The Result<S,F> class is a way to model successes and failures.
// Design: This is essentially a specialized Either[L,R] with optional integer code/string message.
//
// FIELDS:
// 1. data : [required] - data being returned in a success case
// 2. success : [derived ] - success/ failure flag based on Success/Failure branch
// 3. code : [optional] - integer code to describe error
// 4. message : [optional] - string to represent message/error for Success/Failure
// NOTES:
// This is essentially a specialized Either[L,R] with optional integer code/string message.
// - The result is inspired by Scala's Option[T] and Try/Success/Failure
// - It provides a status code as an integer
// - The result has 2 branches ( Success and Failure )
// - You can supply a type parameter for the data
// - Convenience functions are available to mimick HTTP Status Codes( see samples below ).
// - HTTP status are fairly general purpose and can be used outside of an http context.
// However, you can supply and use your own status codes if needed.
// Create success explicity
val result: Result<Int, Err> = Success(1)
// Properties
println(result.success) // true
println(result.status.code) // Codes.SUCCESS.code
println(result.status.desc) // Codes.SUCCESS.msg
// Get value or default to null
val value1: Int? = result.getOrNull()
// Get value or default with value provided
val value2: Int = result.getOrElse { 0 }
// Map over the value
val op1: Result<Int, Err> = result.map { it + 1 }
// Flat Map over the value
val op2: Result<Int, Err> = result.flatMap { Success(it + 1) }
// Fold to transform both the success / failure into something else ( e.g. string here )
val value3: String = result.fold({ "Succeeded : $it" }, { err -> "Failed : ${err.msg}" })
// Check if the value matches the criteria
result.exists { it == 1 } // true
// Check if the value matches the one provided
result.contains(2) // false
// Get value if success
result.onSuccess { println("Number = $it") }
// Get error if failure
result.onFailure { println("Error is ${it.msg}") }
// Pattern match
when (result) {
is Success -> println(result.value) // 1
is Failure -> println(result.error) // Err
}
val result1b = Success(42, msg = "Successfully processed")
val result1c = Success(42, msg = "Successfully processed", code = 200)
val result1d = Outcomes.success(42, Codes.SUCCESS)
// Create failure explicitly
val result1e: Result<Int, Err> = Failure(Err.of("Invalid email"))
val result1f = Failure(Err.of("Invalid email"), msg = "Invalid inputs")
val result1g = Failure(Err.of("Invalid email"), msg = "Invalid inputs", code = Codes.INVALID.code)
val result1h = Outcomes.invalid<Int>(Err.of("Invalid email"), Codes.INVALID)
// PATTERN MATCH 1: Success / Failure
when (result) {
is Success -> println(result.value) // 1
is Failure -> println(result.error) // Err
}
// PATTERN MATCH 2: On status ( logical categories of statuses )
// NOTE: The status property is available on both the Success/Failure branches
when(result) {
is Success -> when(result.status) {
is Passed.Succeeded -> println(result.desc)
is Passed.Pending -> println(result.desc)
}
is Failure -> when(result.status) {
is Failed.Denied -> println(result.desc)
is Failed.Invalid -> println(result.desc)
is Failed.Ignored -> println(result.desc)
is Failed.Errored -> println(result.desc)
is Failed.Unknown -> println(result.desc)
}
}
// PATTERN MATCH 3: On code
when (result.status.code) {
Codes.SUCCESS.code -> "OK"
Codes.QUEUED.code -> "Pending"
Codes.UPDATED.code -> "User updated"
Codes.DENIED.code -> "Log in again"
Codes.DEPRECATED.code -> "No longer supported"
Codes.CONFLICT.code -> "Email already exists"
else -> "Other!!"
}
// Explicitly build a result using the Failure "branch" of Result
val result2: Result<String, Exception> = Failure<Exception>(
error = IllegalArgumentException("user id"),
code = Codes.BAD_REQUEST.code,
msg = "user id not supplied"
)
// NOTES: ResultFuncs object contain methods to easily build up either
// success or failure results that align with Http Status codes.
// HTTP status codes are very general purpose with meaningful intents
// ( bad-request, unauthorized, unexpected, etc ), and since the
// Result class models success / failures, its useful to build up
// results from from a server layer and pass them back up to the top
// level controller / api layer.
// CASE 1: Success ( 200 )
// NOTE:
// 1. The ResultMsg is just a type alias for Result<S, String>
// representing the error type as a simple string.
// 2. There is Try ( also a type alias ) for Result<S, Exception>
// representing the error type as an Exception
val res1: Notice<Int> = Success(123456, msg = "user created")
printResult(res1)
// CASE 2: Failure ( 400 ) with message and ref tag
val res2a = errored<String>(msg = "invalid email")
printResult(res2a)
// CASE 2: Failure ( 400 ) with data ( user ), message, and ref tag
val res2b = errored<String>(msg = "invalid email")
printResult(res2b)
// CASE 4: Unauthorized ( 401 )
val res3 = denied<String>(msg = "invalid email")
printResult(res3)
// CASE 5: Unexpected ( 500 )
val res4 = Tries.unexpected<String>(Err.of("Invalid email"))
printResult(res4)
// CASE 6: Conflict ( 409 )
val res5 = errored<String>(Codes.CONFLICT)
printResult(res5)
// CASE 7: Not found
val res6 = invalid<String>(Codes.NOT_FOUND)
printResult(res6)
// CASE 8: Not available
val res7 = errored<String>(Codes.TIMEOUT)
printResult(res7)
// CASE 9: Build based on the Err model
// This allows you to have pre-defined list of error infos to refer to
//val failure:Result<Int, Err> = failure( ErrInfo(400, "Invalid user", null) )
//</doc:examples>
return Success("")
}
fun printResult(result: Result<*, *>): Unit {
println("success: " + result.success)
println("message: " + result.desc)
println("code : " + result.code)
println()
println()
}
/*
//<doc:output>
{{< highlight bat >}}
success: true
message: user created
code : 200
data : 123456
ref : promoCode:ny001
success: false
message: invalid email
code : 400
data : null
ref : 23SKASDF23
success: false
message: invalid email
code : 401
data : null
ref :
success: false
message: invalid email
code : 500
data : null
ref :
success: false
message: item already exists
code : 409
data : null
ref :
success: false
message: action not found
code : 404
data : null
ref :
success: false
message: operation currently unavailable
code : 503
data : null
ref :
```
//</doc:output>
*/
}
| apache-2.0 | 6de32c441fc2646b70ec4c35b4ec391f | 32.877778 | 107 | 0.586422 | 4.247504 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/filter/adapter/SecurityAdapterTest.kt | 1 | 3487 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.filter.adapter
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.vrem.wifianalyzer.R
import com.vrem.wifianalyzer.settings.Settings
import com.vrem.wifianalyzer.wifi.model.Security
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
class SecurityAdapterTest {
private val settings: Settings = mock()
private val fixture = SecurityAdapter(Security.values().toSet())
@After
fun tearDown() {
verifyNoMoreInteractions(settings)
}
@Test
fun testIsActive() {
assertFalse(fixture.isActive())
}
@Test
fun testIsActiveWithChanges() {
// setup
fixture.toggle(Security.WPA)
// execute & validate
assertTrue(fixture.isActive())
}
@Test
fun testGetValues() {
// setup
val expected = Security.values()
// execute
val actual = fixture.selections
// validate
assertTrue(actual.containsAll(expected.toList()))
}
@Test
fun testGetValuesDefault() {
// setup
val expected = Security.values()
// execute
val actual = fixture.defaults
// validate
assertArrayEquals(expected, actual)
}
@Test
fun testToggleRemoves() {
// execute
val actual = fixture.toggle(Security.WEP)
// validate
assertTrue(actual)
assertFalse(fixture.contains(Security.WEP))
}
@Test
fun testToggleAdds() {
// setup
fixture.toggle(Security.WPA)
// execute
val actual = fixture.toggle(Security.WPA)
// validate
assertTrue(actual)
assertTrue(fixture.contains(Security.WPA))
}
@Test
fun testRemovingAllWillNotRemoveLast() {
// setup
val values: Set<Security> = Security.values().toSet()
// execute
values.forEach { fixture.toggle(it) }
// validate
values.forEach { fixture.contains(it) }
assertTrue(fixture.contains(values.last()))
}
@Test
fun testGetColorWithExisting() {
// execute & validate
assertEquals(R.color.selected, fixture.color(Security.WPA))
}
@Test
fun testGetColorWithNonExisting() {
// setup
fixture.toggle(Security.WPA)
// execute & validate
assertEquals(R.color.regular, fixture.color(Security.WPA))
}
@Test
fun testSave() {
// setup
val expected = fixture.selections
// execute
fixture.save(settings)
// validate
verify(settings).saveSecurities(expected)
}
} | gpl-3.0 | 9cd909da8e53c03bb52cef102ee5747a | 26.464567 | 90 | 0.650129 | 4.53446 | false | true | false | false |
leafclick/intellij-community | platform/workspaceModel-ide/src/com/intellij/workspace/ide/WorkspaceModelCacheImpl.kt | 1 | 5909 | // 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.workspace.ide
import com.google.common.base.Stopwatch
import com.google.common.hash.Hashing
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.pooledThreadSingleAlarm
import com.intellij.workspace.api.*
import com.intellij.workspace.bracket
import org.jetbrains.annotations.ApiStatus
import java.io.File
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.concurrent.atomic.AtomicBoolean
@ApiStatus.Internal
internal class WorkspaceModelCacheImpl(private val project: Project, parentDisposable: Disposable): Disposable {
private val LOG = Logger.getInstance(javaClass)
private val cacheFile: File
private val serializer: EntityStorageSerializer = KryoEntityStorageSerializer(
PluginAwareEntityTypesResolver)
init {
Disposer.register(parentDisposable, this)
val hasher = Hashing.sha256().newHasher()
project.basePath?.let { hasher.putString(it, Charsets.UTF_8) }
project.projectFilePath?.let { hasher.putString(it, Charsets.UTF_8) }
hasher.putString(project.locationHash, Charsets.UTF_8)
hasher.putString(serializer.javaClass.name, Charsets.UTF_8)
hasher.putString(serializer.serializerDataFormatVersion, Charsets.UTF_8)
cacheFile = File(cacheDir, hasher.hash().toString().substring(0, 20) + ".data")
LOG.info("Project Model Cache at $cacheFile")
project.messageBus.connect(this).subscribe(WorkspaceModelTopics.CHANGED, object : WorkspaceModelChangeListener {
override fun changed(event: EntityStoreChanged) = LOG.bracket("${javaClass.simpleName}.EntityStoreChange") {
saveAlarm.request()
}
})
}
private val saveAlarm = pooledThreadSingleAlarm(1000, this) {
val storage = WorkspaceModel.getInstance(project).entityStore.current
if (!cachesInvalidated.get()) {
LOG.info("Saving project model cache to $cacheFile")
saveCache(storage)
}
if (cachesInvalidated.get()) {
FileUtil.delete(cacheFile)
}
}
override fun dispose() = Unit
fun loadCache(): TypedEntityStorage? {
try {
if (!cacheFile.exists()) return null
if (invalidateCachesMarkerFile.exists() && cacheFile.lastModified() < invalidateCachesMarkerFile.lastModified()) {
LOG.info("Skipping project model cache since '$invalidateCachesMarkerFile' is present and newer than cache file '$cacheFile'")
FileUtil.delete(cacheFile)
return null
}
LOG.info("Loading project model cache from $cacheFile")
val stopWatch = Stopwatch.createStarted()
val builder = cacheFile.inputStream().use { serializer.deserializeCache(it) }
LOG.info("Loaded project model cache from $cacheFile in ${stopWatch.stop()}")
return builder
} catch (t: Throwable) {
LOG.warn("Could not deserialize project model cache from $cacheFile", t)
return null
}
}
// Serialize and atomically replace cacheFile. Delete temporary file in any cache to avoid junk in cache folder
private fun saveCache(storage: TypedEntityStorage) {
val tmpFile = FileUtil.createTempFile(cacheFile.parentFile, "cache", ".tmp")
try {
tmpFile.outputStream().use { serializer.serializeCache(it, storage) }
try {
Files.move(tmpFile.toPath(), cacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
}
catch (e: AtomicMoveNotSupportedException) {
LOG.warn(e)
Files.move(tmpFile.toPath(), cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
}
} finally {
tmpFile.delete()
}
}
private object PluginAwareEntityTypesResolver: EntityTypesResolver {
override fun getPluginId(clazz: Class<*>): String? = PluginManager.getPluginOrPlatformByClassName(clazz.name)?.idString
override fun resolveClass(name: String, pluginId: String?): Class<*> {
val id = pluginId?.let { PluginId.getId(it) }
val classloader = if (id == null) {
ApplicationManager::class.java.classLoader
} else {
val plugin = PluginManagerCore.getPlugin(id) ?: error("Could not resolve plugin by id '$pluginId' for type: $name")
plugin.pluginClassLoader ?: ApplicationManager::class.java.classLoader
}
return classloader.loadClass(name)
}
}
companion object {
private val LOG = logger<WorkspaceModelCacheImpl>()
private val cacheDir = appSystemDir.resolve("projectModelCache").toFile()
private val cachesInvalidated = AtomicBoolean(false)
private val invalidateCachesMarkerFile = File(cacheDir, ".invalidate")
fun invalidateCaches() {
LOG.info("Invalidating project model caches by creating $invalidateCachesMarkerFile")
cachesInvalidated.set(true)
try {
FileUtil.createDirectory(cacheDir)
FileUtil.writeToFile(invalidateCachesMarkerFile, System.currentTimeMillis().toString())
}
catch (t: Throwable) {
LOG.warn("Cannot update the invalidation marker file", t)
}
ApplicationManager.getApplication().executeOnPooledThread {
val filesToRemove = (cacheDir.listFiles() ?: emptyArray()).filter { it.isFile && !it.name.startsWith(".") }
FileUtil.asyncDelete(filesToRemove)
}
}
}
}
| apache-2.0 | 7c8cd89673aeb815079e8fe0b4a7e990 | 37.122581 | 140 | 0.733457 | 4.605612 | false | false | false | false |
Raizlabs/DBFlow | lib/src/main/kotlin/com/dbflow5/query/cache/ModelLruCache.kt | 1 | 1664 | package com.dbflow5.query.cache
import android.util.LruCache
import com.dbflow5.annotation.DEFAULT_CACHE_SIZE
/**
* Description: Provides an [android.util.LruCache] under its hood
* and provides synchronization mechanisms.
*/
class ModelLruCache<TModel>(size: Int)
: ModelCache<TModel, LruCache<Long, TModel>>(LruCache<Long, TModel>(size)) {
override fun addModel(id: Any?, model: TModel) {
throwIfNotNumber(id) {
synchronized(cache) {
cache.put(it.toLong(), model)
}
}
}
override fun removeModel(id: Any): TModel? = throwIfNotNumber(id) {
synchronized(cache) {
cache.remove(it.toLong())
}
}
override fun clear() {
synchronized(cache) {
cache.evictAll()
}
}
override fun setCacheSize(size: Int) {
cache.resize(size)
}
override fun get(id: Any?): TModel? = throwIfNotNumber(id) { cache[it.toLong()] }
private inline fun <R> throwIfNotNumber(id: Any?, fn: (Number) -> R) =
if (id is Number) {
fn(id)
} else {
throw IllegalArgumentException("A ModelLruCache must use an id that can cast to"
+ "a Number to convert it into a long")
}
companion object {
/**
* @param size The size, if less than or equal to 0 we set it to [DEFAULT_CACHE_SIZE].
*/
fun <TModel> newInstance(size: Int): ModelLruCache<TModel> {
var locSize = size
if (locSize <= 0) {
locSize = DEFAULT_CACHE_SIZE
}
return ModelLruCache(locSize)
}
}
}
| mit | 9d3d33dbb5402d5788a241b0dedce589 | 26.733333 | 94 | 0.570913 | 4.098522 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SdkComboBox.kt | 1 | 2794 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.Disposer
import com.intellij.ui.PopupMenuListenerAdapter
import javax.swing.event.PopupMenuEvent
class SdkComboBox(model: SdkComboBoxModel) : SdkComboBoxBase<SdkListItem>(model.modelBuilder) {
val model get() = getModel() as SdkComboBoxModel
override fun onModelUpdated(listModel: SdkListModel) {
setModel(model.copyAndSetListModel(listModel))
}
override fun getSelectedItem(): SdkListItem? {
return super.getSelectedItem() as SdkListItem?
}
override fun setSelectedItem(anObject: Any?) {
if (anObject is SdkListItem) {
if (myModel.executeAction(this, anObject, ::setSelectedItem)) {
return
}
}
when (anObject) {
is SdkListItem.ProjectSdkItem -> showProjectSdkItem()
is SdkListItem.InvalidSdkItem -> showInvalidSdkItem(anObject.sdkName)
is SdkListItem.NoneSdkItem -> showNoneSdkItem()
}
reloadModel()
super.setSelectedItem(anObject)
}
fun setSelectedSdk(sdk: Sdk?) {
reloadModel()
val sdkItem = sdk?.let { model.listModel.findSdkItem(sdk) }
selectedItem = when {
sdk == null -> showNoneSdkItem()
sdkItem == null -> showInvalidSdkItem(sdk.name)
else -> sdkItem
}
}
fun getSelectedSdk(): Sdk? {
return when (val it = selectedItem) {
is SdkListItem.ProjectSdkItem -> findSdk(model.sdksModel.projectSdk)
is SdkListItem.SdkItem -> findSdk(it.sdk)
else -> null
}
}
private fun findSdk(sdk: Sdk?) = model.sdksModel.findSdk(sdk)
init {
setModel(model)
setRenderer(SdkListPresenter { [email protected] })
addPopupMenuListener(ModelReloadProvider())
reloadModel()
}
private inner class ModelReloadProvider : PopupMenuListenerAdapter() {
private var disposable: Disposable? = null
override fun popupMenuWillBecomeVisible(e: PopupMenuEvent) {
val disposable = Disposer.newDisposable()
setReloadDisposable(disposable)
myModel.reloadActions()
myModel.detectItems(this@SdkComboBox, disposable)
}
override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent) {
setReloadDisposable(null)
}
private fun setReloadDisposable(parentDisposable: Disposable?) {
ApplicationManager.getApplication().assertIsDispatchThread()
parentDisposable?.let { Disposer.register(model.project, it) }
disposable?.let { Disposer.dispose(it) }
disposable = parentDisposable
}
}
} | apache-2.0 | c52a2ec0954a9c5c723e67785d70e646 | 31.882353 | 140 | 0.724409 | 4.535714 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/objc/ObjCCodeGenerator.kt | 1 | 1859 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.llvm.objc
import llvm.LLVMTypeRef
import llvm.LLVMValueRef
import org.jetbrains.kotlin.backend.konan.descriptors.stdlibModule
import org.jetbrains.kotlin.backend.konan.llvm.*
internal open class ObjCCodeGenerator(val codegen: CodeGenerator) {
val context = codegen.context
val dataGenerator = ObjCDataGenerator(codegen)
fun FunctionGenerationContext.genSelector(selector: String): LLVMValueRef {
val selectorRef = dataGenerator.genSelectorRef(selector)
// TODO: clang emits it with `invariant.load` metadata.
return load(selectorRef.llvm)
}
fun FunctionGenerationContext.genGetSystemClass(name: String): LLVMValueRef {
val classRef = dataGenerator.genClassRef(name)
return load(classRef.llvm)
}
private val objcMsgSend = constPointer(
context.llvm.externalFunction(
"objc_msgSend",
functionType(int8TypePtr, true, int8TypePtr, int8TypePtr),
context.stdlibModule.llvmSymbolOrigin
)
)
// TODO: this doesn't support stret.
fun msgSender(functionType: LLVMTypeRef): LLVMValueRef =
objcMsgSend.bitcast(pointerType(functionType)).llvm
}
| apache-2.0 | 3090ea8e338a9bacd06c704208fc4df9 | 35.45098 | 81 | 0.71759 | 4.36385 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/functions/localFunction.kt | 5 | 690 | fun IntRange.forEach(body : (Int) -> Unit) {
for(i in this) {
body(i)
}
}
fun box() : String {
var seed = 0
fun local(x: Int) {
fun deep() {
seed += x
}
fun deep2(x : Int) {
seed += x
}
fun Int.iter() {
seed += this
}
deep()
deep2(-x)
x.iter()
seed += x
}
for(i in 1..5) {
fun Int.iter() {
seed += this
}
local(i)
(-i).iter()
}
fun local2(y: Int) {
seed += y
}
(1..5).forEach {
local2(it)
}
return if(seed == 30) "OK" else seed.toString()
}
| apache-2.0 | 1f4c1bae7962e70af95f6c956554af36 | 14 | 51 | 0.357971 | 3.45 | false | false | false | false |
InventiDevelopment/AndroidSkeleton | app/src/main/java/cz/inventi/inventiskeleton/presentation/post/detail/PostDetailController.kt | 1 | 3057 | package cz.inventi.inventiskeleton.presentation.post.detail
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import cz.inventi.inventiskeleton.R
import cz.inventi.inventiskeleton.data.comment.Comment
import cz.inventi.inventiskeleton.data.post.Post
import cz.inventi.inventiskeleton.di.conductorlib.ConductorInjection
import cz.inventi.inventiskeleton.presentation.common.BaseController
import cz.inventi.inventiskeleton.presentation.common.bindView
import cz.inventi.inventiskeleton.utils.ImageUtils
import de.hdodenhof.circleimageview.CircleImageView
import javax.inject.Inject
/**
* Created by ecnill on 6/7/2017.
*/
class PostDetailController(bundle: Bundle) : BaseController<PostDetailView, PostDetailPresenter>(bundle), PostDetailView {
companion object {
val TAG: String = PostDetailController::class.java.name
fun instance(id: Int) : PostDetailController {
val args = Bundle()
args.putInt(TAG, id)
return PostDetailController(args)
}
}
@Inject lateinit var postDetailPresenter : PostDetailPresenter
val commentListAdapter = CommentListAdapter()
internal val postTitle: TextView by bindView(R.id.txt_post_title)
internal val postBody: TextView by bindView(R.id.txt_post_body)
internal val userProfilePicture: CircleImageView by bindView(R.id.img_user_avatar)
internal val btnShowComments: Button by bindView(R.id.btn_show_comments)
internal val listComments: RecyclerView by bindView(R.id.list_comments)
override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View {
return inflater.inflate(R.layout.controller_post_detail, container, false)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
ConductorInjection.inject(this)
postDetailPresenter.postId = args.getInt(TAG)
return super.onCreateView(inflater, container)
}
override fun onViewBind(view: View) {
btnShowComments.setOnClickListener { presenter.onShowMoreCommentsClicked() }
listComments.layoutManager = LinearLayoutManager(activity)
listComments.adapter = commentListAdapter
}
override fun createPresenter() = postDetailPresenter
override fun showDetailPost(post: Post) {
postTitle.text = post.title
postBody.text = post.body
presenter.showUserProfilePicture(post.userId)
showComments(post.comments)
}
override fun showProfilePicture(url: String) {
ImageUtils.downloadImageIntoImageView(activity, url, userProfilePicture)
}
override fun showComments(comments: List<Comment>) {
commentListAdapter.commentList = comments as MutableList<Comment>
}
override fun hideMoreCommentButton() {
btnShowComments.visibility = View.GONE
}
}
| apache-2.0 | f283194b6550e4498949747cfbaab39d | 35.831325 | 122 | 0.756951 | 4.603916 | false | false | false | false |
nuxusr/walkman | okreplay-sample/src/main/kotlin/okreplay/sample/MainActivity.kt | 1 | 2374 | package okreplay.sample
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.TextView
import com.google.common.base.Joiner
import com.google.common.collect.FluentIterable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class MainActivity : AppCompatActivity() {
private var textMessage: TextView? = null
private val itemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_activity -> return@OnNavigationItemSelectedListener goToActivity()
R.id.navigation_repositories -> return@OnNavigationItemSelectedListener goToRepositories()
R.id.navigation_organizations -> return@OnNavigationItemSelectedListener goToOrganizations()
}
false
}
private fun goToOrganizations(): Boolean {
textMessage!!.setText(R.string.title_organizations)
return true
}
private fun goToRepositories(): Boolean {
textMessage!!.setText(R.string.title_repositories)
val application = application as SampleApplication
application.graph.service.repos(USERNAME)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
textMessage!!.text =
"${getString(R.string.title_repositories)}: \n${it.body()?.let { it1 -> reposToString(it1) }}"
}, {
Log.e(TAG, "Request failed: ${it.message}", it)
})
return true
}
private fun reposToString(repositories: List<Repository>): String {
return Joiner.on("\n\n").join(FluentIterable.from(repositories)
.transform { r -> r!!.name() + ": " + r.description() }
.toList())
}
private fun goToActivity(): Boolean {
textMessage!!.setText(R.string.title_activity)
return true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textMessage = findViewById<TextView>(R.id.message)
val navigation = findViewById<BottomNavigationView>(R.id.navigation)
navigation.setOnNavigationItemSelectedListener(itemSelectedListener)
}
companion object {
private val TAG = "MainActivity"
private val USERNAME = "felipecsl"
}
}
| apache-2.0 | c64e8748b53dc40bbe4dbadfc5cd076e | 34.432836 | 108 | 0.727885 | 4.664047 | false | false | false | false |
SwiftPengu/ProbabilisticVulnerabilityAnalysis | IEAATParser/src/main/kotlin/nl/utwente/fmt/ieaatparser/prm/PVAExporter.kt | 1 | 1869 | package nl.utwente.fmt.ieaatparser.prm
import nl.utwente.fmt.ieaatparser.io.IEaatParts
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl
import pva.PVAContainer
import java.io.File
fun exportPVA(parts: IEaatParts, outFile: File? = null, overwrite: Boolean = false): PVAContainer {
println("Generating pva")
val startTime = System.currentTimeMillis()
if(!overwrite && outFile?.exists() ?: false){
println("Existing PVA found")
return importPVAfromXMI(outFile!!)
}else {
println("Reading the classmodel took ${System.currentTimeMillis() - startTime}ms")
//Transform to analysis metamodel
val parsedPRM = PRMTransformer(parts.classModel.classes).parse()
//Null-safe access to outFile
outFile?.let { outF ->
outF.delete()
exportPVAtoXMI(parsedPRM, outF)
}
println("Transforming the PRM took ${System.currentTimeMillis() - startTime}ms")
return parsedPRM
}
}
/**
* Exports the given model to the given file in the XMI format
*/
fun exportPVAtoXMI(model : PVAContainer, location: File) {
println("Exporting PVA to XMI")
println("Starting export...")
val rs = ResourceSetImpl()
val outURI = URI.createFileURI(location.absolutePath)
val res = rs.createResource(outURI).apply {
this.contents += model
}
println("Saving...")
location.outputStream().use { stream ->
res.save(stream, mapOf<Any, Any>())
}
println("Finished exporting")
}
fun importPVAfromXMI(location : File): PVAContainer {
println("Importing PVA...")
val rs = ResourceSetImpl()
val inURI = URI.createFileURI(location.absolutePath)
val result = rs.getResource(inURI,true).contents.first() as PVAContainer
println("Finished importing.")
return result
} | mit | 26ab3c36764e11ed443bb3660f8b48fa | 30.694915 | 99 | 0.680043 | 3.829918 | false | false | false | false |
firebase/firebase-android-sdk | firebase-perf/ktx/src/test/kotlin/com/google/firebase/perf/ktx/PerformanceTests.kt | 1 | 5003 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.perf.ktx
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.ktx.Firebase
import com.google.firebase.ktx.app
import com.google.firebase.ktx.initialize
import com.google.firebase.perf.FirebasePerformance
import com.google.firebase.perf.FirebasePerformance.HttpMethod
import com.google.firebase.perf.application.AppStateMonitor
import com.google.firebase.perf.metrics.HttpMetric
import com.google.firebase.perf.metrics.Trace
import com.google.firebase.perf.metrics.getTraceCounter
import com.google.firebase.perf.metrics.getTraceCounterCount
import com.google.firebase.perf.transport.TransportManager
import com.google.firebase.perf.util.Clock
import com.google.firebase.perf.util.Timer
import com.google.firebase.perf.v1.ApplicationProcessState
import com.google.firebase.perf.v1.NetworkRequestMetric
import com.google.firebase.perf.v1.TraceMetric
import com.google.firebase.platforminfo.UserAgentPublisher
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.nullable
import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito.doAnswer
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations.initMocks
import org.robolectric.RobolectricTestRunner
const val APP_ID = "APP_ID"
const val API_KEY = "API_KEY"
const val EXISTING_APP = "existing"
abstract class BaseTestCase {
@Before
open fun setUp() {
Firebase.initialize(
ApplicationProvider.getApplicationContext(),
FirebaseOptions.Builder()
.setApplicationId(APP_ID)
.setApiKey(API_KEY)
.setProjectId("123")
.build()
)
Firebase.initialize(
ApplicationProvider.getApplicationContext(),
FirebaseOptions.Builder()
.setApplicationId(APP_ID)
.setApiKey(API_KEY)
.setProjectId("123")
.build(),
EXISTING_APP
)
}
@After
fun cleanUp() {
FirebaseApp.clearInstancesForTest()
}
}
@RunWith(RobolectricTestRunner::class)
class PerformanceTests : BaseTestCase() {
@Mock lateinit var transportManagerMock: TransportManager
@Mock lateinit var timerMock: Timer
@Mock lateinit var mockTransportManager: TransportManager
@Mock lateinit var mockClock: Clock
@Mock lateinit var mockAppStateMonitor: AppStateMonitor
@Captor lateinit var argMetricCaptor: ArgumentCaptor<NetworkRequestMetric>
@Captor lateinit var argumentsCaptor: ArgumentCaptor<TraceMetric>
var currentTime: Long = 1
@Before
override fun setUp() {
super.setUp()
initMocks(this)
`when`(timerMock.getMicros()).thenReturn(1000L)
`when`(timerMock.getDurationMicros()).thenReturn(2000L).thenReturn(3000L)
doAnswer { Timer(currentTime) }.`when`(mockClock).getTime()
}
@Test
fun `performance should delegate to FirebasePerformance#getInstance()`() {
assertThat(Firebase.performance).isSameInstanceAs(FirebasePerformance.getInstance())
}
@Test
fun `httpMetric wrapper test `() {
val metric =
HttpMetric("https://www.google.com/", HttpMethod.GET, transportManagerMock, timerMock)
metric.trace { setHttpResponseCode(200) }
verify(transportManagerMock)
.log(
argMetricCaptor.capture(),
ArgumentMatchers.nullable(ApplicationProcessState::class.java)
)
val metricValue = argMetricCaptor.getValue()
assertThat(metricValue.getHttpResponseCode()).isEqualTo(200)
}
@Test
fun `trace wrapper test`() {
val trace = Trace("trace_1", mockTransportManager, mockClock, mockAppStateMonitor)
trace.trace { incrementMetric("metric_1", 5) }
assertThat(getTraceCounter(trace)).hasSize(1)
assertThat(getTraceCounterCount(trace, "metric_1")).isEqualTo(5)
verify(mockTransportManager)
.log(argumentsCaptor.capture(), nullable(ApplicationProcessState::class.java))
}
}
@RunWith(RobolectricTestRunner::class)
class LibraryVersionTest : BaseTestCase() {
@Test
fun `library version should be registered with runtime`() {
val publisher = Firebase.app.get(UserAgentPublisher::class.java)
assertThat(publisher.userAgent).contains(LIBRARY_NAME)
}
}
| apache-2.0 | 575a47f090b78e38149514bdedf08587 | 31.070513 | 92 | 0.763542 | 4.190117 | false | true | false | false |
charlesng/SampleAppArch | app/src/main/java/com/cn29/aac/repo/feedentry/FeedEntry.kt | 1 | 566 | package com.cn29.aac.repo.feedentry
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "feedEntrys")
data class FeedEntry(@ColumnInfo(name = "title") var title: String,
@ColumnInfo(name = "subtitle") var subTitle: String,
@ColumnInfo(name = "favourite") var isFavourite: Boolean = false,
@JvmField @ColumnInfo(name = "imageUrl") var imageUrl: String? = null,
@JvmField @PrimaryKey(autoGenerate = true) var uid: Int = 0) | apache-2.0 | 0c6526543b9ff4434c4a425a1ac8fc25 | 46.25 | 91 | 0.651943 | 4.421875 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/Equipment.kt | 1 | 675 | package com.habitrpg.android.habitica.models.inventory
import com.google.gson.annotations.SerializedName
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Equipment : RealmObject() {
var value: Double = 0.toDouble()
var type: String? = ""
@PrimaryKey
var key: String? = ""
var klass: String = ""
var specialClass: String = ""
var index: String = ""
var text: String = ""
var notes: String = ""
var con: Int = 0
var str: Int = 0
var per: Int = 0
@SerializedName("int")
var _int: Int = 0
var owned: Boolean? = null
var twoHanded = false
var mystery = ""
var gearSet = ""
}
| gpl-3.0 | fe7911f670c4f2f4cf16c42ed1096e85 | 23.107143 | 54 | 0.631111 | 3.75 | false | false | false | false |
korotyx/VirtualEntity | src/test/kotlin/com/korotyx/virtualentity/KotlinMain.kt | 1 | 718 | package com.korotyx.virtualentity
object KotlinMain
{
@JvmStatic
fun main(args: Array<String>)
{
val entity: ExampleEntity = ExampleEntity("UNIQUE_ID_EXAMPLE")
entity.create()
println("before: " + entity.serialize())
entity.value1 = "MyName"
entity.value2 = false
entity.value3 = arrayOf("Hello","World")
val generatedEntity : ExampleEntity = ExampleEntity.get("UNIQUE_ID_EXAMPLE")!!
println("after: " + generatedEntity.serialize())
val exampleCommand : ExampleCommand = ExampleCommand()
exampleCommand.getChildCommands()[0].getRelativePermission()
exampleCommand.getChildCommands()[0].getParamPermission()
}
} | mit | 49d4756bee05710d498e7c1f24ac741c | 30.26087 | 86 | 0.66156 | 4.515723 | false | false | false | false |
siosio/intellij-community | platform/util-ex/src/com/intellij/openapi/progress/progress2indicator.kt | 1 | 1623 | // 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 com.intellij.openapi.progress
import com.intellij.openapi.util.Computable
/**
* Installs thread-local [ProgressIndicator] which delegates its cancellation checks to a given [progress].
* This method should be used to call methods which rely on [ProgressManager.checkCanceled].
*/
fun <T> runUnderIndicator(progress: Progress, action: () -> T): T {
if (progress is JobProgress) {
// no sink because this `runUnderIndicator` overload is used with `Progress` instance,
// which is supposed to only handle the cancellation.
return runUnderIndicator(progress.job, null, action)
}
val indicator = object : EmptyProgressIndicatorBase() {
@Volatile
var myProgress: Progress? = null
override fun cancel() {
error("'cancel' must not be called from inside the action")
}
override fun isCanceled(): Boolean {
return myProgress?.isCancelled == true
}
}
try {
return ProgressManager.getInstance().runProcess(Computable {
// set progress inside runProcess to avoid cancelled indicator before even starting the computation
indicator.myProgress = progress
action()
}, indicator)
}
catch (pce: ProcessCanceledException) {
// if canceled, then the next line will throw CancellationException
progress.checkCancelled()
// no exception from previous line
// => progress was not canceled
// => PCE was thrown manually
// => treat it as any other exception
throw pce
}
}
| apache-2.0 | a5d3eabe11d2ade7d6057d4ffc659197 | 34.282609 | 140 | 0.710413 | 4.718023 | false | false | false | false |
lsmaira/gradle | buildSrc/subprojects/packaging/src/main/kotlin/org/gradle/gradlebuild/packaging/ClassGraph.kt | 2 | 2672 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.packaging
internal
class ClassGraph(
private val keepPackages: PackagePatterns,
private val unshadedPackages: PackagePatterns,
private val ignorePackages: PackagePatterns,
shadowPackage: String
) {
private
val classes: MutableMap<String, ClassDetails> = linkedMapOf()
val entryPoints: MutableSet<ClassDetails> = linkedSetOf()
internal
val shadowPackagePrefix =
if (shadowPackage.isEmpty()) ""
else shadowPackage.replace('.', '/') + "/"
operator fun get(className: String) =
classes.computeIfAbsent(className) {
val outputClassName = if (unshadedPackages.matches(className)) className else shadowPackagePrefix + className
ClassDetails(outputClassName).also { classDetails ->
if (keepPackages.matches(className) && !ignorePackages.matches(className)) {
entryPoints.add(classDetails)
}
}
}
fun getDependencies() = classes.map { it.value.outputClassFilename to it.value.dependencies.map { it.outputClassFilename } }.toMap()
}
internal
class ClassDetails(val outputClassName: String) {
var visited: Boolean = false
val dependencies: MutableSet<ClassDetails> = linkedSetOf()
val outputClassFilename
get() = "$outputClassName.class"
}
internal
class PackagePatterns(givenPrefixes: Set<String>) {
private
val prefixes: MutableSet<String> = hashSetOf()
private
val names: MutableSet<String> = hashSetOf()
init {
givenPrefixes.map { it.replace('.', '/') }.forEach { internalName ->
names.add(internalName)
prefixes.add("$internalName/")
}
}
fun matches(packageName: String): Boolean {
if (names.contains(packageName)) {
return true
}
for (prefix in prefixes) {
if (packageName.startsWith(prefix)) {
names.add(packageName)
return true
}
}
return false
}
}
| apache-2.0 | 984777c1e9bf1f03b8e8400fe413d1b1 | 29.022472 | 136 | 0.659057 | 4.831826 | false | false | false | false |
codurance/task-list | kotlin/src/main/java/com/codurance/training/tasks/TaskList.kt | 1 | 3809 | package com.codurance.training.tasks
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.util.*
class TaskList(private val `in`: BufferedReader, private val out: PrintWriter) : Runnable {
private val tasks = LinkedHashMap<String, MutableList<Task>>()
private var lastId: Long = 0
override fun run() {
while (true) {
out.print("> ")
out.flush()
val command: String
try {
command = `in`.readLine()
} catch (e: IOException) {
throw RuntimeException(e)
}
if (command == QUIT) {
break
}
execute(command)
}
}
private fun execute(commandLine: String) {
val commandRest = commandLine.split(" ".toRegex(), 2).toTypedArray()
val command = commandRest[0]
when (command) {
"show" -> show()
"add" -> add(commandRest[1])
"check" -> check(commandRest[1])
"uncheck" -> uncheck(commandRest[1])
"help" -> help()
else -> error(command)
}
}
private fun show() {
for ((key, value) in tasks) {
out.println(key)
for (task in value) {
out.printf(" [%c] %d: %s%n", if (task.isDone) 'x' else ' ', task.id, task.description)
}
out.println()
}
}
private fun add(commandLine: String) {
val subcommandRest = commandLine.split(" ".toRegex(), 2).toTypedArray()
val subcommand = subcommandRest[0]
if (subcommand == "project") {
addProject(subcommandRest[1])
} else if (subcommand == "task") {
val projectTask = subcommandRest[1].split(" ".toRegex(), 2).toTypedArray()
addTask(projectTask[0], projectTask[1])
}
}
private fun addProject(name: String) {
tasks[name] = ArrayList()
}
private fun addTask(project: String, description: String) {
val projectTasks = tasks[project]
if (projectTasks == null) {
out.printf("Could not find a project with the name \"%s\".", project)
out.println()
return
}
projectTasks.add(Task(nextId(), description, false))
}
private fun check(idString: String) {
setDone(idString, true)
}
private fun uncheck(idString: String) {
setDone(idString, false)
}
private fun setDone(idString: String, done: Boolean) {
val id = Integer.parseInt(idString)
for ((_, value) in tasks) {
for (task in value) {
if (task.id == id.toLong()) {
task.isDone = done
return
}
}
}
out.printf("Could not find a task with an ID of %d.", id)
out.println()
}
private fun help() {
out.println("Commands:")
out.println(" show")
out.println(" add project <project name>")
out.println(" add task <project name> <task description>")
out.println(" check <task ID>")
out.println(" uncheck <task ID>")
out.println()
}
private fun error(command: String) {
out.printf("I don't know what the command \"%s\" is.", command)
out.println()
}
private fun nextId(): Long {
return ++lastId
}
companion object {
private val QUIT = "quit"
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
val `in` = BufferedReader(InputStreamReader(System.`in`))
val out = PrintWriter(System.out)
TaskList(`in`, out).run()
}
}
}
| mit | 6f6b9aff7c1a594f2efac49b34f5be8c | 27.639098 | 105 | 0.528485 | 4.338269 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/operations/AlCtl_Psalctl.kt | 1 | 1106 | package alraune.operations
import alraune.*
import vgrechka.*
class AlCtl_Psalctl : AlCtlCommand() {
override fun dance() {
val args = rawArgs.toMutableSet()
val killAll = args.remove("--kill-all")
val pieceOfName = when (args.size) {
0 -> ""
1 -> args.first().toLowerCase()
else -> bitch("Too much shit on command line")
}
fun filter(x: AlCtlCommand.Processes.Item) = x.cmdName.toLowerCase().contains(pieceOfName)
val items = AlCtlCommand.Processes(afterEqualsStart = "", itemFilter = ::filter)
val exceptMe = items.exceptMyPID
if (exceptMe.isEmpty()) {
clog("No fucking processes")
} else {
for ((i, x) in exceptMe.withIndex()) {
clog("${i+1}) ${x.line.user} ${x.line.pid} ${x.cmdName}")
}
}
var sudos = items.sudoWrappers.size
if (isRootUser())
--sudos
if (sudos > 0)
clog("Among that, started via sudo: $sudos")
if (killAll)
items.killExceptMe()
}
}
| apache-2.0 | 1932d86624a5cdced2299f1c159cd238 | 27.358974 | 98 | 0.5434 | 4.036496 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/text/regex/sets/BackReferenceSet.kt | 4 | 3567 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 kotlin.text.regex
/**
* Back reference node;
*/
open internal class BackReferenceSet(val referencedGroup: Int, val consCounter: Int, val ignoreCase: Boolean = false)
: SimpleSet() {
override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int {
val groupValue = getReferencedGroupValue(matchResult)
if (groupValue == null || startIndex + groupValue.length > testString.length) {
return -1
}
if (testString.startsWith(groupValue, startIndex, ignoreCase)) {
matchResult.setConsumed(consCounter, groupValue.length)
return next.matches(startIndex + groupValue.length, testString, matchResult)
}
return -1
}
override fun find(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int {
val groupValue = getReferencedGroupValue(matchResult)
if (groupValue == null || startIndex + groupValue.length > testString.length) {
return -1
}
var index = startIndex
while (index <= testString.length) {
index = testString.indexOf(groupValue, index, ignoreCase)
if (index < 0) {
return -1
}
if (index < testString.length
&& next.matches(index + groupValue.length, testString, matchResult) >=0) {
return index
}
index++
}
return -1
}
override fun findBack(leftLimit: Int, rightLimit: Int, testString: CharSequence, matchResult: MatchResultImpl): Int {
val groupValue = getReferencedGroupValue(matchResult)
if (groupValue == null || leftLimit + groupValue.length > rightLimit) {
return -1
}
var index = rightLimit
while (index >= leftLimit) {
index = testString.lastIndexOf(groupValue, index, ignoreCase)
if (index < 0) {
return -1
}
if (index >= 0 && next.matches(index + groupValue.length, testString, matchResult) >= 0) {
return index
}
index--
}
return -1
}
protected fun getReferencedGroupValue(matchResult: MatchResultImpl) = matchResult.group(referencedGroup)
override val name: String
get() = "back reference: $referencedGroup"
override fun hasConsumed(matchResult: MatchResultImpl): Boolean {
val result = matchResult.getConsumed(consCounter) != 0
matchResult.setConsumed(consCounter, -1)
return result
}
}
| apache-2.0 | 3d3f777b3d39efd57fc3cbcfff9df8a6 | 35.773196 | 121 | 0.644239 | 4.656658 | false | true | false | false |
allotria/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUAnnotation.kt | 4 | 2629 | /*
* 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 org.jetbrains.uast.java
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.ResolveResult
import org.jetbrains.uast.*
import org.jetbrains.uast.java.expressions.JavaUNamedExpression
class JavaUAnnotation(
override val sourcePsi: PsiAnnotation,
givenParent: UElement?
) : JavaAbstractUElement(givenParent), UAnnotationEx, UAnchorOwner, UMultiResolvable {
override val javaPsi: PsiAnnotation = sourcePsi
override val qualifiedName: String?
get() = sourcePsi.qualifiedName
override val attributeValues: List<UNamedExpression> by lz {
val attributes = sourcePsi.parameterList.attributes
attributes.map { attribute -> JavaUNamedExpression(attribute, this) }
}
override val uastAnchor: UIdentifier?
get() = sourcePsi.nameReferenceElement?.referenceNameElement?.let { UIdentifier(it, this) }
override fun resolve(): PsiClass? = sourcePsi.nameReferenceElement?.resolve() as? PsiClass
override fun multiResolve(): Iterable<ResolveResult> =
sourcePsi.nameReferenceElement?.multiResolve(false)?.asIterable() ?: emptyList()
override fun findAttributeValue(name: String?): UExpression? {
val attributeValue = sourcePsi.findAttributeValue(name) ?: return null
return UastFacade.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression(this)
}
override fun findDeclaredAttributeValue(name: String?): UExpression? {
val attributeValue = sourcePsi.findDeclaredAttributeValue(name) ?: return null
return UastFacade.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression(this)
}
companion object {
@JvmStatic
fun wrap(annotation: PsiAnnotation): UAnnotation = JavaUAnnotation(annotation, null)
@JvmStatic
fun wrap(annotations: List<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) }
@JvmStatic
fun wrap(annotations: Array<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) }
}
} | apache-2.0 | 3dbb4fa97563795e9d5090d0bb8b6957 | 37.676471 | 114 | 0.764549 | 4.823853 | false | false | false | false |
stoyicker/dinger | data/src/main/kotlin/data/autoswipe/ProcessRecommendationAction.kt | 1 | 3233 | package data.autoswipe
import android.content.Context
import android.content.SharedPreferences
import data.tinder.dislike.DislikeRecommendationAction
import data.tinder.dislike.DislikeRecommendationActionFactoryWrapper
import data.tinder.like.LikeRecommendationAction
import data.tinder.like.LikeRecommendationActionFactoryWrapper
import domain.dislike.DomainDislikedRecommendationAnswer
import domain.like.DomainLikedRecommendationAnswer
import domain.recommendation.DomainRecommendationUser
import org.stoyicker.dinger.data.R
internal class ProcessRecommendationAction(
private val context: Context,
private val user: DomainRecommendationUser,
private val sharedPreferences: SharedPreferences,
private val likeRecommendationActionFactory
: dagger.Lazy<LikeRecommendationActionFactoryWrapper>,
private val dislikeRecommendationActionFactory
: dagger.Lazy<DislikeRecommendationActionFactoryWrapper>)
: AutoSwipeIntentService.Action<ProcessRecommendationAction.Callback>() {
private var runningAction: AutoSwipeIntentService.Action<*>? = null
override fun execute(owner: AutoSwipeIntentService, callback: Callback) {
when {
sharedPreferences.getBoolean(
context.getString(
R.string.preference_key_dislike_empty_profiles), false) && user.bio.isNullOrBlank() ->
dislikeRecommendation(owner, callback)
sharedPreferences.getBoolean(
context.getString(
R.string.preference_key_dislike_if_friends_in_common), false) &&
user.commonFriends.any() ->
dislikeRecommendation(owner, callback)
else -> likeRecommendation(owner, callback)
}
}
override fun dispose() {
runningAction?.dispose()
}
private fun dislikeRecommendation(owner: AutoSwipeIntentService, callback: Callback) =
dislikeRecommendationActionFactory.get().delegate(user).let {
runningAction = it
it.execute(
owner, object : DislikeRecommendationAction.Callback {
override fun onRecommendationDisliked(
answer: DomainDislikedRecommendationAnswer) {
callback.onRecommendationProcessed(DomainLikedRecommendationAnswer.EMPTY, false)
}
override fun onRecommendationDislikeFailed() {
callback.onRecommendationProcessingFailed()
}
})
}
private fun likeRecommendation(owner: AutoSwipeIntentService, callback: Callback) =
likeRecommendationActionFactory.get().delegate(user).let {
runningAction = it
it.execute(
owner, object : LikeRecommendationAction.Callback {
override fun onRecommendationLiked(answer: DomainLikedRecommendationAnswer) {
commonDelegate.onComplete(owner)
callback.onRecommendationProcessed(answer, answer.rateLimitedUntilMillis == null)
}
override fun onRecommendationLikeFailed(error: Throwable) {
commonDelegate.onError(error, owner)
callback.onRecommendationProcessingFailed()
}
})
}
interface Callback {
fun onRecommendationProcessed(answer: DomainLikedRecommendationAnswer, liked: Boolean)
fun onRecommendationProcessingFailed()
}
}
| mit | 126d1e49fca2634465889d00eb07d3bf | 37.951807 | 100 | 0.737705 | 5.23987 | false | false | false | false |
OpenConference/DroidconBerlin2017 | businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/backend/InstantIsoTypeConverter.kt | 1 | 755 | package de.droidcon.berlin2018.schedule.backend
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import org.threeten.bp.Instant
import org.threeten.bp.format.DateTimeFormatter
/**
* Logan Square json parser type converter for Dates ins ISO format
*
* @author Hannes Dorfmann
*/
class InstantIsoTypeConverter() {
@ToJson
fun convertToString(o: Instant?): String? = if (o == null) {
null
} else {
val timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
timeFormatter.format(o)
}
@FromJson
fun getFromString(str: String?): Instant? = if (str == null) {
null
} else {
val timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
val accessor = timeFormatter.parse(str);
Instant.from(accessor)
}
}
| apache-2.0 | 8aa1149f299fd9254fca1a5490a2579a | 21.878788 | 67 | 0.713907 | 3.79397 | false | false | false | false |
androidx/androidx | navigation/navigation-dynamic-features-fragment/src/main/java/androidx/navigation/dynamicfeatures/fragment/DynamicFragmentNavigator.kt | 3 | 3704 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.dynamicfeatures.fragment
import android.content.Context
import android.util.AttributeSet
import androidx.core.content.withStyledAttributes
import androidx.fragment.app.FragmentManager
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavOptions
import androidx.navigation.Navigator
import androidx.navigation.NavigatorProvider
import androidx.navigation.dynamicfeatures.DynamicExtras
import androidx.navigation.dynamicfeatures.DynamicInstallManager
import androidx.navigation.fragment.FragmentNavigator
/**
* The [Navigator] that enables navigating to destinations within dynamic feature modules.
*/
@Navigator.Name("fragment")
public class DynamicFragmentNavigator(
context: Context,
manager: FragmentManager,
containerId: Int,
private val installManager: DynamicInstallManager
) : FragmentNavigator(context, manager, containerId) {
override fun createDestination(): Destination = Destination(this)
override fun navigate(
entries: List<NavBackStackEntry>,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?
) {
for (entry in entries) {
navigate(entry, navOptions, navigatorExtras)
}
}
private fun navigate(
entry: NavBackStackEntry,
navOptions: NavOptions?,
navigatorExtras: Navigator.Extras?
) {
val destination = entry.destination
val extras = navigatorExtras as? DynamicExtras
if (destination is Destination) {
val moduleName = destination.moduleName
if (moduleName != null && installManager.needsInstall(moduleName)) {
installManager.performInstall(entry, extras, moduleName)
return
}
}
super.navigate(
listOf(entry),
navOptions,
if (extras != null) extras.destinationExtras else navigatorExtras
)
}
/**
* Destination for dynamic feature navigator.
*/
public class Destination : FragmentNavigator.Destination {
public var moduleName: String? = null
@Suppress("unused")
public constructor(navigatorProvider: NavigatorProvider) : super(navigatorProvider)
public constructor(
fragmentNavigator: Navigator<out FragmentNavigator.Destination>
) : super(fragmentNavigator)
override fun onInflate(context: Context, attrs: AttributeSet) {
super.onInflate(context, attrs)
context.withStyledAttributes(attrs, R.styleable.DynamicFragmentNavigator) {
moduleName = getString(R.styleable.DynamicFragmentNavigator_moduleName)
}
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is Destination) return false
return super.equals(other) && moduleName == other.moduleName
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + moduleName.hashCode()
return result
}
}
}
| apache-2.0 | 87a47c2117e7f4ea063e844775716ff0 | 33.943396 | 91 | 0.689525 | 5.209564 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/metadata/DeviceTypes.kt | 3 | 1223 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RestrictTo(RestrictTo.Scope.LIBRARY)
package androidx.health.connect.client.records.metadata
import androidx.annotation.RestrictTo
/**
* List of supported device types on Health Platform.
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
object DeviceTypes {
const val UNKNOWN = "UNKNOWN"
const val WATCH = "WATCH"
const val PHONE = "PHONE"
const val SCALE = "SCALE"
const val RING = "RING"
const val HEAD_MOUNTED = "HEAD_MOUNTED"
const val FITNESS_BAND = "FITNESS_BAND"
const val CHEST_STRAP = "CHEST_STRAP"
const val SMART_DISPLAY = "SMART_DISPLAY"
}
| apache-2.0 | 396fd66e06d83e8aa62856a3e8e06b13 | 31.184211 | 75 | 0.724448 | 3.983713 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/intentions/simplifyBooleanWithConstants/equalsTrueOrFalse.kt | 13 | 67 | fun foo(arg: Boolean): Boolean = <caret>arg == true || arg == false | apache-2.0 | 1931f953b3b71c3d6c29b6beeaa3d5ae | 67 | 67 | 0.641791 | 3.526316 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/versions/KotlinUpdatePluginComponent.kt | 1 | 2406 | // 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.versions
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import org.jetbrains.kotlin.idea.KotlinPluginUtil
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import java.io.File
import java.nio.file.Path
/**
* Component forces update for built-in libraries in plugin directory. They are ignored because of
* com.intellij.util.indexing.FileBasedIndex.isUnderConfigOrSystem()
*/
internal class KotlinUpdatePluginStartupActivity : StartupActivity.DumbAware {
init {
if (isUnitTestMode()) {
throw ExtensionNotApplicableException.INSTANCE
}
}
override fun runActivity(project: Project) {
val propertiesComponent = PropertiesComponent.getInstance()
val installedKotlinVersion = propertiesComponent.getValue(INSTALLED_KOTLIN_VERSION)
if (KotlinPluginUtil.getPluginVersion() != installedKotlinVersion) {
// Force refresh jar handlers
for (libraryJarDescriptor in LibraryJarDescriptor.values()) {
requestFullJarUpdate(libraryJarDescriptor.getPathInPlugin())
}
propertiesComponent.setValue(INSTALLED_KOTLIN_VERSION, KotlinPluginUtil.getPluginVersion())
}
}
private fun requestFullJarUpdate(jarFilePath: Path) {
val localVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(jarFilePath) ?: return
// Build and update JarHandler
val jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(localVirtualFile) ?: return
VfsUtilCore.visitChildrenRecursively(jarFile, object : VirtualFileVisitor<Any?>() {})
((jarFile as NewVirtualFile)).markDirtyRecursively()
}
companion object {
private const val INSTALLED_KOTLIN_VERSION = "installed.kotlin.plugin.version"
}
}
| apache-2.0 | cea9957b07ba6e7fc88277315efb7305 | 41.964286 | 158 | 0.760599 | 5.065263 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/iso/AvcConfigurationRecord.kt | 1 | 8399 | package com.haishinkit.iso
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.util.Log
import com.haishinkit.codec.CodecOption
import com.haishinkit.codec.VideoCodec
import com.haishinkit.util.toPositiveInt
import java.nio.ByteBuffer
import java.util.ArrayList
data class AvcConfigurationRecord(
val configurationVersion: Byte = 0x01,
val avcProfileIndication: Byte = 0,
val profileCompatibility: Byte = 0,
val avcLevelIndication: Byte = 0,
val lengthSizeMinusOneWithReserved: Byte = 0,
val numOfSequenceParameterSetsWithReserved: Byte = 0,
val sequenceParameterSets: List<ByteArray>? = null,
val pictureParameterSets: List<ByteArray>? = null
) {
val naluLength: Byte
get() = ((lengthSizeMinusOneWithReserved.toInt() shr 6) + 1).toByte()
fun encode(buffer: ByteBuffer): AvcConfigurationRecord {
buffer.put(configurationVersion)
buffer.put(avcProfileIndication)
buffer.put(profileCompatibility)
buffer.put(avcLevelIndication)
buffer.put(lengthSizeMinusOneWithReserved)
// SPS
buffer.put(numOfSequenceParameterSetsWithReserved)
sequenceParameterSets?.let {
for (sps in it) {
buffer.putShort(sps.size.toShort())
buffer.put(sps)
}
}
// PPS
pictureParameterSets?.let {
buffer.put(it.size.toByte())
for (pps in it) {
buffer.putShort(pps.size.toShort())
buffer.put(pps)
}
}
return this
}
fun decode(buffer: ByteBuffer): AvcConfigurationRecord {
val configurationVersion = buffer.get()
val avcProfileIndication = buffer.get()
val profileCompatibility = buffer.get()
val avcLevelIndication = buffer.get()
val lengthSizeMinusOneWithReserved = buffer.get()
val numOfSequenceParameterSetsWithReserved = buffer.get()
val numOfSequenceParameterSets =
numOfSequenceParameterSetsWithReserved.toPositiveInt() and RESERVE_NUM_OF_SEQUENCE_PARAMETER_SETS.inv()
val sequenceParameterSets = mutableListOf<ByteArray>()
for (i in 0 until numOfSequenceParameterSets) {
val bytes = ByteArray(buffer.short.toInt())
buffer.get(bytes)
sequenceParameterSets.add(bytes)
}
val numPictureParameterSets = buffer.get().toPositiveInt()
val pictureParameterSets = mutableListOf<ByteArray>()
for (i in 0 until numPictureParameterSets) {
val bytes = ByteArray(buffer.short.toInt())
buffer.get(bytes)
pictureParameterSets.add(bytes)
}
return AvcConfigurationRecord(
configurationVersion = configurationVersion,
avcProfileIndication = avcProfileIndication,
profileCompatibility = profileCompatibility,
avcLevelIndication = avcLevelIndication,
lengthSizeMinusOneWithReserved = lengthSizeMinusOneWithReserved,
numOfSequenceParameterSetsWithReserved = numOfSequenceParameterSetsWithReserved,
sequenceParameterSets = sequenceParameterSets,
pictureParameterSets = pictureParameterSets
)
}
internal fun allocate(): ByteBuffer {
var capacity = 5
sequenceParameterSets?.let {
for (sps in it) {
capacity += 3 + sps.size
}
}
pictureParameterSets?.let {
for (psp in it) {
capacity += 3 + psp.size
}
}
return ByteBuffer.allocate(capacity)
}
internal fun apply(codec: VideoCodec): Boolean {
when (avcProfileIndication.toInt()) {
66 -> codec.profile = MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline
77 -> codec.profile = MediaCodecInfo.CodecProfileLevel.AVCProfileMain
88 -> codec.profile = MediaCodecInfo.CodecProfileLevel.AVCProfileHigh
}
when (avcLevelIndication.toInt()) {
31 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel31
32 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel32
40 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel4
41 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel41
42 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel42
50 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel5
51 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel51
52 -> codec.level = MediaCodecInfo.CodecProfileLevel.AVCLevel52
}
val options = mutableListOf<CodecOption>()
val spsBuffer = ByteBuffer.allocate(128)
sequenceParameterSets?.let {
for (sps in it) {
spsBuffer.put(AvcFormatUtils.START_CODE)
spsBuffer.put(sps)
}
}
spsBuffer.flip()
val ppsBuffer = ByteBuffer.allocate(128)
pictureParameterSets?.let {
for (pps in it) {
ppsBuffer.put(AvcFormatUtils.START_CODE)
ppsBuffer.put((pps))
}
}
ppsBuffer.flip()
if (codec.options.isEmpty()) {
options.add(CodecOption(CSD0, spsBuffer))
options.add(CodecOption(CSD1, ppsBuffer))
} else {
for (option in codec.options) {
if (option.key == CSD0 && spsBuffer.compareTo(option.value as ByteBuffer) != 0) {
options.add(CodecOption(CSD0, spsBuffer))
}
if (option.key == CSD1 && ppsBuffer.compareTo(option.value as ByteBuffer) != 0) {
options.add(CodecOption(CSD1, ppsBuffer))
}
}
if (options.isEmpty()) {
return false
}
}
codec.options = options
Log.i(TAG, "apply value=$this for a videoCodec")
return true
}
internal fun toByteBuffer(): ByteBuffer {
val result = ByteBuffer.allocate(128)
result.put(0x00).put(0x00).put(0x00).put(0x00)
sequenceParameterSets?.let {
for (sps in it) {
result.put(AvcFormatUtils.START_CODE)
result.put(sps)
}
}
pictureParameterSets?.let {
for (pps in it) {
result.put(AvcFormatUtils.START_CODE)
result.put(pps)
}
}
return result
}
@Suppress("unused")
companion object {
const val RESERVE_LENGTH_SIZE_MINUS_ONE = 0x3F
const val RESERVE_NUM_OF_SEQUENCE_PARAMETER_SETS = 0xE0
const val RESERVE_CHROME_FORMAT = 0xFC
const val RESERVE_BIT_DEPTH_LUMA_MINUS8 = 0xF8
const val RESERVE_BIT_DEPTH_CHROME_MINUS8 = 0xF8
private const val CSD0 = "csd-0"
private const val CSD1 = "csd-1"
private var TAG = AvcConfigurationRecord::class.java.simpleName
internal fun create(mediaFormat: MediaFormat): AvcConfigurationRecord {
// SPS => 0x00,0x00,0x00,0x01,0x67,0x42,0x00,0x29,0x8d,0x8d,0x40,0xa0,0xfd,0x00,0xf0,0x88,0x45,0x38
val spsBuffer = mediaFormat.getByteBuffer(CSD0)
// PPS => 0x00,0x00,0x00,0x01,0x68,0xca,0x43,0xc8
val ppsBuffer = mediaFormat.getByteBuffer(CSD1)
if (spsBuffer == null || ppsBuffer == null) {
throw IllegalStateException()
}
return AvcConfigurationRecord(
configurationVersion = 0x01,
avcProfileIndication = spsBuffer[5],
profileCompatibility = spsBuffer[6],
avcLevelIndication = spsBuffer[7],
lengthSizeMinusOneWithReserved = 0xFF.toByte(),
numOfSequenceParameterSetsWithReserved = 0xE1.toByte(),
sequenceParameterSets = ArrayList<ByteArray>(1).apply {
val length = spsBuffer.remaining()
add(spsBuffer.array().slice(4 until length).toByteArray())
},
pictureParameterSets = ArrayList<ByteArray>(1).apply {
val length = ppsBuffer.remaining()
add(ppsBuffer.array().slice(4 until length).toByteArray())
}
)
}
}
}
| bsd-3-clause | 23aa512059f735ac330f152695e940d1 | 37.705069 | 115 | 0.608287 | 4.318252 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/commenter/AbstractKotlinCommenterTest.kt | 4 | 1602 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.editor.commenter
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.kotlin.formatter.FormatSettingsUtil
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.configureCodeStyleAndRun
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import java.io.File
abstract class AbstractKotlinCommenterTest : KotlinLightCodeInsightFixtureTestCase() {
protected fun doTest(testPath: String) {
val fileText = FileUtil.loadFile(File(testPath))
configureCodeStyleAndRun(
project = project,
configurator = {
FormatSettingsUtil.createConfigurator(fileText, it).configureSettings()
},
body = {
doTest(fileText, testPath)
}
)
}
private fun doTest(text: String, testPath: String) {
val action = InTextDirectivesUtils.findStringWithPrefixes(text, "// ACTION:")
?: error("'// ACTION:' directive is not found")
val actionId = when (action) {
"line" -> IdeActions.ACTION_COMMENT_LINE
"block" -> IdeActions.ACTION_COMMENT_BLOCK
else -> error("unexpected '$action' action")
}
myFixture.configureByFile(testPath)
myFixture.performEditorAction(actionId)
myFixture.checkResultByFile(File("$testPath.after"))
}
} | apache-2.0 | df514382a7b319ebbd415462c69adc13 | 39.075 | 120 | 0.691635 | 4.990654 | false | true | false | false |
smmribeiro/intellij-community | uast/uast-tests/src/org/jetbrains/uast/test/common/PossibleSourceTypesTestBase.kt | 5 | 2443 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.common
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.getPossiblePsiSourceTypes
import org.jetbrains.uast.toUElementOfExpectedTypes
import org.junit.Assert
interface PossibleSourceTypesTestBase {
private fun PsiFile.getPsiSourcesByPlainVisitor(psiPredicate: (PsiElement) -> Boolean = { true },
vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val sources = mutableSetOf<PsiElement>()
accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (psiPredicate(element))
element.toUElementOfExpectedTypes(*uastTypes)?.let { sources += element }
super.visitElement(element)
}
})
return sources
}
private fun PsiFile.getPsiSourcesByLanguageAwareVisitor(vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val possibleSourceTypes = getPossiblePsiSourceTypes(language, *uastTypes)
return getPsiSourcesByPlainVisitor(psiPredicate = { it.javaClass in possibleSourceTypes }, uastTypes = *uastTypes)
}
private fun PsiFile.getPsiSourcesByLanguageUnawareVisitor(vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val possibleSourceTypes = UastFacade.getPossiblePsiSourceTypes(*uastTypes)
return getPsiSourcesByPlainVisitor(psiPredicate = { it.javaClass in possibleSourceTypes }, uastTypes = *uastTypes)
}
fun checkConsistencyWithRequiredTypes(psiFile: PsiFile, vararg uastTypes: Class<out UElement>) {
val byPlain = psiFile.getPsiSourcesByPlainVisitor(uastTypes = *uastTypes)
val byLanguageAware = psiFile.getPsiSourcesByLanguageAwareVisitor(uastTypes = *uastTypes)
val byLanguageUnaware = psiFile.getPsiSourcesByLanguageUnawareVisitor(uastTypes = *uastTypes)
Assert.assertEquals(
"Filtering PSI elements with getPossiblePsiSourceTypes should not lost or add any conversions",
byPlain,
byLanguageUnaware)
Assert.assertEquals(
"UastFacade implementation should be in sync with language UastLanguagePlugin's one",
byLanguageAware,
byLanguageUnaware)
}
} | apache-2.0 | 2e2a5d2ed18af41003746e65c261a73a | 43.436364 | 140 | 0.763406 | 5.132353 | false | false | false | false |
NilsRenaud/kotlin-presentation | examples/src/org/nilsr/kotlin/examples/2Classes.kt | 1 | 2351 | package org.nilsr.kotlin.examples
import javax.naming.OperationNotSupportedException
/**
* Shows :
* - Data class definition
* - Data class fields definition using var/val
* - Data class auto generated methods
* - Operator overloads
* - Destructuring declaration
* - Data class components auto-definition
* - Class definition
* - Constructor definition
* - Init method
* - public/private fields
* - Specific getters and setters
* - Lazy evaluation
* - Enums
* - Java interoperability
*/
fun main(args : Array<String>) {
val rect = Rectangle(1, 2)
val rect2 = Rectangle(1, 2)
// "rect.length = 1" does not compile
println("${rect.length}, ${rect.width}")
println(rect == rect2)
val rectMut = MutableRectangle(1, 2)
rectMut.length = 4
val (width, length) = rectMut
println("${rectMut.component1()} = $width, ${rectMut.component2()} = $length")
// Example of an empty class instantiation
val empty = Empty()
// Example of a Customer Instantiation
var customer = Customer("Nils", "Test", "privateVal")
println("${customer.customerKey} : ${customer.firstName} ${customer.lastName}")
// customer.age & customer.privateField are not reachable.
customer = Customer("Nils")
println("$customer has name ? ${customer.hasAName}")
}
data class Rectangle(val width : Int, val length : Int)
data class MutableRectangle(var width : Int, var length : Int)
class Empty
class Customer(val firstName: String, val lastName: String?, privateField: String) {
val customerKey = lastName?.toUpperCase()
private val age : Int
constructor(firstname : String) : this(firstname, null, "secret"){
//Some Stuff
}
init {
age = 0
println("$customerKey : $privateField")
}
var hasAName: Boolean
get() = this.lastName == null
set(value) {
throw OperationNotSupportedException()
}
val lazyField : String by lazy { println("should be printed only once"); "lazyValue" }
}
enum class Color(val red : Int, val green : Int, val blue : Int){
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255)
}
enum class ProtocolState {
WAITING {
override fun signal() = TALKING
},
TALKING {
override fun signal() = WAITING
};
abstract fun signal(): ProtocolState
} | mit | fdc53f9b12fe6074d5c427d8abe54f5e | 24.565217 | 90 | 0.64866 | 4.011945 | false | false | false | false |
sksamuel/ktest | kotest-framework/kotest-framework-engine/src/jvmMain/kotlin/io/kotest/engine/reporter/MochaConsoleReporter.kt | 1 | 6065 | package io.kotest.engine.reporter
import com.github.ajalt.mordant.TermColors
import io.kotest.core.spec.Spec
import io.kotest.core.spec.toDescription
import io.kotest.core.test.Description
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestStatus
import io.kotest.core.test.TestType
import kotlin.reflect.KClass
private val isWindows = System.getProperty("os.name").contains("win")
interface Symbol {
fun print(term: TermColors): String
}
object SuccessSymbol : Symbol {
override fun print(term: TermColors): String = term.brightGreen(if (isWindows) "√" else "✔")
}
object FailureSymbol : Symbol {
override fun print(term: TermColors): String = term.brightRed(if (isWindows) "X" else "✘")
}
object IgnoredSymbol : Symbol {
override fun print(term: TermColors): String = term.gray("-")
}
class MochaConsoleReporter(
private val term: TermColors,
private val slow: Int = 1000,
private val verySlow: Int = 3000
) : Reporter {
private val margin = " ".repeat(2)
private val tests = mutableListOf<TestCase>()
private val results = mutableMapOf<Description, TestResult>()
private var n = 0
private var start = 0L
private var errors = false
private fun Description.indent(): String = "\t".repeat(parents().size)
override fun hasErrors(): Boolean = errors
private fun testLine(testCase: TestCase, result: TestResult): String {
val name = when (result.status) {
TestStatus.Failure, TestStatus.Error -> term.brightRed(testCase.description.name.displayName + " *** FAILED ***")
TestStatus.Success -> testCase.description.name.displayName
TestStatus.Ignored -> term.gray(testCase.description.name.displayName + " ??? IGNORED ???")
}
val symbol = when (result.status) {
TestStatus.Success -> SuccessSymbol
TestStatus.Error, TestStatus.Failure -> FailureSymbol
TestStatus.Ignored -> IgnoredSymbol
}
val duration = when (testCase.type) {
TestType.Test -> durationString(result.duration)
else -> ""
}
return "$margin${testCase.description.indent()} ${symbol.print(term)} $name $duration".padEnd(80, ' ')
}
private fun durationString(durationMs: Long): String {
return when {
durationMs in slow..verySlow -> term.brightYellow("(${durationMs}ms)")
durationMs > verySlow -> term.brightRed("(${durationMs}ms)")
else -> ""
}
}
private fun cause(testCase: TestCase, message: String?): String {
return term.brightRed("$margin\tcause: $message (${testCase.source.fileName}:${testCase.source.lineNumber})")
}
override fun specStarted(kclass: KClass<out Spec>) {}
override fun specFinished(kclass: KClass<out Spec>, t: Throwable?, results: Map<TestCase, TestResult>) {
n += 1
val specDesc = kclass.toDescription()
if (t == null) {
println("$margin$n) " + term.brightWhite(kclass.qualifiedName!!))
} else {
errors = true
print(margin)
println(term.red(specDesc.name.displayName + " *** FAILED ***"))
println(term.red("$margin\tcause: ${t.message})"))
}
println()
tests
.filter { it.spec::class.qualifiedName == kclass.qualifiedName }
.forEach { testCase ->
val result = results[testCase]
if (result != null) {
val line = testLine(testCase, result)
println(line)
when (result.status) {
TestStatus.Error, TestStatus.Failure -> {
errors = true
println()
println(cause(testCase, result.error?.message))
println()
}
else -> {
}
}
}
}
println()
}
override fun engineStarted(classes: List<KClass<out Spec>>) {
start = System.currentTimeMillis()
}
override fun testStarted(testCase: TestCase) {
tests.add(testCase)
}
override fun testFinished(testCase: TestCase, result: TestResult) {
results[testCase.description] = result
}
private fun padNewLines(str: String, pad: String): String = str.lines().joinToString("\n") { "$pad$it" }
override fun engineFinished(t: List<Throwable>) {
val duration = (System.currentTimeMillis() - start)
val ignored = results.filter { it.value.status == TestStatus.Ignored }
val failed = results.filter { it.value.status == TestStatus.Failure || it.value.status == TestStatus.Error }
val passed = results.filter { it.value.status == TestStatus.Success }
val specs = tests.map { it.spec::class.toDescription() }.distinct()
val specDistinctCount = specs.distinct().size
println()
println(term.brightWhite("${margin}Kotest completed in ${duration/1000} seconds / $duration milliseconds"))
println("${margin}Executed $specDistinctCount specs containing ${failed.size + passed.size + ignored.size} tests")
println("$margin${passed.size} passed, ${failed.size} failed, ${ignored.size} ignored")
if (failed.isNotEmpty()) {
println()
println(term.brightWhite("$margin----------------------------- ${failed.size} FAILURES -----------------------------"))
failed.forEach {
println()
println("$margin${term.brightRed(if (isWindows) "X" else "✘")} ${term.brightWhite(it.key.testDisplayPath().value)}")
println()
val error = it.value.error
if (error != null) {
val msg = error.message
val stackTrace = error.stackTrace.joinToString("\n")
if (msg != null) {
println(term.brightRed(padNewLines(msg, margin)))
println()
}
println(margin + term.red(error.javaClass.name))
println(term.red(padNewLines(stackTrace, margin.repeat(2))))
}
}
}
}
}
| mit | b72bf4be49c74aeb3456fa310f541b73 | 34.840237 | 128 | 0.613505 | 4.376445 | false | true | false | false |
shiftize/CalendarView | calendarview/src/main/kotlin/com/shiftize/calendarview/CalendarPanelPager.kt | 1 | 1188 | package com.shiftize.calendarview
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.Log
import java.util.*
class CalendarPanelPager : ViewPager {
var agendaList: List<Agenda> = ArrayList()
set(value) {
(this.adapter as CalendarPanelAdapter).agendaList = value
val calendarPanel = findViewWithTag(currentItem) as CalendarPanel?
calendarPanel?.update(value)
}
var onCalendarClickedListener: CalendarView.OnCalendarClickedListener? = null
set(value) {
(adapter as CalendarPanelAdapter?)?.onCalendarClickedListener = value
}
constructor(context: Context): super(context) {}
fun setUp() {
val calendar = Calendar.getInstance()
setUp(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1)
}
fun setUp(year: Int, month: Int) {
this.adapter = CalendarPanelAdapter(context, year, month)
this.currentItem = getCenterPosition()
}
/**
* calculate center position
* @return calculated center position
*/
fun getCenterPosition(): Int {
return this.adapter.count / 2
}
}
| apache-2.0 | 6aede1595e2d59b9b464c553c2c295fd | 28.7 | 81 | 0.666667 | 4.466165 | false | false | false | false |
alexstyl/Memento-Namedays | android_mobile/src/main/java/com/alexstyl/specialdates/upcoming/widget/today/UpcomingWidgetPreferences.kt | 3 | 1464 | package com.alexstyl.specialdates.upcoming.widget.today
import android.content.Context
import android.content.SharedPreferences
import com.alexstyl.specialdates.EasyPreferences
import com.alexstyl.specialdates.R
class UpcomingWidgetPreferences(context: Context) {
private val preferences: EasyPreferences =
EasyPreferences.createForPrivatePreferences(context, R.string.pref_upcoming_widget_config)
val selectedVariant: WidgetVariant
get() {
val variantId = preferences.getInt(R.string.key_upcoming_widget_variant, DEFAULT_VARIANT_ID)
return WidgetVariant.fromId(variantId)
}
val oppacityLevel: Float
get() = preferences.getFloat(R.string.key_upcoming_widget_opacity, DEFAULT_OPACITY)
fun storeUserOptions(userOptions: UserOptions) {
preferences.setFloat(R.string.key_upcoming_widget_opacity, userOptions.opacityLevel)
preferences.setInteger(R.string.key_upcoming_widget_variant, userOptions.widgetVariant.id)
}
fun addListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
preferences.addOnPreferenceChangedListener(listener)
}
fun removeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
preferences.removeOnPreferenceChagnedListener(listener)
}
companion object {
private val DEFAULT_VARIANT_ID = WidgetVariant.LIGHT.id
private val DEFAULT_OPACITY = 1.0f
}
}
| mit | 85c730f9b83db3d502b76c5a1e0fc6a2 | 34.707317 | 104 | 0.754781 | 4.647619 | false | false | false | false |
br1992/Luzombra | src/main/kotlin/com/github/br1992/material/Dielectric.kt | 1 | 1717 | package com.github.br1992.material
import com.github.br1992.geometry.Ray3
import com.github.br1992.geometry.SurfaceIntersection
import com.github.br1992.geometry.reflect
import com.github.br1992.geometry.refract
import com.github.br1992.geometry.rgb
import com.github.br1992.geometry.unitVector
import org.jetbrains.kotlinx.multik.api.linalg.dot
import org.jetbrains.kotlinx.multik.ndarray.operations.unaryMinus
import java.lang.StrictMath.pow
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.random.Random
class Dielectric(private val refractionIndex: Double) : Material {
override fun scatter(inwardRay: Ray3, intersection: SurfaceIntersection): ScatterResponse? {
val attenuation = rgb(1.0, 1.0, 1.0)
val refractionRatio = if (intersection.isFrontFace) 1.0 / refractionIndex else refractionIndex
val unitDirection = inwardRay.direction.unitVector()
val angleCos = min(-unitDirection dot intersection.normal, 1.0)
val angleSin = sqrt(1.0 - angleCos * angleCos)
val canRefract = refractionRatio * angleSin <= 1.0
return ScatterResponse(
Ray3(
intersection.point,
if (canRefract && reflectance(angleCos, refractionIndex) <= Random.nextDouble()) {
refract(unitDirection, intersection.normal, refractionRatio)
} else {
reflect(unitDirection, intersection.normal)
}
),
attenuation
)
}
}
internal fun reflectance(angleCos: Double, refractionIndex: Double): Double {
var r0 = (1 - refractionIndex) / (1 + refractionIndex)
r0 *= r0
return r0 + (1 - r0) * pow(1 - angleCos, 5.0)
}
| mit | 915723221233081ecd85b22a9cc8b873 | 36.326087 | 102 | 0.68841 | 3.841163 | false | false | false | false |
sujeet4github/MyLangUtils | LangKotlin/Idiomatic/src/main/kotlin/idiomatic/InitBlock.kt | 1 | 1411 | package idiomaticKotlin
import org.apache.http.client.HttpClient
import org.apache.http.impl.client.HttpClientBuilder
import java.util.concurrent.TimeUnit
// think twice before you define a init block/constructor body
// (first, named and default argument can help)
// second, you can refer to primary constructor para in property initializers (and not only in the init block)
// apply() can help to group initialization code and get along with a single expression.
// Don't
class UsersClient(baseUrl: String, appName: String) {
private val usersUrl: String
private val httpClient: HttpClient
init {
usersUrl = "$baseUrl/users"
val builder = HttpClientBuilder.create()
builder.setUserAgent(appName)
builder.setConnectionTimeToLive(10, TimeUnit.SECONDS)
httpClient = builder.build()
}
fun getUsers(){
//call service using httpClient and usersUrl
}
}
// Do
class UsersClient2(baseUrl: String, appName: String) {
private val usersUrl = "$baseUrl/users"
private val httpClient = HttpClientBuilder.create().apply {
setUserAgent(appName)
setConnectionTimeToLive(10, TimeUnit.SECONDS)
}.build()
fun getUsers(){
//call service using httpClient and usersUrl
}
}
//- `with()` returns result of lambda (and it's invoked statically)
//- `apply()` returns receiver obj (and it's invoked on receiver obj) | gpl-3.0 | beb762877937664aa57c3a45c86c1be5 | 33.439024 | 110 | 0.714387 | 4.381988 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/speakers/SpeakerAdapterDelegate.kt | 1 | 1897 | package com.openconference.speakers
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import butterknife.bindView
import com.hannesdorfmann.adapterdelegates2.AbsListItemAdapterDelegate
import com.openconference.R
import com.openconference.model.Speaker
import com.openconference.util.picasso.PicassoScrollListener
import com.squareup.picasso.Picasso
/**
* Displays an profile pic image and name of a given Speaker
*
* @author Hannes Dorfmann
*/
class SpeakerAdapterDelegate(
private val inflater: LayoutInflater,
private val picasso: Picasso,
private val clickListener: (Speaker) -> Unit) : AbsListItemAdapterDelegate<Speaker, Speaker, SpeakerAdapterDelegate.SpeakerViewHolder>() {
override fun isForViewType(item: Speaker, items: MutableList<Speaker>?, position: Int): Boolean =
item is Speaker
override fun onBindViewHolder(item: Speaker, viewHolder: SpeakerViewHolder) =
viewHolder.bind(item)
override fun onCreateViewHolder(parent: ViewGroup): SpeakerViewHolder =
SpeakerViewHolder(inflater.inflate(R.layout.item_speaker, parent, false), picasso,
clickListener)
class SpeakerViewHolder(v: View, val picasso: Picasso, clickListener: (Speaker) -> Unit) : RecyclerView.ViewHolder(
v) {
init {
v.setOnClickListener { clickListener(speaker) }
}
val image: ImageView by bindView(R.id.image)
val name: TextView by bindView(R.id.name)
lateinit var speaker: Speaker
inline fun bind(s: Speaker) {
speaker = s
name.text = s.name()
picasso.load(speaker.profilePic())
.tag(PicassoScrollListener.TAG)
.centerCrop()
.fit()
.placeholder(R.color.speakerslist_placeholder)
.into(image)
}
}
} | apache-2.0 | 3fef0bd41b4f37510e5f9e21acd23b3c | 31.724138 | 142 | 0.739589 | 4.538278 | false | false | false | false |
alzhuravlev/MockAppDemo | app/src/main/java/com/crane/mockappdemo/sample1/BindViews6.kt | 1 | 1457 | package com.crane.mockappdemo.sample1
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.crane.mockapp.annotations.MockAppLayout
import com.crane.mockapp.annotations.MockAppView
import com.crane.mockapp.core.MockApp
import com.crane.mockapp.core.MockAppActivity
@MockAppLayout(projectName = "icountries", layoutName = "page_settings")
class BindViews6 : MockAppActivity() {
@MockAppView("titleText:TextView")
lateinit var titleText: TextView
@MockAppView
lateinit var aboutText: TextView
@MockAppView
lateinit var aboutButton: View
lateinit var feedbackText: TextView
lateinit var feedbackButton: View
override fun bindMockAppLayout(view: Any?) {
super.bindMockAppLayout(view)
feedbackText = MockApp.findViewWithCustomTag(view, "feedbackText:TextView")
feedbackButton = MockApp.findViewWithCustomTag(view, "feedbackButton:View")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
titleText.text = "titleText"
aboutText.text = "aboutText"
aboutButton.setOnClickListener {
Toast.makeText(this, "aboutButton", Toast.LENGTH_LONG).show()
}
feedbackText.text = "feedbackText"
feedbackButton.setOnClickListener {
Toast.makeText(this, "feedbackButton", Toast.LENGTH_LONG).show()
}
}
} | apache-2.0 | 4926f84723803f602c0aa0f9862bb54b | 28.16 | 83 | 0.725463 | 4.223188 | false | false | false | false |
pie-flavor/Kludge | src/main/kotlin/flavor/pie/kludge/delegates.kt | 1 | 2176 | package flavor.pie.kludge
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import org.spongepowered.api.service.ServiceManager
/**
* A delegate which pulls values from the [ServiceManager]. Use the companion
* object for live calls, or the class for a lazy value.
* @see org.spongepowered.api.service.ServiceManager.provide
*/
class Service<out T : Any>(private val clazz: KClass<T>) {
companion object {
inline operator fun <reified T: Any> getValue(thisRef: Any?, property: KProperty<*>): T? {
return !ServiceManager.provide(T::class.java)
}
/**
* @see Service
*/
inline operator fun <reified T: Any> invoke(): Service<T> = Service(T::class)
}
private var t: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
if (t == null) {
t = !ServiceManager.provide(clazz.java)
}
return t
}
}
/**
* A delegate which pulls unchecked values from the [ServiceManager]. Use the
* companion object for live calls, or the class for a lazy value.
* @see ServiceManager.provideUnchecked
*/
class UncheckedService<out T : Any>(private val clazz: KClass<T>) {
companion object {
inline operator fun <reified T: Any> getValue(thisRef: Any?, property: KProperty<*>): T {
return ServiceManager.provideUnchecked(T::class.java)
}
/**
* @see UncheckedService
*/
inline operator fun <reified T: Any> invoke(): UncheckedService<T> = UncheckedService(T::class)
}
private var t: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (t == null) {
t = ServiceManager.provideUnchecked(clazz.java)
}
return t!!
}
}
//object CachedService {
// inline operator fun <reified T: Any> provideDelegate(thisRef: Any?, property: KProperty<*>): Service<T>
// = Service(T::class)
//}
//
//object CachedUncheckedService {
// inline operator fun <reified T: Any> provideDelegate(thisRef: Any?, property: KProperty<*>): UncheckedService<T>
// = UncheckedService(T::class)
//}
| mit | 4a5ed53893990102ef7941c36f4e4454 | 30.536232 | 118 | 0.633272 | 4.129032 | false | false | false | false |
ethauvin/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/dependency/FileDependency.kt | 2 | 1468 | package com.beust.kobalt.maven.dependency
import com.beust.kobalt.api.Dependencies
import com.beust.kobalt.api.IClasspathDependency
import com.beust.kobalt.maven.CompletedFuture
import org.apache.maven.model.Dependency
import java.io.File
open class FileDependency(open val fileName: String, override val optional: Boolean = false)
: IClasspathDependency, Comparable<FileDependency> {
companion object {
val PREFIX_FILE: String = "file://"
}
override val id = PREFIX_FILE + fileName
override val version = "0.0"
override val isMaven = false
override val jarFile = CompletedFuture(File(fileName))
override fun toMavenDependencies(scope: String?): Dependency {
with(Dependency()) {
systemPath = jarFile.get().absolutePath
this.scope = scope
return this
}
}
override val shortId = fileName
override fun directDependencies() = arrayListOf<IClasspathDependency>()
override val excluded = arrayListOf<Dependencies.ExcludeConfig>()
override fun compareTo(other: FileDependency) = fileName.compareTo(other.fileName)
override fun toString() = fileName
override fun equals(other: Any?): Boolean{
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as FileDependency
if (id != other.id) return false
return true
}
override fun hashCode() = id.hashCode()
}
| apache-2.0 | 0b4b90910314c18cdc27d8ee625fd85a | 26.698113 | 92 | 0.688011 | 4.705128 | false | false | false | false |
square/kotlinpoet | kotlinpoet/src/main/java/com/squareup/kotlinpoet/FunSpec.kt | 1 | 24161 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.kotlinpoet
import com.squareup.kotlinpoet.KModifier.ABSTRACT
import com.squareup.kotlinpoet.KModifier.EXPECT
import com.squareup.kotlinpoet.KModifier.EXTERNAL
import com.squareup.kotlinpoet.KModifier.INLINE
import com.squareup.kotlinpoet.KModifier.VARARG
import java.lang.reflect.Type
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.Modifier
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.ExecutableType
import javax.lang.model.type.TypeVariable
import javax.lang.model.util.Types
import kotlin.DeprecationLevel.WARNING
import kotlin.reflect.KClass
/** A generated function declaration. */
@OptIn(ExperimentalKotlinPoetApi::class)
public class FunSpec private constructor(
builder: Builder,
private val tagMap: TagMap = builder.buildTagMap(),
private val delegateOriginatingElementsHolder: OriginatingElementsHolder = builder.buildOriginatingElements(),
private val contextReceivers: ContextReceivers = builder.buildContextReceivers(),
) : Taggable by tagMap, OriginatingElementsHolder by delegateOriginatingElementsHolder, ContextReceivable by contextReceivers {
public val name: String = builder.name
public val kdoc: CodeBlock = builder.kdoc.build()
public val returnKdoc: CodeBlock = builder.returnKdoc
public val receiverKdoc: CodeBlock = builder.receiverKdoc
public val annotations: List<AnnotationSpec> = builder.annotations.toImmutableList()
public val modifiers: Set<KModifier> = builder.modifiers.toImmutableSet()
public val typeVariables: List<TypeVariableName> = builder.typeVariables.toImmutableList()
public val receiverType: TypeName? = builder.receiverType
public val returnType: TypeName? = builder.returnType
public val parameters: List<ParameterSpec> = builder.parameters.toImmutableList()
public val delegateConstructor: String? = builder.delegateConstructor
public val delegateConstructorArguments: List<CodeBlock> =
builder.delegateConstructorArguments.toImmutableList()
public val body: CodeBlock = builder.body.build()
private val isExternalGetter = name == GETTER && builder.modifiers.contains(EXTERNAL)
private val isEmptySetter = name == SETTER && parameters.isEmpty()
init {
require(body.isEmpty() || !builder.modifiers.containsAnyOf(ABSTRACT, EXPECT)) {
"abstract or expect function ${builder.name} cannot have code"
}
if (name == GETTER) {
require(!isExternalGetter || body.isEmpty()) {
"external getter cannot have code"
}
} else if (name == SETTER) {
require(parameters.size <= 1) {
"$name can have at most one parameter"
}
require(parameters.isNotEmpty() || body.isEmpty()) {
"parameterless setter cannot have code"
}
}
require(INLINE in modifiers || typeVariables.none { it.isReified }) {
"only type parameters of inline functions can be reified!"
}
}
internal fun parameter(name: String) = parameters.firstOrNull { it.name == name }
internal fun emit(
codeWriter: CodeWriter,
enclosingName: String?,
implicitModifiers: Set<KModifier>,
includeKdocTags: Boolean = false,
) {
if (includeKdocTags) {
codeWriter.emitKdoc(kdocWithTags())
} else {
codeWriter.emitKdoc(kdoc.ensureEndsWithNewLine())
}
codeWriter.emitContextReceivers(contextReceiverTypes, suffix = "\n")
codeWriter.emitAnnotations(annotations, false)
codeWriter.emitModifiers(modifiers, implicitModifiers)
if (!isConstructor && !name.isAccessor) {
codeWriter.emitCode("fun·")
}
if (typeVariables.isNotEmpty()) {
codeWriter.emitTypeVariables(typeVariables)
codeWriter.emit(" ")
}
emitSignature(codeWriter, enclosingName)
codeWriter.emitWhereBlock(typeVariables)
if (shouldOmitBody(implicitModifiers)) {
codeWriter.emit("\n")
return
}
val asExpressionBody = body.asExpressionBody()
if (asExpressionBody != null) {
codeWriter.emitCode(CodeBlock.of(" = %L", asExpressionBody), ensureTrailingNewline = true)
} else if (!isEmptySetter) {
codeWriter.emitCode("·{\n")
codeWriter.indent()
codeWriter.emitCode(body.returnsWithoutLinebreak(), ensureTrailingNewline = true)
codeWriter.unindent()
codeWriter.emit("}\n")
} else {
codeWriter.emit("\n")
}
}
private fun shouldOmitBody(implicitModifiers: Set<KModifier>): Boolean {
if (canNotHaveBody(implicitModifiers)) {
check(body.isEmpty()) { "function $name cannot have code" }
return true
}
return canBodyBeOmitted(implicitModifiers) && body.isEmpty()
}
private fun canNotHaveBody(implicitModifiers: Set<KModifier>) =
ABSTRACT in modifiers || EXPECT in modifiers + implicitModifiers
private fun canBodyBeOmitted(implicitModifiers: Set<KModifier>) = isConstructor ||
EXTERNAL in (modifiers + implicitModifiers) ||
ABSTRACT in modifiers
private fun emitSignature(codeWriter: CodeWriter, enclosingName: String?) {
if (isConstructor) {
codeWriter.emitCode("constructor", enclosingName)
} else if (name == GETTER) {
codeWriter.emitCode("get")
} else if (name == SETTER) {
codeWriter.emitCode("set")
} else {
if (receiverType != null) {
if (receiverType is LambdaTypeName) {
codeWriter.emitCode("(%T).", receiverType)
} else {
codeWriter.emitCode("%T.", receiverType)
}
}
codeWriter.emitCode("%N", this)
}
if (!isEmptySetter && !isExternalGetter) {
parameters.emit(codeWriter) { param ->
param.emit(codeWriter, includeType = name != SETTER)
}
}
if (returnType != null) {
codeWriter.emitCode(": %T", returnType)
} else if (emitUnitReturnType()) {
codeWriter.emitCode(": %T", UNIT)
}
if (delegateConstructor != null) {
codeWriter.emitCode(
delegateConstructorArguments
.joinToCode(prefix = " : $delegateConstructor(", suffix = ")"),
)
}
}
public val isConstructor: Boolean get() = name.isConstructor
public val isAccessor: Boolean get() = name.isAccessor
private fun kdocWithTags(): CodeBlock {
return with(kdoc.ensureEndsWithNewLine().toBuilder()) {
var newLineAdded = false
val isNotEmpty = isNotEmpty()
if (receiverKdoc.isNotEmpty()) {
if (isNotEmpty) {
add("\n")
newLineAdded = true
}
add("@receiver %L", receiverKdoc.ensureEndsWithNewLine())
}
parameters.forEachIndexed { index, parameterSpec ->
if (parameterSpec.kdoc.isNotEmpty()) {
if (!newLineAdded && index == 0 && isNotEmpty) {
add("\n")
newLineAdded = true
}
add("@param %L %L", parameterSpec.name, parameterSpec.kdoc.ensureEndsWithNewLine())
}
}
if (returnKdoc.isNotEmpty()) {
if (!newLineAdded && isNotEmpty) {
add("\n")
newLineAdded = true
}
add("@return %L", returnKdoc.ensureEndsWithNewLine())
}
build()
}
}
/**
* Returns whether [Unit] should be emitted as the return type.
*
* [Unit] is emitted as return type on a function unless:
* - It's a constructor
* - It's a getter/setter on a property
* - It's an expression body
*/
private fun emitUnitReturnType(): Boolean {
if (isConstructor) {
return false
}
if (name == GETTER || name == SETTER) {
// Getter/setters don't emit return types
return false
}
return body.asExpressionBody() == null
}
private fun CodeBlock.asExpressionBody(): CodeBlock? {
val codeBlock = this.trim()
val asReturnExpressionBody = codeBlock.withoutPrefix(RETURN_EXPRESSION_BODY_PREFIX_SPACE)
?: codeBlock.withoutPrefix(RETURN_EXPRESSION_BODY_PREFIX_NBSP)
if (asReturnExpressionBody != null) {
return asReturnExpressionBody
}
if (codeBlock.withoutPrefix(THROW_EXPRESSION_BODY_PREFIX_SPACE) != null ||
codeBlock.withoutPrefix(THROW_EXPRESSION_BODY_PREFIX_NBSP) != null
) {
return codeBlock
}
return null
}
private fun CodeBlock.returnsWithoutLinebreak(): CodeBlock {
val returnWithSpace = RETURN_EXPRESSION_BODY_PREFIX_SPACE.formatParts[0]
val returnWithNbsp = RETURN_EXPRESSION_BODY_PREFIX_NBSP.formatParts[0]
var originCodeBlockBuilder: CodeBlock.Builder? = null
for ((i, formatPart) in formatParts.withIndex()) {
if (formatPart.startsWith(returnWithSpace)) {
val builder = originCodeBlockBuilder ?: toBuilder()
originCodeBlockBuilder = builder
builder.formatParts[i] = formatPart.replaceFirst(returnWithSpace, returnWithNbsp)
}
}
return originCodeBlockBuilder?.build() ?: this
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
if (javaClass != other.javaClass) return false
return toString() == other.toString()
}
override fun hashCode(): Int = toString().hashCode()
override fun toString(): String = buildCodeString {
emit(
codeWriter = this,
enclosingName = "Constructor",
implicitModifiers = TypeSpec.Kind.CLASS.implicitFunctionModifiers(),
includeKdocTags = true,
)
}
@JvmOverloads
public fun toBuilder(name: String = this.name): Builder {
val builder = Builder(name)
builder.kdoc.add(kdoc)
builder.returnKdoc = returnKdoc
builder.receiverKdoc = receiverKdoc
builder.annotations += annotations
builder.modifiers += modifiers
builder.typeVariables += typeVariables
builder.returnType = returnType
builder.parameters += parameters
builder.delegateConstructor = delegateConstructor
builder.delegateConstructorArguments += delegateConstructorArguments
builder.body.add(body)
builder.receiverType = receiverType
builder.tags += tagMap.tags
builder.originatingElements += originatingElements
builder.contextReceiverTypes += contextReceiverTypes
return builder
}
public class Builder internal constructor(
internal val name: String,
) : Taggable.Builder<Builder>, OriginatingElementsHolder.Builder<Builder>, ContextReceivable.Builder<Builder> {
internal val kdoc = CodeBlock.builder()
internal var returnKdoc = CodeBlock.EMPTY
internal var receiverKdoc = CodeBlock.EMPTY
internal var receiverType: TypeName? = null
internal var returnType: TypeName? = null
internal var delegateConstructor: String? = null
internal var delegateConstructorArguments = listOf<CodeBlock>()
internal val body = CodeBlock.builder()
public val annotations: MutableList<AnnotationSpec> = mutableListOf()
public val modifiers: MutableList<KModifier> = mutableListOf()
public val typeVariables: MutableList<TypeVariableName> = mutableListOf()
public val parameters: MutableList<ParameterSpec> = mutableListOf()
override val tags: MutableMap<KClass<*>, Any> = mutableMapOf()
override val originatingElements: MutableList<Element> = mutableListOf()
override val contextReceiverTypes: MutableList<TypeName> = mutableListOf()
public fun addKdoc(format: String, vararg args: Any): Builder = apply {
kdoc.add(format, *args)
}
public fun addKdoc(block: CodeBlock): Builder = apply {
kdoc.add(block)
}
public fun addAnnotations(annotationSpecs: Iterable<AnnotationSpec>): Builder = apply {
this.annotations += annotationSpecs
}
public fun addAnnotation(annotationSpec: AnnotationSpec): Builder = apply {
annotations += annotationSpec
}
public fun addAnnotation(annotation: ClassName): Builder = apply {
annotations += AnnotationSpec.builder(annotation).build()
}
public fun addAnnotation(annotation: Class<*>): Builder =
addAnnotation(annotation.asClassName())
public fun addAnnotation(annotation: KClass<*>): Builder =
addAnnotation(annotation.asClassName())
public fun addModifiers(vararg modifiers: KModifier): Builder = apply {
this.modifiers += modifiers
}
public fun addModifiers(modifiers: Iterable<KModifier>): Builder = apply {
this.modifiers += modifiers
}
public fun jvmModifiers(modifiers: Iterable<Modifier>) {
var visibility = KModifier.INTERNAL
for (modifier in modifiers) {
when (modifier) {
Modifier.PUBLIC -> visibility = KModifier.PUBLIC
Modifier.PROTECTED -> visibility = KModifier.PROTECTED
Modifier.PRIVATE -> visibility = KModifier.PRIVATE
Modifier.ABSTRACT -> this.modifiers += KModifier.ABSTRACT
Modifier.FINAL -> this.modifiers += KModifier.FINAL
Modifier.NATIVE -> this.modifiers += KModifier.EXTERNAL
Modifier.DEFAULT -> Unit
Modifier.STATIC -> addAnnotation(JvmStatic::class)
Modifier.SYNCHRONIZED -> addAnnotation(Synchronized::class)
Modifier.STRICTFP -> addAnnotation(Strictfp::class)
else -> throw IllegalArgumentException("unexpected fun modifier $modifier")
}
}
this.modifiers += visibility
}
public fun addTypeVariables(typeVariables: Iterable<TypeVariableName>): Builder = apply {
this.typeVariables += typeVariables
}
public fun addTypeVariable(typeVariable: TypeVariableName): Builder = apply {
typeVariables += typeVariable
}
@ExperimentalKotlinPoetApi
override fun contextReceivers(receiverTypes: Iterable<TypeName>): Builder = apply {
check(!name.isConstructor) { "constructors cannot have context receivers" }
check(!name.isAccessor) { "$name cannot have context receivers" }
contextReceiverTypes += receiverTypes
}
@JvmOverloads public fun receiver(
receiverType: TypeName,
kdoc: CodeBlock = CodeBlock.EMPTY,
): Builder = apply {
check(!name.isConstructor) { "$name cannot have receiver type" }
this.receiverType = receiverType
this.receiverKdoc = kdoc
}
@JvmOverloads public fun receiver(
receiverType: Type,
kdoc: CodeBlock = CodeBlock.EMPTY,
): Builder = receiver(receiverType.asTypeName(), kdoc)
public fun receiver(
receiverType: Type,
kdoc: String,
vararg args: Any,
): Builder = receiver(receiverType, CodeBlock.of(kdoc, args))
@JvmOverloads public fun receiver(
receiverType: KClass<*>,
kdoc: CodeBlock = CodeBlock.EMPTY,
): Builder = receiver(receiverType.asTypeName(), kdoc)
public fun receiver(
receiverType: KClass<*>,
kdoc: String,
vararg args: Any,
): Builder = receiver(receiverType, CodeBlock.of(kdoc, args))
@JvmOverloads public fun returns(
returnType: TypeName,
kdoc: CodeBlock = CodeBlock.EMPTY,
): Builder = apply {
check(!name.isConstructor && !name.isAccessor) { "$name cannot have a return type" }
this.returnType = returnType
this.returnKdoc = kdoc
}
@JvmOverloads public fun returns(returnType: Type, kdoc: CodeBlock = CodeBlock.EMPTY): Builder =
returns(returnType.asTypeName(), kdoc)
public fun returns(returnType: Type, kdoc: String, vararg args: Any): Builder =
returns(returnType.asTypeName(), CodeBlock.of(kdoc, args))
@JvmOverloads public fun returns(
returnType: KClass<*>,
kdoc: CodeBlock = CodeBlock.EMPTY,
): Builder = returns(returnType.asTypeName(), kdoc)
public fun returns(returnType: KClass<*>, kdoc: String, vararg args: Any): Builder =
returns(returnType.asTypeName(), CodeBlock.of(kdoc, args))
public fun addParameters(parameterSpecs: Iterable<ParameterSpec>): Builder = apply {
for (parameterSpec in parameterSpecs) {
addParameter(parameterSpec)
}
}
public fun addParameter(parameterSpec: ParameterSpec): Builder = apply {
parameters += parameterSpec
}
public fun callThisConstructor(args: List<CodeBlock>): Builder = apply {
callConstructor("this", args)
}
public fun callThisConstructor(args: Iterable<CodeBlock>): Builder = apply {
callConstructor("this", args.toList())
}
public fun callThisConstructor(vararg args: String): Builder = apply {
callConstructor("this", args.map { CodeBlock.of(it) })
}
public fun callThisConstructor(vararg args: CodeBlock = emptyArray()): Builder = apply {
callConstructor("this", args.toList())
}
public fun callSuperConstructor(args: Iterable<CodeBlock>): Builder = apply {
callConstructor("super", args.toList())
}
public fun callSuperConstructor(args: List<CodeBlock>): Builder = apply {
callConstructor("super", args)
}
public fun callSuperConstructor(vararg args: String): Builder = apply {
callConstructor("super", args.map { CodeBlock.of(it) })
}
public fun callSuperConstructor(vararg args: CodeBlock = emptyArray()): Builder = apply {
callConstructor("super", args.toList())
}
private fun callConstructor(constructor: String, args: List<CodeBlock>) {
check(name.isConstructor) { "only constructors can delegate to other constructors!" }
delegateConstructor = constructor
delegateConstructorArguments = args
}
public fun addParameter(name: String, type: TypeName, vararg modifiers: KModifier): Builder =
addParameter(ParameterSpec.builder(name, type, *modifiers).build())
public fun addParameter(name: String, type: Type, vararg modifiers: KModifier): Builder =
addParameter(name, type.asTypeName(), *modifiers)
public fun addParameter(name: String, type: KClass<*>, vararg modifiers: KModifier): Builder =
addParameter(name, type.asTypeName(), *modifiers)
public fun addParameter(name: String, type: TypeName, modifiers: Iterable<KModifier>): Builder =
addParameter(ParameterSpec.builder(name, type, modifiers).build())
public fun addParameter(name: String, type: Type, modifiers: Iterable<KModifier>): Builder =
addParameter(name, type.asTypeName(), modifiers)
public fun addParameter(
name: String,
type: KClass<*>,
modifiers: Iterable<KModifier>,
): Builder = addParameter(name, type.asTypeName(), modifiers)
public fun addCode(format: String, vararg args: Any?): Builder = apply {
body.add(format, *args)
}
public fun addNamedCode(format: String, args: Map<String, *>): Builder = apply {
body.addNamed(format, args)
}
public fun addCode(codeBlock: CodeBlock): Builder = apply {
body.add(codeBlock)
}
public fun addComment(format: String, vararg args: Any): Builder = apply {
body.add("//·${format.replace(' ', '·')}\n", *args)
}
/**
* @param controlFlow the control flow construct and its code, such as "if (foo == 5)".
* * Shouldn't contain braces or newline characters.
*/
public fun beginControlFlow(controlFlow: String, vararg args: Any): Builder = apply {
body.beginControlFlow(controlFlow, *args)
}
/**
* @param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
* * Shouldn't contain braces or newline characters.
*/
public fun nextControlFlow(controlFlow: String, vararg args: Any): Builder = apply {
body.nextControlFlow(controlFlow, *args)
}
public fun endControlFlow(): Builder = apply {
body.endControlFlow()
}
public fun addStatement(format: String, vararg args: Any): Builder = apply {
body.addStatement(format, *args)
}
public fun clearBody(): Builder = apply {
body.clear()
}
public fun build(): FunSpec {
check(typeVariables.isEmpty() || !name.isAccessor) { "$name cannot have type variables" }
check(!(name == GETTER && parameters.isNotEmpty())) { "$name cannot have parameters" }
check(!(name == SETTER && parameters.size > 1)) { "$name can have at most one parameter" }
return FunSpec(this)
}
}
public companion object {
private const val CONSTRUCTOR = "constructor()"
internal const val GETTER = "get()"
internal const val SETTER = "set()"
internal val String.isConstructor get() = this == CONSTRUCTOR
internal val String.isAccessor get() = this.isOneOf(GETTER, SETTER)
private val RETURN_EXPRESSION_BODY_PREFIX_SPACE = CodeBlock.of("return ")
private val RETURN_EXPRESSION_BODY_PREFIX_NBSP = CodeBlock.of("return·")
private val THROW_EXPRESSION_BODY_PREFIX_SPACE = CodeBlock.of("throw ")
private val THROW_EXPRESSION_BODY_PREFIX_NBSP = CodeBlock.of("throw·")
@JvmStatic public fun builder(name: String): Builder = Builder(name)
@JvmStatic public fun constructorBuilder(): Builder = Builder(CONSTRUCTOR)
@JvmStatic public fun getterBuilder(): Builder = Builder(GETTER)
@JvmStatic public fun setterBuilder(): Builder = Builder(SETTER)
@DelicateKotlinPoetApi(
message = "Element APIs don't give complete information on Kotlin types. Consider using" +
" the kotlinpoet-metadata APIs instead.",
)
@JvmStatic
public fun overriding(method: ExecutableElement): Builder {
var modifiers: Set<Modifier> = method.modifiers
require(
Modifier.PRIVATE !in modifiers &&
Modifier.FINAL !in modifiers &&
Modifier.STATIC !in modifiers,
) {
"cannot override method with modifiers: $modifiers"
}
val methodName = method.simpleName.toString()
val funBuilder = builder(methodName)
funBuilder.addModifiers(KModifier.OVERRIDE)
modifiers = modifiers.toMutableSet()
modifiers.remove(Modifier.ABSTRACT)
funBuilder.jvmModifiers(modifiers)
method.typeParameters
.map { it.asType() as TypeVariable }
.map { it.asTypeVariableName() }
.forEach { funBuilder.addTypeVariable(it) }
funBuilder.returns(method.returnType.asTypeName())
funBuilder.addParameters(ParameterSpec.parametersOf(method))
if (method.isVarArgs) {
funBuilder.parameters[funBuilder.parameters.lastIndex] = funBuilder.parameters.last()
.toBuilder()
.addModifiers(VARARG)
.build()
}
if (method.thrownTypes.isNotEmpty()) {
val throwsValueString = method.thrownTypes.joinToString { "%T::class" }
funBuilder.addAnnotation(
AnnotationSpec.builder(Throws::class)
.addMember(throwsValueString, *method.thrownTypes.toTypedArray())
.build(),
)
}
return funBuilder
}
@Deprecated(
message = "Element APIs don't give complete information on Kotlin types. Consider using" +
" the kotlinpoet-metadata APIs instead.",
level = WARNING,
)
@JvmStatic
public fun overriding(
method: ExecutableElement,
enclosing: DeclaredType,
types: Types,
): Builder {
val executableType = types.asMemberOf(enclosing, method) as ExecutableType
val resolvedParameterTypes = executableType.parameterTypes
val resolvedReturnType = executableType.returnType
val builder = overriding(method)
builder.returns(resolvedReturnType.asTypeName())
var i = 0
val size = builder.parameters.size
while (i < size) {
val parameter = builder.parameters[i]
val type = resolvedParameterTypes[i].asTypeName()
builder.parameters[i] = parameter.toBuilder(parameter.name, type).build()
i++
}
return builder
}
}
}
| apache-2.0 | d1e14a581ae92011d172b0e6236a5c72 | 35.106129 | 127 | 0.686111 | 4.653246 | false | false | false | false |
LorittaBot/Loritta | common/src/commonMain/kotlin/net/perfectdreams/loritta/common/utils/Emotes.kt | 1 | 5007 | package net.perfectdreams.loritta.common.utils
import mu.KotlinLogging
import net.perfectdreams.loritta.common.entities.LorittaEmote
import net.perfectdreams.loritta.common.entities.UnicodeEmote
object Emotes {
private val lazyMgr = resettableManager()
private val logger = KotlinLogging.logger {}
var emoteManager: EmoteManager? = null
val MISSING_EMOTE = UnicodeEmote("\uD83D\uDC1B")
val ONLINE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("online") }
val IDLE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("idle") }
val DO_NOT_DISTURB: LorittaEmote by resettableLazy(lazyMgr) { getEmote("do_not_disturb") }
val OFFLINE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("offline") }
val BOT_TAG: LorittaEmote by resettableLazy(lazyMgr) { getEmote("bot_tag") }
val WUMPUS_BASIC: LorittaEmote by resettableLazy(lazyMgr) { getEmote("wumpus_basic") }
val LORI_TEMMIE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_temmie") }
val LORI_OWO: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_owo") }
val LORI_HAPPY: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_happy") }
val LORI_CRYING: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_crying") }
val LORI_RAGE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_rage") }
val LORI_SHRUG: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_shrug") }
val LORI_NITRO_BOOST: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_nitro_boost") }
val LORI_WOW: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_wow") }
val LORI_SMILE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_smile") }
val LORI_HM: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_hm") }
val LORI_RICH: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_rich") }
val LORI_PAT: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_pat") }
val LORI_YAY: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_yay") }
val LORI_HEART: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_heart") }
val LORI_HMPF: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_hmpf") }
val LORI_DEMON: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_demon") }
val LORI_BAN_HAMMER: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_ban_hammer") }
val LORI_COFFEE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_coffee") }
val LORI_NICE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_nice") }
val LORI_PRAY: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_pray") }
val LORI_STONKS: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_stonks") }
val LORI_HEART1: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_heart_1") }
val LORI_HEART2: LorittaEmote by resettableLazy(lazyMgr) { getEmote("lori_heart_2") }
val MINECRAFT_GRASS: LorittaEmote by resettableLazy(lazyMgr) { getEmote("minecraft_grass") }
val DEFAULT_DANCE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("default_dance") }
val FLOW_PODCAST: LorittaEmote by resettableLazy(lazyMgr) { getEmote("flow_podcast") }
val KOTLIN: LorittaEmote by resettableLazy(lazyMgr) { getEmote("kotlin") }
val JDA: LorittaEmote by resettableLazy(lazyMgr) { getEmote("jda") }
val ROBLOX_PREMIUM: LorittaEmote by resettableLazy(lazyMgr) { getEmote("roblox_premium") }
val DISCORD_BOT_LIST: LorittaEmote by resettableLazy(lazyMgr) { getEmote("discord_bot_list") }
// DISCORD BADGES
val DISCORD_STAFF: LorittaEmote by resettableLazy(lazyMgr) { getEmote("discord_staff") }
val DISCORD_PARTNER: LorittaEmote by resettableLazy(lazyMgr) { getEmote("discord_partner") }
val VERIFIED_DEVELOPER: LorittaEmote by resettableLazy(lazyMgr) { getEmote("verified_developer") }
val HYPESQUAD_EVENTS: LorittaEmote by resettableLazy(lazyMgr) { getEmote("hypesquad_events") }
val EARLY_SUPPORTER: LorittaEmote by resettableLazy(lazyMgr) { getEmote("early_supporter") }
val BUG_HUNTER_1: LorittaEmote by resettableLazy(lazyMgr) { getEmote("bug_hunter_1") }
val BUG_HUNTER_2: LorittaEmote by resettableLazy(lazyMgr) { getEmote("bug_hunter_2") }
// HYPESQUAD BADGES
val BRAVERY_HOUSE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("bravery_house") }
val BRILLIANCE_HOUSE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("brilliance_house") }
val BALANCE_HOUSE: LorittaEmote by resettableLazy(lazyMgr) { getEmote("balance_house") }
var emoteMap = mapOf<String, String>()
fun getEmote(name: String): LorittaEmote {
val code = emoteMap[name] ?: run {
logger.warn { "Missing emote for $name" }
return MISSING_EMOTE
}
val emoteManager = emoteManager ?: throw RuntimeException("emoteManager is null!")
return emoteManager.getEmoteByCode(code)
}
fun resetEmotes() {
lazyMgr.reset()
}
interface EmoteManager {
fun loadEmotes()
fun getEmoteByCode(code: String): LorittaEmote
class DefaultEmoteManager : EmoteManager {
override fun loadEmotes() {}
override fun getEmoteByCode(code: String) = UnicodeEmote(code)
}
}
} | agpl-3.0 | fbb3c601d9718c386c0c08f5cdfea2e3 | 54.032967 | 99 | 0.762133 | 3.145101 | false | false | false | false |
chrsep/Kingfish | app/src/main/java/com/directdev/portal/models/GradeModel.kt | 1 | 459 | package com.directdev.portal.models
import com.squareup.moshi.Json
import io.realm.RealmList
open class GradeModel(
open var credit: CreditModel = CreditModel(),
@Json(name = "grading_list")
open var gradings: List<GradingModel> = mutableListOf(GradingModel()),
@Json(name = "score")
open var scores: List<ScoreModel> = RealmList(ScoreModel()),
@Json(name = "strm")
open var term: String = "N/A"
)
| gpl-3.0 | 085d232e1a292102250956ff89e80d6c | 26 | 78 | 0.649237 | 3.731707 | false | false | false | false |
kekc42/memorizing-pager | app/src/main/java/com/lockwood/pagerdemo/PagerSecondActivity.kt | 1 | 1928 | package com.lockwood.pagerdemo
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.lockwood.pagerdemo.fragment.MessageFragment
import kotlinx.android.synthetic.main.activity_pager_2.*
class PagerSecondActivity : BaseNavigationActivity(R.layout.activity_pager_2) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initViewPager()
}
override fun onBackPressed() {
if (!navigationHistory.isEmpty()) {
// Use false to transition immediately
pager.setCurrentItem(navigationHistory.popLastSelected(), false)
} else if (pager.currentItem != HOME_NAVIGATION_ITEM) {
// return to default/home item
pager.setCurrentItem(HOME_NAVIGATION_ITEM, false)
} else {
super.onBackPressed()
}
}
private fun initViewPager() = with(pager) {
adapter = object : FragmentStateAdapter(this@PagerSecondActivity) {
override fun getItemCount(): Int = navigation.menu.size()
override fun createFragment(p0: Int): Fragment = MessageFragment.newInstance(p0)
}
registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
navigation.menu.getItem(position).isChecked = true
}
})
// disable swipe
isUserInputEnabled = false
}
override fun onNavigationItemSelected(item: MenuItem): Boolean = with(item) {
return if (!isItemSelected(itemId)) {
pager.setCurrentItem(order, false)
navigationHistory.pushItem(order)
true
} else {
false
}
}
}
| apache-2.0 | fee087bad0eb8a8acf092696432029e8 | 34.054545 | 92 | 0.661307 | 4.994819 | false | false | false | false |
usommerl/kotlin-koans | src/ii_collections/_15_AllAnyAndOtherPredicates.kt | 1 | 1126 | 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 true if the customer is from the given city
return this.city == city
}
fun Shop.checkAllCustomersAreFrom(city: City): Boolean {
// Return true if all customers are from the given city
return this.customers.all { it.isFrom(city) }
}
fun Shop.hasCustomerFrom(city: City): Boolean {
// Return true if there is at least one customer from the given city
return customers.any { it.isFrom(city) }
}
fun Shop.countCustomersFrom(city: City): Int {
// Return the number of customers from the given city
return customers.count { it.isFrom(city)}
}
fun Shop.findAnyCustomerFrom(city: City): Customer? {
// Return a customer who lives in the given city, or null if there is none
return customers.firstOrNull { it.isFrom(city) }
}
| mit | 60d2668719f01d623277f601603cc675 | 27.871795 | 78 | 0.694494 | 3.753333 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/activities/PersonInfoActivity.kt | 1 | 2396 | package be.digitalia.fosdem.activities
import android.content.ActivityNotFoundException
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabsIntent
import androidx.fragment.app.add
import androidx.fragment.app.commit
import androidx.lifecycle.lifecycleScope
import be.digitalia.fosdem.R
import be.digitalia.fosdem.db.ScheduleDao
import be.digitalia.fosdem.fragments.PersonInfoListFragment
import be.digitalia.fosdem.model.Person
import be.digitalia.fosdem.utils.configureToolbarColors
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class PersonInfoActivity : AppCompatActivity(R.layout.person_info) {
@Inject
lateinit var scheduleDao: ScheduleDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(findViewById(R.id.toolbar))
val person: Person = intent.getParcelableExtra(EXTRA_PERSON)!!
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = person.name
findViewById<View>(R.id.fab).setOnClickListener {
openPersonDetails(person)
}
if (savedInstanceState == null) {
supportFragmentManager.commit {
add<PersonInfoListFragment>(R.id.content,
args = PersonInfoListFragment.createArguments(person))
}
}
}
private fun openPersonDetails(person: Person) {
val context = this
lifecycleScope.launchWhenStarted {
person.getUrl(scheduleDao.getYear())?.let { url ->
try {
CustomTabsIntent.Builder()
.configureToolbarColors(context, R.color.light_color_primary)
.setStartAnimations(context, R.anim.slide_in_right, R.anim.slide_out_left)
.setExitAnimations(context, R.anim.slide_in_left, R.anim.slide_out_right)
.build()
.launchUrl(context, Uri.parse(url))
} catch (ignore: ActivityNotFoundException) {
}
}
}
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
companion object {
const val EXTRA_PERSON = "person"
}
} | apache-2.0 | d6ae735980325582ab5a31a0228cc660 | 32.291667 | 98 | 0.666945 | 4.909836 | false | false | false | false |
Shynixn/PetBlocks | petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/business/service/GUIPetStorageServiceImpl.kt | 1 | 5856 | package com.github.shynixn.petblocks.core.logic.business.service
import com.github.shynixn.petblocks.api.business.enumeration.MaterialType
import com.github.shynixn.petblocks.api.business.localization.Messages
import com.github.shynixn.petblocks.api.business.service.*
import com.github.shynixn.petblocks.api.persistence.entity.AIInventory
import com.github.shynixn.petblocks.api.persistence.entity.PetMeta
import com.github.shynixn.petblocks.core.logic.persistence.entity.ItemEntity
import com.github.shynixn.petblocks.core.logic.persistence.entity.StorageInventoryCache
import com.google.inject.Inject
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class GUIPetStorageServiceImpl @Inject constructor(
private val persistencePetMetaService: PersistencePetMetaService,
private val itemTypeService: ItemTypeService,
private val proxyService: ProxyService,
private val loggingService: LoggingService
) :
GUIPetStorageService {
private val storageCache = HashMap<Any, StorageInventoryCache>()
/**
* Opens the storage of the given [petMeta] for the given player.
* If the petMeta belongs to a different player than the given player, the
* inventory gets opened in readOnlyMode.
*/
override fun <P> openStorage(player: P, petMeta: PetMeta, from: Int, to: Int) {
require(player is Any)
if (from > to) {
loggingService.warn("Cannot open storage. Script parameter to cannot be smaller than from!")
return
}
val size = if (to - from > 27) {
54
} else {
27
}
val guiTitle = Messages.guiTitle + " " + from + "-" + (from + size - 1)
val inventory = proxyService.openInventory<Any, Any>(player, guiTitle, size)
val inventoryAI = petMeta.aiGoals.firstOrNull { a -> a is AIInventory } as AIInventory?
if (inventoryAI == null) {
loggingService.warn("Player " + proxyService.getPlayerName(player) + " tried to open a pet inventory without a AIInventory.")
loggingService.warn("Apply an AIInventory to your players.")
proxyService.closeInventory(player)
return
}
var index = from - 1
for (i in 0 until size) {
if (index >= inventoryAI.items.size) {
break
}
try {
proxyService.setInventoryItem(inventory, i, inventoryAI.items[index])
} catch (e: Exception) {
// Inventory might not be available.
}
index++
}
storageCache[player] =
StorageInventoryCache(from, to, inventory, proxyService.getPlayerUUID(player) != petMeta.playerMeta.uuid)
proxyService.updateInventory(player)
}
/**
* Returns if the given [inventory] matches the storage inventory of this service.
*/
override fun <I> isStorage(inventory: I): Boolean {
require(inventory is Any)
val holder = proxyService.getPlayerFromInventory<Any, I>(inventory) ?: return false
val originInventory = proxyService.getLowerInventory(inventory)
return this.storageCache.containsKey(holder) && this.storageCache[holder]!!.inventory == originInventory
}
/**
* Saves the storage inventory to the database and clears all resources.
*/
override fun <P> saveStorage(player: P) {
require(player is Any)
if (!storageCache.containsKey(player)) {
return
}
if (storageCache[player]!!.readOnly) {
storageCache.remove(player)
return
}
val from = storageCache[player]!!.from - 1
val to = storageCache[player]!!.to
val inventory = storageCache[player]!!.inventory
val petMeta = persistencePetMetaService.getPetMetaFromPlayer(player)
val inventoryAI = petMeta.aiGoals.first { a -> a is AIInventory } as AIInventory
val newItems = ArrayList<Any?>()
var i = 0
var inventoryI = 0
while (true) {
if (i in from until to) {
val item = proxyService.getInventoryItem<Any, Any>(inventory, inventoryI)
if (item == null) {
newItems.add(itemTypeService.toItemStack(ItemEntity(MaterialType.AIR.name)))
} else {
newItems.add(item)
}
inventoryI++
} else if (i >= inventoryAI.items.size) {
break
} else {
newItems.add(inventoryAI.items[i])
}
i++
}
inventoryAI.items = newItems
storageCache.remove(player)
}
} | apache-2.0 | 48a2da6ed9a68e083afba884787609c8 | 36.787097 | 137 | 0.650786 | 4.553655 | false | false | false | false |
mcmacker4/PBR-Test | src/main/kotlin/net/upgaming/pbrengine/window/Display.kt | 1 | 2679 | package net.upgaming.pbrengine.window
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11.*
import org.lwjgl.system.MemoryUtil.NULL
class Display(var width: Int, var height: Int, title: String) {
val window: Long
var mouseDX = 0
private set
var mouseDY = 0
private set
private var mouseX = 0
private var mouseY = 0
init {
if(!glfwInit())
throw IllegalStateException("Could not initialize GLFW")
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE)
glfwWindowHint(GLFW_VISIBLE, GLFW_TRUE)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
window = glfwCreateWindow(width, height, title, NULL, NULL)
val vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor())
glfwSetWindowPos(
window,
(vidmode.width() - width) / 2,
(vidmode.height() - height) / 2
)
glfwSetKeyCallback(window, { window, key, scancode, action, mods ->
if(key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
markForDestruction()
})
glfwSetWindowSizeCallback(window, { window, width, height ->
this.width = width
this.height = height
glViewport(0, 0, width, height)
})
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED)
glfwMakeContextCurrent(window)
GL.createCapabilities()
glfwSwapInterval(0)
glClearColor(0f, 0f, 0f, 1f)
glEnable(GL_DEPTH_TEST)
}
fun update() {
mouseUpdate()
glfwSwapBuffers(window)
glfwPollEvents()
}
private fun mouseUpdate() {
val amx = DoubleArray(1)
val amy = DoubleArray(1)
glfwGetCursorPos(window, amx, amy)
val mx = amx[0].toInt()
val my = amy[0].toInt()
mouseDX = mx - mouseX
mouseDY = my - mouseY
mouseX = mx
mouseY = my
}
fun shouldClose(): Boolean {
return glfwWindowShouldClose(window)
}
fun markForDestruction() {
glfwSetWindowShouldClose(window, true)
}
fun isKeyDown(glfwKey: Int): Boolean {
return glfwGetKey(window, glfwKey) == GLFW_PRESS
}
fun isBtnDown(glfwBtn: Int): Boolean{
return glfwGetMouseButton(window, glfwBtn) == GLFW_PRESS
}
fun destroy() {
glfwDestroyWindow(window)
}
} | apache-2.0 | 97e22d2ce8e49c9f456b317cd00a6ff1 | 25.534653 | 76 | 0.574095 | 4.487437 | false | false | false | false |
owncloud/android | owncloudApp/src/main/java/com/owncloud/android/providers/DocumentsStorageProvider.kt | 1 | 21727 | /**
* ownCloud Android client application
*
* @author Bartosz Przybylski
* @author Christian Schabesberger
* @author David González Verdugo
* @author Abel García de Prada
* @author Shashvat Kedia
* Copyright (C) 2015 Bartosz Przybylski
* Copyright (C) 2020 ownCloud GmbH.
* <p>
* This program 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.providers
import android.accounts.Account
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.database.Cursor
import android.graphics.Point
import android.net.Uri
import android.os.CancellationSignal
import android.os.Handler
import android.os.ParcelFileDescriptor
import android.preference.PreferenceManager
import android.provider.DocumentsContract
import android.provider.DocumentsProvider
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.authentication.AccountUtils
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.files.services.FileDownloader
import com.owncloud.android.files.services.FileUploader
import com.owncloud.android.files.services.TransferRequester
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.resources.files.FileUtils
import com.owncloud.android.operations.CopyFileOperation
import com.owncloud.android.operations.CreateFolderOperation
import com.owncloud.android.operations.MoveFileOperation
import com.owncloud.android.operations.RefreshFolderOperation
import com.owncloud.android.operations.RemoveFileOperation
import com.owncloud.android.operations.RenameFileOperation
import com.owncloud.android.operations.SynchronizeFileOperation
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.providers.cursors.FileCursor
import com.owncloud.android.providers.cursors.RootCursor
import com.owncloud.android.presentation.ui.settings.fragments.SettingsSecurityFragment.Companion.PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER
import com.owncloud.android.utils.FileStorageUtils
import com.owncloud.android.utils.NotificationUtils
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.util.HashMap
import java.util.Vector
class DocumentsStorageProvider : DocumentsProvider() {
/**
* If a directory requires to sync, it will write the id of the directory into this variable.
* After the sync function gets triggered again over the same directory, it will see that a sync got already
* triggered, and does not need to be triggered again. This way a endless loop is prevented.
*/
private var requestedFolderIdForSync: Long = -1
private var syncRequired = true
private var currentStorageManager: FileDataStorageManager? = null
private lateinit var fileToUpload: OCFile
override fun openDocument(
documentId: String,
mode: String,
signal: CancellationSignal?
): ParcelFileDescriptor? {
Timber.d("Trying to open $documentId in mode $mode")
// If documentId == NONEXISTENT_DOCUMENT_ID only Upload is needed because file does not exist in our database yet.
var ocFile: OCFile
val uploadOnly: Boolean = documentId == NONEXISTENT_DOCUMENT_ID
var accessMode: Int = ParcelFileDescriptor.parseMode(mode)
val isWrite: Boolean = mode.contains("w")
if (!uploadOnly) {
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
ocFile = getFileByIdOrException(docId)
if (!ocFile.isDown) {
val intent = Intent(context, FileDownloader::class.java).apply {
putExtra(FileDownloader.KEY_ACCOUNT, getAccountFromFileId(docId))
putExtra(FileDownloader.KEY_FILE, ocFile)
}
context?.startService(intent)
do {
if (!waitOrGetCancelled(signal)) {
return null
}
ocFile = getFileByIdOrException(docId)
} while (!ocFile.isDown)
}
} else {
ocFile = fileToUpload
accessMode = accessMode or ParcelFileDescriptor.MODE_CREATE
}
val fileToOpen = File(ocFile.storagePath)
if (!isWrite) return ParcelFileDescriptor.open(fileToOpen, accessMode)
val handler = Handler(MainApp.appContext.mainLooper)
// Attach a close listener if the document is opened in write mode.
try {
return ParcelFileDescriptor.open(fileToOpen, accessMode, handler) {
// Update the file with the cloud server. The client is done writing.
Timber.d("A file with id $documentId has been closed! Time to synchronize it with server.")
// If only needs to upload that file
if (uploadOnly) {
ocFile.fileLength = fileToOpen.length()
TransferRequester().run {
uploadNewFile(
context,
currentStorageManager?.account,
ocFile.storagePath,
ocFile.remotePath,
FileUploader.LOCAL_BEHAVIOUR_COPY,
ocFile.mimetype,
false,
UploadFileOperation.CREATED_BY_USER
)
}
} else {
Thread {
SynchronizeFileOperation(
ocFile,
null,
getAccountFromFileId(ocFile.fileId),
false,
context,
false
).apply {
val result = execute(currentStorageManager, context)
if (result.code == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
context?.let {
NotificationUtils.notifyConflict(
ocFile,
getAccountFromFileId(ocFile.fileId),
it
)
}
}
}
}.start()
}
}
} catch (e: IOException) {
throw FileNotFoundException("Failed to open document with id $documentId and mode $mode")
}
}
override fun queryChildDocuments(
parentDocumentId: String,
projection: Array<String>?,
sortOrder: String?
): Cursor {
val folderId = parentDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(folderId)
val resultCursor = FileCursor(projection)
// Create result cursor before syncing folder again, in order to enable faster loading
currentStorageManager?.getFolderContent(currentStorageManager?.getFileById(folderId))
?.forEach { file -> resultCursor.addFile(file) }
//Create notification listener
val notifyUri: Uri = toNotifyUri(toUri(parentDocumentId))
resultCursor.setNotificationUri(context?.contentResolver, notifyUri)
/**
* This will start syncing the current folder. User will only see this after updating his view with a
* pull down, or by accessing the folder again.
*/
if (requestedFolderIdForSync != folderId && syncRequired && currentStorageManager != null) {
// register for sync
syncDirectoryWithServer(parentDocumentId)
requestedFolderIdForSync = folderId
resultCursor.setMoreToSync(true)
} else {
requestedFolderIdForSync = -1
}
syncRequired = true
return resultCursor
}
override fun queryDocument(documentId: String, projection: Array<String>?): Cursor {
Timber.d("Query Document: $documentId")
if (documentId == NONEXISTENT_DOCUMENT_ID) return FileCursor(projection).apply {
addFile(fileToUpload)
}
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
return FileCursor(projection).apply {
getFileById(docId)?.let { addFile(it) }
}
}
override fun onCreate(): Boolean = true
override fun queryRoots(projection: Array<String>?): Cursor {
val result = RootCursor(projection)
val contextApp = context ?: return result
val accounts = AccountUtils.getAccounts(contextApp)
// If access from document provider is not allowed, return empty cursor
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
val lockAccessFromDocumentProvider = preferences.getBoolean(PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER, false)
if (lockAccessFromDocumentProvider && accounts.isNotEmpty()) {
return result.apply { addProtectedRoot(contextApp) }
}
initiateStorageMap()
for (account in accounts) {
result.addRoot(account, contextApp)
}
return result
}
override fun openDocumentThumbnail(
documentId: String,
sizeHint: Point?,
signal: CancellationSignal?
): AssetFileDescriptor {
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
val file = getFileById(docId)
val realFile = File(file?.storagePath)
return AssetFileDescriptor(
ParcelFileDescriptor.open(realFile, ParcelFileDescriptor.MODE_READ_ONLY),
0,
AssetFileDescriptor.UNKNOWN_LENGTH
)
}
override fun querySearchDocuments(
rootId: String,
query: String,
projection: Array<String>?
): Cursor {
updateCurrentStorageManagerIfNeeded(rootId)
val result = FileCursor(projection)
val root = getFileByPath(OCFile.ROOT_PATH) ?: return result
for (f in findFiles(root, query)) {
result.addFile(f)
}
return result
}
override fun createDocument(
parentDocumentId: String,
mimeType: String,
displayName: String
): String {
Timber.d("Create Document ParentID $parentDocumentId Type $mimeType DisplayName $displayName")
val parentDocId = parentDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(parentDocId)
val parentDocument = getFileByIdOrException(parentDocId)
return if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
createFolder(parentDocument, displayName)
} else {
createFile(parentDocument, mimeType, displayName)
}
}
override fun renameDocument(documentId: String, displayName: String): String? {
Timber.d("Trying to rename $documentId to $displayName")
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
val file = getFileByIdOrException(docId)
RenameFileOperation(file.remotePath, displayName).apply {
execute(currentStorageManager, context).also {
checkOperationResult(
it,
file.parentId.toString()
)
}
}
return null
}
override fun deleteDocument(documentId: String) {
Timber.d("Trying to delete $documentId")
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
val file = getFileByIdOrException(docId)
RemoveFileOperation(file.remotePath, false, true).apply {
execute(currentStorageManager, context).also {
checkOperationResult(
it,
file.parentId.toString()
)
}
}
}
override fun copyDocument(sourceDocumentId: String, targetParentDocumentId: String): String {
Timber.d("Trying to copy $sourceDocumentId to $targetParentDocumentId")
val sourceDocId = sourceDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(sourceDocId)
val sourceFile = getFileByIdOrException(sourceDocId)
val targetParentDocId = targetParentDocumentId.toLong()
val targetParentFile = getFileByIdOrException(targetParentDocId)
CopyFileOperation(
sourceFile.remotePath,
targetParentFile.remotePath
).apply {
execute(currentStorageManager, context).also { result ->
syncRequired = false
checkOperationResult(result, targetParentFile.fileId.toString())
//Returns the document id of the document copied at the target destination
var newPath = targetParentFile.remotePath + sourceFile.fileName
if (sourceFile.isFolder) {
newPath += File.separator
}
val newFile = getFileByPathOrException(newPath)
return newFile.fileId.toString()
}
}
}
override fun moveDocument(
sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String
): String {
Timber.d("Trying to move $sourceDocumentId to $targetParentDocumentId")
val sourceDocId = sourceDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(sourceDocId)
val sourceFile = getFileByIdOrException(sourceDocId)
val targetParentDocId = targetParentDocumentId.toLong()
val targetParentFile = getFileByIdOrException(targetParentDocId)
MoveFileOperation(
sourceFile.remotePath,
targetParentFile.remotePath
).apply {
execute(currentStorageManager, context).also { result ->
syncRequired = false
checkOperationResult(result, targetParentFile.fileId.toString())
//Returns the document id of the document moved to the target destination
var newPath = targetParentFile.remotePath + sourceFile.fileName
if (sourceFile.isFolder) newPath += File.separator
val newFile = getFileByPathOrException(newPath)
return newFile.fileId.toString()
}
}
}
private fun checkOperationResult(result: RemoteOperationResult<Any>, folderToNotify: String) {
if (!result.isSuccess) {
if (result.code != RemoteOperationResult.ResultCode.WRONG_CONNECTION) notifyChangeInFolder(
folderToNotify
)
throw FileNotFoundException("Remote Operation failed")
}
syncRequired = false
notifyChangeInFolder(folderToNotify)
}
private fun createFolder(parentDocument: OCFile, displayName: String): String {
val newPath = parentDocument.remotePath + displayName + File.separator
if (!FileUtils.isValidName(displayName)) {
throw UnsupportedOperationException("Folder $displayName contains at least one invalid character")
}
Timber.d("Trying to create folder with path $newPath")
CreateFolderOperation(newPath, false).apply {
execute(currentStorageManager, context).also { result ->
checkOperationResult(result, parentDocument.fileId.toString())
val newFolder = getFileByPathOrException(newPath)
return newFolder.fileId.toString()
}
}
}
private fun createFile(parentDocument: OCFile, mimeType: String, displayName: String): String {
// We just need to return a Document ID, so we'll return an empty one. File does not exist in our db yet.
// File will be created at [openDocument] method.
val tempDir =
File(FileStorageUtils.getTemporalPath(getAccountFromFileId(parentDocument.fileId)?.name))
val newFile = File(tempDir, displayName)
fileToUpload = OCFile(parentDocument.remotePath + displayName).apply {
mimetype = mimeType
parentId = parentDocument.fileId
storagePath = newFile.path
}
return NONEXISTENT_DOCUMENT_ID
}
private fun updateCurrentStorageManagerIfNeeded(docId: Long) {
if (rootIdToStorageManager.isEmpty()) {
initiateStorageMap()
}
if (currentStorageManager == null || (
rootIdToStorageManager.containsKey(docId) &&
currentStorageManager !== rootIdToStorageManager[docId])
) {
currentStorageManager = rootIdToStorageManager[docId]
}
}
private fun updateCurrentStorageManagerIfNeeded(rootId: String) {
if (rootIdToStorageManager.isEmpty()) {
return
}
for (data in rootIdToStorageManager.values) {
if (data.account.name == rootId) {
currentStorageManager = data
}
}
}
private fun initiateStorageMap() {
for (account in AccountUtils.getAccounts(context)) {
val storageManager = FileDataStorageManager(MainApp.appContext, account, MainApp.appContext.contentResolver)
val rootDir = storageManager.getFileByPath(OCFile.ROOT_PATH)
rootIdToStorageManager[rootDir!!.fileId] = storageManager
}
}
private fun syncDirectoryWithServer(parentDocumentId: String) {
Timber.d("Trying to sync $parentDocumentId with server")
val folderId = parentDocumentId.toLong()
getFileByIdOrException(folderId)
val refreshFolderOperation = RefreshFolderOperation(
getFileById(folderId),
false,
getAccountFromFileId(folderId),
context
).apply { syncVersionAndProfileEnabled(false) }
val thread = Thread {
refreshFolderOperation.execute(getStoreManagerFromFileId(folderId), context)
notifyChangeInFolder(parentDocumentId)
}
thread.start()
}
private fun waitOrGetCancelled(cancellationSignal: CancellationSignal?): Boolean {
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
return false
}
return cancellationSignal == null || !cancellationSignal.isCanceled
}
private fun findFiles(root: OCFile, query: String): Vector<OCFile> {
val result = Vector<OCFile>()
val folderContent = currentStorageManager?.getFolderContent(root) ?: return result
folderContent.forEach {
if (it.fileName.contains(query)) {
result.add(it)
if (it.isFolder) result.addAll(findFiles(it, query))
}
}
return result
}
private fun notifyChangeInFolder(folderToNotify: String) {
context?.contentResolver?.notifyChange(toNotifyUri(toUri(folderToNotify)), null)
}
private fun toNotifyUri(uri: Uri): Uri = DocumentsContract.buildDocumentUri(
context?.resources?.getString(R.string.document_provider_authority),
uri.toString()
)
private fun toUri(documentId: String): Uri = Uri.parse(documentId)
private fun getFileByIdOrException(id: Long): OCFile =
getFileById(id) ?: throw FileNotFoundException("File $id not found")
private fun getFileById(id: Long): OCFile? = getStoreManagerFromFileId(id)?.getFileById(id)
private fun getAccountFromFileId(id: Long): Account? = getStoreManagerFromFileId(id)?.account
private fun getStoreManagerFromFileId(id: Long): FileDataStorageManager? {
// If file is found in current storage manager, return it
currentStorageManager?.getFileById(id)?.let { return currentStorageManager }
// Else, look for it in other ones
var fileFromOtherStorageManager: OCFile?
var otherStorageManager: FileDataStorageManager? = null
for (key in rootIdToStorageManager.keys) {
otherStorageManager = rootIdToStorageManager[key]
// Skip current storage manager, already checked
if (otherStorageManager == currentStorageManager) continue
fileFromOtherStorageManager = otherStorageManager?.getFileById(id)
if (fileFromOtherStorageManager != null) {
Timber.d("File with id $id found in storage manager: $otherStorageManager")
break
}
}
return otherStorageManager
}
private fun getFileByPathOrException(path: String): OCFile =
getFileByPath(path) ?: throw FileNotFoundException("File $path not found")
private fun getFileByPath(path: String): OCFile? = currentStorageManager?.getFileByPath(path)
companion object {
private var rootIdToStorageManager: MutableMap<Long, FileDataStorageManager> = HashMap()
const val NONEXISTENT_DOCUMENT_ID = "-1"
}
}
| gpl-2.0 | efa34aa8296f8a7c6c5db0304f5d8624 | 37.519504 | 143 | 0.643406 | 5.32998 | false | false | false | false |
konachan700/Mew | software/MeWSync/app/src/main/java/com/mewhpm/mewsync/ui/recyclerview/RecyclerViewAbstract.kt | 1 | 2445 | package com.mewhpm.mewsync.ui.recyclerview
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView
import com.mewhpm.mewsync.ui.recyclerview.adapters.SimpleTextIconAdapter
import com.mewhpm.mewsync.ui.recyclerview.adapters.TextPairWithIconAdapter
import com.mewhpm.mewsync.ui.recyclerview.data.TextPairWithIcon
abstract class RecyclerViewAbstract<T> : RecyclerView {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
abstract fun requestList() : List<Pair<TextPairWithIcon, T>>
abstract fun onElementClick(position: Int, item: TextPairWithIcon, obj: T)
abstract fun onElementLongClick(position: Int, item: TextPairWithIcon, obj: T)
inner class TextPairWithIconAdapterImpl : TextPairWithIconAdapter() {
override fun requestDataTextPairWithIcon(position: Int): TextPairWithIcon = requestList()[position].first
override fun requestListSize(): Int = requestList().size
override fun requestContext(): Context = [email protected]
override fun onElementClick(position: Int) {
onElementClick(position, requestList()[position].first, requestList()[position].second)
}
override fun onElementLongClick(position: Int) {
onElementLongClick(position, requestList()[position].first, requestList()[position].second)
}
}
inner class SimpleTextIconAdapterImpl : SimpleTextIconAdapter() {
override fun requestDataTextPairWithIcon(position: Int): TextPairWithIcon = requestList()[position].first
override fun requestListSize(): Int = requestList().size
override fun requestContext(): Context = [email protected]
override fun onElementClick(position: Int) {
onElementClick(position, requestList()[position].first, requestList()[position].second)
}
override fun onElementLongClick(position: Int) {
onElementLongClick(position, requestList()[position].first, requestList()[position].second)
}
}
open fun create() {
this.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this.context)
//this.adapter = TextPairWithIconAdapterImpl()
}
} | gpl-3.0 | 8716c8bf036fe78bc7652d00acc7c7ae | 46.960784 | 113 | 0.741922 | 5.180085 | false | false | false | false |
IntershopCommunicationsAG/jiraconnector-gradle-plugin | src/main/kotlin/com/intershop/gradle/jiraconnector/task/SetIssueFieldRunner.kt | 1 | 3621 | /*
* Copyright 2020 Intershop Communications AG.
*
* 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.intershop.gradle.jiraconnector.task
import com.intershop.gradle.jiraconnector.task.jira.InvalidFieldnameException
import com.intershop.gradle.jiraconnector.task.jira.JiraConnector
import com.intershop.gradle.jiraconnector.task.jira.JiraIssueParser
import org.gradle.api.GradleException
import org.gradle.workers.WorkAction
import org.joda.time.DateTime
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Work action implementation for the SetIssueField task.
*/
abstract class SetIssueFieldRunner: WorkAction<SetIssueFieldParameters> {
companion object {
/**
* Logger instance for logging.
*/
val log: Logger = LoggerFactory.getLogger(this::class.java.name)
}
override fun execute() {
var fieldValueInt: String? = null
val issueList = JiraIssueParser.parse(
parameters.issueFile.get().asFile,
parameters.linePattern.get(),
parameters.jiraIssuePattern.get())
val connector = getPreparedConnector()
if(parameters.fieldPattern.get().isNotEmpty()) {
val regex = Regex(parameters.fieldPattern.get())
fieldValueInt = regex.find(parameters.fieldValue.get())?.value
}
if(fieldValueInt == null) {
fieldValueInt = parameters.fieldValue.get()
log.warn("Fieldvalue {} is used, because field pattern does not work correctly.", fieldValueInt)
}
if(connector != null && fieldValueInt != null) {
try {
connector.processIssues(issueList, parameters.fieldName.get(), fieldValueInt,
parameters.versionMessage.get(), parameters.mergeMilestoneVersions.get(), DateTime ())
} catch (ex: InvalidFieldnameException) {
throw GradleException ("It was not possible to write data to Jira server with '${ex.message}'")
} catch (ex: GradleException) {
throw ex
} catch (ex: Exception) {
throw GradleException ("It was not possible to write data to Jira server", ex)
}
} else {
throw GradleException ("It was not possible to initialize the process. Please check the configuration.")
}
}
private fun getPreparedConnector(): JiraConnector? {
if(parameters.baseUrl.isPresent &&
parameters.userName.isPresent &&
parameters.userPassword.isPresent ) {
val connector = JiraConnector(
parameters.baseUrl.get(),
parameters.userName.get(),
parameters.userPassword.get())
if(parameters.socketTimeout.isPresent) {
connector.socketTimeout = parameters.socketTimeout.get()
}
if(parameters.requestTimeout.isPresent) {
connector.requestTimeout = parameters.requestTimeout.get()
}
return connector
}
return null
}
}
| apache-2.0 | 92a8d909d3fd5f200932498583f852d5 | 37.115789 | 116 | 0.648716 | 4.796026 | false | false | false | false |
camsteffen/polite | src/main/java/me/camsteffen/polite/rule/edit/EditCalendarRuleViewModel.kt | 1 | 2109 | package me.camsteffen.polite.rule.edit
import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import me.camsteffen.polite.model.CalendarEventMatchBy
import me.camsteffen.polite.model.CalendarRule
import javax.inject.Inject
class EditCalendarRuleViewModel
@Inject constructor(application: Application) : EditRuleViewModel<CalendarRule>(application) {
val busyOnly = MutableLiveData<Boolean>()
val calendarIds = MutableLiveData<Set<Long>>()
val inverseMatch: LiveData<Boolean>
get() = inverseMatchMutable
val matchBy = MutableLiveData<CalendarEventMatchBy>()
val keywords: LiveData<Set<String>>
get() = keywordsLiveData
private val keywordsLiveData = MutableLiveData<Set<String>>()
private val keywordSet: MutableSet<String> = hashSetOf()
private val inverseMatchMutable = MutableLiveData<Boolean>()
val showKeywords: LiveData<Boolean> = Transformations.map(matchBy) { matchBy ->
matchBy != CalendarEventMatchBy.ALL
}
init {
busyOnly.value = false
calendarIds.value = emptySet()
keywordsLiveData.value = keywordSet
}
override fun setRule(rule: CalendarRule) {
super.setRule(rule)
busyOnly.value = rule.busyOnly
inverseMatchMutable.value = rule.inverseMatch
matchBy.value = rule.matchBy
calendarIds.value = rule.calendarIds
keywordSet.clear()
keywordSet.addAll(rule.keywords)
invalidateKeywordsLiveData()
}
fun addKeyword(keyword: String): Boolean {
val added = keywordSet.add(keyword)
if (added) {
invalidateKeywordsLiveData()
}
return added
}
fun setInverseMatch(inverseSelect: Boolean) {
inverseMatchMutable.value = inverseSelect
}
fun removeWord(word: String) {
if (keywordSet.remove(word)) {
invalidateKeywordsLiveData()
}
}
private fun invalidateKeywordsLiveData() {
keywordsLiveData.value = keywordSet
}
}
| mpl-2.0 | 7d657bd5603b12dd8458fe442f59d5a3 | 27.890411 | 94 | 0.698435 | 4.815068 | false | false | false | false |
drmashu/dikon | src/main/kotlin/io/github/drmashu/dikon/ComponentFactory.kt | 1 | 3069 | package io.github.drmashu.dikon
import kotlin.reflect.*
/**
* オブジェクトの生成方法を定義するためのインターフェイス
* @author NAGASAWA Takahiro<[email protected]>
*/
public interface Factory<T: Any> {
/**
* インスタンスの取得
* @return インスタンス
*/
fun get(dikon: Container) : T?
}
/**
* シングルトンを実装するファクトリ
* @author NAGASAWA Takahiro<[email protected]>
*/
public open class Singleton<T: Any>(val factory: Factory<T>) : Factory<T> {
/**
* インスタンス
*/
private var instance :T? = null
/**
* インスタンスの取得
* @return インスタンス
*/
public override fun get(dikon: Container) : T? {
// インスタンスが存在しない場合だけ、インスタンスを作成する
if (instance == null) {
instance = factory.get(dikon)
}
return instance
}
}
/**
* インスタンスを作るだけのファクトリ.
* @author NAGASAWA Takahiro<[email protected]>
* @param kClass 生成対象のクラス
*/
public open class Create<T: Any>(val kClass: KClass<T>) : Factory<T> {
override fun get(dikon: Container): T? {
return kClass.create()
}
}
/**
* コンストラクターインジェクションを行うファクトリ.
* コンストラクターインジェクションはプライマリコンストラクタを対象に行われる。
* インジェクションさせない項目はnull可とすること。
* デフォルト値を設定してもnullを設定するため注意。
* @author NAGASAWA Takahiro<[email protected]>
* @param kClass 生成対象のクラス
*/
public open class Injection<T: Any>(val kClass: KClass<T>) : Factory<T> {
/**
* インスタンスの取得
* @return インスタンス
*/
public override fun get(dikon: Container): T? {
val constructor = kClass.primaryConstructor
if (constructor != null) {
val params = constructor.parameters
var paramArray = Array<Any?>(params.size(), { null })
for (idx in params.indices) {
val param = params[idx]
var name = param.name
for (anno in param.annotations) {
if (anno is inject) {
name = anno.name
break
}
}
if (name != null) {
if (name == "dikon") {
paramArray[idx] = dikon
} else {
paramArray[idx] = dikon.get(name)
}
}
}
return constructor.call(*paramArray) as T
}
return null
}
}
/**
* オブジェクトを保持し、返すだけのクラス.
* @author NAGASAWA Takahiro<[email protected]>
*/
public class Holder<T: Any>(val value: T) : Factory<T> {
override fun get(dikon: Container): T? {
return value
}
}
| apache-2.0 | fffec0fc97678b5257a7577b88458480 | 23.598039 | 75 | 0.544839 | 3.288336 | false | false | false | false |
SUPERCILEX/Robot-Scouter | feature/templates/src/main/java/com/supercilex/robotscouter/feature/templates/TemplateFragment.kt | 1 | 6402 | package com.supercilex.robotscouter.feature.templates
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.appindexing.FirebaseUserActions
import com.google.firebase.firestore.CollectionReference
import com.supercilex.robotscouter.Refreshable
import com.supercilex.robotscouter.core.data.asLiveData
import com.supercilex.robotscouter.core.data.defaultTemplateId
import com.supercilex.robotscouter.core.data.getTabId
import com.supercilex.robotscouter.core.data.getTabIdBundle
import com.supercilex.robotscouter.core.data.getTemplateViewAction
import com.supercilex.robotscouter.core.data.logFailures
import com.supercilex.robotscouter.core.data.logSelectTemplate
import com.supercilex.robotscouter.core.data.model.add
import com.supercilex.robotscouter.core.data.model.deleteMetrics
import com.supercilex.robotscouter.core.data.model.getTemplateMetricsRef
import com.supercilex.robotscouter.core.data.model.restoreMetrics
import com.supercilex.robotscouter.core.model.Metric
import com.supercilex.robotscouter.core.ui.LifecycleAwareLazy
import com.supercilex.robotscouter.core.ui.animatePopReveal
import com.supercilex.robotscouter.core.ui.longSnackbar
import com.supercilex.robotscouter.core.unsafeLazy
import com.supercilex.robotscouter.shared.scouting.MetricListFragment
import kotlinx.android.synthetic.main.fragment_template_metric_list.*
import com.supercilex.robotscouter.R as RC
internal class TemplateFragment : MetricListFragment(R.layout.fragment_template_metric_list),
Refreshable, View.OnClickListener {
override val metricsRef: CollectionReference by unsafeLazy {
getTemplateMetricsRef(checkNotNull(getTabId(arguments)))
}
override val dataId by unsafeLazy { checkNotNull(metricsRef.parent).id }
private val itemTouchCallback by LifecycleAwareLazy {
TemplateItemTouchCallback<Metric<*>>(requireView())
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val parent = requireParentFragment() as TemplateListFragment
val fab = parent.fab
noMetricsHint.animatePopReveal(true)
holder.metrics.asLiveData().observe(viewLifecycleOwner) {
val noMetrics = it.isEmpty()
noMetricsHint.animatePopReveal(noMetrics)
if (noMetrics) fab.show()
}
val itemTouchHelper = ItemTouchHelper(itemTouchCallback)
itemTouchCallback.itemTouchHelper = itemTouchHelper
itemTouchCallback.adapter = adapter as TemplateAdapter
itemTouchHelper.attachToRecyclerView(metricsView)
metricsView.setRecycledViewPool(parent.recyclerPool)
metricsView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0) fab.hide() else if (dy < 0) fab.show()
}
})
}
override fun onCreateRecyclerAdapter(savedInstanceState: Bundle?) = TemplateAdapter(
this,
holder.metrics,
metricsView,
savedInstanceState,
itemTouchCallback
)
override fun refresh() {
metricsView.smoothScrollToPosition(0)
}
override fun onResume() {
super.onResume()
logAnalytics(true)
}
override fun onPause() {
super.onPause()
logAnalytics(false)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) =
inflater.inflate(R.menu.template_options, menu)
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_set_default_template -> {
val oldDefaultId = defaultTemplateId
defaultTemplateId = checkNotNull(metricsRef.parent).id
metricsView.longSnackbar(R.string.template_set_default_message, RC.string.undo) {
defaultTemplateId = oldDefaultId
}
}
R.id.action_delete_template -> {
metricsView.clearFocus()
DeleteTemplateDialog.show(childFragmentManager, checkNotNull(metricsRef.parent))
}
R.id.action_remove_metrics -> {
metricsView.clearFocus()
deleteMetrics(metricsRef).addOnSuccessListener(requireActivity()) { metrics ->
metricsView.longSnackbar(RC.string.deleted, RC.string.undo) {
restoreMetrics(metrics)
}
}
}
else -> return false
}
return true
}
override fun onClick(v: View) {
val position = adapter.itemCount
val metricRef = metricsRef.document()
itemTouchCallback.addItemToScrollQueue(position)
when (val id = v.id) {
R.id.addHeader -> Metric.Header(position = position, ref = metricRef)
R.id.addCheckBox -> Metric.Boolean(position = position, ref = metricRef)
R.id.addCounter -> Metric.Number(position = position, ref = metricRef)
R.id.addStopwatch -> Metric.Stopwatch(position = position, ref = metricRef)
R.id.addNote -> Metric.Text(position = position, ref = metricRef)
R.id.addSpinner -> Metric.List(position = position, ref = metricRef)
else -> error("Unknown view id: $id")
}.add()
}
private fun logAnalytics(isVisible: Boolean) {
val pagerAdapter = (parentFragment as? TemplateListFragment ?: return).pagerAdapter
val currentTabId = pagerAdapter.currentTabId ?: return
val tabName = pagerAdapter.currentTab?.text.toString()
if (isVisible) {
logSelectTemplate(currentTabId, tabName)
FirebaseUserActions.getInstance().start(getTemplateViewAction(currentTabId, tabName))
} else {
FirebaseUserActions.getInstance().end(getTemplateViewAction(currentTabId, tabName))
}.logFailures("startOrEndTemplateAction")
}
companion object {
fun newInstance(templateId: String) =
TemplateFragment().apply { arguments = getTabIdBundle(templateId) }
}
}
| gpl-3.0 | 33b97c17bfecf813814bdbc8a02df2b4 | 40.303226 | 97 | 0.695095 | 4.958947 | false | false | false | false |
angryziber/picasa-gallery | src/views/album.kt | 1 | 3960 | package views
import integration.Profile
import photos.Album
import photos.AlbumPart
import photos.Config.startTime
import web.RequestProps
// language=HTML
fun album(album: Album, albumPart: AlbumPart, profile: Profile, req: RequestProps) = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>${+album.title} by ${+profile.name} - Photos</title>
<meta name="description" content="${+album.title} photos by ${+profile.name}: ${+album.description}">
<meta name="medium" content="image">
<meta property="og:title" content="${+album.title} photos by ${+profile.name}">
<meta property="og:image" content="https://${req.host}${album.thumbUrlLarge}">
<link rel="image_src" href="https://${req.host}${album.thumbUrlLarge}">
${album.geo / """
<meta property="og:latitude" content="${album.geo!!.lat}">
<meta property="og:longitude" content="${album.geo!!.lon}">
"""}
<meta property="og:description" content="${+album.description}">
<meta property="og:site_name" content="${+profile.name} Photography">
${head(req, profile)}
<script src="/js/album.js?$startTime"></script>
<script>
var viewer = new PhotoViewer();
jQuery(function() {
viewer.setup()
if (location.hash === '#slideshow') {
jQuery('a.photo').eq(0).click()
setTimeout(viewer.slideshow, 500)
}
})
</script>
</head>
<body style="background:black; color: gray">
<div id="header" class="header">
<a href="${req.urlPrefix}" class="button fade">
<span class="text">More albums</span>
</a>
<h1 id="title">
${+album.title}
<small>by ${+profile.name}</small>
</h1>
</div>
<div id="content" class="faded">
${if (album.content != null) """
${if (album.contentIsLong) """
<div id="album-long-content" class="${!req.bot / "closed"}">
${album.content}
</div>
<script>
jQuery('#album-long-content')
.on('mousedown', function() {
jQuery(this).data('time', new Date())
})
.on('mouseup', function(e) {
if (e.target.tagName !== 'A' && new Date() - jQuery(this).data('time') < 300)
jQuery(this).toggleClass('closed')
})
</script>
""" else """
${album.content}
"""}
""" else if (album.description.isNotEmpty()) """
<h1>${+album.title}</h1>
<h2>${+album.description}</h2>
""" else ""}
<br>
<script>var thumbsView = new ThumbsView(144)</script>
<div class="thumbs clear">
${albumPart(albumPart, album, req)}
</div>
<p id="footer">
Photos by ${+profile.name}. All rights reserved.
<br>
Rendered by <a href="https://github.com/angryziber/picasa-gallery">Picasa Gallery</a>.
</p>
</div>
<div id="photo-wrapper">
<div class="loader"></div>
<div class="title-wrapper">
<div class="title"></div>
</div>
<div id="photo-map"></div>
<table id="photo-exif">
<tr>
<td id="time" colspan="2"></td>
</tr>
<tr>
<td id="aperture"></td>
<td id="iso"></td>
</tr>
<tr>
<td id="shutter"></td>
<td id="focal"></td>
</tr>
</table>
<div id="photo-comments">
${album.comments.each { """
<div class="comment photo-$photoId hidden">
<img src="$avatarUrl">
${+author}<br>${+text}
</div>
"""}}
</div>
<div id="photo-controls" class="visible">
<div class="header clearfix">
<a class="button first" id="close" onclick="viewer.close()">Close</a>
<a class="button" id="slideshow" onclick="viewer.slideshow()">Slideshow</a>
<a class="button" id="dec-interval">-</a>
<span class="left"><span id="interval">5</span> <span id="sec">sec</span></span>
<a class="button" id="inc-interval">+</a>
<span class="left" id="time-remaining"></span>
<h1><span id="photo-controls-title">${+album.title}</span>
<small id="position"></small>
</h1>
</div>
</div>
</div>
${sharing()}
</body>
</html>
"""
| gpl-3.0 | 029767b8e48e1564d7bc565ca303f9dd | 27.489209 | 103 | 0.578788 | 3.3 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/movie/get/MovieGet.kt | 1 | 4617 | package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.get
import com.fasterxml.jackson.annotation.*
import java.util.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder(
"adult",
"backdrop_path",
"belongs_to_collection",
"budget",
"movieGetGenres",
"homepage",
"id",
"imdb_id",
"original_language",
"original_title",
"overview",
"popularity",
"poster_path",
"production_companies",
"production_countries",
"release_date",
"revenue",
"runtime",
"spoken_languages",
"status",
"tagline",
"title",
"video",
"vote_average",
"vote_count",
"external_ids"
)
class MovieGet {
@get:JsonProperty("adult")
@set:JsonProperty("adult")
@JsonProperty("adult")
var adult: Boolean? = null
@get:JsonProperty("backdrop_path")
@set:JsonProperty("backdrop_path")
@JsonProperty("backdrop_path")
var backdropPath: String? = null
@get:JsonProperty("belongs_to_collection")
@set:JsonProperty("belongs_to_collection")
@JsonProperty("belongs_to_collection")
var belongsToCollection: MovieGetBelongsToCollection? = null
@get:JsonProperty("budget")
@set:JsonProperty("budget")
@JsonProperty("budget")
var budget: Int? = null
@get:JsonProperty("movieGetGenres")
@set:JsonProperty("movieGetGenres")
@JsonProperty("movieGetGenres")
var movieGetGenres: List<MovieGetGenre>? = null
@get:JsonProperty("homepage")
@set:JsonProperty("homepage")
@JsonProperty("homepage")
var homepage: String? = null
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: Int? = null
@get:JsonProperty("imdb_id")
@set:JsonProperty("imdb_id")
@JsonProperty("imdb_id")
var imdbId: String? = null
@get:JsonProperty("original_language")
@set:JsonProperty("original_language")
@JsonProperty("original_language")
var originalLanguage: String? = null
@get:JsonProperty("original_title")
@set:JsonProperty("original_title")
@JsonProperty("original_title")
var originalTitle: String? = null
@get:JsonProperty("overview")
@set:JsonProperty("overview")
@JsonProperty("overview")
var overview: String? = null
@get:JsonProperty("popularity")
@set:JsonProperty("popularity")
@JsonProperty("popularity")
var popularity: Double? = null
@get:JsonProperty("poster_path")
@set:JsonProperty("poster_path")
@JsonProperty("poster_path")
var posterPath: String? = null
@get:JsonProperty("production_companies")
@set:JsonProperty("production_companies")
@JsonProperty("production_companies")
var productionCompanies: List<MovieGetProductionCompany>? = null
@get:JsonProperty("production_countries")
@set:JsonProperty("production_countries")
@JsonProperty("production_countries")
var productionCountries: List<MovieGetProductionCountry>? = null
@get:JsonProperty("release_date")
@set:JsonProperty("release_date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@JsonProperty("release_date")
var releaseDate: Date? = null
@get:JsonProperty("revenue")
@set:JsonProperty("revenue")
@JsonProperty("revenue")
var revenue: Long? = null
@get:JsonProperty("runtime")
@set:JsonProperty("runtime")
@JsonProperty("runtime")
var runtime: Int? = null
@get:JsonProperty("spoken_languages")
@set:JsonProperty("spoken_languages")
@JsonProperty("spoken_languages")
var movieGetSpokenLanguages: List<MovieGetSpokenLanguage>? = null
@get:JsonProperty("status")
@set:JsonProperty("status")
@JsonProperty("status")
var status: String? = null
@get:JsonProperty("tagline")
@set:JsonProperty("tagline")
@JsonProperty("tagline")
var tagline: String? = null
@get:JsonProperty("title")
@set:JsonProperty("title")
@JsonProperty("title")
var title: String? = null
@get:JsonProperty("video")
@set:JsonProperty("video")
@JsonProperty("video")
var video: Boolean? = null
@get:JsonProperty("vote_average")
@set:JsonProperty("vote_average")
@JsonProperty("vote_average")
var voteAverage: Double? = null
@get:JsonProperty("vote_count")
@set:JsonProperty("vote_count")
@JsonProperty("vote_count")
var voteCount: Int? = null
@get:JsonProperty("external_ids")
@set:JsonProperty("external_ids")
@JsonProperty("external_ids")
var movieGetExternalIds: MovieGetExternalIds? = null
} | apache-2.0 | 624df30c619d07f72c215c486da154d5 | 26.652695 | 72 | 0.673164 | 4.011295 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/JumpToField.kt | 2 | 1830 | package io.github.chrislo27.rhre3.editor.stage
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.screen.EditorScreen
import io.github.chrislo27.rhre3.track.PlayState
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.ui.Stage
import io.github.chrislo27.toolboks.ui.TextField
import io.github.chrislo27.toolboks.ui.UIElement
import io.github.chrislo27.toolboks.ui.UIPalette
import kotlin.math.roundToLong
class JumpToField(val editor: Editor, palette: UIPalette, parent: UIElement<EditorScreen>,
stage: Stage<EditorScreen>)
: TextField<EditorScreen>(palette, parent, stage) {
private var beat: Float = Float.MIN_VALUE
init {
canTypeText = { char ->
(char.isDigit() || char == '-') && text.length < if (text.startsWith("-")) 6 else 5
}
canPaste = false
}
override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
super.render(screen, batch, shapeRenderer)
if (!hasFocus) {
val oldBeat = beat.roundToLong()
beat = editor.camera.position.x
if (oldBeat != beat.roundToLong() || this.text.isEmpty()) {
this.text = "${beat.roundToLong()}"
}
}
}
override fun onTextChange(oldText: String) {
super.onTextChange(oldText)
if (!hasFocus || editor.remix.playState != PlayState.STOPPED)
return
val int = text.toIntOrNull() ?: return
editor.camera.position.x = int.toFloat()
}
override var tooltipText: String?
set(_) {}
get() {
return Localization["editor.jumpTo"]
}
} | gpl-3.0 | ed78581177feb45727d9d1558b80c99e | 32.907407 | 97 | 0.661202 | 4.14966 | false | false | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/ide/surroundWith/statement/RsWithForSurrounderTest.kt | 4 | 5110 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.surroundWith.statement
import org.rust.ide.surroundWith.RsSurrounderTestBase
class RsWithForSurrounderTest : RsSurrounderTestBase(RsWithForSurrounder()) {
fun testNotApplicable1() {
doTestNotApplicable(
"""
fn main() {
let mut server <selection>= Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
)
}
fun testNotApplicable2() {
doTestNotApplicable(
"""
fn main() {
<selection>#![cfg(test)]
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
)
}
fun testNotApplicable3() {
doTestNotApplicable(
"""
fn main() {
loop<selection> {
for 1 in 1..10 {
println!("Hello, world!");
}
}</selection>
}
"""
)
}
fun testApplicableComment() {
doTest(
"""
fn main() {
<selection>// comment
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap(); // comment</selection>
}
"""
,
"""
fn main() {
for <caret> {
// comment
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap(); // comment
}
}
"""
,
checkSyntaxErrors = false
)
}
fun testSimple1() {
doTest(
"""
fn main() {
<selection>let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
,
"""
fn main() {
for <caret> {
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();
}
}
"""
,
checkSyntaxErrors = false
)
}
fun testSimple2() {
doTest(
"""
fn main() {
let mut server = Nickel::new();<selection>
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
,
"""
fn main() {
let mut server = Nickel::new();
for <caret> {
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();
}
}
"""
,
checkSyntaxErrors = false
)
}
fun testSimple3() {
doTest(
"""
fn main() {
<selection>let mut server = Nickel::new();
server.get("**", hello_world);</selection>
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
"""
fn main() {
for <caret> {
let mut server = Nickel::new();
server.get("**", hello_world);
}
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
checkSyntaxErrors = false
)
}
fun testSingleLine() {
doTest(
"""
fn main() {
let mut server = Nickel::new();
server.get("**", hello_world)<caret>;
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
"""
fn main() {
let mut server = Nickel::new();
for <caret> {
server.get("**", hello_world);
}
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
checkSyntaxErrors = false
)
}
fun testNested() {
doTest(
"""
fn main() {
<selection>loop {
println!("Hello");
}</selection>
}
"""
,
"""
fn main() {
for <caret> {
loop {
println!("Hello");
}
}
}
"""
,
checkSyntaxErrors = false
)
}
}
| mit | df4548c057089f8ae84a46dc5a714d65 | 25.205128 | 80 | 0.354403 | 5.289855 | false | true | false | false |
androidthings/endtoend-base | companionApp/src/main/java/com/example/androidthings/endtoend/companion/MainActivity.kt | 1 | 4251 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androidthings.endtoend.companion
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.findNavController
import com.example.androidthings.endtoend.companion.auth.AuthViewModel
import com.example.androidthings.endtoend.companion.auth.AuthViewModel.AuthActionResult.CANCEL
import com.example.androidthings.endtoend.companion.auth.AuthViewModel.AuthActionResult.FAIL
import com.example.androidthings.endtoend.companion.auth.AuthViewModel.AuthActionResult.SUCCESS
import com.example.androidthings.endtoend.companion.auth.AuthViewModel.AuthStateChange.SIGNED_IN
import com.example.androidthings.endtoend.companion.auth.AuthViewModel.AuthStateChange.SIGNED_OUT
import com.example.androidthings.endtoend.companion.auth.AuthViewModel.AuthStateChange.USER_CHANGED
import com.example.androidthings.endtoend.companion.auth.FirebaseAuthProvider
import com.example.androidthings.endtoend.companion.auth.FirebaseAuthUiHelper
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.IdpResponse
class MainActivity : AppCompatActivity(), FirebaseAuthUiHelper {
companion object {
private const val REQUEST_SIGN_IN = 42
private val signInProviders = listOf(AuthUI.IdpConfig.GoogleBuilder().build())
}
private lateinit var authViewModel: AuthViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
FirebaseAuthProvider.setAuthUiHelper(this)
authViewModel = ViewModelProviders.of(this, ViewModelFactory.instance)
.get(AuthViewModel::class.java)
val navController = findNavController(R.id.nav_host)
authViewModel.authStateModelLiveData.observe(this, Observer { event ->
val state = event.getContentIfNotHandled() ?: return@Observer
val dest = when (state.authStateChange) {
SIGNED_OUT -> R.id.nav_action_signed_out
SIGNED_IN, USER_CHANGED -> R.id.nav_action_signed_in
}
navController.navigate(dest)
})
}
override fun onDestroy() {
super.onDestroy()
FirebaseAuthProvider.unsetAuthUiHelper(this)
}
// -- Navigation
override fun onSupportNavigateUp() = findNavController(R.id.nav_host).navigateUp()
// -- FirebaseAuthUiHelper
override fun performSignIn() {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(signInProviders)
.build(),
REQUEST_SIGN_IN
)
}
override fun performSignOut() {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener { task ->
authViewModel.onAuthResult(when {
task.isSuccessful -> SUCCESS
task.isCanceled -> CANCEL
else -> FAIL
})
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_SIGN_IN) {
val idpResponse = IdpResponse.fromResultIntent(data)
if (resultCode == Activity.RESULT_OK) {
authViewModel.onAuthResult(SUCCESS)
} else {
authViewModel.onAuthResult(if (idpResponse == null) CANCEL else FAIL)
}
}
}
}
| apache-2.0 | 84cfd8c594e498bd5e5244b730f9d044 | 37.645455 | 99 | 0.701717 | 4.880597 | false | false | false | false |
simo-andreev/Colourizmus | app/src/main/java/bg/o/sim/colourizmus/utils/ColourModUtil.kt | 1 | 2919 | package bg.o.sim.colourizmus.utils
import android.graphics.Color
import bg.o.sim.colourizmus.model.CustomColour
fun getComplimentaryColour(colourInPlay: CustomColour): CustomColour {
val colInHSV = FloatArray(3)
Color.colorToHSV(colourInPlay.value, colInHSV)
colInHSV[0] = (colInHSV[0] + 180) % 360 // invert the Hue
return CustomColour(Color.HSVToColor(colInHSV), "Complimentary")
}
fun getSaturationSwatch(dominantCol: CustomColour): Array<CustomColour> {
val colInHSV = FloatArray(3)
Color.colorToHSV(dominantCol.value, colInHSV)
colInHSV[1] = 0.2f // set the Saturation to 0 for start of swatch
return Array(5) {
colInHSV[1] += 0.2f // increment saturation from 0.2 to 1 (thus start != white, but ends is [dominantColour])
CustomColour(Color.HSVToColor(colInHSV), "")
}
}
fun getValueSwatch(dominantCol: CustomColour): Array<CustomColour> {
val colInHSV = FloatArray(3)
Color.colorToHSV(dominantCol.value, colInHSV)
return Array(5) {
colInHSV[2] += 0.2f
CustomColour(Color.HSVToColor(colInHSV), "")
}
}
fun getColourTriade(dominantCol: CustomColour): Array<CustomColour> {
val colInHSV = FloatArray(3)
Color.colorToHSV(dominantCol.value, colInHSV)
colInHSV[2] = 0.2f // Value element of HSV to 0.2, to allow for progression, but avoid starting at black
return Array(3) {
colInHSV[0] = (colInHSV[0] + 120) % 360
CustomColour(Color.HSVToColor(colInHSV), "")
}
}
/**
* I have no idea exactly what happens in this method, or exactly what I was drinking when I wrote it.
* It *does* however do *something*.
* And I'm *pretty sure* I wasn't sober when I wrote most of this class (its original Java implementation anyway)
* ...
* Welp.
* It works (I think) so...
*/
fun getHueSwatch(dominantCol: CustomColour): Array<CustomColour> {
val colInHSV = FloatArray(3)
Color.colorToHSV(dominantCol.value, colInHSV)
val hueSwatch = Array(6, { CustomColour(-1, "") }) // default useless objects, so the GC has something to do... (-_-)
colInHSV[0] = (colInHSV[0] - 10) % 360
hueSwatch[0] = CustomColour(Color.HSVToColor(colInHSV), "")
colInHSV[0] = (colInHSV[0] + 20) % 360
hueSwatch[1] = CustomColour(Color.HSVToColor(colInHSV), "")
colInHSV[0] = (colInHSV[0] - 10) % 360
colInHSV[0] = (colInHSV[0] + 60) % 360
colInHSV[0] = (colInHSV[0] - 10) % 360
hueSwatch[2] = CustomColour(Color.HSVToColor(colInHSV), "")
colInHSV[0] = (colInHSV[0] + 20) % 360
hueSwatch[3] = CustomColour(Color.HSVToColor(colInHSV), "")
colInHSV[0] = (colInHSV[0] - 10) % 360
colInHSV[0] = (colInHSV[0] + 60) % 360
colInHSV[0] = (colInHSV[0] - 10) % 360
hueSwatch[4] = CustomColour(Color.HSVToColor(colInHSV), "")
colInHSV[0] = (colInHSV[0] + 20) % 360
hueSwatch[5] = CustomColour(Color.HSVToColor(colInHSV), "")
return hueSwatch
}
| apache-2.0 | 8436d108ef24bef43f20a54ed4f8ee82 | 33.341176 | 121 | 0.67112 | 3.232558 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/ExchangesService.kt | 1 | 3527 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import io.grpc.Status
import io.grpc.StatusException
import java.time.LocalDate
import kotlinx.coroutines.flow.Flow
import org.wfanet.measurement.api.v2alpha.Exchange
import org.wfanet.measurement.api.v2alpha.ExchangeKey
import org.wfanet.measurement.api.v2alpha.ExchangesGrpcKt.ExchangesCoroutineImplBase
import org.wfanet.measurement.api.v2alpha.GetExchangeRequest
import org.wfanet.measurement.api.v2alpha.GetExchangeRequest.PartyCase
import org.wfanet.measurement.api.v2alpha.ListExchangesRequest
import org.wfanet.measurement.api.v2alpha.ListExchangesResponse
import org.wfanet.measurement.api.v2alpha.UploadAuditTrailRequest
import org.wfanet.measurement.api.v2alpha.validateRequestProvider
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.toProtoDate
import org.wfanet.measurement.internal.kingdom.ExchangesGrpcKt.ExchangesCoroutineStub
import org.wfanet.measurement.internal.kingdom.getExchangeRequest
class ExchangesService(private val internalExchanges: ExchangesCoroutineStub) :
ExchangesCoroutineImplBase() {
override suspend fun getExchange(request: GetExchangeRequest): Exchange {
val provider = validateRequestProvider(getProvider(request))
val key = grpcRequireNotNull(ExchangeKey.fromName(request.name))
val getRequest = getExchangeRequest {
externalRecurringExchangeId = apiIdToExternalId(key.recurringExchangeId)
date = LocalDate.parse(key.exchangeId).toProtoDate()
this.provider = provider
}
val internalExchange =
try {
internalExchanges.getExchange(getRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.NOT_FOUND -> failGrpc(Status.NOT_FOUND, ex) { "Exchange not found" }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return try {
internalExchange.toV2Alpha()
} catch (e: Throwable) {
failGrpc(Status.INVALID_ARGUMENT) { e.message ?: "Failed to convert InternalExchange" }
}
}
override suspend fun listExchanges(request: ListExchangesRequest): ListExchangesResponse {
TODO("world-federation-of-advertisers/cross-media-measurement#3: implement this")
}
override suspend fun uploadAuditTrail(requests: Flow<UploadAuditTrailRequest>): Exchange {
TODO("world-federation-of-advertisers/cross-media-measurement#3: implement this")
}
}
private fun getProvider(request: GetExchangeRequest): String {
return when (request.partyCase) {
PartyCase.DATA_PROVIDER -> request.dataProvider
PartyCase.MODEL_PROVIDER -> request.modelProvider
else ->
failGrpc(Status.UNAUTHENTICATED) {
"Caller identity is neither DataProvider nor ModelProvider"
}
}
}
| apache-2.0 | 3e9e88a24fef65f29379849d7f3ba625 | 41.493976 | 93 | 0.775163 | 4.213859 | false | false | false | false |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/BookmarkManager.kt | 1 | 1767 | package com.gdgnantes.devfest.android
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.content.Context
import android.support.annotation.MainThread
import com.gdgnantes.devfest.android.app.PreferencesManager
import com.gdgnantes.devfest.android.content.RemindersManager
@MainThread
class BookmarkManager private constructor(private val context: Context) {
private val preferencesManager = PreferencesManager.from(context)
private val bookmarks = MutableLiveData<Set<String>>()
init {
bookmarks.value = preferencesManager.bookmarks
}
companion object {
private var instance: BookmarkManager? = null
fun from(context: Context): BookmarkManager {
if (instance == null) {
instance = BookmarkManager(context.applicationContext)
}
return instance!!
}
}
fun getLiveData(): LiveData<Set<String>> {
return bookmarks
}
fun isBookmarked(sessionId: String): Boolean {
return bookmarks.value!!.any { sessionId == it }
}
fun bookmark(sessionId: String) {
val bookmarks = HashSet(preferencesManager.bookmarks)
bookmarks.add(sessionId)
preferencesManager.bookmarks = bookmarks
this.bookmarks.value = bookmarks
onBookmarkChanged()
}
fun unbookmark(sessionId: String) {
val bookmarks = HashSet(preferencesManager.bookmarks)
bookmarks.remove(sessionId)
preferencesManager.bookmarks = bookmarks
this.bookmarks.value = bookmarks
onBookmarkChanged()
}
private fun onBookmarkChanged() {
Thread {
RemindersManager.from(context).updateAlarm()
}.start()
}
} | apache-2.0 | 11292093446be6947efba4aab6c8ac26 | 27.516129 | 73 | 0.683645 | 5.181818 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/dialogs/CollectionDialog.kt | 1 | 6281 | package com.pr0gramm.app.ui.dialogs
import android.app.Dialog
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.TextView
import androidx.core.view.updatePadding
import androidx.core.widget.addTextChangedListener
import com.pr0gramm.app.R
import com.pr0gramm.app.databinding.DialogCollectionCreateBinding
import com.pr0gramm.app.services.*
import com.pr0gramm.app.ui.base.ViewBindingDialogFragment
import com.pr0gramm.app.ui.base.launchUntilDestroy
import com.pr0gramm.app.ui.dialog
import com.pr0gramm.app.ui.showDialog
import com.pr0gramm.app.util.*
import com.pr0gramm.app.util.di.instance
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
class CollectionDialog : ViewBindingDialogFragment<DialogCollectionCreateBinding>("CollectionDialog", DialogCollectionCreateBinding::inflate) {
private val collectionsService: CollectionsService by instance()
private val collectionItemService: CollectionItemsService by instance()
private val userService: UserService by instance()
private val editCollectionId: Long? by optionalFragmentArgument(name = "editCollectionId")
override fun onCreateDialog(contentView: View): Dialog {
// lookup collection to edit if it exists.
val editCollection: PostCollection? = editCollectionId?.let { collectionsService.byId(it) }
return dialog(requireContext()) {
title(if (editCollection != null) R.string.collection_edit else R.string.collection_new)
positive(R.string.action_save)
negative { dismissAllowingStateLoss() }
contentView(contentView)
if (editCollection != null) {
neutral(R.string.action_delete) { askToDeleteCollection(editCollection.id) }
}
noAutoDismiss()
onShow { dialog -> configureDialog(dialog, editCollection) }
}
}
private fun configureDialog(dialog: Dialog, editCollection: PostCollection?) {
views.privacyOptions.adapter = PrivacySpinnerAdapter()
views.privacyOptions.setSelection(if (editCollection?.isPublic == true) 1 else 0)
val buttonView: Button = dialog.find(android.R.id.button1)
buttonView.isEnabled = editCollection != null
views.name.setText(editCollection?.title ?: "")
views.name.addTextChangedListener { changedText ->
val name = changedText.toString().trim()
val isValidName = collectionsService.isValidNameForNewCollection(name)
buttonView.isEnabled = isValidName
}
views.defaultCollection.isChecked = editCollection?.isDefault ?: collectionsService.defaultCollection == null
views.defaultCollection.isEnabled = userService.userIsPremium
buttonView.setOnClickListener {
val name = views.name.text.toString().trim()
val isPublic = views.privacyOptions.selectedItemId == 1L
val isDefault = views.defaultCollection.isChecked
if (editCollection == null) {
createCollection(name, isPublic, isDefault)
} else {
updateCollection(editCollection.id, name, isPublic, isDefault)
}
}
}
private fun askToDeleteCollection(id: Long) {
showDialog(this) {
content(R.string.collection_delete_confirm)
positive(R.string.action_delete) {
deleteCollection(id)
}
negative(R.string.cancel)
}
}
private fun deleteCollection(collectionId: Long) {
launchUntilDestroy(busyIndicator = true) {
withContext(NonCancellable) {
val result = collectionsService.delete(collectionId)
if (result is Result.Success) {
collectionItemService.deleteCollection(collectionId)
}
}
dismissAllowingStateLoss()
}
}
private fun createCollection(name: String, public: Boolean, default: Boolean) {
launchUntilDestroy(busyIndicator = true) {
withContext(NonCancellable) {
logger.info { "Create collection with the name: '$name' public=$public, default=$default" }
collectionsService.create(name, public, default)
}
dismissAllowingStateLoss()
}
}
private fun updateCollection(id: Long, name: String, public: Boolean, default: Boolean) {
launchUntilDestroy(busyIndicator = true) {
withContext(NonCancellable) {
logger.info { "Edit collection $id: name='$name', public=$public, default=$default" }
collectionsService.edit(id, name, public, default)
}
dismissAllowingStateLoss()
}
}
companion object {
fun newInstance(collectionToEdit: PostCollection? = null): CollectionDialog {
return CollectionDialog().arguments {
if (collectionToEdit != null) {
putLong("editCollectionId", collectionToEdit.id)
}
}
}
}
}
private class PrivacySpinnerAdapter : BaseAdapter() {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view: TextView = parent.inflateDetachedChild(R.layout.row_collection_privacy)
val (text, icon) = when (position) {
0 -> Pair(R.string.collection_prive, R.drawable.ic_collection_private)
else -> Pair(R.string.collection_public, R.drawable.ic_collection_public)
}
view.setText(text)
view.setCompoundDrawablesRelativeWithIntrinsicBounds(icon, 0, 0, 0)
return view
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return getView(position, convertView, parent).apply {
updatePadding(left = context.dp(16), right = context.dp(16))
minimumHeight = context.dp(48)
}
}
override fun getItem(position: Int): Any {
return position
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return 2
}
}
| mit | 4c10bbcfc944d249ab1f85525f91d277 | 34.891429 | 143 | 0.659927 | 4.798319 | false | false | false | false |
mattyway/PiBells | src/Main.kt | 1 | 1967 | import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import java.io.File
var gpio: Gpio? = null
val music = Music()
val subscriptions = CompositeSubscription()
val enableNoteLogging: Boolean = false
val scaleString = "C4q D4q E4q F4q G4q A4q B4q C5q"
fun main(args: Array<String>) {
setup()
music.play(scaleString)
loop()
gpio?.shutdown()
subscriptions.unsubscribe()
}
private fun setup() {
gpio = try {
Gpio()
} catch (e: UnsatisfiedLinkError) {
println("Failed to setup GPIO. Is Pi4j installed?")
null
}
if (enableNoteLogging) {
music.getNotes()
.observeOn(Schedulers.newThread())
.subscribe { note ->
println("Note parsed: tone = ${note.toneString} octave = ${note.octave} value = ${note.value} duration = ${note.duration}")
}
.apply {
subscriptions.add(this)
}
}
gpio?.subscribeTo(music.getNotes())
}
private fun loop() {
while (true) {
val resourceDir = File("./resources")
val files: List<File> = resourceDir.listFiles { dir, name -> name.endsWith(".xml") }.sortedBy { it.name }
println("Select file")
files.forEachIndexed { index, file ->
println("${index + 1}: ${file.name}")
}
println("${files.size + 1}: Scale")
val input = readLine()
val selectedIndex = try {
input?.toInt()?.minus(1)
} catch(e: Exception) {
println("Invalid input")
break
}
if (selectedIndex == null) {
println("Invalid input")
break
}
if (selectedIndex == files.size) {
music.play(scaleString)
} else if (selectedIndex >= 0 && selectedIndex < files.size) {
val file = files[selectedIndex]
music.play(file)
}
}
}
| gpl-3.0 | 1fc9ffb63710ed88e232546f505d49e5 | 23.898734 | 144 | 0.549568 | 4.176221 | false | false | false | false |
JetBrains/teamcity-sdk-maven-plugin | src/main/kotlin/org/jetbrains/teamcity/maven/sdk/AbstractTeamCityMojo.kt | 1 | 12241 | /*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.teamcity.maven.sdk
import org.apache.commons.io.FileUtils
import org.apache.maven.plugin.AbstractMojo
import org.apache.maven.plugin.MojoExecutionException
import org.apache.maven.plugins.annotations.Parameter
import org.apache.maven.project.MavenProject
import java.io.File
import java.io.IOException
import java.net.ConnectException
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.Charset
import java.util.*
import java.util.jar.JarFile
public abstract class AbstractTeamCityMojo() : AbstractMojo() {
/**
* Location of the TeamCity distribution.
*/
@Parameter( defaultValue = "servers/\${teamcity-version}", property = "teamcityDir", required = true )
protected var teamcityDir: File? = null
@Parameter( defaultValue = "\${teamcity-version}", property = "teamcityVersion", required = true)
protected var teamcityVersion: String = ""
@Parameter( defaultValue = "false", property = "downloadQuietly", required = true)
protected var downloadQuietly: Boolean = false
@Parameter( defaultValue = "https://download.jetbrains.com/teamcity", property = "teamcitySourceURL", required = true)
protected var teamcitySourceURL: String = ""
@Parameter( defaultValue = "\${project.artifactId}.zip")
protected var pluginPackageName : String = ""
@Parameter ( defaultValue = "true", property = "startAgent")
protected var startAgent: Boolean = true
@Parameter(defaultValue = "localhost:8111")
protected var serverAddress = ""
@Parameter(defaultValue = "")
protected var username = ""
@Parameter(defaultValue = "")
protected var password = ""
/**
* Location of the TeamCity data directory.
*/
@Parameter( defaultValue = ".datadir", property = "dataDirectory", required = true )
protected var dataDirectory: String = ""
/**
* The maven project.
*/
@Parameter( defaultValue = "\${project}", readonly = true)
protected var project : MavenProject? = null
override fun execute() {
checkTeamCityDirectory(teamcityDir!!)
doExecute()
}
abstract fun doExecute()
protected fun checkTeamCityDirectory(dir: File) {
when (evalTeamCityDirectory(dir)) {
TCDirectoryState.GOOD -> log.info("TeamCity $teamcityVersion is located at $teamcityDir")
TCDirectoryState.MISVERSION -> log.warn("TeamCity version at [${dir.absolutePath}] is [${getTCVersion(dir)}], but project uses [$teamcityVersion]")
TCDirectoryState.BAD -> {
log.info("TeamCity distribution not found at [${dir.absolutePath}]")
downloadTeamCity(dir) }
}
}
private fun downloadTeamCity(dir: File) {
if (downloadQuietly || askToDownload(dir)) {
val retriever = TeamCityRetriever(teamcitySourceURL, teamcityVersion,
{ message, debug ->
if (debug) {
log.debug(message)
} else {
log.info(message)
}
})
retriever.downloadAndUnpackTeamCity(dir)
} else {
throw MojoExecutionException("TeamCity distribution not found.")
}
}
protected fun evalTeamCityDirectory(dir: File): TCDirectoryState {
if (!dir.exists() || !looksLikeTeamCityDir(dir)) {
return TCDirectoryState.BAD
} else if (wrongTeamCityVersion(dir)) {
return TCDirectoryState.MISVERSION
} else {
return TCDirectoryState.GOOD
}
}
private fun askToDownload(dir: File): Boolean {
print("Download TeamCity $teamcityVersion to ${dir.absolutePath}?: Y:")
val s = readLine()
return s?.length == 0 || s?.toLowerCase()?.first() == 'y'
}
protected fun looksLikeTeamCityDir(dir: File): Boolean = File(dir, "bin/runAll.sh").exists()
private fun wrongTeamCityVersion(dir: File) = !getTCVersion(dir).equals(teamcityVersion)
protected fun getTCVersion(teamcityDir: File): String {
var commonAPIjar = File(teamcityDir, "webapps/ROOT/WEB-INF/lib/common-api.jar")
if (!commonAPIjar.exists() || !commonAPIjar.isFile) {
throw MojoExecutionException("Can not read TeamCity version. Can not access [${commonAPIjar.absolutePath}]."
+ "Check that [$teamcityDir] points to valid TeamCity installation")
} else {
var jarFile = JarFile(commonAPIjar)
val zipEntry = jarFile.getEntry("serverVersion.properties.xml")
if (zipEntry == null) {
throw MojoExecutionException("Failed to read TeamCity's version from [${commonAPIjar.absolutePath}]. Please, verify your intallation.")
} else {
val versionPropertiesStream = jarFile.getInputStream(zipEntry)
try {
val props = Properties()
props.loadFromXML(versionPropertiesStream!!)
return props["Display_Version"] as String
} finally {
versionPropertiesStream?.close()
}
}
}
}
protected fun readOutput(process: Process): Int {
val reader = ThreadedStringReader(process.inputStream!!) {
log.info(it)
}.start()
val returnValue = process.waitFor()
reader.stop()
return returnValue
}
protected fun createRunCommand(vararg params: String): List<String> {
val fileName = getStartScriptName()
return if (isWindows())
listOf("cmd", "/C", "bin\\$fileName") + params
else
listOf("/bin/bash", "bin/$fileName.sh") + params
}
private fun getStartScriptName(): String {
return if (startAgent)
"runAll"
else
"teamcity-server"
}
protected fun isWindows(): Boolean {
return System.getProperty("os.name")!!.contains("Windows")
}
protected fun uploadPluginAgentZip(): String {
val proj = project!!
val packageFile = File(proj.build!!.directory!!, pluginPackageName)
val effectiveDataDir = getDataDir().absolutePath
if (packageFile.exists()) {
val dataDirFile = File(effectiveDataDir)
FileUtils.copyFile(packageFile, File(dataDirFile, "plugins/" + pluginPackageName))
} else {
log.warn("Target file [${packageFile.absolutePath}] does not exist. Nothing will be deployed. Did you forget 'package' goal?")
}
return effectiveDataDir
}
protected fun reloadPluginInRuntime(): Boolean {
if (username.isEmpty()) {
log.debug("No username provided, looking for maintenance token")
val tokenFile = File(getDataDir(), "system${File.separator}pluginData${File.separator}superUser${File.separator}token.txt")
if (!tokenFile.isFile) {
log.warn("Neither username provider nor maintenance token file exists. Cannot send plugin reload request. Check that server has already started with '-Dteamcity.superUser.token.saveToFile=true' parameter or provide username and password.")
return false
} else {
try {
password = tokenFile.readText().toLong().toString()
log.debug("Using $password maintenance token to authenticate")
} catch (ex: NumberFormatException) {
log.warn("Malformed maintenance token: should contain a number")
return false
}
}
}
val authToken = "Basic " + String(Base64.getEncoder().encode("$username:$password".toByteArray(Charset.forName("UTF-8"))))
val disableAction = getPluginReloadURL(false)
log.debug("Sending " + disableAction.toString() + "...")
val disableRequest = disableAction.openConnection()
(disableRequest as HttpURLConnection).requestMethod = "POST"
disableRequest.setRequestProperty ("Authorization", authToken)
try {
disableRequest.getInputStream().use {
val result = it.buffered().bufferedReader(Charset.defaultCharset()).readLine()
if (!result.contains("Plugin unloaded successfully")) {
if (result.contains("Plugin unloaded partially")) {
log.warn("Plugin unloaded partially - some parts could still be running. Server restart could be needed. Check all resources are released and threads are stopped on server shutdown. ")
} else {
log.warn(result)
return false
}
} else {
log.info("Plugin successfully unloaded")
}
}
} catch (ex: ConnectException) {
log.warn("Cannot find running server on http://$serverAddress. Is server started?")
return false
} catch (ex: IOException) {
when (disableRequest.responseCode) {
401 -> log.warn("Cannot authenticate server on http://$serverAddress with " +
if (username.isEmpty())
"maintenance token $password. Check that server has already started with '-Dteamcity.superUser.token.saveToFile=true' parameter or provide username and password."
else
"provided credentials.")
}
log.warn("Cannot connect to the server on http://$serverAddress: ${disableRequest.responseCode}", ex)
return false
}
uploadPluginAgentZip()
val enableAction = getPluginReloadURL(true)
log.debug("Sending " + enableAction.toString() + "...")
val enableRequest = enableAction.openConnection()
(enableRequest as HttpURLConnection).requestMethod = "POST"
enableRequest.setRequestProperty ("Authorization", authToken)
try {
enableRequest.getInputStream().use {
val result = it.buffered().bufferedReader(Charset.defaultCharset()).readLine()
if (!result.contains("Plugin loaded successfully")) {
log.warn(result)
return false
} else {
log.info("Plugin successfully loaded")
}
}
} catch(ex: IOException) {
log.warn("Cannot connect to the server on http://$serverAddress: ${disableRequest.responseCode}", ex)
return false
}
return true
}
private fun getPluginReloadURL(action: Boolean) =
URL("http://$serverAddress/httpAuth/admin/plugins.html?action=setEnabled&enabled=$action&pluginPath=%3CTeamCity%20Data%20Directory%3E/plugins/$pluginPackageName")
private fun getDataDir(): File {
return if (File(dataDirectory).isAbsolute) {
File(dataDirectory)
} else {
File(teamcityDir, dataDirectory)
}
}
protected fun isPluginReloadable(): Boolean {
val pluginDescriptor = File(project!!.basedir, "teamcity-plugin.xml")
if (!pluginDescriptor.exists()) {
log.warn("Plugin descriptor wan't found in ${pluginDescriptor.absolutePath}")
return false
}
return pluginDescriptor.readText(Charset.forName("UTF-8")).contains("allow-runtime-reload=\"true\"")
}
}
public enum class TCDirectoryState {
GOOD,
MISVERSION,
BAD
}
| apache-2.0 | 6241cae9b2d3b4ef1adaa4edf948737d | 38.872964 | 255 | 0.616535 | 4.990216 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/forms/train/TrainNetworkButtonActionListener.kt | 1 | 2567 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.forms.train
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.ui.Messages
import com.intellij.util.PlatformIcons
import com.thomas.needham.neurophidea.Constants.NETWORK_TO_TRAIN_LOCATION_KEY
import com.thomas.needham.neurophidea.Constants.TRAIN_FORM_TRAINING_SET_LOCATION_KEY
import com.thomas.needham.neurophidea.core.NetworkTrainer
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
/**
* Created by Thomas Needham on 31/05/2016.
*/
class TrainNetworkButtonActionListener : ActionListener {
var formInstance: TrainNetworkForm? = null
var networkTrainer: NetworkTrainer? = null
companion object Data {
val properties = PropertiesComponent.getInstance()
}
override fun actionPerformed(e: ActionEvent?) {
if (!formInstance?.txtInputData?.text.equals("")) {
val input = formInstance?.txtInputData?.text
val split = input?.split(",")
val parsedOutput = DoubleArray(split?.size!!)
for (i in 0..split?.size!!) {
parsedOutput[i] = split!![i].toDouble()
}
networkTrainer = NetworkTrainer(properties.getValue(NETWORK_TO_TRAIN_LOCATION_KEY, ""), parsedOutput)
} else {
networkTrainer = NetworkTrainer(properties.getValue(NETWORK_TO_TRAIN_LOCATION_KEY, ""), properties.getValue(TRAIN_FORM_TRAINING_SET_LOCATION_KEY, ""))
}
networkTrainer?.TrainNetwork()
Messages.showOkCancelDialog("Network Successfully Trained!", "Success", PlatformIcons.CHECK_ICON)
}
} | mit | 54030d21a8252324188333a300ba48ff | 41.098361 | 153 | 0.782236 | 4.180782 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/jobs/FilesSyncWork.kt | 1 | 10331 | /*
* Nextcloud Android client application
*
* @author Mario Danic
* @author Chris Narkiewicz
* Copyright (C) 2017 Mario Danic
* Copyright (C) 2017 Nextcloud
* Copyright (C) 2020 Chris Narkiewicz
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.jobs
import android.content.ContentResolver
import android.content.Context
import android.content.res.Resources
import android.text.TextUtils
import androidx.exifinterface.media.ExifInterface
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.core.Clock
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.client.preferences.AppPreferences
import com.owncloud.android.R
import com.owncloud.android.datamodel.ArbitraryDataProvider
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
import com.owncloud.android.datamodel.FilesystemDataProvider
import com.owncloud.android.datamodel.MediaFolderType
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.datamodel.SyncedFolderProvider
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.files.services.FileUploader
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.ui.activity.SettingsActivity
import com.owncloud.android.utils.FileStorageUtils
import com.owncloud.android.utils.FilesSyncHelper
import com.owncloud.android.utils.MimeType
import com.owncloud.android.utils.MimeTypeUtil
import java.io.File
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
@Suppress("LongParameterList") // legacy code
class FilesSyncWork(
private val context: Context,
params: WorkerParameters,
private val resources: Resources,
private val contentResolver: ContentResolver,
private val userAccountManager: UserAccountManager,
private val preferences: AppPreferences,
private val uploadsStorageManager: UploadsStorageManager,
private val connectivityService: ConnectivityService,
private val powerManagementService: PowerManagementService,
private val clock: Clock
) : Worker(context, params) {
companion object {
const val TAG = "FilesSyncJob"
const val SKIP_CUSTOM = "skipCustom"
const val OVERRIDE_POWER_SAVING = "overridePowerSaving"
}
override fun doWork(): Result {
val overridePowerSaving = inputData.getBoolean(OVERRIDE_POWER_SAVING, false)
// If we are in power save mode, better to postpone upload
if (powerManagementService.isPowerSavingEnabled && !overridePowerSaving) {
return Result.success()
}
val resources = context.resources
val lightVersion = resources.getBoolean(R.bool.syncedFolder_light)
val skipCustom = inputData.getBoolean(SKIP_CUSTOM, false)
FilesSyncHelper.restartJobsIfNeeded(
uploadsStorageManager,
userAccountManager,
connectivityService,
powerManagementService
)
FilesSyncHelper.insertAllDBEntries(preferences, clock, skipCustom)
// Create all the providers we'll need
val filesystemDataProvider = FilesystemDataProvider(contentResolver)
val syncedFolderProvider = SyncedFolderProvider(contentResolver, preferences, clock)
val currentLocale = resources.configuration.locale
val dateFormat = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale)
dateFormat.timeZone = TimeZone.getTimeZone(TimeZone.getDefault().id)
for (syncedFolder in syncedFolderProvider.syncedFolders) {
if (syncedFolder.isEnabled && (!skipCustom || MediaFolderType.CUSTOM != syncedFolder.type)) {
syncFolder(
context,
resources,
lightVersion,
filesystemDataProvider,
currentLocale,
dateFormat,
syncedFolder
)
}
}
return Result.success()
}
@Suppress("LongMethod") // legacy code
private fun syncFolder(
context: Context,
resources: Resources,
lightVersion: Boolean,
filesystemDataProvider: FilesystemDataProvider,
currentLocale: Locale,
sFormatter: SimpleDateFormat,
syncedFolder: SyncedFolder
) {
val uploadAction: Int?
val needsCharging: Boolean
val needsWifi: Boolean
var file: File
val accountName = syncedFolder.account
val optionalUser = userAccountManager.getUser(accountName)
if (!optionalUser.isPresent) {
return
}
val user = optionalUser.get()
val arbitraryDataProvider: ArbitraryDataProvider? = if (lightVersion) {
ArbitraryDataProviderImpl(context)
} else {
null
}
val paths = filesystemDataProvider.getFilesForUpload(
syncedFolder.localPath,
syncedFolder.id.toString()
)
if (paths.size == 0) {
return
}
val pathsAndMimes = paths.map { path ->
file = File(path)
val localPath = file.absolutePath
Triple(
localPath,
getRemotePath(file, syncedFolder, sFormatter, lightVersion, resources, currentLocale),
MimeTypeUtil.getBestMimeTypeByFilename(localPath)
)
}
val localPaths = pathsAndMimes.map { it.first }.toTypedArray()
val remotePaths = pathsAndMimes.map { it.second }.toTypedArray()
val mimetypes = pathsAndMimes.map { it.third }.toTypedArray()
if (lightVersion) {
needsCharging = resources.getBoolean(R.bool.syncedFolder_light_on_charging)
needsWifi = arbitraryDataProvider!!.getBooleanValue(
accountName,
SettingsActivity.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI
)
val uploadActionString = resources.getString(R.string.syncedFolder_light_upload_behaviour)
uploadAction = getUploadAction(uploadActionString)
} else {
needsCharging = syncedFolder.isChargingOnly
needsWifi = syncedFolder.isWifiOnly
uploadAction = syncedFolder.uploadAction
}
FileUploader.uploadNewFile(
context,
user,
localPaths,
remotePaths,
mimetypes,
uploadAction!!,
true, // create parent folder if not existent
UploadFileOperation.CREATED_AS_INSTANT_PICTURE,
needsWifi,
needsCharging,
syncedFolder.nameCollisionPolicy
)
for (path in paths) {
// TODO batch update
filesystemDataProvider.updateFilesystemFileAsSentForUpload(
path,
syncedFolder.id.toString()
)
}
}
private fun getRemotePath(
file: File,
syncedFolder: SyncedFolder,
sFormatter: SimpleDateFormat,
lightVersion: Boolean,
resources: Resources,
currentLocale: Locale
): String {
val lastModificationTime = calculateLastModificationTime(file, syncedFolder, sFormatter)
val remoteFolder: String
val useSubfolders: Boolean
if (lightVersion) {
useSubfolders = resources.getBoolean(R.bool.syncedFolder_light_use_subfolders)
remoteFolder = resources.getString(R.string.syncedFolder_remote_folder)
} else {
useSubfolders = syncedFolder.isSubfolderByDate
remoteFolder = syncedFolder.remotePath
}
return FileStorageUtils.getInstantUploadFilePath(
file,
currentLocale,
remoteFolder,
syncedFolder.localPath,
lastModificationTime,
useSubfolders
)
}
private fun hasExif(file: File): Boolean {
val mimeType = FileStorageUtils.getMimeTypeFromName(file.absolutePath)
return MimeType.JPEG.equals(mimeType, ignoreCase = true) || MimeType.TIFF.equals(mimeType, ignoreCase = true)
}
private fun calculateLastModificationTime(
file: File,
syncedFolder: SyncedFolder,
formatter: SimpleDateFormat
): Long {
var lastModificationTime = file.lastModified()
if (MediaFolderType.IMAGE == syncedFolder.type && hasExif(file)) {
@Suppress("TooGenericExceptionCaught") // legacy code
try {
val exifInterface = ExifInterface(file.absolutePath)
val exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME)
if (!TextUtils.isEmpty(exifDate)) {
val pos = ParsePosition(0)
val dateTime = formatter.parse(exifDate, pos)
lastModificationTime = dateTime.time
}
} catch (e: Exception) {
Log_OC.d(TAG, "Failed to get the proper time " + e.localizedMessage)
}
}
return lastModificationTime
}
private fun getUploadAction(action: String): Int? {
return when (action) {
"LOCAL_BEHAVIOUR_FORGET" -> FileUploader.LOCAL_BEHAVIOUR_FORGET
"LOCAL_BEHAVIOUR_MOVE" -> FileUploader.LOCAL_BEHAVIOUR_MOVE
"LOCAL_BEHAVIOUR_DELETE" -> FileUploader.LOCAL_BEHAVIOUR_DELETE
else -> FileUploader.LOCAL_BEHAVIOUR_FORGET
}
}
}
| gpl-2.0 | cc565982bba3c67537d1a9045ae0d84f | 38.132576 | 117 | 0.669248 | 5.012615 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/NoticesParser.kt | 2 | 4321 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.util.Xml
import edu.berkeley.boinc.utils.Logging
import org.xml.sax.Attributes
import org.xml.sax.SAXException
class NoticesParser : BaseParser() {
private lateinit var mNotice: Notice
val notices: MutableList<Notice> = mutableListOf()
@Throws(SAXException::class)
override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) {
super.startElement(uri, localName, qName, attributes)
if (localName.equals(NOTICE_TAG, ignoreCase = true) && !this::mNotice.isInitialized) {
mNotice = Notice()
} else { // primitive
mElementStarted = true
mCurrentElement.setLength(0)
}
}
@Throws(SAXException::class)
override fun endElement(uri: String?, localName: String, qName: String?) {
super.endElement(uri, localName, qName)
try {
if (localName.equals(NOTICE_TAG, ignoreCase = true)) { // Closing tag
if (mNotice.seqno != -1) { // seqno is a must
notices.add(mNotice)
}
mNotice = Notice()
} else { // decode inner tags
if (localName.equals(Notice.Fields.SEQNO, ignoreCase = true)) {
mNotice.seqno = mCurrentElement.toString().toInt()
} else if (localName.equals(Notice.Fields.TITLE, ignoreCase = true)) {
mNotice.title = mCurrentElement.toString()
} else if (localName.equals(DESCRIPTION, ignoreCase = true)) {
mNotice.description = mCurrentElement.toString()
} else if (localName.equals(Notice.Fields.CREATE_TIME, ignoreCase = true)) {
mNotice.createTime = mCurrentElement.toDouble()
} else if (localName.equals(Notice.Fields.ARRIVAL_TIME, ignoreCase = true)) {
mNotice.arrivalTime = mCurrentElement.toDouble()
} else if (localName.equals(Notice.Fields.Category, ignoreCase = true)) {
mNotice.category = mCurrentElement.toString()
if (mNotice.category.equalsAny("server", "scheduler",
ignoreCase = false)) {
mNotice.isServerNotice = true
}
if (mNotice.category == "client") {
mNotice.isClientNotice = true
}
} else if (localName.equals(Notice.Fields.LINK, ignoreCase = true)) {
mNotice.link = mCurrentElement.toString()
} else if (localName.equals(PROJECT_NAME, ignoreCase = true)) {
mNotice.projectName = mCurrentElement.toString()
}
}
mElementStarted = false
} catch (e: Exception) {
Logging.logException(Logging.Category.XML, "NoticesParser.endElement error: ", e)
}
}
companion object {
const val NOTICE_TAG = "notice"
@JvmStatic
fun parse(rpcResult: String): List<Notice> {
return try {
val parser = NoticesParser()
Xml.parse(rpcResult.replace("&", "&"), parser)
parser.notices
} catch (e: SAXException) {
Logging.logException(Logging.Category.RPC, "NoticesParser: malformed XML ", e)
Logging.logDebug(Logging.Category.XML, "NoticesParser: $rpcResult")
emptyList()
}
}
}
}
| lgpl-3.0 | 9ecc711b9333349a020082f75160b306 | 43.091837 | 105 | 0.594307 | 4.661273 | false | false | false | false |
DankBots/Mega-Gnar | src/main/kotlin/gg/octave/bot/apis/patreon/PatreonAPI.kt | 1 | 7249 | package gg.octave.bot.apis.patreon
import gg.octave.bot.Launcher
import gg.octave.bot.utils.RequestUtil
import okhttp3.HttpUrl
import okhttp3.Request
import org.json.JSONObject
import org.slf4j.LoggerFactory
import java.net.URI
import java.net.URLDecoder
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class PatreonAPI(var accessToken: String?) {
// (val clientId: String, val clientSecret: String, val refreshToken: String) {
private val scheduler = Executors.newSingleThreadScheduledExecutor()
//var accessToken: String = ""
init {
if (accessToken?.isEmpty() == false) {
log.info("Initialising sweepy boi // SWEEPER! AW MAN!")
scheduler.schedule(::sweep, 1, TimeUnit.DAYS)
}
}
fun sweep(): CompletableFuture<SweepStats> {
val storedPledges = Launcher.db.premiumUsers
return fetchPledges().thenApply { pledges ->
val total = storedPledges.size
var changed = 0
var removed = 0
for (entry in storedPledges) {
val userId = entry.idLong
val pledge = pledges.firstOrNull { it.discordId != null && it.discordId == userId }
if (pledge == null || pledge.isDeclined) {
Launcher.shardManager.openPrivateChannel(userId)
.flatMap {
it.sendMessage("Your pledge was either declined or removed from Patreon. " +
"As a result, your perks have been revoked. If you believe this was in error, " +
"check your payment method. If not, we hope Octave exceeded your expectations, and " +
"we hope to see you again soon!")
}.queue()
for (guild in entry.premiumGuildsList) {
guild.delete()
}
entry.delete()
removed++
continue
}
val pledging = pledge.pledgeCents.toDouble() / 100
if (pledging < entry.pledgeAmount) { // User is pledging less than what we have stored.
entry.setPledgeAmount(pledging).save()
val entitledServers = entry.totalPremiumGuildQuota
val activatedServers = entry.premiumGuildsList
val exceedingLimitBy = activatedServers.size - entitledServers
if (exceedingLimitBy > 0) {
val remove = (0 until exceedingLimitBy)
for (unused in remove) {
activatedServers.firstOrNull()?.delete()
}
// Message about removed guilds? eh
}
changed++
}
}
SweepStats(total, changed, removed)
}
// Fetch pledges from database. Iterate through results from api.
// If no pledge, or pledge is declined; remove from DB. Purge premium servers.
// If pledgeAmount < stored, remove servers until quota is no longer exceeded.
// Those pledging more than stored, update amount?
}
fun fetchPledges(campaignId: String = "754103") = fetchPledgesOfCampaign0(campaignId)
// fun refreshAccessToken() {
// val url = baseUrl.newBuilder().apply {
// addPathSegment("token")
// addQueryParameter("grant_type", "refresh_token")
// addQueryParameter("refresh_token", refreshToken)
// addQueryParameter("client_id", clientId)
// addQueryParameter("client_secret", clientSecret)
// }.build()
// println(url)
//
// request {
// url(url)
// post(RequestBody.create(null, ByteArray(0)))
// }.thenAccept {
// val token = it.getString("access_token")
// val expiresEpochSeconds = it.getLong("expires_in")
//
// accessToken = token
// scheduler.schedule(::refreshAccessToken, expiresEpochSeconds, TimeUnit.SECONDS)
// log.info("Successfully refreshed Patreon access token.")
// }.exceptionally {
// log.error("Unable to refresh Patreon access token!", it)
// return@exceptionally null
// }
// }
private fun fetchPledgesOfCampaign0(campaignId: String, offset: String? = null): CompletableFuture<List<PatreonUser>> {
val users = mutableListOf<PatreonUser>()
return fetchPageOfPledge(campaignId, offset)
.thenCompose {
users.addAll(it.pledges)
if (it.hasMore) {
fetchPledgesOfCampaign0(campaignId, it.offset)
} else {
CompletableFuture.completedFuture(emptyList())
}
}
.thenAccept { users.addAll(it) }
.thenApply { users }
}
private fun fetchPageOfPledge(campaignId: String, offset: String?): CompletableFuture<ResultPage> {
return get {
addPathSegments("api/campaigns/$campaignId/pledges")
setQueryParameter("include", "pledge,patron")
offset?.let { setQueryParameter("page[cursor]", it) }
}.thenApply {
val pledges = it.getJSONArray("data")
val nextPage = getNextPage(it)
val users = mutableListOf<PatreonUser>()
for ((index, obj) in it.getJSONArray("included").withIndex()) {
obj as JSONObject
if (obj.getString("type") == "user") {
val pledge = pledges.getJSONObject(index)
users.add(PatreonUser.fromJsonObject(obj, pledge))
}
}
ResultPage(users, nextPage != null, nextPage)
}
}
private fun getNextPage(json: JSONObject): String? {
return json.getJSONObject("links")
.takeIf { it.has("next") }
?.let { parseQueryString(it.getString("next"))["page[cursor]"] }
}
private fun parseQueryString(url: String): Map<String, String> {
return URI(url).query
.split('&')
.map { it.split("=") }
.associateBy({ decode(it[0]) }, { decode(it[1]) })
}
private fun decode(s: String) = URLDecoder.decode(s, Charsets.UTF_8)
private fun get(urlOpts: HttpUrl.Builder.() -> Unit): CompletableFuture<JSONObject> {
if (accessToken?.isNotEmpty() != true) {
return CompletableFuture.failedFuture(IllegalStateException("Access token is empty!"))
}
val url = baseUrl.newBuilder().apply(urlOpts).build()
return request { url(url) }
}
private fun request(requestOpts: Request.Builder.() -> Unit): CompletableFuture<JSONObject> {
return RequestUtil.jsonObject({
apply(requestOpts)
header("Authorization", "Bearer $accessToken")
}, true)
}
companion object {
private val log = LoggerFactory.getLogger(PatreonAPI::class.java)
private val baseUrl = HttpUrl.get("https://www.patreon.com/api/oauth2")
}
}
| mit | 25d7a0fe054b33eaf881fb2115f1852a | 36.95288 | 123 | 0.570148 | 4.734814 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/ImitateApplication.kt | 1 | 5040 | package com.engineer.imitate
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Build
import android.util.Log
import android.view.View
import android.webkit.WebView
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.alibaba.android.arouter.launcher.ARouter
import com.didichuxing.doraemonkit.DoraemonKit
import com.engineer.imitate.interfaces.SimpleActivityCallback
import com.engineer.imitate.ui.fragments.di.DaggerApplicationComponent
import com.engineer.imitate.util.SpUtil
import com.engineer.imitate.util.SystemUtil
import com.engineer.imitate.util.TextUtil
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.stetho.Stetho
/**
*
* @author: Rookie
* @date: 2018-08-21 19:14
* @version V1.0
*/
@SuppressLint("LogNotTimber")
class ImitateApplication : Application() {
val applicationComponent = DaggerApplicationComponent.create()
companion object {
lateinit var application: Context
val TAG = "activity_life"
}
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
Log.d(TAG, "attachBaseContext() called with: base = $base")
}
private var view: View? = null
override fun onCreate() {
super.onCreate()
Log.d(TAG, "onCreate() called")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Log.d(TAG, "process name " + getProcessName())
}
Stetho.initializeWithDefaults(this)
WebView.setWebContentsDebuggingEnabled(true)
if (SpUtil(this).getBool(SpUtil.KEY_THEME_NIGHT_ON)) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
DoraemonKit.disableUpload()
DoraemonKit.install(this)
if (BuildConfig.DEBUG) {
ARouter.openLog()
ARouter.openDebug()
}
ARouter.init(this)
try {
Fresco.initialize(this)
} catch (ignore: Exception) {
}
kotlinTest()
application = this
registerActivityLifecycleCallbacks(object : SimpleActivityCallback() {})
ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleObserver {
val TAG = "ProcessLifecycleOwner"
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.d(TAG, "onCreate() called")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Log.d(TAG, "onResume() called")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
Log.d(TAG, "onPause() called")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
Log.d(TAG, "onStop() called")
}
})
val model = SystemUtil.getSystemModel()
Log.e(TAG, "onCreate() called model $model")
val brand = SystemUtil.getDeviceBrand()
Log.e(TAG, "onCreate() called brand $brand")
}
private fun kotlinTest() {
var result = null == true
println("null is true ? $result")
result = null == false
println("null is false? $result")
result = null != false
println("null not false? $result")
result = null != true
println("null not true? $result")
if (view != null) {
println("result ==" + view.hashCode())
} else {
println("result is null")
}
testHighFun()
val json = TextUtil.getJson()
// Log.e("json", "json form json-dsl is : $json")
}
// <editor-fold defaultstate="collapsed" desc="高阶函数测试">
/**
* 高阶函数,接受参数,返回对参数的处理结果
*/
private fun sum(dodo: (x: Int, y: Int) -> Int): Int {
val result = dodo(1, 2)
println(result)
return result
}
/**
* 高阶函数,不接受参数,只是做一件事情,类似装饰者模式的感觉
*/
private fun sum1(x: Int, y: Int, dodo: () -> Unit): Int {
dodo()
return x + y
}
private fun sum2(x: Int, y: Int, dodo: (Int, Int) -> Int) {
val result = dodo(x, y)
println("result from sum2 $result")
}
private fun testHighFun() {
val s = sum { x, y -> x + y }
println("result from sum $s")
val a = 1
val b = 2
val sum1 = sum1(a, b, dodo = {
if (a < b) {
println("this is decoration a < b")
} else {
println("this is decoration a >= b")
}
})
println("result from sum1 $sum1")
sum2(a, b, dodo = { x, y ->
(x * y)
})
}
// </editor-fold>
} | apache-2.0 | ee66d8f678b049ebe881d5b7196c4b33 | 26.702247 | 86 | 0.592698 | 4.081126 | false | false | false | false |
yukuku/androidbible | Alkitab/src/main/java/yuku/alkitab/base/dialog/VersesDialog.kt | 1 | 7774 | package yuku.alkitab.base.dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import kotlin.properties.Delegates.notNull
import yuku.alkitab.base.S
import yuku.alkitab.base.dialog.VersesDialog.Companion.newCompareInstance
import yuku.alkitab.base.dialog.VersesDialog.Companion.newInstance
import yuku.alkitab.base.dialog.base.BaseDialog
import yuku.alkitab.base.model.MVersion
import yuku.alkitab.base.util.Appearances.applyTextAppearance
import yuku.alkitab.base.verses.VersesController
import yuku.alkitab.base.verses.VersesControllerImpl
import yuku.alkitab.base.verses.VersesDataModel
import yuku.alkitab.base.verses.VersesListeners
import yuku.alkitab.base.verses.VersesUiModel
import yuku.alkitab.base.widget.VerseInlineLinkSpan
import yuku.alkitab.debug.R
import yuku.alkitab.model.Version
import yuku.alkitab.util.Ari
import yuku.alkitab.util.IntArrayList
private const val EXTRA_ariRanges = "ariRanges"
private const val EXTRA_ari = "ari"
private const val EXTRA_compareMode = "compareMode"
/**
* Dialog that shows a list of verses. There are two modes:
* "normal mode" that is created via [newInstance] to show a list of verses from a single version.
* -- field ariRanges is used, compareMode==false.
* "compare mode" that is created via [newCompareInstance] to show a list of different version of a verse.
* -- field ari is used, compareMode==true.
*/
class VersesDialog : BaseDialog() {
abstract class VersesDialogListener {
open fun onVerseSelected(ari: Int) {}
open fun onComparedVerseSelected(ari: Int, mversion: MVersion) {}
}
private var ari by notNull<Int>()
private var compareMode by notNull<Boolean>()
private lateinit var ariRanges: IntArrayList
// data that will be passed when one verse is clicked
private sealed class CallbackData {
class WithMVersion(val mversion: MVersion) : CallbackData()
class WithAri(val ari: Int) : CallbackData()
}
private lateinit var customCallbackDatas: Array<CallbackData>
var listener: VersesDialogListener? = null
var onDismissListener: () -> Unit = {}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NO_TITLE, 0)
// TODO appcompat 1.1.0: change to requireArguments()
val arguments = requireNotNull(arguments)
ariRanges = arguments.getParcelable(EXTRA_ariRanges) ?: IntArrayList(0)
ari = arguments.getInt(EXTRA_ari)
compareMode = arguments.getBoolean(EXTRA_compareMode)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val sourceVersion = S.activeVersion()
val sourceVersionId = S.activeVersionId()
val textSizeMult = S.getDb().getPerVersionSettings(sourceVersionId).fontSizeMultiplier
val res = inflater.inflate(R.layout.dialog_verses, container, false)
res.setBackgroundColor(S.applied().backgroundColor)
val tReference = res.findViewById<TextView>(R.id.tReference)
val versesController = VersesControllerImpl(
res.findViewById(R.id.lsView),
"verses",
VersesDataModel.EMPTY,
VersesUiModel.EMPTY.copy(
verseSelectionMode = VersesController.VerseSelectionMode.singleClick,
isVerseNumberShown = true
),
VersesListeners.EMPTY.copy(
selectedVersesListener = selectedVersesListener,
inlineLinkSpanFactory_ = { type, arif ->
object : VerseInlineLinkSpan(type, arif) {
override fun onClick(type: Type, arif: Int) {
val ari = arif ushr 8
selectedVersesListener.onVerseSingleClick(Ari.toVerse(ari))
}
}
}
)
)
// build reference label
val sb = StringBuilder()
if (!compareMode) {
var i = 0
while (i < ariRanges.size()) {
val ari_start = ariRanges[i]
val ari_end = ariRanges[i + 1]
if (sb.isNotEmpty()) {
sb.append("; ")
}
sb.append(sourceVersion.referenceRange(ari_start, ari_end))
i += 2
}
} else {
sb.append(sourceVersion.reference(ari))
}
applyTextAppearance(tReference, textSizeMult)
tReference.text = sb
versesController.versesDataModel = if (!compareMode) {
val displayedAris = IntArrayList()
val displayedVerseTexts = mutableListOf<String>()
val verse_count = sourceVersion.loadVersesByAriRanges(ariRanges, displayedAris, displayedVerseTexts)
customCallbackDatas = Array(verse_count) { i -> CallbackData.WithAri(displayedAris[i]) }
val displayedVerseNumberTexts = List(verse_count) { i ->
val ari = displayedAris[i]
"${Ari.toChapter(ari)}:${Ari.toVerse(ari)}"
}
val firstAri = ariRanges[0]
VersesDataModel(
ari_bc_ = Ari.toBookChapter(firstAri),
verses_ = VersesDialogNormalVerses(displayedVerseTexts, displayedVerseNumberTexts),
version_ = sourceVersion,
versionId_ = sourceVersionId
)
} else { // read each version and display it. First version must be the sourceVersion.
val mversions = S.getAvailableVersions()
// sort such that sourceVersion is first
mversions.sortBy { if (it.versionId == sourceVersionId) -1 else 0 }
val displayedVersion = arrayOfNulls<Version>(mversions.size)
customCallbackDatas = Array(mversions.size) { i -> CallbackData.WithMVersion(mversions[i]) }
VersesDataModel(
ari_bc_ = Ari.toBookChapter(ari),
verses_ = VersesDialogCompareVerses(requireContext(), ari, mversions, displayedVersion)
)
}
return res
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
onDismissListener()
}
private val selectedVersesListener = object : VersesController.SelectedVersesListener() {
override fun onVerseSingleClick(verse_1: Int) {
val listener = listener ?: return
val position = verse_1 - 1
val callbackData = customCallbackDatas[position]
if (!compareMode) {
if (callbackData is CallbackData.WithAri) {
listener.onVerseSelected(callbackData.ari)
}
} else { // only if the verse is available in this version.
if (callbackData is CallbackData.WithMVersion) {
if (callbackData.mversion.version?.loadVerseText(ari) != null) {
listener.onComparedVerseSelected(ari, callbackData.mversion)
}
}
}
}
}
companion object {
@JvmStatic
fun newInstance(ariRanges: IntArrayList) = VersesDialog().apply {
arguments = bundleOf(
EXTRA_ariRanges to ariRanges
)
}
@JvmStatic
fun newCompareInstance(ari: Int) = VersesDialog().apply {
arguments = bundleOf(
EXTRA_ari to ari,
EXTRA_compareMode to true
)
}
}
}
| apache-2.0 | 487c80079f92c374a054f02da9c6c3a6 | 38.663265 | 116 | 0.637252 | 4.621879 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/adapter/RepliesListAdapter.kt | 1 | 8971 | package com.emogoth.android.phone.mimi.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.text.format.DateUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.emogoth.android.phone.mimi.R
import com.emogoth.android.phone.mimi.app.MimiApplication
import com.emogoth.android.phone.mimi.event.ReplyClickEvent
import com.emogoth.android.phone.mimi.fourchan.FourChanEndpoints
import com.emogoth.android.phone.mimi.model.OutsideLink
import com.emogoth.android.phone.mimi.util.GlideApp
import com.emogoth.android.phone.mimi.util.MimiUtil
import com.emogoth.android.phone.mimi.view.LongClickLinkMovementMethod
import com.mimireader.chanlib.models.ArchivedChanPost
import com.mimireader.chanlib.models.ChanPost
import com.mimireader.chanlib.models.ChanThread
// final List<ChanPost> replies, final List<OutsideLink> links, final ChanThread thread
class RepliesListAdapter(val replies: List<ChanPost>, private val links: List<OutsideLink>, val thread: ChanThread) : RecyclerView.Adapter<RepliesViewHolder>() {
companion object {
const val POST_TYPE = 0
const val LINK_TYPE = 1
}
private val boardName: String
private val flagUrl: String
private val trollUrl: String
private val thumbUrlMap: MutableMap<Long, String>
private var timeMap: Array<CharSequence>
var linkClickListener: ((OutsideLink) -> Unit)? = null
var thumbClickListener: ((ChanPost) -> Unit)? = null
var repliesTextClickListener: ((ReplyClickEvent) -> Unit)? = null
var goToPostListener: ((ChanPost) -> Unit)? = null
init {
val context: Context = MimiApplication.instance.applicationContext
flagUrl = MimiUtil.https() + context.getString(R.string.flag_int_link)
trollUrl = MimiUtil.https() + context.getString(R.string.flag_pol_link)
thumbUrlMap = HashMap()
FourChanEndpoints.Image
boardName = thread.boardName
timeMap = Array(replies.size) {
val post = replies[it]
val dateString = DateUtils.getRelativeTimeSpanString(
post.time * 1000L,
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE)
if (post.filename != null && "" != post.filename) {
thumbUrlMap[post.no] = if (post is ArchivedChanPost)
post.thumbLink
?: MimiUtil.https() + context.getString(R.string.thumb_link) + context.getString(R.string.thumb_path, boardName, post.tim)
else
MimiUtil.https() + context.getString(R.string.thumb_link) + context.getString(R.string.thumb_path, boardName, post.tim)
}
dateString
}
}
override fun getItemViewType(position: Int): Int {
return if (position >= replies.size) {
LINK_TYPE
} else {
POST_TYPE
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepliesViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view: View
return if (viewType == POST_TYPE) {
view = inflater.inflate(R.layout.reply_post_item, parent, false)
ChanPostViewHolder(view, thumbClickListener, repliesTextClickListener, goToPostListener)
} else {
view = inflater.inflate(R.layout.reply_link_item, parent, false)
LinkViewHolder(view, linkClickListener)
}
}
override fun getItemCount(): Int {
return replies.size + links.size
}
override fun onBindViewHolder(holder: RepliesViewHolder, position: Int) {
if (replies.isEmpty()) {
return
}
if (holder is ChanPostViewHolder) {
val postItem = replies[position]
val time = timeMap[position]
val thumbUrl = thumbUrlMap[postItem.no]
holder.bind(PostData(postItem, time, thumbUrl))
} else if (holder is LinkViewHolder) {
val pos = position - replies.size
val link = links[pos]
holder.bind(link)
}
}
}
class ChanPostViewHolder(private val v: View,
private val thumbClickListener: ((ChanPost) -> Unit)?,
private val repliesTextClickListener: ((ReplyClickEvent) -> Unit)?,
private val goToPostListener: ((ChanPost) -> Unit)?) : RepliesViewHolder(v) {
companion object {
val LOG_TAG = ChanPostViewHolder::class.java.simpleName
}
var threadId: TextView = v.findViewById(R.id.thread_id)
var thumbnailContainer: ViewGroup = v.findViewById(R.id.thumbnail_container)
var userName: TextView = v.findViewById(R.id.user_name)
var postTime: TextView = v.findViewById(R.id.timestamp)
var userId: TextView = v.findViewById(R.id.user_id)
var tripCode: TextView = v.findViewById(R.id.tripcode)
// var subject: TextView = v.findViewById(R.id.subject)
var comment: TextView = v.findViewById(R.id.comment)
var thumbUrl: ImageView = v.findViewById(R.id.thumbnail)
var menuButton: ImageView? = null
var postContainer: ViewGroup? = null
var gotoPost: TextView = v.findViewById(R.id.goto_post)
var flagIcon: ImageView = v.findViewById(R.id.flag_icon)
var repliesText: TextView = v.findViewById(R.id.replies_number)
init {
comment.movementMethod = LongClickLinkMovementMethod.getInstance()
}
override fun bind(item: Any) {
if (item is PostData) {
val postItem = item.post
val country: String?
val flagUrl: String?
if (postItem.country == null) {
country = postItem.trollCountry
flagUrl = if (country != null) {
FourChanEndpoints.Troll + country.toLowerCase() + ".gif"
} else {
null
}
} else {
country = postItem.country
flagUrl = if (country != null) {
FourChanEndpoints.Flag + country.toLowerCase() + ".gif"
} else {
null
}
}
if (country != null) {
Log.i(LOG_TAG, "flag url=$flagUrl")
flagIcon.visibility = View.VISIBLE
MimiUtil.loadImageWithFallback(v.context, flagIcon, flagUrl, null, R.drawable.placeholder_image, null)
} else {
flagIcon.visibility = View.GONE
}
gotoPost.setOnClickListener {
goToPostListener?.invoke(postItem)
}
threadId.text = postItem.no.toString()
userName.text = postItem.displayedName
postTime.text = item.time
repliesText.text = v.resources.getQuantityString(R.plurals.replies_plural, postItem.repliesFrom.size, postItem.repliesFrom.size)
if (postItem.repliesFrom.isEmpty()) {
repliesText.setOnClickListener(null)
} else {
repliesText.setOnClickListener {
repliesTextClickListener?.invoke(ReplyClickEvent(postItem))
}
}
comment.text = postItem.comment ?: ""
if (item.thumbUrl != null) {
thumbnailContainer.visibility = View.VISIBLE
GlideApp.with(v.context)
.load(item.thumbUrl)
.placeholder(R.drawable.placeholder_image)
.into(thumbUrl)
thumbnailContainer.setOnClickListener {
thumbClickListener?.invoke(postItem)
}
} else {
thumbnailContainer.visibility = View.GONE
GlideApp.with(v.context).clear(thumbUrl)
}
}
}
}
class LinkViewHolder(itemView: View, private val clickListener: ((OutsideLink) -> Unit)?) : RepliesViewHolder(itemView) {
private val linkText: TextView = itemView.findViewById(R.id.link_text)
@SuppressLint("SetTextI18n")
override fun bind(item: Any) {
if (item is OutsideLink) {
if (!TextUtils.isEmpty(item.threadId)) {
linkText.text = "/${item.boardName}/${item.threadId}"
} else {
linkText.text = "/${item.boardName}/"
}
itemView.setOnClickListener {
clickListener?.invoke(item)
}
}
}
}
abstract class RepliesViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun bind(item: Any)
}
data class PostData(val post: ChanPost, val time: CharSequence?, val thumbUrl: String?)
| apache-2.0 | e3f379350283830cb87676ae3de65b4e | 37.337607 | 161 | 0.620109 | 4.523954 | false | false | false | false |
samtstern/quickstart-android | mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/textrecognition/TextRecognitionProcessor.kt | 1 | 2337 | package com.google.firebase.samples.apps.mlkit.kotlin.textrecognition
import android.graphics.Bitmap
import android.util.Log
import com.google.android.gms.tasks.Task
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.text.FirebaseVisionText
import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer
import com.google.firebase.samples.apps.mlkit.common.CameraImageGraphic
import com.google.firebase.samples.apps.mlkit.common.FrameMetadata
import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay
import com.google.firebase.samples.apps.mlkit.kotlin.VisionProcessorBase
import java.io.IOException
/** Processor for the text recognition demo. */
class TextRecognitionProcessor : VisionProcessorBase<FirebaseVisionText>() {
private val detector: FirebaseVisionTextRecognizer = FirebaseVision.getInstance().onDeviceTextRecognizer
override fun stop() {
try {
detector.close()
} catch (e: IOException) {
Log.e(TAG, "Exception thrown while trying to close Text Detector: $e")
}
}
override fun detectInImage(image: FirebaseVisionImage): Task<FirebaseVisionText> {
return detector.processImage(image)
}
override fun onSuccess(
originalCameraImage: Bitmap?,
results: FirebaseVisionText,
frameMetadata: FrameMetadata,
graphicOverlay: GraphicOverlay
) {
graphicOverlay.clear()
originalCameraImage.let { image ->
val imageGraphic = CameraImageGraphic(graphicOverlay, image)
graphicOverlay.add(imageGraphic)
}
val blocks = results.textBlocks
for (i in blocks.indices) {
val lines = blocks[i].lines
for (j in lines.indices) {
val elements = lines[j].elements
for (k in elements.indices) {
val textGraphic = TextGraphic(graphicOverlay, elements[k])
graphicOverlay.add(textGraphic)
}
}
}
graphicOverlay.postInvalidate()
}
override fun onFailure(e: Exception) {
Log.w(TAG, "Text detection failed.$e")
}
companion object {
private const val TAG = "TextRecProc"
}
}
| apache-2.0 | febc56ad1d48ccbf7d44220f5fefd6a4 | 34.409091 | 108 | 0.687206 | 4.75 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/tasks/model/TaskError.kt | 1 | 549 | package com.telenav.osv.tasks.model
private const val ERROR_OUT_OF_PICKUP_LIMIT = "OUT_OF_PICKUP_LIMIT"
private const val ERROR_UNKNOWN = "UNKNOWN"
/**
* This enum stores error codes returned from server for task api
*/
enum class TaskError(val error: String) {
OUT_OF_PICKUP_LIMIT(ERROR_OUT_OF_PICKUP_LIMIT),
UNKNOWN(ERROR_UNKNOWN);
companion object {
fun getByError(error: String): TaskError {
val taskError = values().firstOrNull { it.error == error }
return taskError ?: UNKNOWN
}
}
} | lgpl-3.0 | 3f478825082a432605529385efc2cef8 | 27.947368 | 70 | 0.668488 | 3.8125 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/H4Text.kt | 1 | 532 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun H4Text(
text: String,
modifier: Modifier = Modifier
) {
Text(
text = text,
color = MaterialTheme.colors.onSurface,
style = MaterialTheme.typography.h4,
modifier = modifier
)
}
| mit | d5e87fe46821909215242e791df61190 | 24.333333 | 47 | 0.744361 | 4.15625 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/crate/Crate.kt | 2 | 4540 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.crate
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolderEx
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.CfgOptions
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.project.workspace.CargoWorkspaceData
import org.rust.cargo.project.workspace.FeatureState
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.ide.experiments.RsExperiments
import org.rust.lang.core.crate.impl.FakeCrate
import org.rust.lang.core.psi.RsFile
/**
* An immutable object describes a *crate* from the *rustc* point of view.
* In Cargo-based project this is usually a wrapper around [CargoWorkspace.Target]
*/
interface Crate : UserDataHolderEx {
/**
* This id can be saved to a disk and then used to find the crate via [CrateGraphService.findCrateById].
* Can be `null` for crates that are not represented in the physical filesystem and can't be retrieved
* using [CrateGraphService.findCrateById], or for invalid crates (without a root module)
*/
val id: CratePersistentId?
val edition: CargoWorkspace.Edition
val cargoProject: CargoProject?
val cargoWorkspace: CargoWorkspace?
val cargoTarget: CargoWorkspace.Target?
val kind: CargoWorkspace.TargetKind
val origin: PackageOrigin
val cfgOptions: CfgOptions
val features: Map<String, FeatureState>
/**
* `true` if there isn't a custom build script (`build.rs`) in the package or if the build script is
* successfully evaluated (hence [cfgOptions] is filled). The value affects `#[cfg()]` and `#[cfg_attr()]`
* attributes evaluation.
*/
val evaluateUnknownCfgToFalse: Boolean
/** A map of compile-time environment variables, needed for `env!("FOO")` macros expansion */
val env: Map<String, String>
/** Represents `OUT_DIR` compile-time environment variable. Used for `env!("OUT_DIR")` macros expansion */
val outDir: VirtualFile?
/** Direct dependencies */
val dependencies: Collection<Dependency>
/** All dependencies (including transitive) of this crate. Topological sorted */
val flatDependencies: LinkedHashSet<Crate>
/** Other crates that depends on this crate */
val reverseDependencies: List<Crate>
/**
* A cargo package can have cyclic dependencies through `[dev-dependencies]` (see [CrateGraphService] docs).
* Cyclic dependencies are not contained in [dependencies], [flatDependencies] or [reverseDependencies].
*/
val dependenciesWithCyclic: Collection<Dependency>
get() = dependencies
/** A cargo package can have cyclic dependencies through `[dev-dependencies]` (see [CrateGraphService] docs) */
val hasCyclicDevDependencies: Boolean
get() = false
/**
* A root module of the crate, also known as "crate root". Usually it's `main.rs` or `lib.rs`.
* Use carefully: can be null or invalid ([VirtualFile.isValid])
*/
val rootModFile: VirtualFile?
val rootMod: RsFile?
val areDoctestsEnabled: Boolean
/** A name to display to a user */
val presentableName: String
/**
* A name that can be used as a valid Rust identifier. Usually it is [presentableName] with "-" chars
* replaced to "_".
*
* NOTE that Rust crate doesn't have any kind of "global" name. The actual crate name can be different
* in a particular dependent crate. Use [Dependency.normName] instead
*/
val normName: String
val project: Project
/**
* A procedural macro compiler artifact (compiled binary).
* Non-null only if this crate is a procedural macro, the crate is successfully compiled during
* the Cargo sync phase and [RsExperiments.EVALUATE_BUILD_SCRIPTS] experimental feature is enabled.
*/
val procMacroArtifact: CargoWorkspaceData.ProcMacroArtifact?
data class Dependency(
/** A name of the dependency that can be used in `extern crate name;` or in absolute paths */
val normName: String,
val crate: Crate
)
}
fun Crate.findDependency(normName: String): Crate? =
dependencies.find { it.normName == normName }?.crate
fun Crate.hasTransitiveDependencyOrSelf(other: Crate): Boolean =
other == this || other in flatDependencies
val Crate.asNotFake: Crate? get() = takeIf { this !is FakeCrate }
| mit | b131a69ad231ed4c9d7f000a4bb0f293 | 36.833333 | 115 | 0.715198 | 4.382239 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/extractEnumVariant/RsExtractEnumVariantAction.kt | 2 | 1916 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.extractEnumVariant
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.refactoring.RsBaseEditorRefactoringAction
import org.rust.lang.core.CompilerFeature.Companion.ARBITRARY_ENUM_DISCRIMINANT
import org.rust.lang.core.FeatureAvailability
import org.rust.lang.core.psi.RsEnumVariant
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.lang.core.psi.ext.isFieldless
class RsExtractEnumVariantAction : RsBaseEditorRefactoringAction() {
override fun isAvailableOnElementInEditorAndFile(
element: PsiElement,
editor: Editor,
file: PsiFile,
context: DataContext
): Boolean =
findApplicableContext(editor, file) != null
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
val ctx = findApplicableContext(editor, file) ?: return
val processor = RsExtractEnumVariantProcessor(project, editor, ctx)
processor.setPreviewUsages(false)
processor.run()
}
companion object {
private fun findApplicableContext(editor: Editor, file: PsiFile): RsEnumVariant? {
val offset = editor.caretModel.offset
val variant = file.findElementAt(offset)?.ancestorOrSelf<RsEnumVariant>() ?: return null
if (variant.isFieldless) {
return null
}
if (variant.variantDiscriminant != null &&
ARBITRARY_ENUM_DISCRIMINANT.availability(variant.containingMod) != FeatureAvailability.AVAILABLE) {
return null
}
return variant
}
}
}
| mit | 763264546b52c89fdff98bcb0cd3be41 | 34.481481 | 115 | 0.708246 | 4.551069 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.