repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
kurtyan/guitarchina-hunter | src/main/java/com/github/kurtyan/guitarchinahunter/schedule/IntervalConfigSet.kt | 1 | 932 | package com.github.kurtyan.guitarchinahunter.schedule
import java.time.LocalTime
import java.time.format.DateTimeFormatter
/**
* Created by yanke on 2016/4/19.
*/
class IntervalConfigSet {
val configList = arrayListOf<IntervalConfig>()
val patterns = listOf<String>(
"HHmm",
"HHmmss",
"HH:mm",
"HH:mm:ss"
).map { DateTimeFormatter.ofPattern(it) }
fun parse(time: String): LocalTime {
for (pt in patterns) {
try {
return LocalTime.parse(time, pt)
} catch (e: Exception) {}
}
throw IllegalArgumentException("unformatable time: ${time}")
}
fun addIntervalConfig(start: String, end: String, interval: Long): IntervalConfigSet {
configList.add(IntervalConfig(
parse(start),
parse(end),
interval
))
return this
}
}
| apache-2.0 |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/Builder.kt | 1 | 814 | package org.hexworks.zircon.api.builder
import org.hexworks.zircon.api.behavior.Copiable
/**
* Simple builder pattern interface for [build]ing instances of type [T].
* All builders have sensible defaults. If there are no sensible defaults a [Builder]
* should provide a factory method that ensures that mandatory parameters are passed
* to the [Builder] when it is created. This ensures that exceptions are not thrown from
* [build] if its state is inconsistent.
*
* All configuration properties in a [Builder] should have a fluent setter like this:
*
* ```kotlin
* fun withFocusNext(focusNext: KeyboardEventMatcher) = also {
* this.focusNext = focusNext
* }
* ```
*/
interface Builder<out T> : Copiable<Builder<T>> {
/**
* Builds an object of type [T].
*/
fun build(): T
}
| apache-2.0 |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/text/MotionWordLeftAction.kt | 1 | 2128 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.action.motion.text
import com.maddyhome.idea.vim.action.ComplicatedKeysAction
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MotionType
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.Motion
import com.maddyhome.idea.vim.handler.MotionActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import java.awt.event.KeyEvent
import java.util.*
import javax.swing.KeyStroke
class MotionWordLeftAction : MotionActionHandler.ForEachCaret() {
override val motionType: MotionType = MotionType.EXCLUSIVE
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
return injector.motion.findOffsetOfNextWord(editor, caret.offset.point, -operatorArguments.count1, false)
}
}
class MotionWordLeftInsertAction : MotionActionHandler.ForEachCaret(), ComplicatedKeysAction {
override val motionType: MotionType = MotionType.EXCLUSIVE
override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.CTRL_DOWN_MASK)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, KeyEvent.CTRL_DOWN_MASK))
)
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_STROKE)
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
return injector.motion.findOffsetOfNextWord(editor, caret.offset.point, -operatorArguments.count1, false)
}
}
| mit |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/modifier/TextureTransformModifier.kt | 1 | 277 | package org.hexworks.zircon.api.modifier
import org.hexworks.zircon.api.data.Tile
/**
* A [TextureTransformModifier] is a kind of [Modifier]
* that transforms the actual texture represented by
* a [Tile] before rendering.
*/
interface TextureTransformModifier : Modifier
| apache-2.0 |
dempe/pinterest-java | src/main/java/com/chrisdempewolf/pinterest/responses/pin/Board.kt | 1 | 230 | package com.chrisdempewolf.pinterest.responses.pin
import com.google.gson.annotations.SerializedName
data class Board(val id: String?, val name: String?, val url: String?, @SerializedName("counts") val boardCounts: BoardCounts?) | mit |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/engagement/LikerViewHolder.kt | 1 | 2594 | package org.wordpress.android.ui.engagement
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import org.wordpress.android.R
import org.wordpress.android.ui.engagement.EngageItem.Liker
import org.wordpress.android.ui.engagement.EngagedListNavigationEvent.OpenUserProfileBottomSheet.UserProfile
import org.wordpress.android.util.GravatarUtils
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.image.ImageType
import org.wordpress.android.viewmodel.ResourceProvider
class LikerViewHolder(
parent: ViewGroup,
private val imageManager: ImageManager,
private val resourceProvider: ResourceProvider
) : EngagedPeopleViewHolder(parent, R.layout.liker_user) {
private val likerName = itemView.findViewById<TextView>(R.id.user_name)
private val likerLogin = itemView.findViewById<TextView>(R.id.user_login)
private val likerAvatar = itemView.findViewById<ImageView>(R.id.user_avatar)
private val likerRootView = itemView.findViewById<View>(R.id.liker_root_view)
fun bind(liker: Liker) {
this.likerName.text = liker.name
this.likerLogin.text = if (liker.login.isNotBlank()) {
resourceProvider.getString(R.string.at_username, liker.login)
} else {
liker.login
}
val likerAvatarUrl = GravatarUtils.fixGravatarUrl(
liker.userAvatarUrl,
likerRootView.context.resources.getDimensionPixelSize(R.dimen.avatar_sz_medium)
)
imageManager.loadIntoCircle(this.likerAvatar, ImageType.AVATAR_WITH_BACKGROUND, likerAvatarUrl)
if (liker.onClick != null) {
likerRootView.isEnabled = true
likerRootView.setOnClickListener {
liker.onClick.invoke(
UserProfile(
userAvatarUrl = liker.userAvatarUrl,
blavatarUrl = liker.preferredBlogBlavatar,
userName = liker.name,
userLogin = liker.login,
userBio = liker.userBio,
siteTitle = liker.preferredBlogName,
siteUrl = liker.preferredBlogUrl,
siteId = liker.preferredBlogId
),
liker.source
)
}
} else {
likerRootView.isEnabled = true
likerRootView.setOnClickListener(null)
}
}
}
| gpl-2.0 |
y20k/transistor | app/src/main/java/org/y20k/transistor/helpers/NotificationHelper.kt | 1 | 6712 | /*
* NotificationHelper.kt
* Implements the NotificationHelper class
* A NotificationHelper creates and configures a notification
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor.helpers
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.y20k.transistor.Keys
import org.y20k.transistor.R
/*
* NotificationHelper class
* Credit: https://github.com/android/uamp/blob/5bae9316b60ba298b6080de1fcad53f6f74eb0bf/common/src/main/java/com/example/android/uamp/media/UampNotificationManager.kt
*/
class NotificationHelper(private val context: Context, sessionToken: MediaSessionCompat.Token, notificationListener: PlayerNotificationManager.NotificationListener) {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(NotificationHelper::class.java)
/* Main class variables */
private val serviceJob = SupervisorJob()
private val serviceScope = CoroutineScope(Main + serviceJob)
private val notificationManager: PlayerNotificationManager
private val mediaController: MediaControllerCompat = MediaControllerCompat(context, sessionToken)
/* Constructor */
init {
// create a notification builder
val notificationBuilder = PlayerNotificationManager.Builder(context, Keys.NOW_PLAYING_NOTIFICATION_ID, Keys.NOW_PLAYING_NOTIFICATION_CHANNEL_ID)
notificationBuilder.apply {
setChannelNameResourceId(R.string.notification_now_playing_channel_name)
setChannelDescriptionResourceId(R.string.notification_now_playing_channel_description)
setMediaDescriptionAdapter(DescriptionAdapter(mediaController))
setNotificationListener(notificationListener)
}
// create and configure the notification manager
notificationManager = notificationBuilder.build()
notificationManager.apply {
// note: notification icons are customized in values.xml
setMediaSessionToken(sessionToken)
setSmallIcon(R.drawable.ic_notification_app_icon_white_24dp)
setUsePlayPauseActions(true)
setUseStopAction(true) // set true to display the dismiss button
setUsePreviousAction(true)
setUsePreviousActionInCompactView(false)
setUseNextAction(true) // only visible, if player is set to Player.REPEAT_MODE_ALL
setUseNextActionInCompactView(false)
setUseChronometer(true)
}
}
/* Hides notification via notification manager */
fun hideNotification() {
notificationManager.setPlayer(null)
}
/* Displays notification via notification manager */
fun showNotificationForPlayer(player: Player) {
notificationManager.setPlayer(player)
}
/* Triggers notification */
fun updateNotification() {
notificationManager.invalidate()
}
// /*
// * Inner class: Intercept stop button tap
// */
// private inner class Dispatcher: DefaultControlDispatcher(0L, 0L /* hide fast forward and rewind */) {
// override fun dispatchStop(player: Player, reset: Boolean): Boolean {
// // Default implementation see: https://github.com/google/ExoPlayer/blob/b1000940eaec9e1202d9abf341a48a58b728053f/library/core/src/main/java/com/google/android/exoplayer2/DefaultControlDispatcher.java#L137
// mediaController.sendCommand(Keys.CMD_DISMISS_NOTIFICATION, null, null)
// return true
// }
//
// override fun dispatchSetPlayWhenReady(player: Player, playWhenReady: Boolean): Boolean {
// // changes the default behavior of !playWhenReady from player.pause() to player.stop()
// when (playWhenReady) {
// true -> player.play()
// false -> player.stop()
// }
// return true
// }
//
// override fun dispatchPrevious(player: Player): Boolean {
// mediaController.sendCommand(Keys.CMD_PREVIOUS_STATION, null, null)
// return true
// }
//
// override fun dispatchNext(player: Player): Boolean {
// mediaController.sendCommand(Keys.CMD_NEXT_STATION, null, null)
// return true
// }
// }
// /*
// * End of inner class
// */
/*
* Inner class: Create content of notification from metaddata
*/
private inner class DescriptionAdapter(private val controller: MediaControllerCompat) : PlayerNotificationManager.MediaDescriptionAdapter {
var currentIconUri: Uri? = null
var currentBitmap: Bitmap? = null
override fun createCurrentContentIntent(player: Player): PendingIntent? = controller.sessionActivity
override fun getCurrentContentText(player: Player) = controller.metadata.description.subtitle.toString()
override fun getCurrentContentTitle(player: Player) = controller.metadata.description.title.toString()
override fun getCurrentLargeIcon(player: Player, callback: PlayerNotificationManager.BitmapCallback): Bitmap? {
val iconUri: Uri? = controller.metadata.description.iconUri
return if (currentIconUri != iconUri || currentBitmap == null) {
// Cache the bitmap for the current song so that successive calls to
// `getCurrentLargeIcon` don't cause the bitmap to be recreated.
currentIconUri = iconUri
serviceScope.launch {
currentBitmap = iconUri?.let {
resolveUriAsBitmap(it)
}
currentBitmap?.let { callback.onBitmap(it) }
}
null
} else {
currentBitmap
}
}
private suspend fun resolveUriAsBitmap(currentIconUri: Uri): Bitmap {
return withContext(IO) {
// Block on downloading artwork.
ImageHelper.getStationImage(context, currentIconUri.toString())
}
}
}
/*
* End of inner class
*/
}
| mit |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/repository/topics/TopicsRepository.kt | 1 | 704 | package forpdateam.ru.forpda.model.repository.topics
import forpdateam.ru.forpda.entity.remote.topics.TopicsData
import forpdateam.ru.forpda.model.SchedulersProvider
import forpdateam.ru.forpda.model.data.remote.api.topcis.TopicsApi
import forpdateam.ru.forpda.model.repository.BaseRepository
import io.reactivex.Observable
import io.reactivex.Single
/**
* Created by radiationx on 03.01.18.
*/
class TopicsRepository(
private val schedulers: SchedulersProvider,
private val topicsApi: TopicsApi
) : BaseRepository(schedulers) {
fun getTopics(id: Int, st: Int): Single<TopicsData> = Single
.fromCallable { topicsApi.getTopics(id, st) }
.runInIoToUi()
}
| gpl-3.0 |
fengzhizi715/SAF-Kotlin-Utils | saf-kotlin-utils/src/main/java/com/safframework/utils/NetUtils.kt | 1 | 1616 | package com.safframework.utils
import android.content.Context
import android.net.wifi.WifiManager
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.*
/**
*
* @FileName:
* com.safframework.utils.NetUtils
* @author: Tony Shen
* @date: 2020-11-19 15:02
* @version: V1.0 <描述当前版本功能>
*/
/**
* 获取内网IP地址
*/
val localIPAddress: String by lazy {
val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val intf: NetworkInterface = en.nextElement()
val enumIpAddr: Enumeration<InetAddress> = intf.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress: InetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
return@lazy inetAddress.hostAddress.toString()
}
}
}
"null"
}
/**
* 获取局域网的网关地址
*/
fun getGatewayIP(context: Context):String {
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
val info = wifiManager.dhcpInfo
val gateway = info.gateway
return intToIp(gateway)
}
/**
* int值转换为ip
* @param addr
* @return
*/
private fun intToIp(addr: Int): String {
var addr = addr
return (addr and 0xFF).toString() + "." +
(8.let { addr = addr ushr it; addr } and 0xFF) + "." +
(8.let { addr = addr ushr it; addr } and 0xFF) + "." +
(8.let { addr = addr ushr it; addr } and 0xFF)
} | apache-2.0 |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/ui/modules/inspector/BaseInspectorWidget.kt | 1 | 4043 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.ui.modules.inspector
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.ui.Cell
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.kotcrab.vis.ui.widget.Separator
import com.kotcrab.vis.ui.widget.VisLabel
import com.kotcrab.vis.ui.widget.VisTable
import com.mbrlabs.mundus.commons.scene3d.GameObject
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.ui.widgets.CollapseWidget
import com.mbrlabs.mundus.editor.ui.widgets.FaTextButton
import com.mbrlabs.mundus.editor.utils.Fa
/**
* @author Marcus Brummer
* @version 19-01-2016
*/
abstract class BaseInspectorWidget(title: String) : VisTable() {
companion object {
private val COLLAPSE_BTN_DOWN = Fa.CARET_UP
private val COLLAPSE_BTN_UP = Fa.CARET_DOWN
}
var title: String? = null
set(title) {
field = title
titleLabel.setText(title)
}
private val collapseBtn = FaTextButton(COLLAPSE_BTN_UP)
private val deleteBtn = FaTextButton(Fa.TIMES)
private var deletableBtnCell: Cell<*>? = null
protected val collapsibleContent = VisTable()
private val collapsibleWidget = CollapseWidget(collapsibleContent)
private val titleLabel = VisLabel()
private var deletable: Boolean = false
init {
collapseBtn.label.setFontScale(0.7f)
deleteBtn.label.setFontScale(0.7f)
deleteBtn.style.up = null
deletable = false
setupUI()
setupListeners()
this.title = title
}
private fun setupListeners() {
// collapse
collapseBtn.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
collapse(!isCollapsed)
}
})
// delete
deleteBtn.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
onDelete()
}
})
}
private fun setupUI() {
// header
val header = VisTable()
deletableBtnCell = header.add(deleteBtn).top().left().padBottom(4f)
header.add(titleLabel)
header.add(collapseBtn).right().top().width(20f).height(20f).expand().row()
// add seperator
header.add(Separator(UI.greenSeperatorStyle)).fillX().expandX().colspan(3).row()
// add everything to root
add(header).expand().fill().padBottom(10f).row()
add(collapsibleWidget).expand().fill().row()
isDeletable = deletable
}
var isDeletable: Boolean
get() = deletable
set(deletable) {
this.deletable = deletable
if (deletable) {
deleteBtn.isVisible = true
deletableBtnCell!!.width(20f).height(20f).padRight(5f)
} else {
deleteBtn.isVisible = false
deletableBtnCell!!.width(0f).height(0f).padRight(0f)
}
}
val isCollapsed: Boolean
get() = collapsibleWidget.isCollapsed
fun collapse(collapse: Boolean) {
collapsibleWidget.setCollapsed(collapse, false)
if (collapse) {
collapseBtn.setText(COLLAPSE_BTN_DOWN)
} else {
collapseBtn.setText(COLLAPSE_BTN_UP)
}
}
abstract fun onDelete()
abstract fun setValues(go: GameObject)
}
| apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/increaseVisibility/exposedTypeParameterBound.kt | 7 | 350 | // "Make 'InternalString' public" "true"
// ACTION: Create test
// ACTION: Enable a trailing comma by default in the formatter
// ACTION: Introduce import alias
// ACTION: Make 'InternalString' public
// ACTION: Make 'User' internal
// ACTION: Make 'User' private
internal open class InternalString
class User<T : <caret>User<T, InternalString>, R> | apache-2.0 |
ingokegel/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventLogProvidersHolder.kt | 5 | 2880 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.eventLog
import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider.Companion.EP_NAME
import com.intellij.internal.statistic.utils.PluginType
import com.intellij.internal.statistic.utils.StatisticsRecorderUtil
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.util.PlatformUtils
import java.util.concurrent.atomic.AtomicReference
@Service(Service.Level.APP)
internal class StatisticsEventLogProvidersHolder {
private val eventLoggerProviders: AtomicReference<Map<String, StatisticsEventLoggerProvider>> =
AtomicReference(calculateEventLogProvider())
init {
if (ApplicationManager.getApplication().extensionArea.hasExtensionPoint(EP_NAME)) {
EP_NAME.addChangeListener(Runnable { eventLoggerProviders.set(calculateEventLogProvider()) }, null)
}
}
fun getEventLogProvider(recorderId: String): StatisticsEventLoggerProvider {
return eventLoggerProviders.get()[recorderId] ?: EmptyStatisticsEventLoggerProvider(recorderId)
}
fun getEventLogProviders(): Collection<StatisticsEventLoggerProvider> {
return eventLoggerProviders.get().values
}
private fun calculateEventLogProvider(): Map<String, StatisticsEventLoggerProvider> {
return getAllEventLogProviders().associateBy { it.recorderId }
}
private fun getAllEventLogProviders(): Sequence<StatisticsEventLoggerProvider> {
val providers = EP_NAME.extensionsIfPointIsRegistered
if (providers.isEmpty()) {
return emptySequence()
}
val isJetBrainsProduct = isJetBrainsProduct()
return providers.asSequence()
.filter { isProviderApplicable(isJetBrainsProduct, it.recorderId, it) }
.distinctBy { it.recorderId }
}
private fun isJetBrainsProduct(): Boolean {
val appInfo = ApplicationInfo.getInstance()
return if (appInfo == null || appInfo.shortCompanyName.isNullOrEmpty()) true else PlatformUtils.isJetBrainsProduct()
}
private fun isProviderApplicable(isJetBrainsProduct: Boolean, recorderId: String, extension: StatisticsEventLoggerProvider): Boolean {
if (recorderId == extension.recorderId) {
if (!isJetBrainsProduct || !StatisticsRecorderUtil.isBuildInRecorder(recorderId)) {
return true
}
val pluginInfo = getPluginInfo(extension::class.java)
return if (recorderId == "MLSE") {
pluginInfo.isDevelopedByJetBrains()
}
else {
pluginInfo.type == PluginType.PLATFORM || pluginInfo.type == PluginType.FROM_SOURCES || pluginInfo.isAllowedToInjectIntoFUS()
}
}
return false
}
} | apache-2.0 |
DroidSmith/TirePressureGuide | tireguide/src/main/java/com/droidsmith/tireguide/splash/SplashActivity.kt | 1 | 499 | package com.droidsmith.tireguide.splash
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.droidsmith.tireguide.TireGuideActivity
/**
* The initial splash screen.
*/
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = Intent(this, TireGuideActivity::class.java)
startActivity(intent)
finish()
}
}
| apache-2.0 |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/repository/data/RemoteArtistDataSource.kt | 1 | 476 | package com.kelsos.mbrc.repository.data
import com.kelsos.mbrc.constants.Protocol
import com.kelsos.mbrc.data.library.Artist
import com.kelsos.mbrc.networking.ApiBase
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class RemoteArtistDataSource
@Inject constructor(private val service: ApiBase) : RemoteDataSource<Artist> {
override suspend fun fetch(): Flow<List<Artist>> {
return service.getAllPages(Protocol.LibraryBrowseArtists, Artist::class)
}
}
| gpl-3.0 |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/nextfare/record/NextfareRecord.kt | 1 | 4150 | /*
* NextfareRecord.kt
*
* Copyright 2015-2019 Michael Farrell <[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 au.id.micolous.metrodroid.transit.nextfare.record
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.NumberUtils
/**
* Represents a record on a Nextfare card
* This fans out parsing to subclasses.
* https://github.com/micolous/metrodroid/wiki/Cubic-Nextfare-MFC
*/
interface NextfareRecord {
companion object {
private const val TAG = "NextfareRecord"
fun recordFromBytes(input: ImmutableByteArray, sectorIndex: Int, blockIndex: Int, timeZone: MetroTimeZone): NextfareRecord? {
Log.d(TAG, "Record: $input")
when {
sectorIndex == 1 && blockIndex <= 1 -> {
Log.d(TAG, "Balance record")
return NextfareBalanceRecord.recordFromBytes(input)
}
sectorIndex == 1 && blockIndex == 2 -> {
Log.d(TAG, "Configuration record")
return NextfareConfigRecord.recordFromBytes(input, timeZone)
}
sectorIndex == 2 -> {
Log.d(TAG, "Top-up record")
return NextfareTopupRecord.recordFromBytes(input, timeZone)
}
sectorIndex == 3 -> {
Log.d(TAG, "Travel pass record")
return NextfareTravelPassRecord.recordFromBytes(input, timeZone)
}
sectorIndex in 5..8 -> {
Log.d(TAG, "Transaction record")
return NextfareTransactionRecord.recordFromBytes(input, timeZone)
}
else -> return null
}
}
/**
* Date format:
*
*
* Top two bytes:
* 0001111 1100 00100 = 2015-12-04
* yyyyyyy mmmm ddddd
*
*
* Bottom 11 bits = minutes since 00:00
* Time is represented in localtime
*
*
* Assumes that data has not been byte-reversed.
*
* @param input Bytes of input representing the timestamp to parse
* @param offset Offset in byte to timestamp
* @return Date and time represented by that value
*/
fun unpackDate(input: ImmutableByteArray, offset: Int, timeZone: MetroTimeZone): TimestampFull {
val timestamp = input.byteArrayToIntReversed(offset, 4)
val minute = NumberUtils.getBitsFromInteger(timestamp, 16, 11)
val year = NumberUtils.getBitsFromInteger(timestamp, 9, 7) + 2000
val month = NumberUtils.getBitsFromInteger(timestamp, 5, 4)
val day = NumberUtils.getBitsFromInteger(timestamp, 0, 5)
//noinspection MagicCharacter
Log.d(TAG, "unpackDate: $minute minutes, $year-$month-$day")
if (minute > 1440)
throw AssertionError("Minute > 1440 ($minute)")
if (minute < 0)
throw AssertionError("Minute < 0 ($minute)")
if (day > 31) throw AssertionError("Day > 31 ($day)")
if (month > 12)
throw AssertionError("Month > 12 ($month)")
return TimestampFull(timeZone, year, month - 1, day, minute / 60, minute % 60, 0)
}
}
}
| gpl-3.0 |
squanchy-dev/squanchy-android | app/src/test/java/net/squanchy/favorites/ListItemFixtures.kt | 1 | 457 | package net.squanchy.favorites
import net.squanchy.favorites.view.FavoritesItem
import net.squanchy.schedule.domain.view.Event
import net.squanchy.schedule.domain.view.aDay
import net.squanchy.schedule.domain.view.anEvent
import org.threeten.bp.LocalDate
fun aFavoriteHeaderListItem(
date: LocalDate = aDay().date
) = FavoritesItem.Header(date = date)
fun aFavoriteItemListItem(
event: Event = anEvent()
) = FavoritesItem.Favorite(event = event)
| apache-2.0 |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/troika/TroikaTransitData.kt | 1 | 3214 | /*
* TroikaTransitData.kt
*
* Copyright 2015-2016 Michael Farrell <[email protected]>
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.troika
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.UnauthorizedClassicSector
import au.id.micolous.metrodroid.multi.*
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.ui.ListItem
/**
* Troika cards.
*/
@Parcelize
class TroikaTransitData(private val mBlocks: List<TroikaBlock>) : Parcelable {
val serialNumber: String?
get() = mBlocks[0].serialNumber
val info: List<ListItem>?
get() = mBlocks.flatMap { it.info.orEmpty() }.ifEmpty { null }
val balance: TransitBalance
get() = mBlocks[0].balance ?: TransitCurrency.RUB(0)
val warning: String?
get() = if (mBlocks[0].balance == null && subscriptions.isEmpty())
Localizer.localizeString(R.string.troika_unformatted)
else
null
val trips: List<Trip>
get() = mBlocks.flatMap { it.trips.orEmpty() }
val subscriptions: List<Subscription>
get() = mBlocks.mapNotNull { it.subscription }
constructor(card: ClassicCard) : this(listOfNotNull(
decodeSector(card, 8),
decodeSector(card, 7),
decodeSector(card, 4),
decodeSector(card, 1)
)
)
companion object {
internal val CARD_INFO = CardInfo(
imageId = R.drawable.troika_card,
imageAlphaId = R.drawable.iso7810_id1_alpha,
name = R.string.card_name_troika,
locationId = R.string.location_moscow,
cardType = CardType.MifareClassic,
resourceExtraNote = R.string.card_note_russia,
region = TransitRegion.RUSSIA,
keysRequired = true, preview = true, keyBundle = "troika")
private const val TAG = "TroikaTransitData"
private fun decodeSector(card: ClassicCard, idx: Int): TroikaBlock? {
try {
val sector = card.getSector(idx)
if (sector is UnauthorizedClassicSector)
return null
val block = sector.readBlocks(0, 3)
return if (!TroikaBlock.check(block)) null else TroikaBlock.parseBlock(block)
} catch (e: Exception) {
Log.w(TAG, "Error decoding troika sector", e)
return null
}
}
}
}
| gpl-3.0 |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/search/algolia/MoshiResponseParser.kt | 1 | 414 | package net.squanchy.search.algolia
import com.squareup.moshi.JsonAdapter
interface ResponseParser<out T> {
fun parse(json: String): T?
}
class MoshiResponseParser<out AlgoliaSearchResponse>(
private val adapter: JsonAdapter<AlgoliaSearchResponse>
) : ResponseParser<AlgoliaSearchResponse> {
override fun parse(json: String): AlgoliaSearchResponse? {
return adapter.fromJson(json)
}
}
| apache-2.0 |
team401/SnakeSkin | SnakeSkin-CTRE/src/main/kotlin/org/snakeskin/component/impl/HardwareTalonSrxDevice.kt | 1 | 4163 | package org.snakeskin.component.impl
import com.ctre.phoenix.motorcontrol.ControlMode
import com.ctre.phoenix.motorcontrol.DemandType
import com.ctre.phoenix.motorcontrol.can.TalonSRX
import org.snakeskin.component.CTREFeedforwardScalingMode
import org.snakeskin.component.ITalonSrxDevice
import org.snakeskin.component.provider.IFollowableProvider
import org.snakeskin.measure.distance.angular.AngularDistanceMeasureRadians
import org.snakeskin.measure.velocity.angular.AngularVelocityMeasureRadiansPerSecond
import org.snakeskin.runtime.SnakeskinRuntime
class HardwareTalonSrxDevice(val device: TalonSRX, sensorTicksPerRevolution: Double = 4096.0, val ffMode: CTREFeedforwardScalingMode = CTREFeedforwardScalingMode.ScaleVbusSystem) : ITalonSrxDevice {
private val sensorTicksPerRadian = sensorTicksPerRevolution / (2.0 * Math.PI)
private fun scaleFfVolts(voltage: Double): Double {
return when (ffMode) {
CTREFeedforwardScalingMode.Scale12V -> voltage / 12.0
CTREFeedforwardScalingMode.ScaleVbusSystem -> {
val vbus = SnakeskinRuntime.voltage
return voltage / vbus
}
CTREFeedforwardScalingMode.ScaleVbusDevice -> {
val vbus = device.busVoltage
voltage / vbus
}
}
}
override fun follow(master: IFollowableProvider) {
when (master) {
is HardwareTalonSrxDevice -> device.follow(master.device)
is HardwareVictorSpxDevice -> device.follow(master.device)
}
}
override fun unfollow() {
//CTRE devices unfollow when a 0.0 percent output command is sent
device.set(ControlMode.PercentOutput, 0.0)
}
override fun setPercentOutput(percentOut: Double) {
device.set(ControlMode.PercentOutput, percentOut)
}
override fun getPercentOutput(): Double {
return device.motorOutputPercent
}
override fun getOutputVoltage(): Double {
return device.motorOutputVoltage
}
override fun getInputVoltage(): Double {
return device.busVoltage
}
override fun stop() {
setPercentOutput(0.0)
}
override fun getAngularPosition(): AngularDistanceMeasureRadians {
val ticks = device.selectedSensorPosition.toDouble()
return AngularDistanceMeasureRadians(ticks / sensorTicksPerRadian)
}
override fun setAngularPosition(angle: AngularDistanceMeasureRadians) {
val ticks = (angle.value * sensorTicksPerRadian).toInt()
device.selectedSensorPosition = ticks
}
override fun getAngularVelocity(): AngularVelocityMeasureRadiansPerSecond {
val ticks = device.selectedSensorVelocity.toDouble()
return AngularVelocityMeasureRadiansPerSecond((ticks / sensorTicksPerRadian) * 10.0) //Multiply by 10 to convert deciseconds (100 ms) to seconds
}
override fun getOutputCurrent(): Double {
return device.statorCurrent
}
override fun setAngularPositionSetpoint(setpoint: AngularDistanceMeasureRadians, ffVolts: Double) {
val ticks = setpoint.value * sensorTicksPerRadian
val ffPercent = scaleFfVolts(ffVolts)
device.set(ControlMode.Position, ticks, DemandType.ArbitraryFeedForward, ffPercent)
}
override fun setAngularVelocitySetpoint(setpoint: AngularVelocityMeasureRadiansPerSecond, ffVolts: Double) {
val ticksPer100Ms = (setpoint.value * sensorTicksPerRadian) / 10.0 //Divide by 10 to convert seconds to deciseconds (100 ms)
val ffPercent = scaleFfVolts(ffVolts)
device.set(ControlMode.Velocity, ticksPer100Ms, DemandType.ArbitraryFeedForward, ffPercent)
}
override fun setProfiledSetpoint(setpoint: AngularDistanceMeasureRadians, ffVolts: Double) {
val ticks = setpoint.value * sensorTicksPerRadian
val ffPercent = scaleFfVolts(ffVolts)
device.set(ControlMode.MotionMagic, ticks, DemandType.ArbitraryFeedForward, ffPercent)
}
override fun invert(invert: Boolean) {
device.inverted = invert
}
override fun invertInput(invert: Boolean) {
device.setSensorPhase(invert)
}
} | gpl-3.0 |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/commandframework/CommandExecutor.kt | 1 | 6637 | package me.aberrantfox.hotbot.commandframework
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.launch
import me.aberrantfox.hotbot.commandframework.commands.utility.macros
import me.aberrantfox.hotbot.commandframework.parsing.*
import me.aberrantfox.hotbot.dsls.command.Command
import me.aberrantfox.hotbot.dsls.command.CommandEvent
import me.aberrantfox.hotbot.dsls.command.CommandsContainer
import me.aberrantfox.hotbot.extensions.jda.*
import me.aberrantfox.hotbot.logging.BotLogger
import me.aberrantfox.hotbot.permissions.PermissionManager
import me.aberrantfox.hotbot.services.CommandRecommender
import me.aberrantfox.hotbot.services.Configuration
import me.aberrantfox.hotbot.services.MService
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.entities.Message
import net.dv8tion.jda.core.entities.MessageChannel
import net.dv8tion.jda.core.entities.User
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.core.events.message.priv.PrivateMessageReceivedEvent
import net.dv8tion.jda.core.hooks.ListenerAdapter
import me.aberrantfox.hotbot.commandframework.parsing.ConversionResult.*
class CommandExecutor(val config: Configuration,
val container: CommandsContainer,
val jda: JDA,
val log: BotLogger,
val manager: PermissionManager,
val mService: MService) : ListenerAdapter() {
override fun onGuildMessageReceived(e: GuildMessageReceivedEvent) {
handleInvocation(e.channel, e.message, e.author, true)
}
override fun onPrivateMessageReceived(e: PrivateMessageReceivedEvent) {
handleInvocation(e.channel, e.message, e.author, false)
}
private fun handleInvocation(channel: MessageChannel, message: Message, author: User, invokedInGuild: Boolean) =
launch(CommonPool) {
if (!(isUsableCommand(message, channel.id, author))) return@launch
val (commandName, actualArgs) = cleanCommandMessage(message.contentRaw, config)
if (!(canPerformCommand(channel, message, author))) return@launch
val command = container[commandName]
val macro = macros.firstOrNull { it.name == commandName }
when {
command != null -> {
invokeCommand(command, commandName, actualArgs, message, author, invokedInGuild)
log.cmd("${author.descriptor()} -- invoked $commandName in ${channel.name}")
}
macro != null -> {
channel.sendMessage(macro.message).queue()
log.cmd("${author.descriptor()} -- invoked $commandName in ${channel.name}")
}
else -> {
val recommended = CommandRecommender.recommendCommand(commandName)
channel.sendMessage("I don't know what ${commandName.replace("@", "")} is, perhaps you meant $recommended?").queue()
}
}
if (invokedInGuild) handleDelete(message, config.serverInformation.prefix)
}
private fun invokeCommand(command: Command, name: String, actual: List<String>, message: Message, author: User, invokedInGuild: Boolean) {
val channel = message.channel
if( !(manager.canUseCommand(author, name)) ) {
channel.sendMessage("Did you really think I would let you do that? :thinking:").queue()
return
}
getArgCountError(actual, command)?.let {
channel.sendMessage(it).queue()
return
}
val event = CommandEvent(config, jda, channel, author, message, jda.getGuildById(config.serverInformation.guildid), manager, container, mService, actual)
val conversionResult = convertArguments(actual, command.expectedArgs.toList(), event)
when(conversionResult) {
is Results -> event.args = conversionResult.results.requireNoNulls()
is Error -> {
event.safeRespond(conversionResult.error)
return
}
}
executeCommand(command, event, invokedInGuild)
}
private fun executeCommand(command: Command, event: CommandEvent, invokedInGuild: Boolean) {
if(isDoubleInvocation(event.message, event.config.serverInformation.prefix)) {
event.message.addReaction("\uD83D\uDC40").queue()
}
if (command.parameterCount == 0) {
command.execute(event)
return
}
if (command.requiresGuild && !invokedInGuild) {
event.respond("This command must be invoked in a guild channel, and not through PM")
} else {
command.execute(event)
}
}
private fun isUsableCommand(message: Message, channel: String, author: User): Boolean {
if (message.contentRaw.length > 1500) return false
if (config.security.lockDownMode && author.id != config.serverInformation.ownerID) return false
if (!(message.isCommandInvocation(config))) return false
if (config.security.ignoredIDs.contains(channel) || config.security.ignoredIDs.contains(author.id)) return false
if (author.isBot) return false
return true
}
private fun canPerformCommand(channel: MessageChannel, message: Message, user: User): Boolean {
if (!manager.canPerformAction(user, config.permissionedActions.commandMention) && message.mentionsSomeone()) {
channel.sendMessage("Your permission level is below the required level to use a command mention.").queue()
return false
}
if (!manager.canPerformAction(user, config.permissionedActions.sendInvite) && message.containsInvite()) {
channel.sendMessage("Ayyy lmao. Nice try, try that again. I dare you. :rllynow:").queue()
return false
}
if (!manager.canPerformAction(user, config.permissionedActions.sendURL) && message.containsURL()) {
channel.sendMessage("Your permission level is below the required level to use a URL in a command.").queue()
return false
}
return true
}
private fun handleDelete(message: Message, prefix: String) =
if (!isDoubleInvocation(message, prefix)) {
message.deleteIfExists()
} else Unit
private fun isDoubleInvocation(message: Message, prefix: String) = message.contentRaw.startsWith(prefix + prefix)
}
| mit |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/JKExternalConversion.kt | 1 | 4026 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.externalCodeProcessing
import com.intellij.psi.*
import org.jetbrains.kotlin.j2k.AccessorKind
import org.jetbrains.kotlin.j2k.usageProcessing.AccessorToPropertyProcessing
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.utils.addToStdlib.cast
internal sealed class JKExternalConversion : Comparable<JKExternalConversion> {
abstract val usage: PsiElement
abstract fun apply()
private val depth by lazy(LazyThreadSafetyMode.NONE) { usage.parentsWithSelf.takeWhile { it !is PsiFile }.count() }
private val offset by lazy(LazyThreadSafetyMode.NONE) { usage.textRange.startOffset }
override fun compareTo(other: JKExternalConversion): Int {
val depth1 = depth
val depth2 = other.depth
if (depth1 != depth2) { // put deeper elements first to not invalidate them when processing ancestors
return -depth1.compareTo(depth2)
}
// process elements with the same deepness from right to left
// so that right-side of assignments is not invalidated by processing of the left one
return -offset.compareTo(other.offset)
}
}
internal class AccessorToPropertyKotlinExternalConversion(
private val name: String,
private val accessorKind: AccessorKind,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
AccessorToPropertyProcessing.processUsage(usage, name, accessorKind)
}
}
internal class AccessorToPropertyJavaExternalConversion(
private val name: String,
private val accessorKind: AccessorKind,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is PsiReferenceExpression) return
val methodCall = usage.parent as? PsiMethodCallExpression ?: return
val factory = PsiElementFactory.getInstance(usage.project)
val propertyAccess = factory.createReferenceExpression(usage.qualifierExpression)
val newExpression = when (accessorKind) {
AccessorKind.GETTER -> propertyAccess
AccessorKind.SETTER -> {
val value = methodCall.argumentList.expressions.singleOrNull() ?: return
factory.createAssignment(propertyAccess, value)
}
}
methodCall.replace(newExpression)
}
private fun PsiElementFactory.createReferenceExpression(qualifier: PsiExpression?): PsiReferenceExpression =
createExpressionFromText(qualifier?.let { "qualifier." }.orEmpty() + name, usage).cast<PsiReferenceExpression>().apply {
qualifierExpression?.replace(qualifier ?: return@apply)
}
private fun PsiElementFactory.createAssignment(target: PsiExpression, value: PsiExpression): PsiAssignmentExpression =
createExpressionFromText("x = 1", usage).cast<PsiAssignmentExpression>().apply {
lExpression.replace(target)
rExpression!!.replace(value)
}
}
internal class PropertyRenamedKotlinExternalUsageConversion(
private val newName: String,
override val usage: KtElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is KtSimpleNameExpression) return
val factory = KtPsiFactory(usage)
usage.getReferencedNameElement().replace(factory.createExpression(newName))
}
}
internal class PropertyRenamedJavaExternalUsageConversion(
private val newName: String,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is PsiReferenceExpression) return
val factory = PsiElementFactory.getInstance(usage.project)
usage.referenceNameElement?.replace(factory.createExpressionFromText(newName, usage))
}
}
| apache-2.0 |
SpineEventEngine/base | base/src/main/kotlin/io/spine/protobuf/UtilExtensions.kt | 1 | 2470 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@file:JvmName("UtilExtensions")
package io.spine.protobuf
import com.google.protobuf.FieldMask
import com.google.protobuf.Message
import com.google.protobuf.util.FieldMaskUtil.fromFieldNumbers
import com.google.protobuf.util.FieldMaskUtil.isValid
/**
* Constructs a [FieldMask] from the passed field numbers.
*
* @throws IllegalArgumentException
* if any of the fields are invalid for the message.
*/
public inline fun <reified T : Message> fromFieldNumbers(vararg fieldNumbers: Int): FieldMask =
fromFieldNumbers<T>(fieldNumbers.toList())
/**
* Constructs a [FieldMask] from the passed field numbers.
*
* @throws IllegalArgumentException
* if any of the fields are invalid for the message.
*/
public inline fun <reified T : Message> fromFieldNumbers(fieldNumbers: Iterable<Int>): FieldMask =
fromFieldNumbers(T::class.java, fieldNumbers)
/**
* Checks whether paths in a given fields mask are valid.
*/
public inline fun <reified T : Message> isValid(fieldMask: FieldMask): Boolean =
isValid(T::class.java, fieldMask)
/**
* Checks whether a given field path is valid.
*/
public inline fun <reified T : Message> isValid(path: String): Boolean =
isValid(T::class.java, path)
| apache-2.0 |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/plugins/debian/InitDBuilder.kt | 1 | 709 | package org.roylance.yaclib.core.plugins.debian
import org.roylance.common.service.IBuilder
import java.io.File
class InitDBuilder(projectName: String, port: Int,
private val fileLocation: String) : IBuilder<Boolean> {
private val InitialTemplate = """#!/usr/bin/env bash
# /etc/init.d/$projectName
touch /var/lock/$projectName
case "$1" in
start)
pushd /opt/$projectName
bash proc.sh > web.out 2>&1&
;;
stop)
kill -9 $(lsof -i:$port -t)
;;
*)
echo "Usage: /etc/init.d/$projectName {start|stop}"
exit 1
;;
esac
exit 0
"""
override fun build(): Boolean {
File(fileLocation).delete()
File(fileLocation).writeText(InitialTemplate)
return true
}
} | mit |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/clock/ClockContract.kt | 1 | 328 | package lt.markmerkk.widgets.clock
interface ClockContract {
interface View {
fun showActive(timeAsString: String)
fun showInactive()
}
interface Presenter {
fun onAttach(view: View)
fun onDetach()
fun toggleClock()
fun cancelClock()
fun renderClock()
}
} | apache-2.0 |
ktorio/ktor | ktor-utils/common/test/io/ktor/util/PipelineContractsTest.kt | 1 | 8728 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util
import io.ktor.util.collections.*
import io.ktor.util.pipeline.*
import io.ktor.utils.io.concurrent.*
import kotlinx.atomicfu.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.test.*
@Suppress("KDocMissingDocumentation", "DEPRECATION")
class PipelineContractsTest {
private val checkList = mutableListOf<String>()
private var v = 0
private val caught = atomic(false)
private val phase1 = PipelinePhase("A")
private val phase2 = PipelinePhase("B")
private val interceptor1: PipelineInterceptor<Unit, Unit> = { v = 1; checkList.add("1") }
private val interceptor2: PipelineInterceptor<Unit, Unit> = { v = 2; checkList.add("2") }
@Test
fun testMergeEmpty() {
val first = Pipeline<Unit, Unit>(phase1)
val second = Pipeline<Unit, Unit>(phase1)
second.merge(first)
assertTrue { first.isEmpty }
assertTrue { second.isEmpty }
assertSame(first.interceptorsForTests(), second.interceptorsForTests())
}
@Test
fun testMergeSingle() {
val first = Pipeline<Unit, Unit>(phase1)
val second = Pipeline<Unit, Unit>(phase1)
first.intercept(phase1) {}
second.merge(first)
assertSame(first.interceptorsForTests(), second.interceptorsForTests())
assertSame(first.interceptorsForTests(), first.phaseInterceptors(phase1))
}
@Test
fun testModifyAfterMerge() {
val first = Pipeline<Unit, Unit>(phase1)
val second = Pipeline<Unit, Unit>(phase1)
first.intercept(phase1, interceptor1)
second.merge(first)
first.intercept(phase1, interceptor2)
assertNotSame(first.interceptorsForTests(), second.interceptorsForTests())
second.execute()
assertEquals(listOf("1", "completed"), checkList)
}
@Test
fun testLastPhase() {
val first = Pipeline<Unit, Unit>(phase1, phase2)
first.intercept(phase1, interceptor1)
first.intercept(phase2, interceptor2)
val before = first.interceptorsForTests()
first.intercept(phase2, interceptor2)
// adding an interceptor to the last phase shouldn't reallocate unshared list
val after = first.interceptorsForTests()
assertSame(before, after)
// intercepting earlier phase should
first.intercept(phase1, interceptor1)
assertNotSame(before, first.interceptorsForTests())
val second = Pipeline<Unit, Unit>(phase1, phase2)
second.merge(first)
}
@Test
fun testLastPhaseThenMerge() {
val first = Pipeline<Unit, Unit>(phase1, phase2)
first.intercept(phase1, interceptor1)
first.intercept(phase2, interceptor2)
val before = first.interceptorsForTests()
first.intercept(phase2, interceptor2)
// adding an interceptor to the last phase shouldn't reallocate unshared list
val after = first.interceptorsForTests()
assertSame(before, after)
val second = Pipeline<Unit, Unit>(phase1, phase2)
second.merge(first)
// it should be shared during merge
assertSame(before, second.interceptorsForTests())
// intercepting first should reallocate
first.intercept(phase2, interceptor2)
assertNotSame(first.interceptorsForTests(), second.interceptorsForTests())
}
@Test
fun executeEmptyPipelineSmokeTest() {
val pipeline = Pipeline<Unit, Unit>(phase1)
pipeline.execute()
assertEquals(listOf("completed"), checkList)
}
@Test
fun testExecutePipelineSingleSmokeTest() {
val pipeline = Pipeline<Unit, Unit>(phase1)
pipeline.intercept(phase1, interceptor1)
pipeline.execute()
assertEquals(listOf("1", "completed"), checkList)
}
@Test
fun testExecutePipelineSimpleSmokeTest() {
val pipeline = Pipeline<Unit, Unit>(phase1)
pipeline.intercept(phase1, interceptor1)
pipeline.intercept(phase1, interceptor2)
pipeline.execute()
assertEquals(listOf("1", "2", "completed"), checkList)
}
@Test
fun executePipelineSmokeTest() {
val pipeline = Pipeline<Unit, Unit>(phase1)
pipeline.intercept(phase1) {
checkList.add("1")
}
pipeline.intercept(phase1) {
try {
checkList.add("2")
proceed()
} finally {
checkList.add("3")
}
}
pipeline.intercept(phase1) {
checkList.add("4")
}
pipeline.execute()
assertEquals(listOf("1", "2", "4", "3", "completed"), checkList)
}
@Test
fun executePipelineWithSuspension() {
val pipeline = Pipeline<Unit, Unit>(phase1)
var continuation: Continuation<Unit>? = null
pipeline.intercept(phase1) {
checkList.add("1")
}
pipeline.intercept(phase1) {
try {
checkList.add("2")
proceed()
} finally {
checkList.add("3")
}
}
pipeline.intercept(phase1) {
checkList.add("4")
suspendCoroutine<Unit> {
continuation = it
}
checkList.add("5")
}
pipeline.execute()
assertEquals(listOf("1", "2", "4"), checkList)
continuation!!.resume(Unit)
assertEquals(listOf("1", "2", "4", "5", "3", "completed"), checkList)
}
@Test
fun executePipelineWithSuspensionAndImmediateResume() {
val pipeline = Pipeline<Unit, Unit>(phase1)
pipeline.intercept(phase1) {
checkList.add("1")
}
pipeline.intercept(phase1) {
try {
checkList.add("2")
proceed()
} finally {
checkList.add("3")
}
}
pipeline.intercept(phase1) {
checkList.add("4")
suspendCoroutineUninterceptedOrReturn<Unit> {
it.resume(Unit)
COROUTINE_SUSPENDED
}
checkList.add("5")
}
pipeline.execute()
assertEquals(listOf("1", "2", "4", "5", "3", "completed"), checkList)
}
@Test
fun executePipelineWithSuspensionAndNestedProceed() {
val pipeline = Pipeline<Unit, Unit>(phase1)
var continuation: Continuation<Unit>? = null
pipeline.intercept(phase1) {
checkList.add("1")
}
pipeline.intercept(phase1) {
checkList.add("2")
suspendCoroutineUninterceptedOrReturn<Unit> {
continuation = it
COROUTINE_SUSPENDED
}
checkList.add("3")
}
pipeline.intercept(phase1) {
try {
checkList.add("4")
proceed()
} finally {
checkList.add("5")
}
}
pipeline.intercept(phase1) {
checkList.add("6")
}
pipeline.execute()
assertEquals(listOf("1", "2"), checkList)
continuation!!.resume(Unit)
assertEquals(listOf("1", "2", "3", "4", "6", "5", "completed"), checkList)
}
@Test
fun testExecutePipelineTwiceTest() {
val pipeline = Pipeline<Unit, Unit>(phase1)
pipeline.intercept(phase1, interceptor1)
pipeline.execute()
pipeline.execute()
assertEquals(listOf("1", "completed", "1", "completed"), checkList)
}
@Test
fun testExecutePipelineFailureTest() {
val pipeline = Pipeline<Unit, Unit>(phase1)
pipeline.intercept(phase1) {
throw IllegalStateException()
}
pipeline.execute()
}
@Test
fun testExecutePipelineCaughtFailureTest() {
val pipeline = Pipeline<Unit, Unit>(phase1)
class MyException : Exception()
pipeline.intercept(phase1) {
try {
proceed()
} catch (expected: MyException) {
caught.value = true
}
}
pipeline.intercept(phase1) {
throw MyException()
}
pipeline.execute()
assertTrue { caught.value }
}
private fun Pipeline<Unit, Unit>.execute() {
val body = suspend {
execute(Unit, Unit)
}
val completion: Continuation<Unit> = Continuation(EmptyCoroutineContext) {
checkList.add("completed")
}
body.startCoroutine(completion)
}
}
| apache-2.0 |
Fantast/project-euler | src/main/euler/solved/Task_539.kt | 1 | 4400 | package solved
import tasks.AbstractTask
import tasks.Tester
import utils.MyMath
import utils.log.Logger
import java.math.BigInteger
//Answer : 426334056
class Task_539 : AbstractTask() {
override fun solving() {
println(S(1000000000000000000))
println(S(1000000000000000000) % bi(987654321))
}
fun P(n: Long): Long {
if (n == 1L) {
return 1L;
}
return 2*(f(n/2) + e(n/2))
}
fun S(n: Long): BigInteger {
return fs(n) + es(n);
}
fun e(n: Long): Long {
if (n == 1L) {
return 1L;
}
val s2: Long;
val bits = 64 - java.lang.Long.numberOfLeadingZeros(n)
if (bits % 2 == 0) {
val ss = (1L shl bits) - 1L;
s2 = -(ss and 0b0101010101010101010101010101010101010101010101010101010101010101L);
} else {
val ss = (1L shl bits) - 1L;
s2 = (ss and 0b010101010101010101010101010101010101010101010101010101010101010L) + 1L;
}
return s2;
}
fun f(n: Long): Long {
if (n == 1L) {
return 0L;
}
val bits = 64 - java.lang.Long.numberOfLeadingZeros(n)
val s1 = n and 0b0101010101010101010101010101010101010101010101010101010101010101L;
val last = 1L shl (bits - 1);
return s1 + (if (bits % 2 == 0) last else -last);
}
fun fs(nn: Long): BigInteger {
assert(nn % 2L == 0L); //for convinience
val n = nn / 2L;
var s = bi(0);
for (bit in 0..61) {
val ds = (1L shl bit)
var cnt = 0L;
if (bit % 2 != 0) {
val maxn = (1L shl (bit + 1)) - 1;
val minn = (1L shl bit);
if (minn > n) {
cnt = 0;
} else {
cnt = Math.min(n, maxn) - minn + 1;
}
} else {
for (bits in (bit+1)..63) {
if (bits % 2 == 0 || (bits >= bit + 3)) {
val maxn = (1L shl bits) - 1;
val minn = (1L shl (bits - 1)) + (1L shl bit);
if (minn > n) {
// cnt += 0;
} else if (maxn <= n) {
cnt += 1L shl (bits - 2);
} else {
val leftParts = (n - (1L shl (bits - 1))) shr (bit + 1);
val hasBit = MyMath.isBitSet(n, bit);
val rightParts = n % (1L shl bit)
if (hasBit) {
//numbers that has the same prefix as n
cnt += rightParts + 1
}
if (leftParts != 0L) {
//fit numbers below n
cnt += leftParts * (1L shl bit);
}
}
}
}
}
s += bi(cnt) * bi(ds);
}
s = s * bi(4L) - bi(2*f(n))
return s;
}
fun es(nn: Long): BigInteger {
assert(nn % 2L == 0L); //for convinience
val n = nn / 2L;
var s = bi(1); // for 1 bit
for (bits in 2..61) {
val pmax = (1L shl bits) - 1L
val pmin = (1L shl (bits - 1))
if (pmin > n) {
break;
}
val cnt = Math.min(pmax, n) - pmin + 1L;
val s2: Long;
if (bits % 2 == 0) {
val ss = (1L shl bits) - 1L;
s2 = -(ss and 0b0101010101010101010101010101010101010101010101010101010101010101L);
} else {
val ss = (1L shl bits) - 1L;
s2 = (ss and 0b010101010101010101010101010101010101010101010101010101010101010L) + 1L;
}
s += bi(cnt) * bi(s2);
}
s = s * bi(4L) - bi(2*e(n)) + bi(1)
return s;
}
fun P0(n: Long): Long {
if (n == 1L) {
return 1L;
}
val nn = n / 2;
return 2 * (nn + 1 - P(nn));
}
companion object {
@JvmStatic fun main(args: Array<String>) {
Logger.init("default.log")
Tester.test(Task_539())
Logger.close()
}
}
} | mit |
google/android-fhir | datacapture/src/test/java/com/google/android/fhir/datacapture/MoreExpressionsTest.kt | 1 | 1748 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture
import android.os.Build
import com.google.common.truth.Truth.assertThat
import org.hl7.fhir.r4.model.Expression
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.P])
class MoreExpressionsTest {
@Test
fun `isXFhirQuery should return true`() {
val expression = Expression().apply { this.language = "application/x-fhir-query" }
assertThat(expression.isXFhirQuery).isTrue()
}
@Test
fun `isXFhirQuery should return false`() {
val expression = Expression().apply { this.language = "text/cql" }
assertThat(expression.isXFhirQuery).isFalse()
}
@Test
fun `isFhirPath should return true`() {
val expression = Expression().apply { this.language = "text/fhirpath" }
assertThat(expression.isFhirPath).isTrue()
}
@Test
fun `isFhirPath should return false`() {
val expression = Expression().apply { this.language = "application/x-fhir-query" }
assertThat(expression.isFhirPath).isFalse()
}
}
| apache-2.0 |
code-disaster/lwjgl3 | modules/lwjgl/egl/src/templates/kotlin/egl/templates/KHR_stream_producer_eglsurface.kt | 4 | 925 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package egl.templates
import egl.*
import org.lwjgl.generator.*
val KHR_stream_producer_eglsurface = "KHRStreamProducerEGLSurface".nativeClassEGL("KHR_stream_producer_eglsurface", postfix = KHR) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows an EGLSurface to be created as a producer of images to an EGLStream. Each call to eglSwapBuffers posts a new image frame into the
EGLStream.
Requires ${EGL12.core}.
"""
IntConstant(
"",
"STREAM_BIT_KHR"..0x0800
)
EGLSurface(
"CreateStreamProducerSurfaceKHR",
"",
EGLDisplay("dpy", ""),
EGLConfig("config", ""),
EGLStreamKHR("stream", ""),
nullable..noneTerminated..EGLint.const.p("attrib_list", "")
)
} | bsd-3-clause |
fabioCollini/ArchitectureComponentsDemo | viewlib/src/main/java/it/codingjam/github/util/ViewModelUtils.kt | 1 | 1126 | package it.codingjam.github.util
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
inline fun <reified VM : ViewModel> Fragment.viewModel(crossinline provider: () -> VM): Lazy<VM> {
return lazy {
val factory = object : ViewModelProvider.Factory {
override fun <T1 : ViewModel> create(aClass: Class<T1>): T1 {
val viewModel = provider.invoke()
return viewModel as T1
}
}
ViewModelProviders.of(this, factory).get(VM::class.java)
}
}
inline fun <reified VM : ViewModel> FragmentActivity.viewModel(crossinline provider: () -> VM): Lazy<VM> {
return lazy {
val factory = object : ViewModelProvider.Factory {
override fun <T1 : ViewModel> create(aClass: Class<T1>): T1 {
val viewModel = provider.invoke()
return viewModel as T1
}
}
ViewModelProviders.of(this, factory).get(VM::class.java)
}
}
| apache-2.0 |
C6H2Cl2/YukariLib | src/main/java/c6h2cl2/YukariLib/Client/TestResourcePack.kt | 1 | 1294 | package c6h2cl2.YukariLib.Client
import net.minecraft.client.resources.IResourcePack
import net.minecraft.client.resources.data.IMetadataSection
import net.minecraft.client.resources.data.MetadataSerializer
import net.minecraft.util.ResourceLocation
import java.awt.image.BufferedImage
import java.io.InputStream
/**
* @author C6H2Cl2
*/
class TestResourcePack: IResourcePack {
override fun resourceExists(location: ResourceLocation?): Boolean {
println("\n\n\n\n\n\n")
println(location?.toString())
return false
}
override fun getPackImage(): BufferedImage? {
println("\n\n\n\n\n\n")
return null
}
override fun <T : IMetadataSection?> getPackMetadata(metadataSerializer: MetadataSerializer?, metadataSectionName: String?): T? {
println("\n\n\n\n\n\n")
return null
}
override fun getInputStream(location: ResourceLocation?): InputStream {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getPackName(): String {
println("\n\n\n\n\n\n")
return "TestPack"
}
override fun getResourceDomains(): MutableSet<String> {
println("\n\n\n\n\n\n")
return setOf("test").toMutableSet()
}
} | mpl-2.0 |
StPatrck/edac | app/src/main/java/com/phapps/elitedangerous/companion/data/repos/ProfileRepository.kt | 1 | 12282 | package com.phapps.elitedangerous.companion.data.repos
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.phapps.elitedangerous.companion.EdacApp
import com.phapps.elitedangerous.companion.EdacExecutors
import com.phapps.elitedangerous.companion.api.ApiResponse
import com.phapps.elitedangerous.companion.api.edc.EdcService
import com.phapps.elitedangerous.companion.api.edc.dtos.EdcProfileDto
import com.phapps.elitedangerous.companion.data.doa.CommanderDao
import com.phapps.elitedangerous.companion.data.doa.ShipDao
import com.phapps.elitedangerous.companion.data.doa.StarSystemDao
import com.phapps.elitedangerous.companion.data.entities.*
import com.phapps.elitedangerous.companion.domain.Resource
import com.phapps.elitedangerous.companion.ext.withRanks
import com.phapps.elitedangerous.companion.ext.withRanksAndProgress
import com.phapps.elitedangerous.companion.util.SharedPrefsHelper
import com.phapps.elitedangerous.edsm.EdsmClient
import com.phapps.elitedangerous.edsm.callbacks.GetCommanderRanksCallbacks
import com.phapps.elitedangerous.edsm.dto.CommanderDto
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
import timber.log.Timber
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProfileRepository @Inject constructor(private var executors: EdacExecutors,
private var commanderDao: CommanderDao, private var shipDao: ShipDao,
private var systemDao: StarSystemDao, private var prefs: SharedPrefsHelper) :
IProfileRepository {
override fun getProfile(name: String,
forceRefresh: Boolean): LiveData<Resource<CommanderProfile>> {
return object : WebBoundResource<CommanderProfile, EdcProfileDto>(executors) {
override fun loadFromDb(): LiveData<CommanderProfile> {
return commanderDao.getCommanderByName(name)
}
override fun shouldFetch(data: CommanderProfile?): Boolean {
if (data == null) return true
val now = Date().time
return forceRefresh || now >= calculateStaleDate(data.lastUpdatedTimestamp)
}
override fun createCall(): LiveData<ApiResponse<EdcProfileDto>> {
val liveData = MutableLiveData<ApiResponse<EdcProfileDto>>()
launch {
liveData.postValue(EdcService(EdacApp.instance).getProfile())
}
return liveData
}
override fun saveCallResult(response: EdcProfileDto) {
val newProfile = CommanderProfile().also { it ->
with(response) {
it.id = commander.id
it.name = name
it.credits = commander.credits
it.debt = commander.debt
it.alive = commander.alive
it.currentShipId = commander.currentShipId
it.lastUpdatedTimestamp = Date().time
it.ranks = runBlocking { createRanks(it) }
}
}
val ships = mutableListOf<Ship>()
val stations = mutableListOf<Station>()
val systems = mutableListOf<StarSystem>()
val moduleSlots = mutableListOf<ModuleSlot>()
// The current ship is the only ship populated with full details
ships.add(Ship().also { ship ->
with(response.ship) {
newProfile.currentShipName = this.name
ship.id = this.id
ship.name = this.name
ship.free = this.free
ship.stationId = this.station.id
ship.starSystemId = this.starsystem.id
ship.oxygenRemaining = this.oxygenRemaining
ship.cockpitBreached = this.cockpitBreached
ship.alive = this.alive
this.health?.let {
ship.hullHealth = it.hull
ship.shieldHealth = it.shield
ship.shieldUp = it.shieldup
ship.integrity = it.integrity
ship.paintwork = it.paintwork
}
ship.hullValue = this.value.hull
ship.modulesValue = this.value.hull
ship.cargoValue = this.value.cargo
ship.totalValue = this.value.total
ship.unloanedValue = this.value.unloaned
this.modules?.let { map ->
for (entry in map) {
moduleSlots.add(ModuleSlot().also { ms ->
ms.name = entry.key
})
}
}
}
})
// List of owned ships does not include all ship details.
if (response.ships.isNotEmpty()) {
for (dto in response.ships) {
if (dto.id != response.ship.id) {
ships.add(Ship().also { ship ->
with(dto) {
ship.id = this.id
ship.name = this.name
ship.free = this.free
ship.stationId = this.station.id
with(this.station) {
stations.add(Station().also { s ->
s.name = this.name
s.id = this.id
})
}
ship.starSystemId = this.starsystem.id
with(this.starsystem) {
systems.add(StarSystem().also { s ->
s.id = this.id
s.name = this.name
s.address = this.systemaddress.toString()
})
}
ship.alive = this.alive
}
})
}
}
}
val starport = Starport().also { s ->
with(response.lastStarport) {
s.id = this.id
s.name = this.name
s.faction = this.faction
s.minorFaction = this.minorfaction
s.services = StarportServices().also { services ->
with(this.services) {
services.dock = this.dock == "ok"
services.contacts = this.contacts == "ok"
services.cartographers = this.exploration == "ok"
services.refuel = this.refuel == "ok"
services.repair = this.repair == "ok"
services.outfitting = this.outfitting == "ok"
services.crewLounge = this.crewlounge == "ok"
services.powerPlay = this.powerplay == "ok"
services.searchAndRescue = this.searchrescue == "ok"
services.engineer = this.engineer == "ok"
}
}
}
}
commanderDao.insert(newProfile)
systemDao.insert(*stations.toTypedArray())
systemDao.insert(*systems.toTypedArray())
systemDao.insert(starport)
shipDao.insert(*ships.toTypedArray())
}
}.asLiveData()
}
private suspend fun createRanks(commanderProfile: CommanderProfile): Ranks {
var ranks = Ranks.withRanks(commanderProfile.ranks.combatRank,
commanderProfile.ranks.traderRank, commanderProfile.ranks.explorerRank,
commanderProfile.ranks.cqcRank, commanderProfile.ranks.federationRank,
commanderProfile.ranks.empireRank, commanderProfile.ranks.crime,
commanderProfile.ranks.power, commanderProfile.ranks.service)
async {
EdsmClient.getInstance().getCommanderRanks(commanderProfile.name, prefs.getEdsmApiKey(),
object : GetCommanderRanksCallbacks {
override fun onSuccess(commander: CommanderDto) {
Timber.d("commander = $commander")
var combatProgress = commanderProfile.ranks.combatProgress
var tradeProgress = commanderProfile.ranks.traderProgress
var exploreProgress = commanderProfile.ranks.explorerProgress
var cqcProgress = commanderProfile.ranks.cqcProgress
var empireProgress = commanderProfile.ranks.empireProgress
var federationProgress = commanderProfile.ranks.federationProgress
if (commander.ranks != null) {
if (commanderProfile.ranks.combatRank == commander.ranks.combat) {
combatProgress = commander.progress.combat
}
if (commanderProfile.ranks.traderRank == commander.ranks.trade) {
tradeProgress = commander.ranks.trade
}
if (commanderProfile.ranks.explorerRank == commander.ranks.explore) {
exploreProgress = commander.progress.explore
}
if (commanderProfile.ranks.cqcProgress == commander.ranks.cqc) {
cqcProgress = commander.progress.cqc
}
if (commanderProfile.ranks.empireRank == commander.ranks.empire) {
empireProgress = commander.progress.empire
}
if (commanderProfile.ranks.federationRank == commander.ranks.federation) {
federationProgress = commander.progress.federation
}
}
ranks = Ranks.withRanksAndProgress(
Pair(commanderProfile.ranks.combatRank, combatProgress),
Pair(commanderProfile.ranks.traderRank, tradeProgress),
Pair(commanderProfile.ranks.explorerRank, exploreProgress),
Pair(commanderProfile.ranks.cqcRank, cqcProgress),
Pair(commanderProfile.ranks.federationRank, federationProgress),
Pair(commanderProfile.ranks.empireRank, empireProgress),
commanderProfile.ranks.crime, commanderProfile.ranks.power,
commanderProfile.ranks.service)
}
override fun onFail(message: String) {
Timber.w("Error fetching rank details from EDSM: $message")
}
override fun onError() {
Timber.w("Unable to communicate with EDSM servers to fetch Ranks.")
}
})
}.await()
return ranks
}
}
| gpl-3.0 |
imknown/ImkGithub | ZMain/ImkGithubApp/src/main/java/net/imknown/imkgithub/global/BaseFragment.kt | 1 | 436 | package net.imknown.imkgithub.global
import androidx.fragment.app.Fragment
import com.umeng.analytics.MobclickAgent
import net.imknown.imkgithub.mvp.IMvpView
abstract class BaseFragment : Fragment(), IMvpView {
override fun onResume() {
super.onResume()
MobclickAgent.onPageStart(javaClass.name)
}
override fun onPause() {
super.onPause()
MobclickAgent.onPageEnd(javaClass.name)
}
} | apache-2.0 |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/CachingGithubUserAvatarLoader.kt | 2 | 3061 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.util
import com.google.common.cache.CacheBuilder
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.LowMemoryWatcher
import com.intellij.util.ImageLoader
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.data.GithubUser
import java.awt.Image
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.function.Supplier
class CachingGithubUserAvatarLoader(private val progressManager: ProgressManager) : Disposable {
private val LOG = logger<CachingGithubUserAvatarLoader>()
private val executor = AppExecutorUtil.getAppExecutorService()
private val progressIndicator: EmptyProgressIndicator = NonReusableEmptyProgressIndicator()
private val avatarCache = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build<GithubUser, CompletableFuture<Image?>>()
init {
LowMemoryWatcher.register(Runnable { avatarCache.invalidateAll() }, this)
}
fun requestAvatar(requestExecutor: GithubApiRequestExecutor, user: GithubUser): CompletableFuture<Image?> {
val indicator = progressIndicator
// store images at maximum used size with maximum reasonable scale to avoid upscaling (3 for system scale, 2 for user scale)
val imageSize = MAXIMUM_ICON_SIZE * 6
return avatarCache.get(user) {
val url = user.avatarUrl
if (url == null) CompletableFuture.completedFuture(null)
else CompletableFuture.supplyAsync(Supplier {
try {
progressManager.runProcess(Computable { loadAndDownscale(requestExecutor, indicator, url, imageSize) }, indicator)
}
catch (e: ProcessCanceledException) {
null
}
}, executor)
}
}
private fun loadAndDownscale(requestExecutor: GithubApiRequestExecutor, indicator: EmptyProgressIndicator,
url: String, maximumSize: Int): Image? {
try {
val image = requestExecutor.execute(indicator, GithubApiRequests.CurrentUser.getAvatar(url))
return if (image.getWidth(null) <= maximumSize && image.getHeight(null) <= maximumSize) image
else ImageLoader.scaleImage(image, maximumSize)
}
catch (e: ProcessCanceledException) {
return null
}
catch (e: Exception) {
LOG.info("Error loading image from $url", e)
return null
}
}
override fun dispose() {
progressIndicator.cancel()
}
companion object {
private const val MAXIMUM_ICON_SIZE = 40
}
} | apache-2.0 |
mdanielwork/intellij-community | platform/credential-store/src/NativeCredentialStoreWrapper.kt | 1 | 4634 | // 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.credentialStore
import com.google.common.cache.CacheBuilder
import com.intellij.credentialStore.keePass.InMemoryCredentialStore
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.concurrency.QueueProcessor
import com.intellij.util.containers.ContainerUtil
import java.util.concurrent.TimeUnit
internal val NOTIFICATION_MANAGER by lazy {
// we use name "Password Safe" instead of "Credentials Store" because it was named so previously (and no much sense to rename it)
SingletonNotificationManager(NotificationGroup("Password Safe", NotificationDisplayType.STICKY_BALLOON, true), NotificationType.ERROR)
}
// used only for native keychains, not for KeePass, so, postponedCredentials and other is not overhead if KeePass is used
private class NativeCredentialStoreWrapper(private val store: CredentialStore) : CredentialStore {
private val fallbackStore = lazy { InMemoryCredentialStore() }
private val queueProcessor = QueueProcessor<() -> Unit> { it() }
private val postponedCredentials = InMemoryCredentialStore()
private val postponedRemovedCredentials = ContainerUtil.newConcurrentSet<CredentialAttributes>()
private val deniedItems = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<CredentialAttributes, Boolean>()
override fun get(attributes: CredentialAttributes): Credentials? {
if (postponedRemovedCredentials.contains(attributes)) {
return null
}
postponedCredentials.get(attributes)?.let {
return it
}
if (deniedItems.getIfPresent(attributes) != null) {
LOG.warn("User denied access to $attributes")
return null
}
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
val value = store.get(attributes)
if (value === ACCESS_TO_KEY_CHAIN_DENIED) {
deniedItems.put(attributes, true)
}
return value
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
return store.get(attributes)
}
catch (e: Throwable) {
LOG.error(e)
return null
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
LOG.runAndLogException {
if (fallbackStore.isInitialized()) {
fallbackStore.value.set(attributes, credentials)
return
}
if (credentials == null) {
postponedRemovedCredentials.add(attributes)
}
else {
postponedCredentials.set(attributes, credentials)
}
queueProcessor.add {
try {
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
store.set(attributes, credentials)
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
store.set(attributes, credentials)
}
catch (e: Throwable) {
LOG.error(e)
}
}
finally {
if (!postponedRemovedCredentials.remove(attributes)) {
postponedCredentials.set(attributes, null)
}
}
}
}
}
}
private fun notifyUnsatisfiedLinkError(e: UnsatisfiedLinkError) {
LOG.error(e)
var message = "Credentials are remembered until ${ApplicationNamesInfo.getInstance().fullProductName} is closed."
if (SystemInfo.isLinux) {
message += "\nPlease install required package libsecret-1-0: sudo apt-get install libsecret-1-0 gnome-keyring"
}
NOTIFICATION_MANAGER.notify("Cannot Access Native Keychain", message)
}
private class MacOsCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? {
if (isMacOsCredentialStoreSupported) {
return NativeCredentialStoreWrapper(KeyChainCredentialStore())
}
return null
}
}
private class LinuxSecretCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? {
if (SystemInfo.isLinux) {
return NativeCredentialStoreWrapper(SecretCredentialStore("com.intellij.credentialStore.Credential"))
}
return null
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/completion/tests/testData/handlers/smart/LastParamIsFunction.kt | 13 | 92 | fun foo(p: Int, handler: () -> Unit){}
fun bar(p: Int) {
foo(<caret>)
}
// ELEMENT: p
| apache-2.0 |
dahlstrom-g/intellij-community | java/java-tests/testData/inspection/jvm/deadCode/primaryConstructor2/src/App.kt | 7 | 305 | data class ToolItem(
val type: String,
val order: Int
) {
constructor(tool: Tool) : this(tool.type, tool.order)
}
data class Tool(
val type: String,
val order: Int
)
fun main() {
listOf("1", "2", "3")
.map { Tool(it, 1) }
.map{ ToolItem(it) }
.forEach {
println(it)
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveTop/moveTopLevelClassToAnotherPackage/after/c/onDemandTargetPackageImport.kt | 13 | 55 | package c
import b.*
fun bar() {
val t: A = A()
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/intentions/addAnnotationUseSiteTarget/constructor/val/field.kt | 13 | 98 | // CHOOSE_USE_SITE_TARGET: field
annotation class A
class Constructor(@A<caret> val foo: String) | apache-2.0 |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/metric/BackendKeyFilter.kt | 1 | 3783 | /*
* Copyright (c) 2019 Spotify AB.
*
* 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 com.spotify.heroic.metric
import com.spotify.heroic.common.OptionalLimit
import java.util.*
data class BackendKeyFilter(
val start: Optional<Start> = Optional.empty(),
val end: Optional<End> = Optional.empty(),
val limit: OptionalLimit = OptionalLimit.empty()
) {
fun withStart(start: Start): BackendKeyFilter = BackendKeyFilter(Optional.of(start), end, limit)
fun withEnd(end: End): BackendKeyFilter = BackendKeyFilter(start, Optional.of(end), limit)
fun withLimit(limit: OptionalLimit): BackendKeyFilter = BackendKeyFilter(start, end, limit)
companion object {
/**
* Match keys strictly greater than the given key.
*
* @param key Key to match against.
* @return A {@link BackendKeyFilter} matching if a key is strictly greater than the given key.
*/
@JvmStatic fun gt(key: BackendKey): GT = GT(key)
}
interface Start
interface End
/**
* Match keys strictly greater than the given key.
*
* @param key Key to match against.
* @return A {@link BackendKeyFilter} matching if a key is strictly greater than the given key.
*/
data class GT(val key: BackendKey): Start
/**
* Match keys greater or equal to the given key.
*
* @param key The key to match against.
* @return A {@link BackendKeyFilter} matching if a key is greater or equal to the given key.
*/
data class GTE(val key: BackendKey): Start
/**
* Match keys larger or equal to the given percentage.
*
* @param percentage The percentage to match against, should be a value between {@code [0, 1]}.
* @return A {@link BackendKeyFilter} matching if a key is larger or equal to the given
* percentage.
*/
data class GTEPercentage(val percentage: Float): Start
/**
* Match keys larger or equal to the given token.
*
* @param token The token to match against.
* @return A {@link BackendKeyFilter} matching if a key is larger or equal to the given token.
*/
data class GTEToken(val token: Long): Start
/**
* Match keys strictly smaller than the given key.
*
* @param key Key to match against.
* @return A {@link BackendKeyFilter} matching if a key is strictly smaller than the given key.
*/
data class LT(val key: BackendKey): End
/**
* Match keys smaller than the given percentage.
*
* @param percentage The percentage to match against, should be a value between {@code [0, 1]}
* @return A {@link BackendKeyFilter} matching if a key is smaller than a given percentage.
*/
data class LTPercentage(val percentage: Float): End
/**
* Match keys smaller than the given token.
*
* @param token The token to match against.
* @return A {@link BackendKeyFilter} matching if a key is smaller than the given token.
*/
data class LTToken(val token: Long): End
} | apache-2.0 |
dahlstrom-g/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/dsl/builder/ButtonsGroupTest.kt | 4 | 1977 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder
import com.intellij.ui.dsl.UiDslException
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import kotlin.reflect.KMutableProperty0
class ButtonsGroupTest {
enum class Enum1 {
VALUE1,
VALUE2
}
/**
* Enum with overriding, so Enum2 class and Enum2.VALUE1 class are different
*/
enum class Enum2(val id: Int) {
VALUE1(1) {
override fun toString(): String {
return "$id"
}
},
VALUE2(2) {
override fun toString(): String {
return "$id"
}
}
}
var boolean = true
var int = 1
var string = "a"
var enum1 = Enum1.VALUE1
var enum2 = Enum2.VALUE1
@Test
fun testInvalidGroups() {
assertThrows<UiDslException> {
testButtonsGroup(1, 2)
}
assertThrows<UiDslException> {
testButtonsGroup("1", "2", ::int)
}
assertThrows<UiDslException> {
testButtonsGroup(null, null, ::int)
}
}
@Test
fun testValidGroups() {
testButtonsGroup(null, null)
testButtonsGroup(true, false, ::boolean)
testButtonsGroup(1, 2, ::int)
testButtonsGroup("b", "c", ::string)
testButtonsGroup(Enum1.VALUE1, Enum1.VALUE2, ::enum1)
testButtonsGroup(Enum2.VALUE1, Enum2.VALUE2, ::enum2)
}
private fun testButtonsGroup(value1: Any?, value2: Any?) {
panel {
buttonsGroup(value1, value2)
}
}
private inline fun <reified T : Any> testButtonsGroup(value1: Any?, value2: Any?, prop: KMutableProperty0<T>) {
panel {
buttonsGroup(value1, value2)
.bind(prop)
}
}
private fun Panel.buttonsGroup(value1: Any?, value2: Any?): ButtonsGroup {
return buttonsGroup {
row {
radioButton("radioButton1", value1)
}
row {
radioButton("radioButton2", value2)
}
}
}
}
| apache-2.0 |
cdietze/klay | klay-demo/src/main/kotlin/klay/tests/core/SurfaceTest.kt | 1 | 8921 | package klay.tests.core
import klay.core.*
import klay.scene.ClippedLayer
import klay.scene.GroupLayer
import klay.scene.ImageLayer
import klay.scene.Layer
import euklid.f.AffineTransform
import euklid.f.Rectangle
import react.RFuture
import react.Slot
import kotlin.math.PI
import kotlin.math.absoluteValue
import kotlin.math.cos
import kotlin.math.sin
class SurfaceTest(game: TestsGame) : Test(game, "Surface", "Tests various Surface rendering features.") {
private var paintUpped: TextureSurface? = null
val random = Random()
override fun init() {
val tile = game.assets.getImage("images/tile.png")
val orange = game.assets.getImage("images/orange.png")
var errY = 0f
val onError: Slot<Throwable> = { err: Throwable ->
addDescrip("Error: " + err.message, 10f, errY, game.graphics.viewSize.width - 20)
errY += 30f
}
tile.state.onFailure(onError)
orange.state.onFailure(onError)
RFuture.collect(listOf(tile.state, orange.state)).onSuccess { _ -> addTests(orange, tile) }
}
override fun dispose() {
super.dispose()
if (paintUpped != null) {
paintUpped!!.close()
paintUpped = null
}
}
private fun addTests(orange: Image, tile: Image) {
val otex = orange.texture()
val ttex = tile.createTexture(Texture.Config.DEFAULT.repeat(true, true))
// make samples big enough to force a buffer size increase
val samples = 128
val hsamples = samples / 2
val verts = FloatArray((samples + 1) * 4)
val indices = IntArray(samples * 6)
tessellateCurve(0f, 40 * PI.toFloat(), verts, indices, object : F {
override fun apply(x: Float): Float {
return sin((x / 20).toDouble()).toFloat() * 50
}
})
val ygap = 20f
var ypos = 10f
// draw some wide lines
ypos = ygap + addTest(10f, ypos, object : Layer() {
override fun paintImpl(surf: Surface) {
drawLine(surf, 0f, 0f, 50f, 50f, 15f)
drawLine(surf, 70f, 50f, 120f, 0f, 10f)
drawLine(surf, 0f, 70f, 120f, 120f, 10f)
}
}, 120f, 120f, "drawLine with width")
ypos = ygap + addTest(20f, ypos, object : Layer() {
override fun paintImpl(surf: Surface) {
surf.setFillColor(0xFF0000FF.toInt()).fillRect(0f, 0f, 100f, 25f)
// these two alpha fills should look the same
surf.setFillColor(0x80FF0000.toInt()).fillRect(0f, 0f, 50f, 25f)
surf.setAlpha(0.5f).setFillColor(0xFFFF0000.toInt()).fillRect(50f, 0f, 50f, 25f).setAlpha(1f)
}
}, 100f, 25f, "left and right half both same color")
ypos = ygap + addTest(20f, ypos, object : Layer() {
override fun paintImpl(surf: Surface) {
surf.setFillColor(0xFF0000FF.toInt()).fillRect(0f, 0f, 100f, 50f)
surf.setAlpha(0.5f)
surf.fillRect(0f, 50f, 50f, 50f)
surf.draw(otex, 55f, 5f)
surf.draw(otex, 55f, 55f)
surf.setAlpha(1f)
}
}, 100f, 100f, "fillRect and drawImage at 50% alpha")
ypos = 10f
val triangleBatch = TriangleBatch(game.graphics.gl)
val af = AffineTransform().scale(game.graphics.scale().factor, game.graphics.scale().factor).translate(160f, ygap + 150)
ypos = ygap + addTest(160f, ypos, object : Layer() {
override fun paintImpl(surf: Surface) {
// fill some shapes with patterns
surf.setFillPattern(ttex).fillRect(10f, 0f, 100f, 100f)
// render a sliding window of half of our triangles to test the slice rendering
triangleBatch.addTris(ttex, Tint.NOOP_TINT, af,
verts, offset * 4, (hsamples + 1) * 4, ttex.width, ttex.height,
indices, offset * 6, hsamples * 6, offset * 2)
offset += doff
if (offset == 0)
doff = 1
else if (offset == hsamples) doff = -1
}
private var offset = 0
private var doff = 1
}.setBatch(triangleBatch), 120f, 210f, "ImmediateLayer patterned fillRect, fillTriangles")
val patted = game.createSurface(100f, 100f)
patted.begin().clear().setFillPattern(ttex).fillRect(0f, 0f, 100f, 100f).end().close()
ypos = ygap + addTest(170f, ypos, ImageLayer(patted.texture),
"SurfaceImage patterned fillRect")
ypos = 10f
// fill a patterned quad in a clipped group layer
val twidth = 150f
val theight = 75f
val group = GroupLayer()
ypos = ygap + addTest(315f, 10f, group, twidth, theight,
"Clipped pattern should not exceed grey rectangle")
group.add(object : Layer() {
override fun paintImpl(surf: Surface) {
surf.setFillColor(0xFFCCCCCC.toInt()).fillRect(0f, 0f, twidth, theight)
}
})
group.add(object : ClippedLayer(twidth, theight) {
override fun paintClipped(surf: Surface) {
surf.setFillPattern(ttex).fillRect(-10f, -10f, twidth + 20, theight + 20)
}
})
// add a surface layer that is updated on every call to paint
// (a bad practice, but one that should actually work)
paintUpped = game.createSurface(100f, 100f)
ypos = ygap + addTest(315f, ypos, ImageLayer(paintUpped!!.texture),
"SurfaceImage updated in paint()")
// draw some randomly jiggling dots inside a bounded region
val dots = ArrayList<ImageLayer>()
val dotBox = Rectangle(315f, ypos, 200f, 100f)
ypos = ygap + addTest(dotBox.x, dotBox.y, object : Layer() {
override fun paintImpl(surf: Surface) {
surf.setFillColor(0xFFCCCCCC.toInt()).fillRect(0f, 0f, dotBox.width, dotBox.height)
}
}, dotBox.width, dotBox.height, "Randomly positioned SurfaceImages")
for (ii in 0..9) {
val dot = game.createSurface(10f, 10f)
dot.begin().setFillColor(0xFFFF0000.toInt()).fillRect(0f, 0f, 5f, 5f).fillRect(5f, 5f, 5f, 5f).setFillColor(0xFF0000FF.toInt()).fillRect(5f, 0f, 5f, 5f).fillRect(0f, 5f, 5f, 5f).end().close()
val dotl = ImageLayer(dot.texture)
dotl.setTranslation(dotBox.x + random.nextFloat() * (dotBox.width - 10),
dotBox.y + random.nextFloat() * (dotBox.height - 10))
dots.add(dotl)
game.rootLayer.add(dotl)
}
conns.add(game.paint.connect { clock: Clock ->
for (dot in dots) {
if (random.nextFloat() > 0.95f) {
dot.setTranslation(dotBox.x + random.nextFloat() * (dotBox.width - 10),
dotBox.y + random.nextFloat() * (dotBox.height - 10))
}
}
val now = clock.tick / 1000f
val sin = sin(now).absoluteValue
val cos = cos(now).absoluteValue
val sinColor = (sin * 255).toInt()
val cosColor = (cos * 255).toInt()
val c1 = 0xFF shl 24 or (sinColor shl 16) or (cosColor shl 8)
val c2 = 0xFF shl 24 or (cosColor shl 16) or (sinColor shl 8)
paintUpped!!.begin().clear().setFillColor(c1).fillRect(0f, 0f, 50f, 50f).setFillColor(c2).fillRect(50f, 50f, 50f, 50f).end()
})
}
internal fun drawLine(surf: Surface, x1: Float, y1: Float, x2: Float, y2: Float, width: Float) {
val xmin = minOf(x1, x2)
val xmax = maxOf(x1, x2)
val ymin = minOf(y1, y2)
val ymax = maxOf(y1, y2)
surf.setFillColor(0xFF0000AA.toInt()).fillRect(xmin, ymin, xmax - xmin, ymax - ymin)
surf.setFillColor(0xFF99FFCC.toInt()).drawLine(x1, y1, x2, y2, width)
surf.setFillColor(0xFFFF0000.toInt()).fillRect(x1, y1, 1f, 1f).fillRect(x2, y2, 1f, 1f)
}
interface F {
fun apply(x: Float): Float
}
internal fun tessellateCurve(minx: Float, maxx: Float, verts: FloatArray, indices: IntArray, f: F) {
val slices = (verts.size - 1) / 4
var vv = 0
val dx = (maxx - minx) / slices
var x = minx
while (vv < verts.size) {
verts[vv++] = x
verts[vv++] = 0f
verts[vv++] = x
verts[vv++] = f.apply(x)
x += dx
}
var ss = 0
var ii = 0
while (ss < slices) {
val base = ss * 2
indices[ii++] = base
indices[ii++] = base + 1
indices[ii++] = base + 3
indices[ii++] = base
indices[ii++] = base + 3
indices[ii++] = base + 2
ss++
}
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassImportAliasAllUsages.0.kt | 5 | 1067 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtImportAlias
// OPTIONS: usages, constructorUsages
package client
import server.Server as Srv<caret>
import server.Server
class Client(name: String = Server.NAME) : Srv() {
var nextServer: Server? = Server()
val name = Server.NAME
/**
* [Srv] parameter
*/
fun foo(s: Srv) {
val server: Server = s
println("Server: $server")
}
fun getNextServer2(): Server? {
return nextServer
}
override fun work() {
super<Server>.work()
println("Client")
}
companion object : Server() {
}
}
object ClientObject : Server() {
}
abstract class Servers : Iterator<Server> {
}
fun Iterator<Server>.f(p: Iterator<Server>): Iterator<Server> = this
fun Client.bar(s: Server = Server()) {
foo(s)
}
fun Client.hasNextServer(): Boolean {
return getNextServer2() != null
}
fun Any.asServer(): Server? {
when (this) {
is Server -> println("Server!")
}
return if (this is Server) this as Server else this as? Server
}
| apache-2.0 |
KrzysztofBogdan/Kodeks_formater | src/main/kotlin/pl/codeweaver/kodeks/formater/MarkdownTableFormatter.kt | 1 | 6013 | package pl.codeweaver.kodeks.formater
import javax.script.Invocable
import javax.script.ScriptEngineManager
object MarkdownTableFormatter {
fun format(value: String): String {
val runtime = ScriptEngineManager().getEngineByName("javascript");
runtime.eval(jsCode)
runtime.eval("""
function format_table(value) {
var mtf = new MarkdownTableFormatter();
mtf.format_table(value)
return mtf.output_table;
}
""")
if (runtime is Invocable) {
return runtime.invokeFunction("format_table", value) as String;
} else {
throw RuntimeException("ScriptEngine is not Invocable")
}
}
}
// https://github.com/alanwsmith/markdown_table_formatter
private val jsCode = """
function MarkdownTableFormatter() {
// Setup instance variables.
this.cells = new Array();
this.column_widths = new Array();
this.output_table = "";
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.add_missing_cell_columns = function() {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
for (var col_i = 0, col_l = this.column_widths.length; col_i < col_l; col_i = col_i + 1) {
if (typeof this.cells[row_i][col_i] === 'undefined') {
this.cells[row_i][col_i] = '';
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.format_table = function(table) {
this.import_table(table);
this.get_column_widths();
this.add_missing_cell_columns();
this.pad_cells_for_output();
// Header
this.output_table = "| ";
this.output_table += this.cells[0].join(" | ");
this.output_table += " |\n";
// Separator
this.output_table += "|-";
this.output_table += this.cells[1].join("-|-");
this.output_table += "-|\n";
for (var row_i = 2, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
this.output_table += "| ";
this.output_table += this.cells[row_i].join(" | ");
this.output_table += " |\n";
}
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.get_column_widths = function() {
this.column_widths = new Array();
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
for (var col_i = 0, col_l = this.cells[row_i].length; col_i < col_l; col_i = col_i + 1) {
if (typeof this.column_widths[col_i] === 'undefined') {
this.column_widths[col_i] = this.cells[row_i][col_i].length;
}
else if (this.column_widths[col_i] < this.cells[row_i][col_i].length) {
this.column_widths[col_i] = this.cells[row_i][col_i].length;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.import_table = function(table) {
var table_rows = table.split("\n");
// Remove leading empty lines
while (table_rows[0].indexOf('|') == -1) {
table_rows.shift();
}
for (var row_i = 0, row_l = table_rows.length; row_i < row_l; row_i = row_i + 1) {
// TODO: Set up the indexes so that empty lines at either the top or bottom will
// be removed. Right now, this is only helpful for empty lines at the bottom.
if(table_rows[row_i].indexOf('|') == -1) {
continue;
}
this.cells[row_i] = new Array();
var row_columns = table_rows[row_i].split("\|");
for (var col_i = 0, col_l = row_columns.length; col_i < col_l; col_i = col_i + 1) {
this.cells[row_i][col_i] = row_columns[col_i]
this.cells[row_i][col_i] = this.cells[row_i][col_i].replace(/^\s+/g,"");
this.cells[row_i][col_i] = this.cells[row_i][col_i].replace(/\s+$/g,"");
// If it's the separator row, parse down the dashes
// Only do this if it matches to avoid adding a
// dash in an empty column and messing with the column widths.
if (row_i == 1) {
this.cells[row_i][col_i] = this.cells[row_i][col_i].replace(/-+/g,"-");
}
}
}
// Remove leading and trailing rows if they are empty.
this.get_column_widths();
if (this.column_widths[0] == 0) {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
this.cells[row_i].shift();
}
}
this.get_column_widths();
// check to see if the last item in column widths is empty
if (this.column_widths[ (this.column_widths.length - 1) ] == 0) {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
// Only remove the row if it is in the proper last slot.
if (this.cells[row_i].length == this.column_widths.length) {
this.cells[row_i].pop();
}
}
}
this.get_column_widths();
}
////////////////////////////////////////////////////////////////////////////////
MarkdownTableFormatter.prototype.pad_cells_for_output = function() {
for (var row_i = 0, row_l = this.cells.length; row_i < row_l; row_i = row_i + 1) {
for (var col_i = 0, col_l = this.cells[row_i].length; col_i < col_l; col_i = col_i + 1) {
// Handle anything that's not the separator row
if (row_i != 1) {
while(this.cells[row_i][col_i].length < this.column_widths[col_i]) {
this.cells[row_i][col_i] += " ";
}
}
// Handle the separator row.
else {
while(this.cells[row_i][col_i].length < this.column_widths[col_i]) {
this.cells[row_i][col_i] += "-";
}
}
}
}
}
""" | mit |
pflammertsma/cryptogram | app/src/main/java/com/pixplicity/cryptogram/activities/CryptogramActivity.kt | 1 | 51352 | package com.pixplicity.cryptogram.activities
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.ProgressDialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.drawable.AnimatedVectorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.InputType
import android.util.Log
import android.util.SparseBooleanArray
import android.view.*
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.GravityCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.getkeepsafe.taptargetview.TapTarget
import com.getkeepsafe.taptargetview.TapTargetView
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.common.images.ImageManager
import com.google.android.gms.games.Games
import com.google.android.gms.games.GamesActivityResultCodes
import com.google.android.gms.games.snapshot.SnapshotMetadata
import com.google.android.gms.games.snapshot.Snapshots
import com.google.android.material.button.MaterialButton
import com.google.firebase.Timestamp
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PlayGamesAuthProvider
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.pixplicity.cryptogram.BuildConfig
import com.pixplicity.cryptogram.CryptogramApp
import com.pixplicity.cryptogram.R
import com.pixplicity.cryptogram.adapters.PuzzleAdapter
import com.pixplicity.cryptogram.db.PuzzleStateDao
import com.pixplicity.cryptogram.events.PuzzleEvent
import com.pixplicity.cryptogram.events.PuzzlesEvent
import com.pixplicity.cryptogram.events.RemoteConfigEvent
import com.pixplicity.cryptogram.models.Puzzle
import com.pixplicity.cryptogram.models.PuzzleState
import com.pixplicity.cryptogram.utils.*
import com.pixplicity.cryptogram.utils.BillingUtils.DONATIONS_ENABLED
import com.pixplicity.cryptogram.views.CryptogramView
import com.pixplicity.easyprefs.library.Prefs
import com.skydoves.balloon.ArrowOrientation
import com.skydoves.balloon.BalloonAnimation
import com.skydoves.balloon.createBalloon
import com.squareup.otto.Subscribe
import kotlinx.android.synthetic.main.activity_cryptogram.*
import kotlinx.android.synthetic.main.in_drawer.*
import kotlinx.android.synthetic.main.in_statistics.*
import net.soulwolf.widget.ratiolayout.widget.RatioFrameLayout
import java.util.*
class CryptogramActivity : BaseActivity() {
companion object {
private val TAG = CryptogramActivity::class.java.simpleName
private const val RC_UNUSED = 1000
private const val RC_PLAY_GAMES = 1001
private const val RC_SAVED_GAMES = 1002
private const val ONBOARDING_PAGES = 2
const val EXTRA_LAUNCH_SETTINGS = "launch_settings"
}
private var keyboardView: View? = null
private lateinit var puzzleAdapter: PuzzleAdapter
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var auth: FirebaseAuth
private val db = Firebase.firestore
private var lastConnectionError: Int = 0
private var freshInstall: Boolean = false
private var activityVisible = false
set(value) {
field = value
// Also persist it
CryptogramApp.activityVisible = value
}
private lateinit var puzzleState: PuzzleState
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cryptogram)
// Create the GoogleSignIn client with access to Games
googleSignInClient = GoogleSignIn.getClient(this, SignInUtil.getOptions(this, googleSignIn = true))
googleSignInClient.silentSignIn().addOnCompleteListener { task ->
updateGooglePlayGames()
if (task.isSuccessful) {
task.result?.serverAuthCode?.let { authCode ->
val credential = PlayGamesAuthProvider.getCredential(authCode)
auth.currentUser?.linkWithCredential(credential)?.addOnCompleteListener { task ->
if (task.isSuccessful) {
val user = task.result?.user
Log.d(TAG, "linkWithCredential: success; user=${user?.uid}")
} else {
Log.w(TAG, "linkWithCredential: failure", task.exception)
// Instead just log in as that user
auth.signInWithCredential(credential)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "signInWithCredential: success; user UID: ${auth.currentUser?.uid}")
} else {
// TODO Handle sign in failure more gracefully
Log.w(TAG, "signInWithCredential: failure", task.exception)
}
}
}
}
}
}
}
// Initialize Firebase Auth
auth = FirebaseAuth.getInstance()
if (auth.currentUser == null) {
auth.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, hold on to signed-in user's information
Log.d(TAG, "signInAnonymously: success; user UID: ${auth.currentUser?.uid}")
} else {
// TODO Handle sign in failure more gracefully
Log.w(TAG, "signInAnonymously: failure", task.exception)
}
}
} else {
Log.d(TAG, "user UID: ${auth.currentUser?.uid}")
}
RatingsBooster.init(this)
refreshPuzzles()
vg_cryptogram.setCryptogramView(cryptogram)
cryptogram.setOnHighlightListener(object : CryptogramView.OnHighlightListener {
private val mHighlightShown = SparseBooleanArray()
override fun onHighlight(type: Int, point: PointF) {
if (mHighlightShown.get(type, false)) {
return
}
if (PrefsUtils.getHighlighted(type)) {
return
}
mHighlightShown.put(type, true)
when (type) {
PrefsUtils.TYPE_HIGHLIGHT_HYPHENATION -> showHighlight(type, createTapTargetFromPoint(
point,
getString(R.string.highlight_hyphenation_title),
getString(R.string.highlight_hyphenation_description)),
1200
)
}
}
})
if (PrefsUtils.useSystemKeyboard) {
keyboardView?.visibility = View.GONE
} else {
if (keyboardView == null) {
vs_keyboard.layoutResource = when (PrefsUtils.keyboardLayout) {
KeyboardLayouts.LAYOUT_QWERTY -> R.layout.in_keyboard_qwerty
KeyboardLayouts.LAYOUT_QWERTZ -> R.layout.in_keyboard_qwertz
KeyboardLayouts.LAYOUT_AZERTY -> R.layout.in_keyboard_azerty
KeyboardLayouts.LAYOUT_ABC -> R.layout.in_keyboard_abc
}
keyboardView = vs_keyboard.inflate()
}
keyboardView?.visibility = View.VISIBLE
cryptogram.setKeyboardView(keyboardView)
}
val intent = intent
if (intent != null) {
if (intent.getBooleanExtra(EXTRA_LAUNCH_SETTINGS, false)) {
startActivity(SettingsActivity.create(this))
}
}
if (UpdateManager.consumeEnabledShowUsedLetters()) {
showHighlight(-1, TapTarget.forToolbarOverflow(
viewToolbar,
getString(R.string.highlight_used_letters_title),
getString(R.string.highlight_used_letters_description)),
1200
)
}
vg_google_play_games.setOnClickListener {
onClickGooglePlayGames()
}
bt_next.setOnClickListener {
nextPuzzle()
}
bt_flag.setOnClickListener {
FlaggingUtil.showDialog(this, PrefsUtils.theme.isDark, db, PuzzleProvider.getInstance(this).current, auth.currentUser)
}
bt_star.setOnClickListener {
PuzzleProvider.getInstance(this).current?.apply {
// Toggle puzzle state
puzzleState.starred = !puzzleState.starred
// Update record
PuzzleStateDao.set(puzzleState)
}
}
bt_covid.setOnClickListener {
AlertDialog.Builder(this)
.setMessage(R.string.covid_19_prevention)
.setPositiveButton(R.string.covid_19_learn_more) { _, _ ->
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://g.co/kgs/i6Pdqv")).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
})
} catch (e: Exception) {
}
}
.show()
}
RemoteConfig.refreshRemoteConfig()
}
override fun onStart() {
super.onStart()
activityVisible = true
EventProvider.bus.register(this)
val puzzleProvider = PuzzleProvider.getInstance(this)
val puzzle = puzzleProvider.current
puzzle?.onResume()
showHintView(puzzle)
if (hasOnBoardingPages()) {
showOnboarding(0)
} else {
onGameplayReady()
if (!PrefsUtils.notificationsPuzzlesSet) {
// Ask to enable notifications
AlertDialog.Builder(this)
.setTitle(R.string.enable_notifications_title)
.setMessage(R.string.enable_notifications_message)
.setPositiveButton(R.string.enable_notifications_yes) { _, _ ->
PrefsUtils.notificationsPuzzles = true
}
.setNegativeButton(R.string.enable_notifications_no) { _, _ ->
PrefsUtils.notificationsPuzzles = false
}
.show()
}
}
updateGooglePlayGames()
}
override fun onResume() {
super.onResume()
val puzzleProvider = PuzzleProvider.getInstance(this)
puzzleProvider.current?.let {
onPuzzleChanged(it, true, layoutChange = true)
}
}
override fun onStop() {
super.onStop()
activityVisible = false
val puzzleProvider = PuzzleProvider.getInstance(this)
val puzzle = puzzleProvider.current
puzzle?.onPause()
EventProvider.bus.unregister(this)
}
override fun onBackPressed() {
if (viewDrawerLayout != null && viewDrawerLayout!!.isDrawerOpen(GravityCompat.START)) {
viewDrawerLayout!!.closeDrawer(GravityCompat.START)
return
}
if (keyboardView != null && keyboardView!!.isShown) {
cryptogram.hideSoftInput()
return
}
super.onBackPressed()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
when (requestCode) {
RC_PLAY_GAMES -> {
when (resultCode) {
RESULT_OK -> {
// Logged in
Log.d(TAG, "user UID: ${auth.currentUser?.uid}")
// Analytics
CryptogramApp.instance.firebaseAnalytics.logEvent(FirebaseAnalytics.Event.LOGIN, null)
}
GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED -> {
// Logged out
googleSignInClient.signOut()
}
RESULT_CANCELED -> {
// Canceled; do nothing
}
else -> {
// Assume some error
showGmsError(resultCode)
}
}
updateGooglePlayGames()
loadGame(intent)
}
RC_SAVED_GAMES -> {
loadGame(intent)
if (viewDrawerLayout != null) {
viewDrawerLayout!!.closeDrawers()
}
}
}
}
private fun loadGame(intent: Intent?) {
val account = GoogleSignIn.getLastSignedInAccount(this)
if (intent != null && account != null) {
val snapshotsClient = Games.getSnapshotsClient(this, account)
if (intent.hasExtra(Snapshots.EXTRA_SNAPSHOT_METADATA)) {
// TODO replace with a better UI
// Load a snapshot
val pd = ProgressDialog(this)
pd.setMessage(getString(R.string.saved_game_loading))
pd.setCancelable(false)
pd.show()
intent.getParcelableExtra<SnapshotMetadata>(Snapshots.EXTRA_SNAPSHOT_METADATA)?.let { snapshotMetadata ->
PuzzleProvider.getInstance(this).load(this, snapshotsClient, snapshotMetadata,
object : SavegameManager.OnLoadResult {
override fun onLoadSuccess() {
PuzzleProvider.getInstance(this@CryptogramActivity).current?.let {
onPuzzleChanged(it, false)
showSnackbar(getString(R.string.saved_game_loaded))
}
pd.dismiss()
}
override fun onLoadFailure(reason: String) {
showSnackbar(getString(R.string.saved_game_load_failed, reason))
pd.dismiss()
}
})
}
} else if (intent.hasExtra(Snapshots.EXTRA_SNAPSHOT_NEW)) {
PuzzleProvider.getInstance(this).save(this, snapshotsClient,
object : SavegameManager.OnSaveResult {
override fun onSaveSuccess() {
showSnackbar(getString(R.string.saved_game_saved))
}
override fun onSaveFailure(reason: String) {
showSnackbar(getString(R.string.saved_game_save_failed, reason))
}
})
}
}
}
private fun hasOnBoardingPages(): Boolean {
return PrefsUtils.onboarding < ONBOARDING_PAGES - 1
}
private fun createTapTargetFromPoint(point: PointF, title: String,
description: String): TapTarget {
val viewRect = Rect()
cryptogram.getGlobalVisibleRect(viewRect)
val targetX = (point.x + viewRect.left).toInt()
val targetY = (point.y + viewRect.top).toInt()
val targetRadius = 48
return TapTarget.forBounds(Rect(targetX - targetRadius, targetY - targetRadius, targetX + targetRadius, targetY + targetRadius),
title, description)
}
private fun showHighlight(type: Int, tapTarget: TapTarget, delayMillis: Int) {
Handler().postDelayed({
val showTime = System.currentTimeMillis()
TapTargetView.showFor(
this@CryptogramActivity,
tapTarget
.titleTextColor(R.color.white)
.descriptionTextColor(R.color.white)
.outerCircleColor(R.color.highlight_color)
.cancelable(true)
.tintTarget(false)
.transparentTarget(true),
object : TapTargetView.Listener() {
override fun onTargetClick(view: TapTargetView) {
dismiss(view)
}
override fun onOuterCircleClick(view: TapTargetView?) {
dismiss(view)
}
override fun onTargetCancel(view: TapTargetView) {
dismiss(view)
}
private fun dismiss(view: TapTargetView?) {
if (type >= 0 && System.currentTimeMillis() - showTime >= 1500) {
// Ensure that the user saw the message
PrefsUtils.setHighlighted(type, true)
}
view!!.dismiss(false)
}
})
}, delayMillis.toLong())
}
private fun showOnboarding(page: Int) {
if (!activityVisible) {
// Do nothing if activity was paused
return
}
val titleStringResId: Int
val textStringResId: Int
var actionStringResId = R.string.intro_next
val video: VideoUtils.Video
when (page) {
0 -> {
titleStringResId = R.string.intro1_title
textStringResId = R.string.intro1_text
video = VideoUtils.VIDEO_INSTRUCTION
}
1 -> {
titleStringResId = R.string.intro2_title
textStringResId = R.string.intro2_text
actionStringResId = R.string.intro_done
video = VideoUtils.VIDEO_HELP
}
ONBOARDING_PAGES -> {
onGameplayReady()
return
}
else -> {
onGameplayReady()
return
}
}
val onboarding = PrefsUtils.onboarding
if (onboarding == -1) {
freshInstall = true
}
if (onboarding >= page) {
showOnboarding(page + 1)
return
}
val customView = LayoutInflater.from(this).inflate(R.layout.dialog_intro, null)
val tvIntro = customView.findViewById<TextView>(R.id.tv_intro)
tvIntro.setText(textStringResId)
val vgRatio = customView.findViewById<RatioFrameLayout>(R.id.vg_ratio)
val player = VideoUtils.setup(this, vgRatio, video)
MaterialDialog.Builder(this)
.title(titleStringResId)
.customView(customView, false)
.cancelable(false)
.positiveText(actionStringResId)
.showListener { _ ->
player?.start()
}
.onAny { _, _ ->
PrefsUtils.onboarding = page
showOnboarding(page + 1)
}
.show()
}
private fun onClickGooglePlayGames() {
val account = GoogleSignIn.getLastSignedInAccount(this)
if (account != null) {
// Connected; show gameplay options
val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_google_play_games, null)
val dialog = AlertDialog.Builder(this)
.setView(dialogView)
.show()
val btLeaderboards = dialogView.findViewById<Button>(R.id.bt_leaderboards)
btLeaderboards.setOnClickListener { _ ->
dialog.dismiss()
// Analytics
CryptogramApp.instance.firebaseAnalytics.logEvent(CryptogramApp.CONTENT_LEADERBOARDS, null)
Games.getLeaderboardsClient(this, account).getLeaderboardIntent(getString(R.string.leaderboard_scoreboard)).addOnSuccessListener {
try {
startActivityForResult(
it,
RC_UNUSED)
} catch (e: SecurityException) {
// Not sure why we're still seeing errors about the connection state, but here we are
FirebaseCrashlytics.getInstance().recordException(e)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@CryptogramActivity, R.string.google_play_games_not_installed, Toast.LENGTH_LONG).show()
}
}
}
val btAchievements = dialogView.findViewById<Button>(R.id.bt_achievements)
btAchievements.setOnClickListener { _ ->
dialog.dismiss()
// Analytics
CryptogramApp.instance.firebaseAnalytics.logEvent(CryptogramApp.CONTENT_ACHIEVEMENTS, null)
Games.getAchievementsClient(this, account).achievementsIntent.addOnSuccessListener {
try {
startActivityForResult(it, RC_UNUSED)
} catch (e: SecurityException) {
// Not sure why we're still seeing errors about the connection state, but here we are
FirebaseCrashlytics.getInstance().recordException(e)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@CryptogramActivity, R.string.google_play_games_not_installed, Toast.LENGTH_LONG).show()
}
}
}
val btRestoreSavedGames = dialogView.findViewById<Button>(R.id.bt_restore_saved_games)
btRestoreSavedGames.setOnClickListener { _ ->
dialog.dismiss()
val maxNumberOfSavedGamesToShow = 5
val task = Games.getSnapshotsClient(this, account).getSelectSnapshotIntent(
getString(R.string.google_play_games_saved_games_window_title), true, true, maxNumberOfSavedGamesToShow)
task.addOnFailureListener { e ->
FirebaseCrashlytics.getInstance().recordException(e)
}
task.addOnSuccessListener {
try {
startActivityForResult(it, RC_SAVED_GAMES)
} catch (e: SecurityException) {
// Not sure why we're still seeing errors about the connection state, but here we are
FirebaseCrashlytics.getInstance().recordException(e)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@CryptogramActivity, R.string.google_play_games_not_installed, Toast.LENGTH_LONG).show()
}
}
}
val btSignOut = dialogView.findViewById<Button>(R.id.bt_sign_out)
btSignOut.setOnClickListener { _ ->
dialog.dismiss()
googleSignInClient.signOut()
updateGooglePlayGames()
}
} else {
// Start the sign-in flow
startActivityForResult(googleSignInClient.signInIntent, RC_PLAY_GAMES)
}
}
private fun refreshPuzzles() {
rv_drawer.layoutManager = LinearLayoutManager(this)
puzzleAdapter = PuzzleAdapter(this, object : PuzzleAdapter.OnItemClickListener {
override fun onItemClick(position: Int) {
if (viewDrawerLayout != null) {
viewDrawerLayout!!.closeDrawers()
}
PuzzleProvider.getInstance(this@CryptogramActivity)[position]?.let {
onPuzzleChanged(it, false)
}
}
})
rv_drawer.adapter = puzzleAdapter
}
private fun updateCryptogram(puzzle: Puzzle?, layoutChange: Boolean = false) {
if (puzzle != null) {
// Pause the previous puzzle
cryptogram.puzzle?.onPause()
// Resume the current puzzle
puzzle.onResume()
val provider = PuzzleProvider.getInstance(this)
provider.setCurrentId(puzzle.id)
// Update UI
rv_drawer.scrollToPosition(provider.currentIndex)
tv_error.visibility = View.GONE
vg_cryptogram.visibility = View.VISIBLE
// Apply the puzzle to the CryptogramView
cryptogram.puzzle = puzzle
// Show other puzzle details
val author = puzzle.author
if (!PrefsUtils.showAuthor && !puzzle.isCompleted || author == null) {
tv_author.visibility = View.GONE
} else {
tv_author.visibility = View.VISIBLE
tv_author.text = getString(R.string.quote, author)
}
val topic = puzzle.topic
if (!PrefsUtils.showTopic && !puzzle.isCompleted || topic == null) {
tv_topic.visibility = View.GONE
} else {
tv_topic.visibility = View.VISIBLE
tv_topic.text = getString(R.string.topic, topic)
}
if (puzzle.isInstruction || puzzle.isNoScore) {
setToolbarSubtitle(puzzle.getTitle(this))
} else {
setToolbarSubtitle(getString(
R.string.puzzle_number,
puzzle.number))
}
// Invoke various events
showPuzzleState(puzzle, layoutChange = layoutChange)
} else {
tv_error.visibility = View.VISIBLE
vg_cryptogram.visibility = View.GONE
setToolbarSubtitle(null)
}
}
private fun onGameplayReady() {
cryptogram.requestFocus()
if (UpdateManager.consumeScoreExcludesExcessInputs()) {
MaterialDialog.Builder(this)
.title(R.string.scoring_changed_title)
.content(R.string.scoring_changed_message)
.cancelable(false)
.positiveText(R.string.ok)
.show()
}
}
private fun showPuzzleState(puzzle: Puzzle, layoutChange: Boolean = false) {
// Update the HintView as the puzzle updates
puzzleAdapter.notifyDataSetChanged()
if (puzzle.isCompleted) {
if (PrefsUtils.randomize) {
bt_next.setText(R.string.continue_to_puzzle_random)
} else {
bt_next.setText(R.string.continue_to_puzzle_sequential)
}
vg_stats.apply {
// Show the stats
visibility = View.VISIBLE
animate()
.translationY(0f)
.alpha(1f)
.setListener(null)
iv_check.visibility = View.VISIBLE
}
// C-19 information message
bt_covid.visibility = if (puzzle.number == Puzzle.PUZZLE_UNIQUE_COVID) View.VISIBLE else View.GONE
// Orient buttons to make space for stats if needed
if (layoutChange) {
ConstraintSet().apply {
clone(vg_stats)
if (PrefsUtils.showScore) {
connect(R.id.bt_star, ConstraintSet.TOP, R.id.bt_flag, ConstraintSet.BOTTOM, 8.px)
connect(R.id.bt_star, ConstraintSet.END, R.id.vg_stats, ConstraintSet.END, 0)
} else {
connect(R.id.bt_star, ConstraintSet.TOP, R.id.vg_stats, ConstraintSet.TOP, 0)
connect(R.id.bt_star, ConstraintSet.END, R.id.bt_flag, ConstraintSet.START, 8.px)
}
applyTo(vg_stats)
}
}
vg_solved.visibility =
if (PrefsUtils.showScore || PrefsUtils.showSolveTime || puzzle.isNoScore) View.GONE else View.VISIBLE
val durationMs = puzzle.durationMs
if (!PrefsUtils.showSolveTime || durationMs <= 0) {
vg_stats_time.visibility = View.GONE
} else {
vg_stats_time.visibility = View.VISIBLE
tv_stats_time.text = StringUtils.getDurationString(durationMs)
}
var reveals = -1
var score: Float? = null
if (PrefsUtils.showScore) {
reveals = puzzle.reveals
score = puzzle.score
}
if (reveals < 0) {
vg_stats_reveals.visibility = View.GONE
} else {
vg_stats_reveals.visibility = View.VISIBLE
tv_stats_reveals.text = getString(R.string.stats_reveals_value, reveals, resources.getQuantityString(R.plurals.stats_reveals_chars, reveals))
}
if (score != null) {
vg_stats_practice.visibility = View.GONE
vg_stats_score.visibility = View.VISIBLE
tv_stats_score.text = String.format(
Locale.ENGLISH,
"%.1f%%",
score * 100)
} else {
vg_stats_score.visibility = View.GONE
vg_stats_practice.visibility = if (puzzle.isNoScore) View.VISIBLE else View.GONE
}
if (CryptogramApp.instance.remoteConfig.getBoolean(RemoteConfig.ALLOW_USER_FLAGGING) && !puzzle.isNoScore) {
bt_flag.visibility = View.VISIBLE
} else {
bt_flag.visibility = View.GONE
}
bt_star.visibility = if (puzzle.isNoScore) View.GONE else View.VISIBLE
} else {
bt_covid.visibility = View.GONE
if (vg_stats.isShown) {
vg_stats.apply {
animate()
.translationY(height.toFloat())
.alpha(0f)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
visibility = View.GONE
}
})
}
}
}
showHintView(puzzle)
puzzle.apply {
bt_star.isEnabled = false
(PuzzleStateDao.get(id.toLong())).observe(this@CryptogramActivity, Observer {
puzzleState = it.firstOrNull() ?: PuzzleState(id.toLong(), false)
puzzleState.apply {
(bt_star as MaterialButton).setIconResource(if (starred) R.drawable.ic_star else R.drawable.ic_star_border)
}
bt_star.isEnabled = true
})
}
}
private fun showHintView(puzzle: Puzzle?) {
hint.visibility = if (puzzle != null && !puzzle.isCompleted
&& PrefsUtils.showUsedChars && PrefsUtils.useSystemKeyboard)
View.VISIBLE
else
View.GONE
}
fun onPuzzleChanged(puzzle: Puzzle, delayEvent: Boolean, layoutChange: Boolean = false) {
updateCryptogram(puzzle, layoutChange = layoutChange)
if (delayEvent) {
EventProvider.postEventDelayed(PuzzleEvent.PuzzleProgressEvent(puzzle), 200)
} else {
EventProvider.postEvent(PuzzleEvent.PuzzleProgressEvent(puzzle))
}
cryptogram.onPuzzleResume()
}
@Subscribe
fun onPuzzleProgress(event: PuzzleEvent.PuzzleProgressEvent) {
event.puzzle?.let {
showPuzzleState(it)
}
}
@Subscribe
fun onPuzzleStarted(event: PuzzleEvent.PuzzleStartedEvent) {
// Submit any achievements
AchievementProvider.onCryptogramStart()
cryptogram.onPuzzleResume()
}
@Subscribe
fun onPuzzleReset(event: PuzzleEvent.PuzzleResetEvent) {
updateCryptogram(event.puzzle)
}
@Subscribe
fun onPuzzleCompleted(event: PuzzleEvent.PuzzleCompletedEvent) {
updateCryptogram(event.puzzle)
cryptogram.onPuzzleCompleted()
// TODO animate finish vector
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && iv_check.drawable is AnimatedVectorDrawable) {
(iv_check.drawable as AnimatedVectorDrawable).apply {
iv_check.visibility = View.INVISIBLE
iv_check.postDelayed({
iv_check.visibility = View.VISIBLE
start()
}, 1000)
}
}
if (!FirebaseCrashlytics.getInstance().didCrashOnPreviousExecution()) {
// Increment the trigger for displaying the rating dialog
RatingsBooster.incrementAndPrompt()
}
// Conditional behavior after X triggers
val provider = PuzzleProvider.getInstance(this)
var count = 0L
for (c in provider.all) {
if (!c.isInstruction && c.isCompleted) {
count++
}
}
val suggestDonationCount = PrefsUtils.suggestDonationCount
if (DONATIONS_ENABLED && count >= suggestDonationCount) {
// Prompt for donations only if user hasn't already donated
val purchases = PrefsUtils.purchases
PrefsUtils.suggestDonationCount = count + BillingUtils.DONATION_SUGGESTION_FREQUENCY
if (purchases == null) {
// Query purchases
BillingUtils.updatePurchases(this)
} else if (purchases.isEmpty()) {
BillingUtils.suggestDonation(this)
} else {
AchievementProvider.onDonated()
}
}
// Show prompts for frustrated users
if (bt_flag.isShown && !PrefsUtils.highlightedFrustrationFlag && CryptogramApp.instance.remoteConfig.getBoolean(RemoteConfig.FRUSTRATION_HINT)) {
val createBalloon = createBalloon(this) {
setArrowSize(12)
setCornerRadius(4f)
setPadding(8)
setArrowPosition(0.88f)
setArrowOrientation(ArrowOrientation.BOTTOM)
setText(getString(R.string.highlight_frustration_flag))
setTextColor(getColorFromAttr(R.attr.textColorOnPrimary))
setBackgroundColor(getColorFromAttr(R.attr.colorPrimaryDark))
setBalloonAnimation(BalloonAnimation.FADE)
setLifecycleOwner(lifecycleOwner)
dismissWhenTouchOutside = true
dismissWhenClicked = true
}
bt_flag.postDelayed({
createBalloon.showAlignTop(bt_flag)
}, 500)
bt_flag.postDelayed({
// Only stop showing this if it was visible for a moment
if (createBalloon.isShowing) {
PrefsUtils.highlightedFrustrationFlag = true
}
}, 1300)
}
// Using the Google sign in
val account = GoogleSignIn.getLastSignedInAccount(this)
if (account != null) {
// Attach view for popups
Games.getGamesClient(this, account).setViewForPopups(drawer_layout)
// Submit score
LeaderboardProvider.submit(Games.getLeaderboardsClient(this, account))
// Submit any achievements
AchievementProvider.onCryptogramCompleted(this, Games.getAchievementsClient(this, account))
// Attempt to save the game to Google Play Saved Games
provider.save(this, Games.getSnapshotsClient(this, account), null)
} else if (BuildConfig.DEBUG) {
// Check achievements for offline
AchievementProvider.onCryptogramCompleted(this, null)
}
}
@Subscribe
fun onPuzzleKeyboardInput(event: PuzzleEvent.KeyboardInputEvent) {
val keyCode = event.keyCode
cryptogram.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
keyCode, 0))
cryptogram.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_UP,
keyCode, 0))
}
@Subscribe
fun onRemoteConfigPush(event: RemoteConfigEvent.Push) {
if (BuildConfig.DEBUG) {
Toast.makeText(this, "Remote configuration changing…", Toast.LENGTH_SHORT).show()
}
}
@Subscribe
fun onRemoteConfigChanged(event: RemoteConfigEvent.Change) {
if (event.updated) {
updateCryptogram(cryptogram.puzzle)
}
}
@Subscribe
fun onPuzzlesChanged(event: PuzzlesEvent.Change) {
if (event.newPuzzles > 0) {
showSnackbar(event.message, autoDismiss = false)
}
refreshPuzzles()
updateCryptogram(cryptogram.puzzle)
}
override fun onDrawerOpened(drawerView: View?) {}
override fun onDrawerClosed(drawerView: View?) {}
override fun onDrawerMoving() {
cryptogram.hideSoftInput()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_cryptogram, menu)
menu.findItem(R.id.action_reveal_puzzle).apply {
isVisible = BuildConfig.DEBUG
}
menu.findItem(R.id.action_donate).apply {
isVisible = DONATIONS_ENABLED
}
menu.findItem(R.id.action_admin).apply {
isVisible = BuildConfig.DEBUG
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (super.onOptionsItemSelected(item)) {
return true
}
val puzzle = cryptogram.puzzle
when (item.itemId) {
R.id.action_next -> {
nextPuzzle()
return true
}
R.id.action_reveal_letter -> {
if (puzzle == null || !cryptogram.hasSelectedCharacter()) {
showSnackbar(getString(R.string.reveal_letter_instruction))
} else {
if (PrefsUtils.neverAskRevealLetter) {
revealLetter()
} else {
MaterialDialog.Builder(this)
.content(R.string.reveal_letter_confirmation)
.checkBoxPromptRes(R.string.never_ask_again, false, null)
.positiveText(R.string.reveal)
.onPositive { dialog, _ ->
PrefsUtils.neverAskRevealLetter = dialog.isPromptCheckBoxChecked
revealLetter()
}
.negativeText(R.string.cancel)
.show()
}
}
return true
}
R.id.action_reveal_mistakes -> {
puzzle?.let {
if (PrefsUtils.neverAskRevealMistakes) {
revealMistakes(it)
} else {
MaterialDialog.Builder(this)
.content(R.string.reveal_mistakes_confirmation)
.checkBoxPromptRes(R.string.never_ask_again, false, null)
.positiveText(R.string.reveal)
.onPositive { dialog, _ ->
PrefsUtils.neverAskRevealMistakes = dialog.isPromptCheckBoxChecked
revealMistakes(it)
}
.negativeText(R.string.cancel)
.show()
}
}
return true
}
R.id.action_reveal_puzzle -> {
if (BuildConfig.DEBUG) {
puzzle?.revealPuzzle()
cryptogram.redraw()
} else {
throw IllegalStateException("Only applicable to debug builds")
}
return true
}
R.id.action_reset -> {
if (puzzle != null) {
AlertDialog.Builder(this)
.setMessage(R.string.reset_puzzle)
.setPositiveButton(R.string.reset) { _, _ ->
puzzle.reset(true)
cryptogram.reset()
showPuzzleState(puzzle)
onPuzzleChanged(puzzle, false)
}
.setNegativeButton(R.string.cancel) { _, _ -> }
.show()
}
return true
}
R.id.action_go_to -> {
if (puzzle == null) {
if (viewDrawerLayout != null) {
viewDrawerLayout!!.openDrawer(GravityCompat.START)
}
} else {
var prefilledText: String? = null
val currentId = puzzle.number
if (currentId > 0) {
prefilledText = currentId.toString()
}
MaterialDialog.Builder(this)
.content(R.string.go_to_puzzle_content)
.inputType(InputType.TYPE_CLASS_NUMBER)
.input(null, prefilledText) { dialog, input ->
val button = dialog.getActionButton(DialogAction.POSITIVE)
try {
button.isEnabled = Integer.parseInt(input.toString()) > 0
} catch (ignored: NumberFormatException) {
button.isEnabled = false
}
}
.alwaysCallInputCallback()
.showListener { dialogInterface ->
val dialog = dialogInterface as MaterialDialog
dialog.inputEditText!!.selectAll()
}
.onPositive { dialog, _ ->
val input = dialog.inputEditText!!.text
try {
val puzzleNumber = Integer.parseInt(input.toString())
val provider = PuzzleProvider
.getInstance(this@CryptogramActivity)
val newPuzzle = provider.getByNumber(puzzleNumber)
if (newPuzzle == null) {
showSnackbar(getString(R.string.puzzle_nonexistant, puzzleNumber))
} else {
onPuzzleChanged(newPuzzle, false)
}
} catch (ignored: NumberFormatException) {
}
}.show()
}
return true
}
R.id.action_share -> {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
val text = if (puzzle != null && puzzle.isCompleted) {
getString(
R.string.share_full,
puzzle.text,
puzzle.author,
getString(R.string.share_url))
} else {
getString(
R.string.share_partial,
if (puzzle == null)
getString(R.string.author_unknown)
else
puzzle.author,
getString(R.string.share_url))
}
intent.putExtra(Intent.EXTRA_TEXT, text)
startActivity(Intent.createChooser(intent, getString(R.string.share)))
// Analytics
val puzzleId = puzzle?.id?.toString()
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.LEVEL, puzzleId)
bundle.putString(FirebaseAnalytics.Param.CONTENT, text)
CryptogramApp.instance.firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE, bundle)
return true
}
R.id.action_stats -> {
// Make sure to save the puzzle first
puzzle?.save()
// Now show the stats
StatisticsUtils.showDialog(this);
return true
}
R.id.action_settings -> {
startActivity(SettingsActivity.create(this))
return true
}
R.id.action_how_to_play -> {
startActivity(HowToPlayActivity.create(this))
return true
}
R.id.action_gameplay_tips -> {
startActivity(TipsActivity.create(this))
return true
}
R.id.action_about -> {
startActivity(AboutActivity.create(this))
return true
}
R.id.action_donate -> {
startActivity(DonateActivity.create(this))
return true
}
R.id.action_admin -> {
startActivity(AdminActivity.create(this))
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun revealLetter() {
val c = cryptogram.caretChar
cryptogram.revealCharacterMapping(c)
if (CryptogramApp.instance.remoteConfig.getBoolean(RemoteConfig.SUBMIT_REVEALS)) {
// Submit which character was revealed for analytics
auth.currentUser?.let { user ->
cryptogram.puzzle?.let { puzzle ->
val reveals = mutableMapOf<String, Any>(Pair(c.toString(), true))
reveals["timestamp"] = Timestamp(Date())
db.collection("users").document(user.uid)
.collection("reveals").document(puzzle.id.toString())
.set(reveals, SetOptions.merge())
.addOnSuccessListener {
Log.d(TAG, "DocumentSnapshot written")
}
.addOnFailureListener { e ->
Log.w(TAG, "DocumentSnapshot failed writing", e)
}
}
}
}
}
private fun revealMistakes(puzzle: Puzzle) {
if (puzzle.revealMistakes() == 0) {
showSnackbar(getString(R.string.reveal_mistakes_none))
} else {
// Show those mistakes
cryptogram.redraw()
}
}
private fun nextPuzzle() {
val puzzle = PuzzleProvider.getInstance(this).next
puzzle.let {
if (it == null) {
val customView = LayoutInflater.from(this).inflate(R.layout.dialog_game_completed, null)
MaterialDialog.Builder(this)
.customView(customView, false)
.cancelable(false)
.positiveText(android.R.string.ok)
.show()
} else {
onPuzzleChanged(it, false)
}
}
}
private fun updateGooglePlayGames() {
val account = GoogleSignIn.getLastSignedInAccount(this)
if (account != null) {
val playerTask = Games.getPlayersClient(this, account).currentPlayer
playerTask.addOnFailureListener {
bt_google_play_games.visibility = View.VISIBLE
iv_google_play_games_avatar.visibility = View.GONE
tv_google_play_games.visibility = View.VISIBLE
tv_google_play_games_name.visibility = View.GONE
vg_google_play_games_actions.visibility = View.GONE
}
playerTask.addOnSuccessListener { p ->
val displayName: String
val imageUri: Uri?
if (p != null) {
displayName = p.displayName
imageUri = if (p.hasHiResImage()) p.hiResImageUri else p.iconImageUri
//bannerUri = p.getBannerImageLandscapeUri();
} else {
// Set the greeting appropriately on main menu
displayName = account.displayName
?: getString(R.string.google_play_games_player_unknown)
imageUri = account.photoUrl
}
Log.w(TAG, "onConnected(): current player is $displayName")
bt_google_play_games.visibility = View.GONE
iv_google_play_games_avatar.visibility = View.VISIBLE
ImageManager.create(this).loadImage(iv_google_play_games_avatar, imageUri, R.drawable.im_avatar)
tv_google_play_games.visibility = View.GONE
tv_google_play_games_name.visibility = View.VISIBLE
tv_google_play_games_name.text = displayName
vg_google_play_games_actions.visibility = View.VISIBLE
}
} else {
bt_google_play_games.visibility = View.VISIBLE
iv_google_play_games_avatar.visibility = View.GONE
tv_google_play_games.visibility = View.VISIBLE
tv_google_play_games_name.visibility = View.GONE
vg_google_play_games_actions.visibility = View.GONE
}
}
private fun showGmsError(errorCode: Int) {
if (isFinishing) {
return
}
AlertDialog.Builder(this)
.setMessage(getString(R.string.google_play_games_connection_failure, lastConnectionError, errorCode))
.setPositiveButton(android.R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
}
}
| mit |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/lesson/view/LessonController.kt | 1 | 4413 | package org.secfirst.umbrella.feature.lesson.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.bluelinelabs.conductor.RouterTransaction
import com.xwray.groupie.ExpandableGroup
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.lesson_view.*
import kotlinx.android.synthetic.main.lesson_view.view.*
import org.secfirst.umbrella.R
import org.secfirst.umbrella.UmbrellaApplication
import org.secfirst.umbrella.data.database.lesson.Lesson
import org.secfirst.umbrella.data.database.lesson.Subject
import org.secfirst.umbrella.data.database.segment.Markdown
import org.secfirst.umbrella.feature.base.view.BaseController
import org.secfirst.umbrella.feature.difficulty.view.DifficultyController
import org.secfirst.umbrella.feature.lesson.DaggerLessonComponent
import org.secfirst.umbrella.feature.lesson.interactor.LessonBaseInteractor
import org.secfirst.umbrella.feature.lesson.presenter.LessonBasePresenter
import org.secfirst.umbrella.feature.segment.view.controller.HostSegmentController
import org.secfirst.umbrella.misc.AboutController
import javax.inject.Inject
class LessonController : BaseController(), LessonView {
@Inject
internal lateinit var presenter: LessonBasePresenter<LessonView, LessonBaseInteractor>
private val lessonClick: (Subject) -> Unit = this::onLessonClicked
private val groupClick: (Lesson) -> Unit = this::onGroupClicked
private val groupAdapter = GroupAdapter<ViewHolder>()
private var isRecycledView = false
companion object {
private const val RECYCLER_STATE = "recycle_state"
}
override fun onInject() {
DaggerLessonComponent.builder()
.application(UmbrellaApplication.instance)
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
val view = inflater.inflate(R.layout.lesson_view, container, false)
presenter.onAttach(this)
presenter.submitLoadAllLesson()
view.lessonRecyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = groupAdapter
}
setUpToolbar(view)
return view
}
override fun showAllLesson(lessons: List<Lesson>) {
if (!isRecycledView) {
lessons.forEach { lesson ->
val hasChild = lesson.topics.isNotEmpty()
val lessonGroup = LessonGroup(lesson,
hasChild, groupClick)
val groups = ExpandableGroup(lessonGroup)
if (hasChild) groups.add(LessonDecorator())
lesson.topics.forEach { subject ->
groups.add(LessonItem(subject, lessonClick))
}
if (hasChild) groups.add(LessonDecorator())
groupAdapter.add(groups)
}
lessonRecyclerView?.apply { adapter = groupAdapter }
}
}
override fun onSaveViewState(view: View, outState: Bundle) {
super.onSaveViewState(view, outState)
outState.putBoolean(RECYCLER_STATE, true)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
isRecycledView = savedViewState.getBoolean(RECYCLER_STATE)
}
private fun setUpToolbar(view: View) {
view.lessonToolbar.let {
mainActivity.setSupportActionBar(it)
mainActivity.supportActionBar?.title = context.getString(R.string.lesson_title)
}
}
private fun onLessonClicked(subject: Subject) = presenter.submitSelectLesson(subject)
private fun onGroupClicked(lesson: Lesson) = presenter.submitSelectHead(lesson)
override fun startSegment(markdownIds: ArrayList<String>, enableFilter: Boolean) =
router.pushController(RouterTransaction.with(HostSegmentController(markdownIds, enableFilter)))
override fun startDifficultyController(subject: Subject) =
router.pushController(RouterTransaction.with(DifficultyController(subject.id)))
override fun startSegmentAlone(markdown: Markdown) =
router.pushController(RouterTransaction.with(AboutController(markdown)))
} | gpl-3.0 |
TheMrMilchmann/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_external_fence_fd.kt | 1 | 7783 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val KHR_external_fence_fd = "KHRExternalFenceFd".nativeClassVK("KHR_external_fence_fd", type = "device", postfix = "KHR") {
documentation =
"""
An application using external memory may wish to synchronize access to that memory using fences. This extension enables an application to export fence payload to and import fence payload from POSIX file descriptors.
<h5>VK_KHR_external_fence_fd</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_KHR_external_fence_fd}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>116</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRExternalFence VK_KHR_external_fence} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Jesse Hall <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_external_fence_fd]%20@critsec%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_external_fence_fd%20extension%3E%3E">critsec</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2017-05-08</dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Jesse Hall, Google</li>
<li>James Jones, NVIDIA</li>
<li>Jeff Juliano, NVIDIA</li>
<li>Cass Everitt, Oculus</li>
<li>Contributors to {@link KHRExternalSemaphoreFd VK_KHR_external_semaphore_fd}</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"KHR_EXTERNAL_FENCE_FD_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME".."VK_KHR_external_fence_fd"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR".."1000115000",
"STRUCTURE_TYPE_FENCE_GET_FD_INFO_KHR".."1000115001"
)
VkResult(
"ImportFenceFdKHR",
"""
Import a fence from a POSIX file descriptor.
<h5>C Specification</h5>
To import a fence payload from a POSIX file descriptor, call:
<pre><code>
VkResult vkImportFenceFdKHR(
VkDevice device,
const VkImportFenceFdInfoKHR* pImportFenceFdInfo);</code></pre>
<h5>Description</h5>
Importing a fence payload from a file descriptor transfers ownership of the file descriptor from the application to the Vulkan implementation. The application <b>must</b> not perform any operations on the file descriptor after a successful import.
Applications <b>can</b> import the same fence payload into multiple instances of Vulkan, into the same instance from which it was exported, and multiple times into a given Vulkan instance.
<h5>Valid Usage</h5>
<ul>
<li>{@code fence} <b>must</b> not be associated with any queue command that has not yet completed execution on that queue</li>
</ul>
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
<li>{@code pImportFenceFdInfo} <b>must</b> be a valid pointer to a valid ##VkImportFenceFdInfoKHR structure</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_OUT_OF_HOST_MEMORY</li>
<li>#ERROR_INVALID_EXTERNAL_HANDLE</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##VkImportFenceFdInfoKHR
""",
VkDevice("device", "the logical device that created the fence."),
VkImportFenceFdInfoKHR.const.p("pImportFenceFdInfo", "a pointer to a ##VkImportFenceFdInfoKHR structure specifying the fence and import parameters.")
)
VkResult(
"GetFenceFdKHR",
"""
Get a POSIX file descriptor handle for a fence.
<h5>C Specification</h5>
To export a POSIX file descriptor representing the payload of a fence, call:
<pre><code>
VkResult vkGetFenceFdKHR(
VkDevice device,
const VkFenceGetFdInfoKHR* pGetFdInfo,
int* pFd);</code></pre>
<h5>Description</h5>
Each call to {@code vkGetFenceFdKHR} <b>must</b> create a new file descriptor and transfer ownership of it to the application. To avoid leaking resources, the application <b>must</b> release ownership of the file descriptor when it is no longer needed.
<div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
Ownership can be released in many ways. For example, the application can call {@code close}() on the file descriptor, or transfer ownership back to Vulkan by using the file descriptor to import a fence payload.
</div>
If {@code pGetFdInfo→handleType} is #EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT and the fence is signaled at the time {@code vkGetFenceFdKHR} is called, {@code pFd} <b>may</b> return the value {@code -1} instead of a valid file descriptor.
Where supported by the operating system, the implementation <b>must</b> set the file descriptor to be closed automatically when an {@code execve} system call is made.
Exporting a file descriptor from a fence <b>may</b> have side effects depending on the transference of the specified handle type, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#synchronization-fences-importing">Importing Fence State</a>.
<h5>Valid Usage (Implicit)</h5>
<ul>
<li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
<li>{@code pGetFdInfo} <b>must</b> be a valid pointer to a valid ##VkFenceGetFdInfoKHR structure</li>
<li>{@code pFd} <b>must</b> be a valid pointer to an {@code int} value</li>
</ul>
<h5>Return Codes</h5>
<dl>
<dt>On success, this command returns</dt>
<dd><ul>
<li>#SUCCESS</li>
</ul></dd>
<dt>On failure, this command returns</dt>
<dd><ul>
<li>#ERROR_TOO_MANY_OBJECTS</li>
<li>#ERROR_OUT_OF_HOST_MEMORY</li>
</ul></dd>
</dl>
<h5>See Also</h5>
##VkFenceGetFdInfoKHR
""",
VkDevice("device", "the logical device that created the fence being exported."),
VkFenceGetFdInfoKHR.const.p("pGetFdInfo", "a pointer to a ##VkFenceGetFdInfoKHR structure containing parameters of the export operation."),
Check(1)..int.p("pFd", "will return the file descriptor representing the fence payload.")
)
} | bsd-3-clause |
github/codeql | java/kotlin-extractor/src/main/kotlin/utils/versions/v_1_7_20-Beta/createImplicitParameterDeclarationWithWrappedDescriptor.kt | 1 | 321 | package com.github.codeql.utils.versions
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.util.createImplicitParameterDeclarationWithWrappedDescriptor
fun IrClass.createImplicitParameterDeclarationWithWrappedDescriptor() = this.createImplicitParameterDeclarationWithWrappedDescriptor() | mit |
github/codeql | java/ql/integration-tests/all-platforms/kotlin/default-parameter-mad-flow/user.kt | 1 | 1584 | fun source() = 1
fun sink(x: Any) { }
fun test(c: LibClass, sourcec: SourceClass, sinkc: SinkClass) {
sink(ConstructorWithDefaults(source(), 0)) // $ flow
sink(ConstructorWithDefaults(source())) // $ flow
sink(topLevelWithDefaults(source(), 0)) // $ flow
sink(topLevelWithDefaults(source())) // $ flow
sink("Hello world".extensionWithDefaults(source(), 0)) // $ flow
sink("Hello world".extensionWithDefaults(source())) // $ flow
sink(c.memberWithDefaults(source(), 0)) // $ flow
sink(c.memberWithDefaults(source())) // $ flow
sink(c.multiParameterTest(source(), 0, 0)) // $ flow
sink(c.multiParameterTest(0, source(), 0)) // $ flow
sink(c.multiParameterTest(0, 0, source()))
with(c) {
sink("Hello world".extensionMemberWithDefaults(source(), 0)) // $ flow
sink("Hello world".extensionMemberWithDefaults(source())) // $ flow
}
with(c) {
sink(source().multiParameterExtensionTest(0, 0)) // $ flow
sink(0.multiParameterExtensionTest(source(), 0)) // $ flow
sink(0.multiParameterExtensionTest(0, source()))
}
run {
val st = SomeToken()
topLevelArgSource(st)
sink(st) // $ flow
}
run {
val st = SomeToken()
"Hello world".extensionArgSource(st)
sink(st) // $ flow
}
run {
val st = SomeToken()
sourcec.memberArgSource(st)
sink(st) // $ flow
}
SinkClass(source()) // $ flow
topLevelSink(source()) // $ flow
"Hello world".extensionSink(source()) // $ flow
sinkc.memberSink(source()) // $ flow
with(sinkc) {
"Hello world".extensionMemberSink(source()) // $ flow
}
}
| mit |
JuliaSoboleva/SmartReceiptsLibrary | app/src/test/java/co/smartreceipts/android/identity/widget/account/AccountPresenterTest.kt | 2 | 3909 | package co.smartreceipts.android.identity.widget.account
import co.smartreceipts.android.identity.apis.organizations.Organization
import co.smartreceipts.android.identity.apis.organizations.OrganizationModel
import co.smartreceipts.core.identity.store.EmailAddress
import co.smartreceipts.android.purchases.model.InAppPurchase
import co.smartreceipts.android.purchases.subscriptions.RemoteSubscription
import co.smartreceipts.android.widget.model.UiIndicator
import com.nhaarman.mockitokotlin2.*
import io.reactivex.Observable
import io.reactivex.Single
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.util.*
@RunWith(RobolectricTestRunner::class)
class AccountPresenterTest {
companion object {
private const val EMAIL = "[email protected]"
}
// Class under test
private lateinit var presenter: AccountPresenter
private val view = mock<AccountView>()
private val interactor = mock<AccountInteractor>()
private val organizationModel = mock<OrganizationModel>()
private val organization = mock<Organization>()
@Before
fun setUp() {
whenever(view.applySettingsClicks).thenReturn(Observable.never())
whenever(view.logoutButtonClicks).thenReturn(Observable.never())
whenever(view.uploadSettingsClicks).thenReturn(Observable.never())
whenever(interactor.getEmail()).thenReturn(EmailAddress(EMAIL))
whenever(interactor.getOrganizations()).thenReturn(Single.just(Collections.emptyList()))
whenever(interactor.getOcrRemainingScansStream()).thenReturn(Observable.just(5))
whenever(interactor.getSubscriptionsStream()).thenReturn(Observable.empty())
whenever(organizationModel.organization).thenReturn(organization)
presenter = AccountPresenter(view, interactor)
}
@Test
fun presentEmailTest() {
presenter.subscribe()
verify(view).presentEmail(eq(EmailAddress(EMAIL)))
}
@Test
fun presentNoOrganization() {
presenter.subscribe()
verify(view, times(2)).presentOrganizations(any())
verify(view).presentOrganizations(UiIndicator.loading())
verify(view).presentOrganizations(UiIndicator.idle())
verify(interactor, times(1)).getOrganizations()
}
@Test
fun presentOrganizations() {
val organizationModel = mock<OrganizationModel>()
whenever(interactor.getOrganizations()).thenReturn(Single.just(listOf(organizationModel)))
whenever(organizationModel.organization).thenReturn(mock<Organization>())
presenter.subscribe()
verify(view, times(2)).presentOrganizations(any())
verify(view).presentOrganizations(UiIndicator.loading())
verify(view).presentOrganizations(UiIndicator.success(listOf(organizationModel)))
verify(interactor, times(1)).getOrganizations()
}
@Test
fun presentOcrScansTest() {
presenter.subscribe()
verify(view).presentOcrScans(5)
}
@Test
fun presentSubscriptions() {
val subscriptions = listOf(RemoteSubscription(45, InAppPurchase.SmartReceiptsPlus, Date()))
whenever(interactor.getSubscriptionsStream()).thenReturn(Observable.just(subscriptions))
presenter.subscribe()
verify(view).presentSubscriptions(subscriptions)
}
@Test
fun applySettingsClickTest() {
whenever(view.applySettingsClicks).thenReturn(Observable.just(organizationModel))
presenter.subscribe()
verify(interactor).applyOrganizationSettings(organizationModel.organization)
}
@Test
fun uploadSettingsClickTest() {
whenever(view.uploadSettingsClicks).thenReturn(Observable.just(organizationModel))
presenter.subscribe()
verify(interactor).uploadOrganizationSettings(organizationModel.organization)
}
} | agpl-3.0 |
paplorinc/intellij-community | platform/diff-impl/src/com/intellij/diff/editor/DiffEditorProvider.kt | 1 | 1926 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.editor
import com.intellij.openapi.fileEditor.AsyncFileEditorProvider
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorPolicy
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
class DiffEditorProvider : AsyncFileEditorProvider, DumbAware {
override fun accept(project: Project, file: VirtualFile): Boolean {
return file is DiffVirtualFile
}
override fun createEditorAsync(project: Project, file: VirtualFile): AsyncFileEditorProvider.Builder {
val builder = (file as DiffVirtualFile).createProcessorAsync(project)
return object : AsyncFileEditorProvider.Builder() {
override fun build() = DiffRequestProcessorEditor(file, builder.build())
}
}
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
val builder = (file as DiffVirtualFile).createProcessorAsync(project)
return DiffRequestProcessorEditor(file, builder.build())
}
override fun disposeEditor(editor: FileEditor) {
Disposer.dispose(editor)
}
override fun getEditorTypeId(): String = "DiffEditor"
override fun getPolicy(): FileEditorPolicy = FileEditorPolicy.HIDE_DEFAULT_EDITOR
}
| apache-2.0 |
vitaliy555/stdkotlin | src/ii_collections/_15_AllAnyAndOtherPredicates.kt | 1 | 1212 | 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.city==city }
}
fun Shop.hasCustomerFrom(city: City): Boolean {
// Return true if there is at least one customer from the given city
// todoCollectionTask()
return this.customers.any { it.city==city}
}
fun Shop.countCustomersFrom(city: City): Int {
// Return the number of customers from the given city
// todoCollectionTask()
return this.customers.count { it.city==city }
}
fun Shop.findAnyCustomerFrom(city: City): Customer? {
// Return a customer who lives in the given city, or null if there is none
// todoCollectionTask()
return this.customers.firstOrNull { it.city==city }
}
| mit |
ssseasonnn/RxDownload | rxdownload4/src/main/java/zlc/season/rxdownload4/storage/Storage.kt | 1 | 181 | package zlc.season.rxdownload4.storage
import zlc.season.rxdownload4.task.Task
interface Storage {
fun load(task: Task)
fun save(task: Task)
fun delete(task: Task)
} | apache-2.0 |
breandan/idear | src/main/java/org/openasr/idear/actions/recognition/FindUsagesActionRecognizer.kt | 2 | 2753 | package org.openasr.idear.actions.recognition
import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.psi.PsiElement
import com.intellij.usages.*
import org.openasr.idear.ide.IDEService
import org.openasr.idear.psi.PsiUtil.findContainingClass
import org.openasr.idear.psi.PsiUtil.findElementUnderCaret
import org.openasr.idear.tts.TTSService
import java.util.*
//runs only selected configuration
class FindUsagesActionRecognizer : ActionRecognizer {
override fun isMatching(sentence: String) = "find" in sentence
override fun getActionInfo(sentence: String, dataContext: DataContext): ActionCallInfo {
val aci = ActionCallInfo("FindUsages")
// Ok, that's lame
val words = listOf(*sentence.split("\\W+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
val wordsSet = HashSet(words)
val editor = IDEService.getEditor(dataContext)
val project = IDEService.getProject(dataContext)
if (editor == null || project == null) return aci
val klass = editor.findElementUnderCaret()!!.findContainingClass() ?: return aci
var targets = arrayOf<PsiElement>()
var targetName: String? = null
var subject: String? = null
if ("field" in wordsSet) {
subject = "field"
targetName = extractNameOf("field", words)
if (targetName.isEmpty()) return aci
targets = arrayOf(klass.findFieldByName(targetName, /*checkBases*/ true)!!)
} else if ("method" in wordsSet) {
subject = "method"
targetName = extractNameOf("method", words)
if (targetName.isEmpty()) return aci
targets = arrayOf(*klass.findMethodsByName(targetName, /*checkBases*/ true))
}
// TODO(kudinkin): need to cure this pain someday
aci.actionEvent = AnActionEvent(null,
SimpleDataContext.getSimpleContext(UsageView.USAGE_TARGETS_KEY.name, prepare(targets[0]), dataContext),
ActionPlaces.UNKNOWN, Presentation(), ActionManager.getInstance(), 0)
// TODO(kudinkin): move it to appropriate place
TTSService.say("Looking for usages of the $subject $targetName")
return aci
}
private fun prepare(target: PsiElement): Array<UsageTarget> = arrayOf(PsiElement2UsageTargetAdapter(target))
private fun extractNameOf(pivot: String, sentence: List<String>): String {
val target = StringBuilder()
for (i in sentence.indexOf(pivot) + 1 until sentence.size) {
target.append(sentence[i])
}
return target.toString()
}
}
| apache-2.0 |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/map/LoadGeoJsonFeaturesUseCase.kt | 1 | 2554 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.map
import android.content.Context
import android.text.TextUtils
import com.google.android.gms.maps.GoogleMap
import com.google.maps.android.data.geojson.GeoJsonFeature
import com.google.maps.android.data.geojson.GeoJsonLayer
import com.google.maps.android.ktx.utils.geojson.geoJsonLayer
import com.google.samples.apps.iosched.shared.di.IoDispatcher
import com.google.samples.apps.iosched.shared.domain.UseCase
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import javax.inject.Inject
/** Parameters for this use case. */
typealias LoadGeoJsonParams = Pair<GoogleMap, Int>
/** Data loaded by this use case. */
data class GeoJsonData(
val geoJsonLayer: GeoJsonLayer,
val featureMap: Map<String, GeoJsonFeature>
)
/** Use case that loads a GeoJsonLayer and its features. */
class LoadGeoJsonFeaturesUseCase @Inject constructor(
@ApplicationContext private val context: Context,
@IoDispatcher dispatcher: CoroutineDispatcher
) : UseCase<LoadGeoJsonParams, GeoJsonData>(dispatcher) {
override suspend fun execute(parameters: LoadGeoJsonParams): GeoJsonData {
val (googleMap, markersRes) = parameters
val layer = geoJsonLayer(
map = googleMap,
resourceId = markersRes,
context = context
)
processGeoJsonLayer(layer, context)
return GeoJsonData(layer, buildFeatureMap(layer))
}
private fun buildFeatureMap(layer: GeoJsonLayer): Map<String, GeoJsonFeature> {
val featureMap: MutableMap<String, GeoJsonFeature> = mutableMapOf()
layer.features.forEach {
val id = it.id
if (!TextUtils.isEmpty(id)) {
// Marker can map to multiple room IDs
for (part in id.split(",")) {
featureMap[part] = it
}
}
}
return featureMap
}
}
| apache-2.0 |
StephaneBg/ScoreIt | app/src/main/kotlin/com/sbgapps/scoreit/app/ui/edition/universal/UniversalEditionAdapter.kt | 1 | 2360 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.app.ui.edition.universal
import com.google.android.material.button.MaterialButton
import com.sbgapps.scoreit.app.R
import com.sbgapps.scoreit.app.databinding.ListItemEditionUniversalBinding
import com.sbgapps.scoreit.core.widget.BaseViewHolder
import com.sbgapps.scoreit.core.widget.ItemAdapter
import com.sbgapps.scoreit.data.model.Player
class UniversalEditionAdapter(
val player: Player,
val score: Int,
private val incrementCallback: (Int, Int) -> Unit,
private val inputCallback: (Int) -> Unit
) : ItemAdapter(R.layout.list_item_edition_universal) {
private lateinit var binding: ListItemEditionUniversalBinding
override fun onBindViewHolder(viewHolder: BaseViewHolder) {
binding = ListItemEditionUniversalBinding.bind(viewHolder.itemView)
binding.name.apply {
text = player.name
setTextColor(player.color)
}
val position = viewHolder.adapterPosition
initButton(binding.pointsPlusOne, position, 1)
initButton(binding.pointsPlusFive, position, 5)
initButton(binding.pointsPlusTen, position, 10)
initButton(binding.pointsPlusHundred, position, 100)
initButton(binding.pointsMinusOne, position, -1)
initButton(binding.pointsMinusFive, position, -5)
initButton(binding.pointsMinusTen, position, -10)
initButton(binding.pointsMinusHundred, position, -100)
binding.score.apply {
text = score.toString()
setOnClickListener { inputCallback(position) }
}
}
private fun initButton(button: MaterialButton, position: Int, increment: Int) {
button.setOnClickListener {
incrementCallback(position, increment)
}
}
}
| apache-2.0 |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/ir/OperationBasedModelGroupBuilder.kt | 1 | 16804 | package com.apollographql.apollo3.compiler.ir
import com.apollographql.apollo3.api.BPossibleTypes
import com.apollographql.apollo3.api.BTerm
import com.apollographql.apollo3.api.BVariable
import com.apollographql.apollo3.api.BooleanExpression
import com.apollographql.apollo3.api.and
import com.apollographql.apollo3.ast.GQLField
import com.apollographql.apollo3.ast.GQLFragmentDefinition
import com.apollographql.apollo3.ast.GQLFragmentSpread
import com.apollographql.apollo3.ast.GQLInlineFragment
import com.apollographql.apollo3.ast.GQLNamedType
import com.apollographql.apollo3.ast.GQLNonNullType
import com.apollographql.apollo3.ast.GQLSelection
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.ast.transformation.mergeTrivialInlineFragments
import com.apollographql.apollo3.compiler.capitalizeFirstLetter
import com.apollographql.apollo3.compiler.codegen.CodegenLayout.Companion.lowerCamelCaseIgnoringNonLetters
import com.apollographql.apollo3.compiler.codegen.CodegenLayout.Companion.modelName
import com.apollographql.apollo3.compiler.decapitalizeFirstLetter
import com.apollographql.apollo3.compiler.escapeKotlinReservedWord
internal class OperationBasedModelGroupBuilder(
private val schema: Schema,
private val allFragmentDefinitions: Map<String, GQLFragmentDefinition>,
private val fieldMerger: FieldMerger,
private val compat: Boolean
) : ModelGroupBuilder {
private val insertFragmentSyntheticField = compat
private val collectAllInlineFragmentFields = compat
private val mergeTrivialInlineFragments = compat
private fun resolveNameClashes(usedNames: MutableSet<String>, modelName: String): String {
if (!compat) {
return modelName
}
var i = 0
var name = modelName
while (usedNames.contains(name)) {
i++
name = "$modelName$i"
}
usedNames.add(name)
return name
}
override fun buildOperationData(selections: List<GQLSelection>, rawTypeName: String, operationName: String): IrModelGroup {
val info = IrFieldInfo(
responseName = "data",
description = null,
type = IrNonNullType(IrModelType(MODEL_UNKNOWN)),
deprecationReason = null,
gqlType = GQLNonNullType(type = GQLNamedType(name = rawTypeName))
)
val mergedSelections = if (mergeTrivialInlineFragments) {
selections.mergeTrivialInlineFragments(schema, rawTypeName)
} else {
selections
}
val usedNames = mutableSetOf<String>()
return buildField(
path = "${MODEL_OPERATION_DATA}.$operationName",
info = info,
selections = mergedSelections.map { SelectionWithParent(it, rawTypeName) },
condition = BooleanExpression.True,
usedNames = usedNames,
).toModelGroup()!!
}
override fun buildFragmentInterface(fragmentName: String): IrModelGroup? {
return null
}
override fun buildFragmentData(fragmentName: String): IrModelGroup {
val fragmentDefinition = allFragmentDefinitions[fragmentName]!!
/**
* XXX: because we want the model to be named after the fragment (and not data), we use
* fragmentName below. This means the id for the very first model is going to be
* FragmentName.FragmentName unlike operations where it's OperationName.Data
*/
val info = IrFieldInfo(
responseName = fragmentName,
description = null,
type = IrNonNullType(IrModelType(MODEL_UNKNOWN)),
deprecationReason = null,
gqlType = GQLNonNullType(type = fragmentDefinition.typeCondition)
)
val mergedSelections = if (mergeTrivialInlineFragments) {
fragmentDefinition.selectionSet.selections.mergeTrivialInlineFragments(schema, fragmentDefinition.typeCondition.name)
} else {
fragmentDefinition.selectionSet.selections
}
val usedNames = mutableSetOf<String>()
return buildField(
path = "${MODEL_FRAGMENT_DATA}.$fragmentName",
info = info,
selections = mergedSelections.map { SelectionWithParent(it, fragmentDefinition.typeCondition.name) },
condition = BooleanExpression.True,
usedNames = usedNames,
).toModelGroup()!!
}
/**
* A grouping key for fragments
*/
private data class InlineFragmentKey(val typeCondition: String, val condition: BooleanExpression<BVariable>)
private fun BooleanExpression<BVariable>.toName(): String = when (this) {
is BooleanExpression.True -> "True"
is BooleanExpression.False -> "False"
is BooleanExpression.And -> this.operands.joinToString("And") { it.toName() }
is BooleanExpression.Or -> this.operands.joinToString("Or") { it.toName() }
is BooleanExpression.Not -> "Not${this.operand.toName()}"
is BooleanExpression.Element -> this.value.name.capitalizeFirstLetter()
else -> error("")
}
private fun InlineFragmentKey.toName(): String = buildString {
append(typeCondition.capitalizeFirstLetter())
if (condition != BooleanExpression.True) {
append("If")
append(condition.toName())
}
}
private class SelectionWithParent(val selection: GQLSelection, val parent: String)
/**
* @param kind the [IrKind] used to identify the resulting model
* @param path the path up to but not including this field
* @param info information about this field
* @param selections the sub-selections of this fields. If [collectAllInlineFragmentFields] is true, might contain parent fields that
* might not all be on the same parent type. Hence [SelectionWithParent]
* @param condition the condition for this field. Might be a mix of include directives and type conditions
* @param usedNames the used names for 2.x compat name conflicts resolution
* @param modelName the modelName to use for this field
*/
private fun buildField(
path: String,
info: IrFieldInfo,
selections: List<SelectionWithParent>,
condition: BooleanExpression<BTerm>,
usedNames: MutableSet<String>,
): OperationField {
if (selections.isEmpty()) {
return OperationField(
info = info,
condition = condition,
fieldSet = null,
hide = false,
)
}
val selfPath = path + "." + info.responseName
/**
* Merge fragments with the same type condition and include directive to avoid name clashes
*
* We don't merge inline fragments with different include directives as nested fields would all have to become nullable:
*
* ```
* {
* ... on Droid @include(if: $a) {
* primaryFunction
* friend {
* firstName
* }
* }
* ... on Droid @include(if: $b) {
* friend {
* lastName
* }
* }
* }
* ```
*
* Merging these would yield
*
* ```
* class onDroid(val primaryFunction: String?, val friend: Friend)
* class Friend(val firstName: String?, val lastName: String?)
* ```
*
* While this is technically doable, it goes against mapping to the operation 1:1 and also makes invalid states representable
* (for an example both firstName = null and lastName = null)
*
*/
val inlineFragmentsFields = selections.filter { it.selection is GQLInlineFragment }
.groupBy {
(it.selection as GQLInlineFragment).typeCondition.name
}.entries.flatMap {
val typeCondition = it.key
// If there is only one fragment, no need to disambiguate it
val nameNeedsCondition = it.value.size > 1
val inlineFragmentsWithSameTypeCondition = it.value.map { it.selection as GQLInlineFragment }
/**
* Because fragments are not merged regardless of [collectAllInlineFragmentFields], all inline fragments
* should have the same parentType here
*/
val parentTypeCondition = it.value.first().parent
inlineFragmentsWithSameTypeCondition.groupBy { it.directives.toBooleanExpression() }
.entries.map { entry ->
val prefix = if (collectAllInlineFragmentFields) "as" else "on"
val name = if (nameNeedsCondition) {
InlineFragmentKey(typeCondition, entry.key).toName()
} else {
InlineFragmentKey(typeCondition, BooleanExpression.True).toName()
}
val possibleTypes = schema.possibleTypes(typeCondition)
var childCondition: BooleanExpression<BTerm> = if (typeCondition == parentTypeCondition) {
BooleanExpression.True
} else {
BooleanExpression.Element(BPossibleTypes(possibleTypes))
}
childCondition = entry.key.and(childCondition).simplify()
var type: IrType = IrModelType(MODEL_UNKNOWN)
if (childCondition == BooleanExpression.True) {
type = IrNonNullType(type)
}
val childInfo = IrFieldInfo(
responseName = "$prefix$name",
description = "Synthetic field for inline fragment on $typeCondition",
deprecationReason = null,
type = type,
gqlType = null
)
var childSelections = entry.value.flatMap {
it.selectionSet.selections.map { SelectionWithParent(it, typeCondition) }
}
if (collectAllInlineFragmentFields) {
childSelections = selections.filter { it.selection is GQLField } + childSelections
}
buildField(
path = selfPath,
info = childInfo,
selections = childSelections,
condition = childCondition,
usedNames = usedNames,
)
}
}
/**
* Merge fragment spreads, regardless of the type condition
*
* Since they all have the same shape, it's ok, contrary to inline fragments above
*/
val fragmentSpreadFields = selections.filter { it.selection is GQLFragmentSpread }
.groupBy {
(it.selection as GQLFragmentSpread).name
}.values.map { values ->
val fragmentSpreadsWithSameName = values.map { it.selection as GQLFragmentSpread }
val first = fragmentSpreadsWithSameName.first()
val fragmentDefinition = allFragmentDefinitions[first.name]!!
val typeCondition = fragmentDefinition.typeCondition.name
/**
* Because fragments are not merged regardless of [collectAllInlineFragmentFields], all inline fragments
* should have the same parentType here
*/
val parentTypeCondition = values.first().parent
val possibleTypes = schema.possibleTypes(typeCondition)
var childCondition: BooleanExpression<BTerm> = if (typeCondition != parentTypeCondition) {
BooleanExpression.Element(BPossibleTypes(possibleTypes))
} else {
BooleanExpression.True
}
/**
* That's more involved than the inline fragment case because fragment spreads have different @include/@skip directives get merged together
*/
childCondition = BooleanExpression.Or(fragmentSpreadsWithSameName.map { it.directives.toBooleanExpression() }.toSet())
.simplify()
.and(childCondition)
.simplify()
val fragmentModelPath = "${MODEL_FRAGMENT_DATA}.${first.name}.${first.name}"
var type: IrType = IrModelType(fragmentModelPath)
if (childCondition == BooleanExpression.True) {
type = IrNonNullType(type)
}
val childInfo = IrFieldInfo(
responseName = first.name.decapitalizeFirstLetter().escapeKotlinReservedWord(),
description = "Synthetic field for '${first.name}'",
deprecationReason = null,
type = type,
gqlType = null
)
val p = if (insertFragmentSyntheticField) {
"$selfPath.$FRAGMENTS_SYNTHETIC_FIELD"
} else {
selfPath
}
buildField(
path = p,
info = childInfo,
selections = emptyList(), // Don't create a model for fragments spreads
condition = childCondition,
usedNames = usedNames,
)
}
/**
* Add the "Fragments" synthetic field for compat codegen
*/
val fragmentsFields = if (insertFragmentSyntheticField && fragmentSpreadFields.isNotEmpty()) {
val childPath = "$selfPath.$FRAGMENTS_SYNTHETIC_FIELD"
val fragmentsFieldInfo = IrFieldInfo(
responseName = FRAGMENTS_SYNTHETIC_FIELD,
description = "Synthetic field for grouping fragments",
deprecationReason = null,
type = IrNonNullType(IrModelType(childPath)),
gqlType = null
)
val fragmentsFieldSet = OperationFieldSet(
id = childPath,
// No need to resolve the nameclashes here, "Fragments" are never flattened
modelName = modelName(fragmentsFieldInfo),
fields = listOf(hiddenTypenameField) + fragmentSpreadFields
)
listOf(
OperationField(
info = fragmentsFieldInfo,
condition = BooleanExpression.True,
fieldSet = fragmentsFieldSet,
hide = false
)
)
} else {
fragmentSpreadFields
}
val modelName = resolveNameClashes(usedNames, modelName(info))
/**
* Merge fields with the same response name in the selectionSet
* This comes last so that it mimics the 2.x behaviour of nameclash resolution
*/
val fieldsWithParent = selections.mapNotNull {
if (it.selection is GQLField) {
FieldWithParent(it.selection, it.parent)
} else {
null
}
}
val fields = fieldMerger.merge(fieldsWithParent).map { mergedField ->
val childInfo = mergedField.info.maybeNullable(mergedField.condition != BooleanExpression.True)
buildField(
path = selfPath,
info = childInfo,
selections = mergedField.selections.map { SelectionWithParent(it, mergedField.rawTypeName) },
condition = BooleanExpression.True,
usedNames = usedNames,
)
}
val fieldSet = OperationFieldSet(
id = selfPath,
modelName = modelName,
fields = fields + inlineFragmentsFields + fragmentsFields
)
val patchedInfo = info.copy(
type = info.type.replacePlaceholder(fieldSet.id),
responseName = if (info.gqlType == null) {
lowerCamelCaseIgnoringNonLetters(setOf(modelName))
} else {
info.responseName
}
)
return OperationField(
info = patchedInfo,
condition = condition,
fieldSet = fieldSet,
hide = false
)
}
companion object {
const val FRAGMENTS_SYNTHETIC_FIELD = "fragments"
private val hiddenTypenameField by lazy {
val info = IrFieldInfo(
responseName = "__typename",
description = null,
deprecationReason = null,
type = IrNonNullType(IrScalarType("String")),
gqlType = GQLNamedType(name = "String")
)
OperationField(
info = info,
condition = BooleanExpression.True,
fieldSet = null,
hide = true
)
}
}
}
private class OperationField(
val info: IrFieldInfo,
val condition: BooleanExpression<BTerm>,
val fieldSet: OperationFieldSet?,
val hide: Boolean,
) {
val isSynthetic: Boolean
get() = info.gqlType == null
}
private data class OperationFieldSet(
val id: String,
val modelName: String,
val fields: List<OperationField>,
)
private fun OperationField.toModelGroup(): IrModelGroup? {
if (fieldSet == null) {
return null
}
val model = fieldSet.toModel()
return IrModelGroup(
models = listOf(model),
baseModelId = model.id
)
}
private fun OperationFieldSet.toModel(): IrModel {
return IrModel(
modelName = modelName,
id = id,
properties = fields.map { it.toProperty() },
accessors = emptyList(),
implements = emptyList(),
isFallback = false,
isInterface = false,
modelGroups = fields.mapNotNull { it.toModelGroup() },
possibleTypes = emptySet(),
typeSet = emptySet(),
)
}
private fun OperationField.toProperty(): IrProperty {
return IrProperty(
info = info,
override = false,
condition = condition,
requiresBuffering = fieldSet?.fields?.any { it.isSynthetic } ?: false,
hidden = hide
)
}
| mit |
SimpleMobileTools/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/models/Medium.kt | 1 | 3980 | package com.simplemobiletools.gallery.pro.models
import android.content.Context
import androidx.room.*
import com.bumptech.glide.signature.ObjectKey
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.gallery.pro.helpers.*
import java.io.File
import java.io.Serializable
import java.util.*
@Entity(tableName = "media", indices = [(Index(value = ["full_path"], unique = true))])
data class Medium(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "filename") var name: String,
@ColumnInfo(name = "full_path") var path: String,
@ColumnInfo(name = "parent_path") var parentPath: String,
@ColumnInfo(name = "last_modified") var modified: Long,
@ColumnInfo(name = "date_taken") var taken: Long,
@ColumnInfo(name = "size") var size: Long,
@ColumnInfo(name = "type") var type: Int,
@ColumnInfo(name = "video_duration") var videoDuration: Int,
@ColumnInfo(name = "is_favorite") var isFavorite: Boolean,
@ColumnInfo(name = "deleted_ts") var deletedTS: Long,
@ColumnInfo(name = "media_store_id") var mediaStoreId: Long,
@Ignore var gridPosition: Int = 0 // used at grid view decoration at Grouping enabled
) : Serializable, ThumbnailItem() {
constructor() : this(null, "", "", "", 0L, 0L, 0L, 0, 0, false, 0L, 0L, 0)
companion object {
private const val serialVersionUID = -6553149366975655L
}
fun isWebP() = name.isWebP()
fun isGIF() = type == TYPE_GIFS
fun isImage() = type == TYPE_IMAGES
fun isVideo() = type == TYPE_VIDEOS
fun isRaw() = type == TYPE_RAWS
fun isSVG() = type == TYPE_SVGS
fun isPortrait() = type == TYPE_PORTRAITS
fun isApng() = name.isApng()
fun isHidden() = name.startsWith('.')
fun isHeic() = name.toLowerCase().endsWith(".heic") || name.toLowerCase().endsWith(".heif")
fun getBubbleText(sorting: Int, context: Context, dateFormat: String, timeFormat: String) = when {
sorting and SORT_BY_NAME != 0 -> name
sorting and SORT_BY_PATH != 0 -> path
sorting and SORT_BY_SIZE != 0 -> size.formatSize()
sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate(context, dateFormat, timeFormat)
sorting and SORT_BY_RANDOM != 0 -> name
else -> taken.formatDate(context)
}
fun getGroupingKey(groupBy: Int): String {
return when {
groupBy and GROUP_BY_LAST_MODIFIED_DAILY != 0 -> getDayStartTS(modified, false)
groupBy and GROUP_BY_LAST_MODIFIED_MONTHLY != 0 -> getDayStartTS(modified, true)
groupBy and GROUP_BY_DATE_TAKEN_DAILY != 0 -> getDayStartTS(taken, false)
groupBy and GROUP_BY_DATE_TAKEN_MONTHLY != 0 -> getDayStartTS(taken, true)
groupBy and GROUP_BY_FILE_TYPE != 0 -> type.toString()
groupBy and GROUP_BY_EXTENSION != 0 -> name.getFilenameExtension().toLowerCase()
groupBy and GROUP_BY_FOLDER != 0 -> parentPath
else -> ""
}
}
fun getIsInRecycleBin() = deletedTS != 0L
private fun getDayStartTS(ts: Long, resetDays: Boolean): String {
val calendar = Calendar.getInstance(Locale.ENGLISH).apply {
timeInMillis = ts
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
if (resetDays) {
set(Calendar.DAY_OF_MONTH, 1)
}
}
return calendar.timeInMillis.toString()
}
fun getSignature(): String {
val lastModified = if (modified > 1) {
modified
} else {
File(path).lastModified()
}
return "$path-$lastModified-$size"
}
fun getKey() = ObjectKey(getSignature())
fun toFileDirItem() = FileDirItem(path, name, false, 0, size, modified, mediaStoreId)
}
| gpl-3.0 |
aquatir/remember_java_api | code-sample-kotlin/spring-boot/code-sample-kotlin-graphql/src/main/kotlin/codesample/kotlin/graphql/repository/CartRepository.kt | 1 | 272 | package codesample.kotlin.graphql.repository
import codesample.kotlin.graphql.entitry.Cart
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface CartRepository: JpaRepository<Cart, Long> {
}
| mit |
HITGIF/SchoolPower | app/src/main/java/com/carbonylgroup/schoolpower/data/SortableTerm.kt | 1 | 848 | /**
* Copyright (C) 2019 SchoolPower Studio
*/
package com.carbonylgroup.schoolpower.data
class SortableTerm(raw: String) {
private var raw: String = ""
private var letter: String = ""
private var index: Int = 0
init {
this.raw = raw
this.letter = raw.substring(0, 1)
this.index = raw.substring(1, 2).toInt()
}
fun getValue(): Int {
return valueOfLetter(letter) * index
}
fun getRaw(): String {
return raw
}
private fun valueOfLetter(letter: String): Int {
// This is so that S1 > T4/Q4, Y1 > S2, X1 > Y1
// Don't know what's X, assume it's greater than Y here :P
return when (letter) {
"T" -> 1
"Q" -> 1
"S" -> 5
"Y" -> 11
"X" -> 12
else -> 0
}
}
}
| apache-2.0 |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/feed/EditFeedDialog.kt | 1 | 4107 | package com.nononsenseapps.feeder.ui.compose.feed
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeightIn
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.nononsenseapps.feeder.R
import com.nononsenseapps.feeder.ui.compose.deletefeed.DeletableFeed
import com.nononsenseapps.feeder.ui.compose.minimumTouchSize
import com.nononsenseapps.feeder.ui.compose.theme.FeederTheme
import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder
import com.nononsenseapps.feeder.ui.compose.utils.PreviewThemes
import com.nononsenseapps.feeder.ui.compose.utils.immutableListHolderOf
@Composable
fun EditFeedDialog(
feeds: ImmutableHolder<List<DeletableFeed>>,
onDismiss: () -> Unit,
onEdit: (Long) -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
confirmButton = {
// Button(onClick = onOk) {
// Text(text = stringResource(id = R.string.ok))
// }
},
dismissButton = {
Button(onClick = onDismiss) {
Text(text = stringResource(id = android.R.string.cancel))
}
},
title = {
Text(
text = stringResource(id = R.string.edit_feed),
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
modifier = Modifier
.padding(vertical = 8.dp)
)
},
text = {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
) {
items(feeds.item) { feed ->
Row(
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.requiredHeightIn(min = minimumTouchSize)
.clickable {
onEdit(feed.id)
onDismiss()
}
.semantics(mergeDescendants = true) {}
) {
RadioButton(
selected = false,
onClick = {
onEdit(feed.id)
onDismiss()
},
modifier = Modifier.clearAndSetSemantics { }
)
Spacer(modifier = Modifier.width(32.dp))
Text(
text = feed.title,
style = MaterialTheme.typography.titleMedium
)
}
}
}
}
)
}
@Composable
@PreviewThemes
private fun preview() {
FeederTheme {
EditFeedDialog(
feeds = immutableListHolderOf(
DeletableFeed(1, "A Feed"),
DeletableFeed(2, "Another Feed")
),
onDismiss = {},
onEdit = {}
)
}
}
| gpl-3.0 |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/banner/BannerFeature.kt | 1 | 704 | package org.stepik.android.presentation.banner
import org.stepik.android.domain.banner.model.Banner
interface BannerFeature {
sealed class State {
object Idle : State()
object Loading : State()
object Empty : State()
data class Content(val banners: List<Banner>) : State()
}
sealed class Message {
data class InitMessage(
val screen: Banner.Screen,
val forceUpdate: Boolean = false
) : Message()
object BannersError : Message()
data class BannersResult(val banners: List<Banner>) : Message()
}
sealed class Action {
data class LoadBanners(val screen: Banner.Screen) : Action()
}
} | apache-2.0 |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/typedescriptor/predefined/PredefinedDescriptionTypeDescriptor.kt | 1 | 713 | package com.aemtools.analysis.htl.callchain.typedescriptor.predefined
import com.aemtools.analysis.htl.callchain.typedescriptor.base.BaseTypeDescriptor
import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor
import com.aemtools.completion.htl.predefined.PredefinedCompletion
import com.intellij.codeInsight.lookup.LookupElement
/**
* @author Dmytro Troynikov
*/
class PredefinedDescriptionTypeDescriptor(val predefined: PredefinedCompletion) : BaseTypeDescriptor() {
override fun myVariants(): List<LookupElement> = emptyList()
override fun subtype(identifier: String): TypeDescriptor = TypeDescriptor.empty()
override fun documentation(): String? = predefined.documentation
}
| gpl-3.0 |
ursjoss/sipamato | public/public-web/src/test/kotlin/ch/difty/scipamato/publ/web/common/BasePanelTest.kt | 2 | 873 | package ch.difty.scipamato.publ.web.common
import ch.difty.scipamato.common.web.Mode
import ch.difty.scipamato.publ.web.WicketTest
import org.amshove.kluent.shouldBeEqualTo
import org.apache.wicket.model.Model
import org.junit.jupiter.api.Test
class BasePanelTest : WicketTest() {
private lateinit var panel: BasePanel<String>
@Test
fun instantiatingWithIdOnly() {
panel = object : BasePanel<String>("panel") {}
panel.localization shouldBeEqualTo "en_us"
}
@Test
fun instantiatingWithIdAndModel() {
panel = object : BasePanel<String>("panel", Model.of("foo")) {}
panel.localization shouldBeEqualTo "en_us"
}
@Test
fun instantiatingWithIdAndModelAndMode() {
panel = object : BasePanel<String>("panel", Model.of("foo"), Mode.EDIT) {}
panel.localization shouldBeEqualTo "en_us"
}
}
| gpl-3.0 |
square/okio | okio/src/nonJvmMain/kotlin/okio/BufferedSink.kt | 1 | 1822 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
actual sealed interface BufferedSink : Sink {
actual val buffer: Buffer
actual fun write(byteString: ByteString): BufferedSink
actual fun write(byteString: ByteString, offset: Int, byteCount: Int): BufferedSink
actual fun write(source: ByteArray): BufferedSink
actual fun write(source: ByteArray, offset: Int, byteCount: Int): BufferedSink
actual fun writeAll(source: Source): Long
actual fun write(source: Source, byteCount: Long): BufferedSink
actual fun writeUtf8(string: String): BufferedSink
actual fun writeUtf8(string: String, beginIndex: Int, endIndex: Int): BufferedSink
actual fun writeUtf8CodePoint(codePoint: Int): BufferedSink
actual fun writeByte(b: Int): BufferedSink
actual fun writeShort(s: Int): BufferedSink
actual fun writeShortLe(s: Int): BufferedSink
actual fun writeInt(i: Int): BufferedSink
actual fun writeIntLe(i: Int): BufferedSink
actual fun writeLong(v: Long): BufferedSink
actual fun writeLongLe(v: Long): BufferedSink
actual fun writeDecimalLong(v: Long): BufferedSink
actual fun writeHexadecimalUnsignedLong(v: Long): BufferedSink
actual fun emit(): BufferedSink
actual fun emitCompleteSegments(): BufferedSink
}
| apache-2.0 |
allotria/intellij-community | plugins/ide-features-trainer/src/training/learn/course/LessonProperties.kt | 3 | 284 | // 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 training.learn.course
data class LessonProperties(
val canStartInDumbMode: Boolean = false,
val openFileAtStart: Boolean = true,
) | apache-2.0 |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/BuilderContractsTest.kt | 1 | 1366 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
import kotlin.test.*
class BuilderContractsTest : TestBase() {
@Test
fun testContracts() = runTest {
// Coroutine scope
val cs: Int
coroutineScope {
cs = 42
}
consume(cs)
// Supervisor scope
val svs: Int
supervisorScope {
svs = 21
}
consume(svs)
// with context scope
val wctx: Int
withContext(Dispatchers.Unconfined) {
wctx = 239
}
consume(wctx)
val wt: Int
withTimeout(Long.MAX_VALUE) {
wt = 123
}
consume(wt)
val s: Int
select<Unit> {
s = 42
Job().apply { complete() }.onJoin {}
}
consume(s)
val ch: Int
val i = Channel<Int>()
i.consume {
ch = 321
}
consume(ch)
}
private fun consume(a: Int) {
/*
* Verify the value is actually set correctly
* (non-zero, VerificationError is not triggered, can be read)
*/
assertNotEquals(0, a)
assertEquals(a.hashCode(), a)
}
}
| apache-2.0 |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/viewmodel/ClientConnectionViewModel.kt | 1 | 3120 | /*
* 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.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.data.ClientRepository
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.database.model.UClientAddress
import org.monora.uprotocol.client.android.protocol.NoAddressException
import org.monora.uprotocol.core.CommunicationBridge
import org.monora.uprotocol.core.persistence.PersistenceProvider
import org.monora.uprotocol.core.protocol.ConnectionFactory
import javax.inject.Inject
@HiltViewModel
class ClientConnectionViewModel @Inject internal constructor(
val connectionFactory: ConnectionFactory,
val persistenceProvider: PersistenceProvider,
var clientRepository: ClientRepository,
) : ViewModel() {
private var job: Job? = null
val state = MutableLiveData<ConnectionState>()
fun start(client: UClient, address: UClientAddress?): Job = job ?: viewModelScope.launch(Dispatchers.IO) {
val addresses = address?.let { listOf(it.inetAddress) } ?: clientRepository.getAddresses(client.clientUid).map {
it.inetAddress
}
try {
if (addresses.isEmpty()) {
throw NoAddressException()
}
state.postValue(ConnectionState.Connecting())
val bridge = CommunicationBridge.Builder(
connectionFactory, persistenceProvider, addresses
).apply {
setClearBlockedStatus(true)
setClientUid(client.clientUid)
}
state.postValue(ConnectionState.Connected(bridge.connect()))
} catch (e: Exception) {
state.postValue(ConnectionState.Error(e))
} finally {
job = null
}
}.also { job = it }
}
sealed class ConnectionState(val isConnecting: Boolean = false, val isError: Boolean = false) {
class Connected(val bridge: CommunicationBridge) : ConnectionState()
class Error(val e: Exception) : ConnectionState(isError = true)
class Connecting : ConnectionState(isConnecting = true)
} | gpl-2.0 |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/titleLabel/TitlePart.kt | 1 | 783 | // 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.wm.impl.customFrameDecorations.header.titleLabel
import java.awt.FontMetrics
import javax.swing.JComponent
interface TitlePart {
enum class State {
LONG,
MIDDLE,
SHORT,
HIDE,
IGNORED
}
var active: Boolean
val longWidth: Int
val shortWidth: Int
val toolTipPart: String
fun refresh(label: JComponent, fm: FontMetrics)
fun getLong(): String
fun getShort(): String
}
interface BaseTitlePart : TitlePart {
var longText: String
var shortText: String
}
interface ShrinkingTitlePart : TitlePart {
fun shrink(label: JComponent, fm: FontMetrics, maxWidth: Int): String
} | apache-2.0 |
agoda-com/Kakao | sample/src/main/kotlin/com/agoda/sample/DrawableListActivity.kt | 1 | 2208 | package com.agoda.sample
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.ListView
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
class DrawableListActivity : AppCompatActivity() {
val drawableIds = listOf(DrawableResource(R.drawable.ic_android_black_24dp),
DrawableResource(R.drawable.ic_sentiment_very_satisfied_black_24dp),
DrawableResource(R.drawable.ic_android_black_24dp, android.R.color.holo_red_dark))
val list: ListView by lazy { findViewById<ListView>(R.id.drawableList) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_drawable_list)
list.adapter = object : BaseAdapter() {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view: View
val vh = if (convertView != null) {
view = convertView
convertView.tag as ViewHolder
} else {
view = layoutInflater.inflate(R.layout.item_image, null)
ViewHolder(view.findViewById(R.id.imgView)).apply { view.tag = this }
}
drawableIds[position].run {
vh.imageView.setImageResource(resId)
tint?.let {
vh.imageView.setColorFilter(
ContextCompat.getColor(vh.imageView.context, it),
android.graphics.PorterDuff.Mode.SRC_IN)
}
}
return view
}
override fun getItem(position: Int) = drawableIds[position]
override fun getItemId(position: Int) = position.toLong()
override fun getCount() = drawableIds.size
}
}
class ViewHolder(val imageView: ImageView)
data class DrawableResource(@DrawableRes val resId: Int, val tint: Int? = null)
}
| apache-2.0 |
crispab/codekvast | product/server/backoffice/src/main/java/io/codekvast/backoffice/CodekvastBackofficeApplication.kt | 1 | 1753 | /*
* Copyright (c) 2015-2022 Hallin Information Technology AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.codekvast.backoffice
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
import org.springframework.context.annotation.ComponentScan
/**
* The Spring Boot main for codekvast-backoffice,
*
* @author [email protected]
*/
@SpringBootApplication
@ConfigurationPropertiesScan
@ComponentScan(basePackages = ["io.codekvast"])
class CodekvastBackofficeApplication
fun main(args: Array<String>) {
runApplication<CodekvastBackofficeApplication>(*args)
}
| mit |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/gui/ButtonPiece.kt | 1 | 1420 | package net.ndrei.teslacorelib.gui
import net.ndrei.teslacorelib.inventory.BoundingRectangle
/**
* Created by CF on 2017-06-28.
*/
@Suppress("unused")
abstract class ButtonPiece(left: Int, top: Int, width: Int, height: Int) : BasicContainerGuiPiece(left, top, width, height) {
protected abstract fun renderState(container: BasicTeslaGuiContainer<*>, over: Boolean, box: BoundingRectangle)
protected abstract fun clicked()
protected open val isEnabled: Boolean = true
override fun drawForegroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, mouseX: Int, mouseY: Int) {
this.renderState(container, super.isInside(container, mouseX, mouseY),
BoundingRectangle(this.left, this.top, this.width, this.height))
}
override fun mouseClicked(container: BasicTeslaGuiContainer<*>, mouseX: Int, mouseY: Int, mouseButton: Int) {
if (this.isInside(container, mouseX, mouseY) && this.isEnabled) {
this.clicked()
}
}
companion object {
fun drawHoverArea(container: BasicTeslaGuiContainer<*>, piece: IGuiContainerPiece, offset: Int = 0) {
container.drawFilledRect(
container.guiLeft + piece.left + offset,
container.guiTop + piece.top + offset,
piece.width - offset * 2,
piece.height - offset * 2,
0x42FFFFFF)
}
}
}
| mit |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/anonymousObject/kt13182.kt | 3 | 319 | // FILE: 1.kt
package test
inline fun test(cond: Boolean, crossinline cif: () -> String): String {
return if (cond) {
{ cif() }()
}
else {
cif()
}
}
// FILE: 2.kt
import test.*
fun box(): String {
val s = "OK"
return test(true) {
{
s
}()
}
}
| apache-2.0 |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/inventory/FluidTank.kt | 1 | 461 | package net.ndrei.teslacorelib.inventory
import net.minecraft.nbt.NBTTagCompound
/**
* Created by CF on 2017-06-28.
*/
open class FluidTank(capacity: Int)
: net.minecraftforge.fluids.FluidTank(capacity), ISerializableFluidTank {
override fun serializeNBT(): NBTTagCompound {
val nbt = NBTTagCompound()
return super.writeToNBT(nbt)
}
override fun deserializeNBT(nbt: NBTTagCompound) {
super.readFromNBT(nbt)
}
}
| mit |
JuliusKunze/kotlin-native | backend.native/tests/codegen/lateinit/notInitialized.kt | 1 | 299 | package codegen.lateinit.notInitialized
import kotlin.test.*
class A {
lateinit var s: String
fun foo() = s
}
@Test fun runTest() {
val a = A()
try {
println(a.foo())
}
catch (e: RuntimeException) {
println("OK")
return
}
println("Fail")
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/labels/controlLabelClashesWithFuncitonName.kt | 5 | 329 | fun test1(): Boolean {
test1@ for(i in 1..2) {
continue@test1
return false
}
return true
}
fun test2(): Boolean {
test2@ while (true) {
break@test2
}
return true
}
fun box(): String {
if (!test1()) return "fail test1"
if (!test2()) return "fail test2"
return "OK"
} | apache-2.0 |
samirma/MeteoriteLandings | app/src/main/java/com/antonio/samir/meteoritelandingsspots/service/AddressService.kt | 1 | 3919 | package com.antonio.samir.meteoritelandingsspots.service
import android.util.Log
import com.antonio.samir.meteoritelandingsspots.data.Result
import com.antonio.samir.meteoritelandingsspots.data.local.MeteoriteLocalRepository
import com.antonio.samir.meteoritelandingsspots.data.repository.model.Meteorite
import com.antonio.samir.meteoritelandingsspots.util.DefaultDispatcherProvider
import com.antonio.samir.meteoritelandingsspots.util.DispatcherProvider
import com.antonio.samir.meteoritelandingsspots.util.GeoLocationUtilInterface
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
import org.apache.commons.lang3.StringUtils
import java.util.*
/**
* Evaluate convert this class to work manager
*/
@ExperimentalCoroutinesApi
class AddressService(
private val meteoriteLocalRepository: MeteoriteLocalRepository,
private val geoLocationUtil: GeoLocationUtilInterface,
private val dispatchers: DispatcherProvider = DefaultDispatcherProvider()
) : AddressServiceInterface {
private val TAG = AddressService::class.java.simpleName
override fun recoveryAddress(): Flow<Result<Float>> = meteoriteLocalRepository.meteoritesWithOutAddress()
.onEach { recoverAddress(it) }
.flowOn(dispatchers.default())
.map {
getReturn(it)
}
private suspend fun getReturn(it: List<Meteorite>): Result<Float> {
return if (!it.isNullOrEmpty()) {
val meteoritesWithoutAddressCount = meteoriteLocalRepository.getMeteoritesWithoutAddressCount()
val meteoritesCount = meteoriteLocalRepository.getMeteoritesCount()
val progress = (1 - (meteoritesWithoutAddressCount.toFloat() / meteoritesCount)) * 100
Result.InProgress(progress)
} else {
Result.Success(100f)
}
}
private suspend fun recoverAddress(list: List<Meteorite>) = withContext(dispatchers.default()) {
list.onEach { meteorite ->
try {
meteorite.address = getAddressFromMeteorite(meteorite)
} catch (e: Exception) {
Log.e(TAG, "Fail to retrieve address", e)
}
}
meteoriteLocalRepository.updateAll(list)
}
override suspend fun recoverAddress(meteorite: Meteorite) = withContext(dispatchers.default()) {
meteorite.address = getAddressFromMeteorite(meteorite)
meteoriteLocalRepository.update(meteorite)
}
private fun getAddressFromMeteorite(meteorite: Meteorite): String {
val recLat = meteorite.reclat
val recLong = meteorite.reclong
var metAddress = " "
if (recLat != null && recLong != null) {
val address = getAddress(recLat.toDouble(), recLong.toDouble())
metAddress = address ?: " "
}
return metAddress
}
private fun getAddress(recLat: Double, recLong: Double): String? {
var addressString: String? = null
val address = geoLocationUtil.getAddress(recLat, recLong)
if (address != null) {
val finalAddress = ArrayList<String>()
val city = address.locality
if (StringUtils.isNoneEmpty(city)) {
finalAddress.add(city)
}
val state = address.adminArea
if (StringUtils.isNoneEmpty(state)) {
finalAddress.add(state)
}
val countryName = address.countryName
if (StringUtils.isNoneEmpty(countryName)) {
finalAddress.add(countryName)
}
if (finalAddress.isNotEmpty()) {
addressString = finalAddress.joinToString(", ")
}
}
return addressString
}
}
| mit |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/jvmOverloads/generics.kt | 2 | 488 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
// FILE: Test.java
public class Test {
public static String invokeMethodWithOverloads() {
C<String> c = new C<String>();
return c.foo("O");
}
}
// FILE: generics.kt
class C<T> {
@kotlin.jvm.JvmOverloads public fun foo(o: T, k: String = "K"): String = o.toString() + k
}
fun box(): String {
return Test.invokeMethodWithOverloads()
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/ElementAnnotator.kt | 3 | 9081 | // 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.highlighter
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.openapi.util.TextRange
import com.intellij.psi.MultiRangeReference
import com.intellij.psi.PsiElement
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtReferenceExpression
internal class ElementAnnotator(
private val element: PsiElement,
private val shouldSuppressUnusedParameter: (KtParameter) -> Boolean
) {
fun registerDiagnosticsAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) = diagnostics.groupBy { it.factory }
.forEach {
registerSameFactoryDiagnosticsAnnotations(
holder,
it.value,
highlightInfoByDiagnostic,
highlightInfoByTextRange,
noFixes,
calculatingInProgress
)
}
private fun registerSameFactoryDiagnosticsAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) {
val presentationInfo = presentationInfo(diagnostics) ?: return
setUpAnnotations(
holder,
diagnostics,
presentationInfo,
highlightInfoByDiagnostic,
highlightInfoByTextRange,
noFixes,
calculatingInProgress
)
}
fun registerDiagnosticsQuickFixes(
diagnostics: List<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>
) = diagnostics.groupBy { it.factory }
.forEach { registerDiagnosticsSameFactoryQuickFixes(it.value, highlightInfoByDiagnostic) }
private fun registerDiagnosticsSameFactoryQuickFixes(
diagnostics: List<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>
) {
val presentationInfo = presentationInfo(diagnostics) ?: return
val fixesMap = createFixesMap(diagnostics) ?: return
diagnostics.forEach {
val highlightInfo = highlightInfoByDiagnostic[it] ?: return
presentationInfo.applyFixes(fixesMap, it, highlightInfo)
}
}
private fun presentationInfo(diagnostics: Collection<Diagnostic>): AnnotationPresentationInfo? {
if (diagnostics.isEmpty() || !diagnostics.any { it.isValid }) return null
val diagnostic = diagnostics.first()
// hack till the root cause #KT-21246 is fixed
if (isUnstableAbiClassDiagnosticForModulesWithEnabledUnstableAbi(diagnostic)) return null
val factory = diagnostic.factory
assert(diagnostics.all { it.psiElement == element && it.factory == factory })
val ranges = diagnostic.textRanges
val presentationInfo: AnnotationPresentationInfo = when (factory.severity) {
Severity.ERROR -> {
when (factory) {
in Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS -> {
val referenceExpression = element as KtReferenceExpression
val reference = referenceExpression.mainReference
if (reference is MultiRangeReference) {
AnnotationPresentationInfo(
ranges = reference.ranges.map { it.shiftRight(referenceExpression.textOffset) },
highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
)
} else {
AnnotationPresentationInfo(ranges, highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL)
}
}
Errors.ILLEGAL_ESCAPE -> AnnotationPresentationInfo(
ranges, textAttributes = KotlinHighlightingColors.INVALID_STRING_ESCAPE
)
Errors.REDECLARATION -> AnnotationPresentationInfo(
ranges = listOf(diagnostic.textRanges.first()), nonDefaultMessage = ""
)
else -> {
AnnotationPresentationInfo(
ranges,
highlightType = if (factory == Errors.INVISIBLE_REFERENCE)
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
else
null
)
}
}
}
Severity.WARNING -> {
if (factory == Errors.UNUSED_PARAMETER && shouldSuppressUnusedParameter(element as KtParameter)) {
return null
}
AnnotationPresentationInfo(
ranges,
textAttributes = when (factory) {
Errors.DEPRECATION -> CodeInsightColors.DEPRECATED_ATTRIBUTES
Errors.UNUSED_ANONYMOUS_PARAMETER -> CodeInsightColors.WEAK_WARNING_ATTRIBUTES
else -> null
},
highlightType = when (factory) {
in Errors.UNUSED_ELEMENT_DIAGNOSTICS, Errors.UNUSED_DESTRUCTURED_PARAMETER_ENTRY ->
ProblemHighlightType.LIKE_UNUSED_SYMBOL
Errors.UNUSED_ANONYMOUS_PARAMETER -> ProblemHighlightType.WEAK_WARNING
else -> null
}
)
}
Severity.INFO -> AnnotationPresentationInfo(ranges, highlightType = ProblemHighlightType.INFORMATION)
}
return presentationInfo
}
private fun setUpAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
data: AnnotationPresentationInfo,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) {
val fixesMap =
createFixesMap(diagnostics, noFixes)
data.processDiagnostics(holder, diagnostics, highlightInfoByDiagnostic, highlightInfoByTextRange, fixesMap, calculatingInProgress)
}
private fun createFixesMap(
diagnostics: Collection<Diagnostic>,
noFixes: Boolean = false
): MultiMap<Diagnostic, IntentionAction>? = if (noFixes) {
null
} else {
try {
createQuickFixes(diagnostics)
} catch (e: Exception) {
if (e is ControlFlowException) {
throw e
}
LOG.error(e)
MultiMap()
}
}
private fun isUnstableAbiClassDiagnosticForModulesWithEnabledUnstableAbi(diagnostic: Diagnostic): Boolean {
val factory = diagnostic.factory
if (factory != Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS && factory != Errors.FIR_COMPILED_CLASS) return false
val module = element.module ?: return false
val moduleFacetSettings = KotlinFacetSettingsProvider.getInstance(element.project)?.getSettings(module) ?: return false
return when (factory) {
Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS ->
moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useIR) &&
!moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useOldBackend)
Errors.FIR_COMPILED_CLASS ->
moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useFir)
else -> error(factory)
}
}
companion object {
val LOG = Logger.getInstance(ElementAnnotator::class.java)
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveAsMember/moveClassToExternalNestedClass/after/onDemandImportOfTargetClassMembers.kt | 13 | 57 | import B.*
fun bar(s: String) {
val t: C.X = C.X()
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MapPlatformClassToKotlinFix.kt | 3 | 8390 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.rename.inplace.MyLookupExpression
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class MapPlatformClassToKotlinFix(
element: KtReferenceExpression,
private val platformClass: ClassDescriptor,
private val possibleClasses: Collection<ClassDescriptor>
) : KotlinQuickFixAction<KtReferenceExpression>(element) {
override fun getText(): String {
val platformClassQualifiedName = DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(platformClass.defaultType)
val singleClass = possibleClasses.singleOrNull()
return if (singleClass != null)
KotlinBundle.message(
"change.all.usages.of.0.in.this.file.to.1",
platformClassQualifiedName,
DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(singleClass.defaultType)
)
else
KotlinBundle.message("change.all.usages.of.0.in.this.file.to.a.kotlin.class", platformClassQualifiedName)
}
override fun getFamilyName() = KotlinBundle.message("change.to.kotlin.class")
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val bindingContext = file.analyzeWithContent()
val imports = ArrayList<KtImportDirective>()
val usages = ArrayList<KtUserType>()
for (diagnostic in bindingContext.diagnostics) {
if (diagnostic.factory !== Errors.PLATFORM_CLASS_MAPPED_TO_KOTLIN) continue
val refExpr = getImportOrUsageFromDiagnostic(diagnostic) ?: continue
if (resolveToClass(refExpr, bindingContext) != platformClass) continue
val import = refExpr.getStrictParentOfType<KtImportDirective>()
if (import != null) {
imports.add(import)
} else {
usages.add(refExpr.getStrictParentOfType<KtUserType>() ?: continue)
}
}
imports.forEach { it.delete() }
if (usages.isEmpty()) {
// if we are not going to replace any usages, there's no reason to continue at all
return
}
val replacedElements = replaceUsagesWithFirstClass(project, usages)
if (possibleClasses.size > 1 && editor != null) {
val possibleTypes = LinkedHashSet<String>()
for (klass in possibleClasses) {
possibleTypes.add(klass.name.asString())
}
buildAndShowTemplate(project, editor, file, replacedElements, possibleTypes)
}
}
private fun replaceUsagesWithFirstClass(project: Project, usages: List<KtUserType>): List<PsiElement> {
val replacementClass = possibleClasses.first()
val replacementClassName = replacementClass.name.asString()
val replacedElements = ArrayList<PsiElement>()
for (usage in usages) {
val typeArguments = usage.typeArgumentList
val typeArgumentsString = typeArguments?.text ?: ""
val replacementType = KtPsiFactory(project).createType(replacementClassName + typeArgumentsString)
val replacementTypeElement = replacementType.typeElement!!
val replacedElement = usage.replace(replacementTypeElement)
val replacedExpression = replacedElement.firstChild
assert(replacedExpression is KtSimpleNameExpression) // assumption: the Kotlin class requires no imports
replacedElements.add(replacedExpression)
}
return replacedElements
}
private val PRIMARY_USAGE = "PrimaryUsage"
private val OTHER_USAGE = "OtherUsage"
private fun buildAndShowTemplate(
project: Project, editor: Editor, file: PsiFile,
replacedElements: Collection<PsiElement>, options: LinkedHashSet<String>
) {
PsiDocumentManager.getInstance(project).commitAllDocuments()
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
val primaryReplacedExpression = replacedElements.iterator().next()
val caretModel = editor.caretModel
val oldOffset = caretModel.offset
caretModel.moveToOffset(file.node.startOffset)
val builder = TemplateBuilderImpl(file)
val expression = MyLookupExpression(
primaryReplacedExpression.text,
options,
null,
null,
false,
KotlinBundle.message("choose.an.appropriate.kotlin.class")
)
builder.replaceElement(primaryReplacedExpression, PRIMARY_USAGE, expression, true)
for (replacedExpression in replacedElements) {
if (replacedExpression === primaryReplacedExpression) continue
builder.replaceElement(replacedExpression, OTHER_USAGE, PRIMARY_USAGE, false)
}
TemplateManager.getInstance(project).startTemplate(editor, builder.buildInlineTemplate(), object : TemplateEditingAdapter() {
override fun templateFinished(template: Template, brokenOff: Boolean) {
caretModel.moveToOffset(oldOffset)
}
})
}
companion object : KotlinSingleIntentionActionFactoryWithDelegate<KtReferenceExpression, Companion.Data>() {
data class Data(
val platformClass: ClassDescriptor,
val possibleClasses: Collection<ClassDescriptor>
)
override fun getElementOfInterest(diagnostic: Diagnostic): KtReferenceExpression? = getImportOrUsageFromDiagnostic(diagnostic)
override fun extractFixData(element: KtReferenceExpression, diagnostic: Diagnostic): Data? {
val context = element.analyze(BodyResolveMode.PARTIAL)
val platformClass = resolveToClass(element, context) ?: return null
val possibleClasses = Errors.PLATFORM_CLASS_MAPPED_TO_KOTLIN.cast(diagnostic).a
return Data(platformClass, possibleClasses)
}
override fun createFix(originalElement: KtReferenceExpression, data: Data): IntentionAction? {
return MapPlatformClassToKotlinFix(originalElement, data.platformClass, data.possibleClasses)
}
private fun resolveToClass(referenceExpression: KtReferenceExpression, context: BindingContext): ClassDescriptor? {
return referenceExpression.mainReference.resolveToDescriptors(context).firstIsInstanceOrNull<ClassDescriptor>()
}
private fun getImportOrUsageFromDiagnostic(diagnostic: Diagnostic): KtReferenceExpression? {
val import = diagnostic.psiElement.getNonStrictParentOfType<KtImportDirective>()
return if (import != null) {
import.importedReference?.getQualifiedElementSelector() as? KtReferenceExpression
} else {
(diagnostic.psiElement.getNonStrictParentOfType<KtUserType>() ?: return null).referenceExpression
}
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/weighers/basic/PreferFromJdk.Data.kt | 13 | 37 | package dependency
public class Data | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt | 2 | 16569 | // 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.references.ReferenceAccess
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinIdeaAnalysisBundle.lazyMessage("replace.overloaded.operator.with.function.call"),
) {
companion object {
fun replaceExplicitInvokeCallWithImplicit(qualifiedExpression: KtDotQualifiedExpression): KtExpression? {
/*
* `a.b.invoke<>(){}` -> `a.b<>(){}`
* `a.b<>(){}.invoke<>(){}` -> `a.b<>(){}<>(){}`
* `b.invoke<>(){}` -> `b<>(){}`
* `b<>(){}.invoke<>(){}` -> `b<>(){}<>(){}`
* `invoke<>(){}` -> not applicable
*/
val callExpression = qualifiedExpression.selectorExpression.safeAs<KtCallExpression>()?.copied() ?: return null
val calleExpression = callExpression.calleeExpression as KtNameReferenceExpression
val receiverExpression = qualifiedExpression.receiverExpression
val selectorInReceiver = receiverExpression.safeAs<KtDotQualifiedExpression>()?.selectorExpression
return if (selectorInReceiver is KtNameReferenceExpression) {
calleExpression.rawReplace(selectorInReceiver.copied())
selectorInReceiver.rawReplace(callExpression)
qualifiedExpression.replaced(receiverExpression)
} else {
if ((receiverExpression is KtCallExpression || receiverExpression is KtDotQualifiedExpression) &&
callExpression.valueArgumentList == null && callExpression.typeArgumentList == null) {
calleExpression.replace(receiverExpression)
} else {
calleExpression.rawReplace(receiverExpression)
}
qualifiedExpression.replaced(callExpression)
}
}
private fun isApplicableUnary(element: KtUnaryExpression, caretOffset: Int): Boolean {
if (element.baseExpression == null) return false
val opRef = element.operationReference
if (!opRef.textRange.containsOffset(caretOffset)) return false
return when (opRef.getReferencedNameElementType()) {
KtTokens.PLUS, KtTokens.MINUS, KtTokens.EXCL -> true
KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> !isUsedAsExpression(element)
else -> false
}
}
// TODO: replace to `element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))` after fix KT-25682
private fun isUsedAsExpression(element: KtExpression): Boolean {
val parent = element.parent
return if (parent is KtBlockExpression) parent.lastBlockStatementOrThis() == element && parentIsUsedAsExpression(parent.parent)
else parentIsUsedAsExpression(parent)
}
private fun parentIsUsedAsExpression(element: PsiElement): Boolean = when (val parent = element.parent) {
is KtLoopExpression, is KtFile -> false
is KtIfExpression, is KtWhenExpression -> (parent as KtExpression).isUsedAsExpression(parent.analyze(BodyResolveMode.PARTIAL_WITH_CFA))
else -> true
}
private fun isApplicableBinary(element: KtBinaryExpression, caretOffset: Int): Boolean {
if (element.left == null || element.right == null) return false
val opRef = element.operationReference
if (!opRef.textRange.containsOffset(caretOffset)) return false
return when (opRef.getReferencedNameElementType()) {
KtTokens.PLUS, KtTokens.MINUS, KtTokens.MUL, KtTokens.DIV, KtTokens.PERC, KtTokens.RANGE,
KtTokens.IN_KEYWORD, KtTokens.NOT_IN, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ,
KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ
-> true
KtTokens.EQEQ, KtTokens.EXCLEQ -> listOf(element.left, element.right).none { it?.node?.elementType == KtNodeTypes.NULL }
KtTokens.EQ -> element.left is KtArrayAccessExpression
else -> false
}
}
private fun isApplicableArrayAccess(element: KtArrayAccessExpression, caretOffset: Int): Boolean {
val lbracket = element.leftBracket ?: return false
val rbracket = element.rightBracket ?: return false
val access = element.readWriteAccess(useResolveForReadWrite = true)
if (access == ReferenceAccess.READ_WRITE) return false // currently not supported
return lbracket.textRange.containsOffset(caretOffset) || rbracket.textRange.containsOffset(caretOffset)
}
private fun isApplicableCall(element: KtCallExpression, caretOffset: Int): Boolean {
val lbrace = (element.valueArgumentList?.leftParenthesis
?: element.lambdaArguments.firstOrNull()?.getLambdaExpression()?.leftCurlyBrace
?: return false) as PsiElement
if (!lbrace.textRange.containsOffset(caretOffset)) return false
val resolvedCall = element.resolveToCall(BodyResolveMode.FULL)
val descriptor = resolvedCall?.resultingDescriptor
if (descriptor is FunctionDescriptor && descriptor.getName() == OperatorNameConventions.INVOKE) {
if (element.parent is KtDotQualifiedExpression &&
element.calleeExpression?.text == OperatorNameConventions.INVOKE.asString()
) return false
return element.valueArgumentList != null || element.lambdaArguments.isNotEmpty()
}
return false
}
private fun convertUnary(element: KtUnaryExpression): KtExpression {
val operatorName = when (element.operationReference.getReferencedNameElementType()) {
KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> return convertUnaryWithAssignFix(element)
KtTokens.PLUS -> OperatorNameConventions.UNARY_PLUS
KtTokens.MINUS -> OperatorNameConventions.UNARY_MINUS
KtTokens.EXCL -> OperatorNameConventions.NOT
else -> return element
}
val transformed = KtPsiFactory(element).createExpressionByPattern("$0.$1()", element.baseExpression!!, operatorName)
return element.replace(transformed) as KtExpression
}
private fun convertUnaryWithAssignFix(element: KtUnaryExpression): KtExpression {
val operatorName = when (element.operationReference.getReferencedNameElementType()) {
KtTokens.PLUSPLUS -> OperatorNameConventions.INC
KtTokens.MINUSMINUS -> OperatorNameConventions.DEC
else -> return element
}
val transformed = KtPsiFactory(element).createExpressionByPattern("$0 = $0.$1()", element.baseExpression!!, operatorName)
return element.replace(transformed) as KtExpression
}
//TODO: don't use creation by plain text
private fun convertBinary(element: KtBinaryExpression): KtExpression {
val op = element.operationReference.getReferencedNameElementType()
val left = element.left!!
val right = element.right!!
if (op == KtTokens.EQ) {
if (left is KtArrayAccessExpression) {
convertArrayAccess(left)
}
return element
}
val context = element.analyze(BodyResolveMode.PARTIAL)
val functionCandidate = element.getResolvedCall(context)
val functionName = functionCandidate?.candidateDescriptor?.name.toString()
val elemType = context.getType(left)
@NonNls
val pattern = when (op) {
KtTokens.PLUS -> "$0.plus($1)"
KtTokens.MINUS -> "$0.minus($1)"
KtTokens.MUL -> "$0.times($1)"
KtTokens.DIV -> "$0.div($1)"
KtTokens.PERC -> "$0.rem($1)"
KtTokens.RANGE -> "$0.rangeTo($1)"
KtTokens.IN_KEYWORD -> "$1.contains($0)"
KtTokens.NOT_IN -> "!$1.contains($0)"
KtTokens.PLUSEQ -> if (functionName == "plusAssign") "$0.plusAssign($1)" else "$0 = $0.plus($1)"
KtTokens.MINUSEQ -> if (functionName == "minusAssign") "$0.minusAssign($1)" else "$0 = $0.minus($1)"
KtTokens.MULTEQ -> if (functionName == "timesAssign") "$0.timesAssign($1)" else "$0 = $0.times($1)"
KtTokens.DIVEQ -> if (functionName == "divAssign") "$0.divAssign($1)" else "$0 = $0.div($1)"
KtTokens.PERCEQ -> {
val remSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.OperatorRem)
if (remSupported && functionName == "remAssign") "$0.remAssign($1)"
else if (functionName == "modAssign") "$0.modAssign($1)"
else if (remSupported) "$0 = $0.rem($1)"
else "$0 = $0.mod($1)"
}
KtTokens.EQEQ -> if (elemType?.isMarkedNullable != false) "$0?.equals($1) ?: ($1 == null)" else "$0.equals($1)"
KtTokens.EXCLEQ -> if (elemType?.isMarkedNullable != false) "!($0?.equals($1) ?: ($1 == null))" else "!$0.equals($1)"
KtTokens.GT -> "$0.compareTo($1) > 0"
KtTokens.LT -> "$0.compareTo($1) < 0"
KtTokens.GTEQ -> "$0.compareTo($1) >= 0"
KtTokens.LTEQ -> "$0.compareTo($1) <= 0"
else -> return element
}
val transformed = KtPsiFactory(element).createExpressionByPattern(pattern, left, right)
return element.replace(transformed) as KtExpression
}
private fun convertArrayAccess(element: KtArrayAccessExpression): KtExpression {
var expressionToReplace: KtExpression = element
val transformed = KtPsiFactory(element).buildExpression {
appendExpression(element.arrayExpression)
appendFixedText(".")
if (isAssignmentLeftSide(element)) {
val parent = element.parent
expressionToReplace = parent as KtBinaryExpression
appendFixedText("set(")
appendExpressions(element.indexExpressions)
appendFixedText(",")
appendExpression(parent.right)
} else {
appendFixedText("get(")
appendExpressions(element.indexExpressions)
}
appendFixedText(")")
}
return expressionToReplace.replace(transformed) as KtExpression
}
private fun isAssignmentLeftSide(element: KtArrayAccessExpression): Boolean {
val parent = element.parent
return parent is KtBinaryExpression &&
parent.operationReference.getReferencedNameElementType() == KtTokens.EQ && element == parent.left
}
//TODO: don't use creation by plain text
private fun convertCall(element: KtCallExpression): KtExpression {
val callee = element.calleeExpression!!
val receiver = element.parent?.safeAs<KtQualifiedExpression>()?.receiverExpression
val isAnonymousFunctionWithReceiver = receiver != null && callee.deparenthesize() is KtNamedFunction
val argumentsList = element.valueArgumentList
val argumentString = argumentsList?.text?.removeSurrounding("(", ")") ?: ""
val argumentsWithReceiverIfNeeded = if (isAnonymousFunctionWithReceiver) {
val receiverText = receiver?.text ?: ""
val delimiter = if (receiverText.isNotEmpty() && argumentString.isNotEmpty()) ", " else ""
receiverText + delimiter + argumentString
} else {
argumentString
}
val funcLitArgs = element.lambdaArguments
val calleeText = callee.text
val transformation = "$calleeText.${OperatorNameConventions.INVOKE.asString()}" + "($argumentsWithReceiverIfNeeded)"
val transformed = KtPsiFactory(element).createExpression(transformation)
val callExpression = transformed.getCalleeExpressionIfAny()?.parent as? KtCallExpression
if (callExpression != null && funcLitArgs.isNotEmpty()) {
funcLitArgs.forEach { callExpression.add(it) }
if (argumentsWithReceiverIfNeeded.isEmpty()) {
callExpression.valueArgumentList?.delete()
}
}
val elementToReplace = if (isAnonymousFunctionWithReceiver) element.parent else callee.parent
return elementToReplace.replace(transformed) as KtExpression
}
fun convert(element: KtExpression): Pair<KtExpression, KtSimpleNameExpression> {
var elementToBeReplaced = element
if (element is KtArrayAccessExpression && isAssignmentLeftSide(element)) {
elementToBeReplaced = element.parent as KtExpression
}
val commentSaver = CommentSaver(elementToBeReplaced, saveLineBreaks = true)
val result = when (element) {
is KtUnaryExpression -> convertUnary(element)
is KtBinaryExpression -> convertBinary(element)
is KtArrayAccessExpression -> convertArrayAccess(element)
is KtCallExpression -> convertCall(element)
else -> throw IllegalArgumentException(element.toString())
}
commentSaver.restore(result)
val callName = findCallName(result) ?: error("No call name found in ${result.text}")
return result to callName
}
private fun findCallName(result: KtExpression): KtSimpleNameExpression? = when (result) {
is KtBinaryExpression -> {
if (KtPsiUtil.isAssignment(result))
findCallName(result.right!!)
else
findCallName(result.left!!)
}
is KtUnaryExpression -> result.baseExpression?.let { findCallName(it) }
is KtParenthesizedExpression -> result.expression?.let { findCallName(it) }
else -> result.getQualifiedElementSelector() as KtSimpleNameExpression?
}
}
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean = when (element) {
is KtUnaryExpression -> isApplicableUnary(element, caretOffset)
is KtBinaryExpression -> isApplicableBinary(element, caretOffset)
is KtArrayAccessExpression -> isApplicableArrayAccess(element, caretOffset)
is KtCallExpression -> isApplicableCall(element, caretOffset)
else -> false
}
override fun applyTo(element: KtExpression, editor: Editor?) {
convert(element)
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/topLevel/constantJavaWithCustomFileName/Main.kt | 10 | 82 | @file:JvmName("CustomKotlinName")
package top.level
const val topLevelConst = 42 | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/features-trainer/src/org/jetbrains/kotlin/training/ift/KotlinLessonsBundle.kt | 9 | 590 | // 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.kotlin.training.ift
import com.intellij.DynamicBundle
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.KotlinLessonsBundle"
object KotlinLessonsBundle : DynamicBundle(BUNDLE) {
@Nls
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/NotPropertyList.kt | 2 | 954 | // 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.util
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeUniqueAsSequence
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
fun FunctionDescriptor.shouldNotConvertToProperty(notProperties: Set<FqNameUnsafe>): Boolean {
if (fqNameUnsafe in notProperties) return true
return this.overriddenTreeUniqueAsSequence(false).any { fqNameUnsafe in notProperties }
}
fun SyntheticJavaPropertyDescriptor.suppressedByNotPropertyList(set: Set<FqNameUnsafe>) =
getMethod.shouldNotConvertToProperty(set) || setMethod?.shouldNotConvertToProperty(set) ?: false | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/funInInlinePublicFun.kt | 13 | 89 | // "Create function 'g'" "true"
class C {
inline fun f() {
<caret>g()
}
} | apache-2.0 |
google/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/gridLayoutTestAction/GridLayoutTestAction.kt | 5 | 15867 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui.gridLayoutTestAction
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.dsl.gridLayout.*
import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import javax.swing.*
import javax.swing.border.Border
import kotlin.random.Random
internal class GridLayoutTestAction : DumbAwareAction("Show GridLayout Test") {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
object : DialogWrapper(e.project, null, true, IdeModalityType.IDE, false) {
init {
title = "GridLayout Test"
init()
}
override fun createContentPaneBorder(): Border? {
return null
}
override fun createCenterPanel(): JComponent {
val result = JBTabbedPane()
result.minimumSize = Dimension(300, 200)
result.preferredSize = Dimension(800, 600)
result.addTab("TODO", createTodoPanel())
result.addTab(
"NoResizableCells", createTabPanel("No resizable cells",
createPanelLabels(3, 4) { _, _, _ -> null })
)
result.addTab("ResizableCell[1, 1]", createResizableCell11Panel())
result.addTab("CellAlignments", createCellAlignmentsPanel())
result.addTab("SubGrid", createSubGridPanel())
result.addTab("JointCells", createJointCellsPanel())
result.addTab("Gaps", createGapsPanel())
result.addTab("Col/row gaps", createColRowGapsPanel())
result.addTab("VisualPaddings", createVisualPaddingsPanel())
result.addTab("Baseline", createBaselinePanel())
result.addTab("SizeGroup", SizeGroupPanel().panel)
return result
}
}.show()
}
fun createTodoPanel(): JPanel {
val result = JPanel()
val todo = listOf(
"Implement cells which occupies all remaining columns",
"Resize non resizable cells when there is no enough space",
"Tests",
"visualPaddings can depend on component size? E.g. checkBox",
"SubGrids: visibility, visualPaddings"
)
result.add(
JLabel("<html>TODO list<br><br>&bull " + todo.joinToString("<br>&bull "))
)
return result
}
fun createBaselinePanel(): JPanel {
fun RowsGridBuilder.label(verticalAlign: VerticalAlign, size: Int): RowsGridBuilder {
val label = JLabel("${verticalAlign.name} $size")
label.font = label.font.deriveFont(size.toFloat())
cell(label, verticalAlign = verticalAlign)
return this
}
fun RowsGridBuilder.title(text: String): RowsGridBuilder {
val label = JLabel(text)
label.preferredSize = Dimension(150, 40)
label.verticalAlignment = SwingConstants.TOP
cell(label, verticalAlign = VerticalAlign.FILL)
return this
}
val panel = JPanel(GridLayout())
val builder = RowsGridBuilder(panel)
.defaultBaselineAlign(true)
builder
.title("Vertical align: TOP")
.label(VerticalAlign.TOP, 14)
.label(VerticalAlign.TOP, 10)
.label(VerticalAlign.TOP, 16)
.row()
.title("Vertical align: CENTER")
.label(VerticalAlign.CENTER, 12)
.label(VerticalAlign.CENTER, 14)
.label(VerticalAlign.CENTER, 16)
.row()
.title("Vertical align: BOTTOM")
.label(VerticalAlign.BOTTOM, 12)
.label(VerticalAlign.BOTTOM, 10)
.label(VerticalAlign.BOTTOM, 16)
.row()
.title("Vertical align: mixed")
.label(VerticalAlign.TOP, 12)
.label(VerticalAlign.CENTER, 10)
.label(VerticalAlign.BOTTOM, 14)
.label(VerticalAlign.CENTER, 16)
.label(VerticalAlign.TOP, 14)
.label(VerticalAlign.BOTTOM, 10)
.row()
builder
.subGridBuilder(width = 7)
.title("sub-panels")
.label(VerticalAlign.CENTER, 14)
.subGridBuilder(verticalAlign = VerticalAlign.CENTER)
.label(VerticalAlign.CENTER, 12)
.subGridBuilder(verticalAlign = VerticalAlign.CENTER)
.label(VerticalAlign.CENTER, 16)
.label(VerticalAlign.CENTER, 10)
return createTabPanel("Labels are aligned by baseline", panel)
}
fun createVisualPaddingsPanel(): JPanel {
val layoutManager = GridLayout()
val rootGrid = layoutManager.rootGrid
rootGrid.resizableColumns.add(1)
rootGrid.resizableRows.add(2)
val panel = JPanel(layoutManager)
fillGridByLabels(panel, rootGrid, 3, 4) { grid, x, y ->
if (x == 0 && y == 1) {
Constraints(grid, x, y, visualPaddings = Gaps(10, 10, 10, 10))
}
else if (x == 1 && y == 2) {
Constraints(
grid, x, y, horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL,
visualPaddings = Gaps(10, 10, 10, 10)
)
}
else {
null
}
}
return createTabPanel("Every second cell has own Gaps", panel)
}
fun createGapsPanel(): JPanel {
val panel = createPanelLabels(4, 4) { grid, x, y ->
Constraints(
grid,
x,
y,
horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL,
gaps = if ((x + y) % 2 == 0) Gaps.EMPTY else Gaps(y * 20, x * 20, y * 30, x * 30)
)
}
val grid = (panel.layout as GridLayout).rootGrid
grid.resizableColumns.addAll(0..HorizontalAlign.values().size)
grid.resizableRows.addAll(0..VerticalAlign.values().size)
return createTabPanel("Every second cell has own Gaps", panel)
}
fun createColRowGapsPanel(): JPanel {
val layoutManager = GridLayout()
val grid = layoutManager.rootGrid
grid.resizableColumns.addAll(0..4)
grid.resizableRows.addAll(0..3)
grid.columnsGaps.addAll((0..4).map { HorizontalGaps(it * 20, it * 20 + 10) })
grid.rowsGaps.addAll((0..3).map { VerticalGaps(it * 5 + 5, it * 5 + 15) })
val panel = JPanel(layoutManager)
fillGridByCompoundLabels(panel, grid)
return createTabPanel("Different distances between columns/rows", panel)
}
fun createJointCellsPanel(): JPanel {
val layoutManager = GridLayout()
val grid = layoutManager.rootGrid
grid.resizableColumns.add(1)
grid.resizableRows.add(1)
val panel = JPanel(layoutManager)
fun addLabel(x: Int, y: Int, width: Int = 1, height: Int = 1) {
panel.addLabel(
Constraints(
grid, x, y, width = width, height = height,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
)
}
addLabel(0, 0, height = 2)
addLabel(1, 0, width = 3)
addLabel(4, 0, height = 3)
addLabel(1, 1)
val constraints = Constraints(
grid, 2, 1, width = 2, height = 2,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
panel.add(
JLabel(
"<html>HighLabel<br>Label<br>Label<br>Label<br>Label<br>Label<br>Label<br>${
constraintsToHtmlString(
constraints
)
}"
),
constraints
)
addLabel(0, 2, width = 2, height = 2)
addLabel(2, 3, width = 3)
return createTabPanel("Cells have different shapes", panel)
}
fun createCellAlignmentsPanel(): JPanel {
val panel = createPanelLabels(HorizontalAlign.values().size, VerticalAlign.values().size) { grid, x, y ->
Constraints(
grid,
x,
y,
horizontalAlign = HorizontalAlign.values()[x],
verticalAlign = VerticalAlign.values()[y]
)
}
val grid = (panel.layout as GridLayout).rootGrid
grid.resizableColumns.addAll(0..HorizontalAlign.values().size)
grid.resizableRows.addAll(0..VerticalAlign.values().size)
return createTabPanel("Cells size is equal, component layouts have different alignments", panel)
}
fun createResizableCell11Panel(): JPanel {
val panel = createPanelLabels(3, 4) { grid, x, y ->
if (x == 1 && y == 1)
Constraints(grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL)
else
null
}
val grid = (panel.layout as GridLayout).rootGrid
grid.resizableColumns.add(1)
grid.resizableRows.add(1)
return createTabPanel("One column and row are resizable", panel)
}
fun createSubGridPanel(): JPanel {
val layoutManager = GridLayout()
layoutManager.rootGrid.resizableColumns.add(1)
layoutManager.rootGrid.resizableRows.add(1)
val panel = JPanel(layoutManager)
val subGrid = layoutManager.addLayoutSubGrid(
Constraints(
layoutManager.rootGrid, 1, 1,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
)
subGrid.resizableColumns.add(1)
subGrid.resizableRows.add(1)
fillGridByLabels(panel, subGrid, 3, 3) { grid, x, y ->
if (x == 1 && y == 1)
Constraints(grid, x, y, horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL)
else
null
}
RowsGridBuilder(panel)
.cell(label(0, 0))
.cell(label(1, 0))
.cell(label(2, 0))
.row()
.cell(label(0, 1))
.skip()
.cell(label(2, 1))
.row()
.cell(label(0, 2))
.cell(label(1, 2))
.cell(label(2, 2))
return createTabPanel("cell[1, 1] contains another grid inside", panel)
}
fun createPanelLabels(
width: Int,
height: Int,
constraintFactory: (grid: Grid, x: Int, y: Int) -> Constraints?
): JPanel {
val layoutManager = GridLayout()
val result = JPanel(layoutManager)
fillGridByLabels(result, layoutManager.rootGrid, width, height, constraintFactory)
return result
}
fun fillGridByLabels(
container: JComponent,
grid: Grid,
width: Int,
height: Int,
constraintFactory: (grid: Grid, x: Int, y: Int) -> Constraints?
) {
for (x in 0 until width) {
for (y in 0 until height) {
val constraints =
constraintFactory.invoke(grid, x, y) ?: Constraints(grid, x, y)
container.addLabel(constraints, longLabel = x == y)
}
}
}
fun fillGridByCompoundLabels(
container: JComponent,
grid: Grid
) {
fun addLabel(x: Int, y: Int, width: Int = 1, height: Int = 1) {
container.addLabel(
Constraints(
grid, x, y, width = width, height = height,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
)
}
addLabel(0, 0, height = 2)
addLabel(1, 0, width = 3)
addLabel(4, 0, height = 3)
addLabel(1, 1)
val constraints = Constraints(
grid, 2, 1, width = 2, height = 2,
horizontalAlign = HorizontalAlign.FILL, verticalAlign = VerticalAlign.FILL
)
container.add(
JLabel(
"<html>HighLabel<br>Label<br>Label<br>Label<br>Label<br>Label<br>Label<br>${
constraintsToHtmlString(
constraints
)
}"
),
constraints
)
addLabel(0, 2, width = 2, height = 2)
addLabel(2, 3, width = 3)
}
fun label(constraints: Constraints, longLabel: Boolean = false): JLabel {
val text = if (longLabel) "Very very very very very long label" else "Label"
return JLabel("<html>$text<br>${constraintsToHtmlString(constraints)}")
}
fun constraintsToHtmlString(constraints: Constraints): String {
var result = "x = ${constraints.x}, y = ${constraints.y}<br>" +
"width = ${constraints.width}, height = ${constraints.height}<br>" +
"hAlign = ${constraints.horizontalAlign}, vAlign = ${constraints.verticalAlign}<br>"
if (constraints.gaps != Gaps.EMPTY) {
result += "gaps = ${constraints.gaps}<br>"
}
if (constraints.visualPaddings != Gaps.EMPTY) {
result += "visualPaddings = ${constraints.visualPaddings}<br>"
}
return result
}
fun label(x: Int, y: Int, longLabel: Boolean = false): JLabel {
val text = if (longLabel) "Very very very very very long label" else "Label"
return JLabel("$text [x = $x, y = $y]")
}
fun JComponent.addLabel(constraints: Constraints, longLabel: Boolean = false) {
val label = label(constraints, longLabel)
add(label, constraints)
}
}
private fun gridToHtmlString(grid: Grid): String {
val result = mutableListOf<String>()
if (grid.resizableColumns.isNotEmpty()) {
result.add("resizableColumns = ${grid.resizableColumns.joinToString()}")
}
if (grid.resizableRows.isNotEmpty()) {
result.add("resizableRows = ${grid.resizableRows.joinToString()}")
}
if (grid.columnsGaps.isNotEmpty()) {
result.add("<br>columnsGaps = ${grid.columnsGaps.joinToString()}")
}
if (grid.rowsGaps.isNotEmpty()) {
result.add("<br>rowsGaps = ${grid.rowsGaps.joinToString()}")
}
return result.joinToString()
}
fun createTabPanel(title: String, content: JComponent): JPanel {
val layoutManager = GridLayout()
val rootGrid = layoutManager.rootGrid
val result = JPanel(layoutManager)
rootGrid.resizableColumns.add(0)
rootGrid.resizableRows.add(1)
val label = JLabel("<html>$title<br>${gridToHtmlString((content.layout as GridLayout).rootGrid)}")
label.background = Color.LIGHT_GRAY
label.isOpaque = true
result.add(label, Constraints(rootGrid, 0, 0, width = 2, horizontalAlign = HorizontalAlign.FILL))
result.add(
content, Constraints(
rootGrid, 0, 1, verticalAlign = VerticalAlign.FILL,
horizontalAlign = HorizontalAlign.FILL
)
)
val controlGrid = layoutManager.addLayoutSubGrid(
Constraints(
rootGrid,
1,
1,
verticalAlign = VerticalAlign.FILL
)
)
createControls(result, content, controlGrid)
return result
}
private fun createControls(container: JComponent, content: JComponent, grid: Grid) {
val cbHighlight = JCheckBox("Highlight components")
cbHighlight.addActionListener {
for (component in content.components) {
if (component is JLabel) {
component.background = if (cbHighlight.isSelected) Color(Random.nextInt()) else null
component.isOpaque = cbHighlight.isSelected
}
}
}
cbHighlight.doClick()
val list = JBList(content.components.filterIsInstance<JLabel>())
val btnHide = JButton("Hide")
val btnShow = JButton("Show")
list.cellRenderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(
list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
val label = value as JLabel
val result = super.getListCellRendererComponent(
list,
label.text,
index,
isSelected,
cellHasFocus
) as DefaultListCellRenderer
result.foreground = if (label.isVisible) Color.BLACK else Color.LIGHT_GRAY
return result
}
}
btnHide.addActionListener {
list.selectedValuesList.forEach { it.isVisible = false }
list.updateUI()
}
btnShow.addActionListener {
list.selectedValuesList.forEach { it.isVisible = true }
list.updateUI()
}
grid.resizableColumns.addAll(0..1)
grid.resizableRows.add(0)
container.add(
JScrollPane(list), Constraints(
grid, 0, 0, width = 2, horizontalAlign = HorizontalAlign.FILL,
verticalAlign = VerticalAlign.FILL
)
)
container.add(btnHide, Constraints(grid, 0, 1, horizontalAlign = HorizontalAlign.CENTER))
container.add(btnShow, Constraints(grid, 1, 1, horizontalAlign = HorizontalAlign.CENTER))
container.add(cbHighlight, Constraints(grid, 0, 2, width = 2))
}
| apache-2.0 |
skroll/kt-acollections | src/main/kotlin/org/skroll/acollections/AbstractList.kt | 1 | 5988 | package org.skroll.acollections
import java.util.NoSuchElementException
import java.util.RandomAccess
/**
* This class provides a skeletal implementation of the [List] interface
* to minimize the effort required to implement this interface backed by a
* "random access" data store (such as an array).
*
* For sequential access data (such as a linked list), [AbstractSequentialList]
* should be used in preference to this class.
*/
public abstract class AbstractList<E> : AbstractCollection<E>(), List<E> {
override fun indexOf(element: E): Int {
val it = listIterator()
while (it.hasNext()) {
if (it.next() == element)
return it.previousIndex()
}
return -1
}
override fun lastIndexOf(element: E): Int {
val it = listIterator(size)
while (it.hasPrevious()) {
if (it.previous() == element)
return it.nextIndex()
}
return -1
}
/**
* Returns an iterator over the elements in this list (in proper sequence).
*
* This implementation merely returns a list iterator over the list.
*
* @return an iterator over the elements in this list (in proper sequence)
*/
override fun iterator(): Iterator<E> = Itr()
override fun listIterator(): ListIterator<E> = listIterator(0)
override fun listIterator(index: Int): ListIterator<E> {
rangeCheckForAdd(index)
return ListItr(index)
}
open inner class Itr(protected var cursor: Int) : Iterator<E> {
protected var lastRet = -1
constructor() : this(0)
override fun hasNext(): Boolean = cursor != size
override fun next(): E {
try {
val i = cursor
val next = get(i)
lastRet = i
cursor = i + 1
return next
} catch (e: IndexOutOfBoundsException) {
throw NoSuchElementException()
}
}
}
inner class ListItr(index: Int) : Itr(index), ListIterator<E> {
override fun hasPrevious(): Boolean = cursor != 0
override fun previous(): E {
try {
val i = cursor - 1
val previous = get(i)
lastRet = i
cursor = i
return previous
} catch (unused: IndexOutOfBoundsException) {
throw NoSuchElementException()
}
}
override fun nextIndex(): Int = cursor
override fun previousIndex(): Int = cursor - 1
}
override fun subList(fromIndex: Int, toIndex: Int): List<E> {
return if (this is RandomAccess) RandomAccessSubList<E>(this, fromIndex, toIndex) else SubList(this, fromIndex, toIndex)
}
override fun equals(other: Any?): Boolean {
if (other === this)
return true
if (other !is List<*>)
return false
val e1 = listIterator()
val e2 = other.listIterator()
while (e1.hasNext() && e2.hasNext()) {
if (e1.next() != e2.next())
return false
}
return !(e1.hasNext() || e2.hasNext())
}
override fun hashCode(): Int {
var hashCode = 1
for (e in this)
hashCode = 31 * hashCode + (e?.hashCode() ?: 0)
return hashCode
}
private fun rangeCheckForAdd(index: Int) {
if (index < 0 || index > size)
throw IndexOutOfBoundsException("Index: $index, Size: $size")
}
}
private open class SubList<E>(private val list: AbstractList<E>, fromIndex: Int, toIndex: Int) : AbstractList<E>() {
private val offset = fromIndex
private val subSize: Int
init {
if (fromIndex < 0)
throw IndexOutOfBoundsException("fromIndex = $fromIndex")
if (toIndex > list.size)
throw IndexOutOfBoundsException("toIndex = $toIndex")
if (fromIndex > toIndex)
throw IllegalAccessException("fromIndex($fromIndex) > toIndex($toIndex)")
subSize = toIndex - fromIndex
}
override val size: Int
get() = subSize
override fun get(index: Int): E {
rangeCheck(index)
return list[index + offset]
}
override fun iterator() = listIterator()
override fun listIterator(index: Int): ListIterator<E> {
rangeCheckForAdd(index)
return object : ListIterator<E> {
val i = list.listIterator(index + offset)
override fun hasNext(): Boolean = nextIndex() < subSize
override fun next(): E {
if (hasNext())
return i.next()
else
throw NoSuchElementException()
}
override fun hasPrevious(): Boolean = previousIndex() >= 0
override fun previous(): E {
if (hasPrevious())
return i.previous()
else
throw NoSuchElementException()
}
override fun nextIndex(): Int = i.nextIndex() - offset
override fun previousIndex(): Int = i.previousIndex() - offset
}
}
override fun subList(fromIndex: Int, toIndex: Int): List<E> {
return SubList(this, fromIndex, toIndex)
}
private fun rangeCheck(index: Int) {
if (index < 0 || index >= subSize)
throw IndexOutOfBoundsException(outOfBoundsMsg(index))
}
private fun rangeCheckForAdd(index: Int) {
if (index < 0 || index > subSize)
throw IndexOutOfBoundsException(outOfBoundsMsg(index))
}
private fun outOfBoundsMsg(index: Int) = "Index: $index, Size: $subSize"
}
private class RandomAccessSubList<E>(list: AbstractList<E>, fromIndex: Int, toIndex: Int) : SubList<E>(list, fromIndex, toIndex), RandomAccess {
override fun subList(fromIndex: Int, toIndex: Int): List<E> {
return RandomAccessSubList(this, fromIndex, toIndex)
}
} | mit |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliBaseInspection.kt | 2 | 1954 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.p3c.idea.inspection
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
/**
* @author caikang
* @date 2016/12/08
*/
interface AliBaseInspection {
/**
* ruleName
* @return ruleName
*/
fun ruleName(): String
/**
* display info for inspection
* @return display
*/
fun getDisplayName(): String
/**
* group display info for inspection
* @return group display
*/
fun getGroupDisplayName(): String
/**
* inspection enable by default
* @return true -> enable
*/
fun isEnabledByDefault(): Boolean
/**
* default inspection level
* @return level
*/
fun getDefaultLevel(): HighlightDisplayLevel
/**
* inspection short name
* @return shor name
*/
fun getShortName(): String
fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? = null
fun manualParsePsiElement(psiFile: PsiFile, manager: InspectionManager,
start: Int, end: Int): PsiElement {
return psiFile.findElementAt(start)!!
}
companion object {
val GROUP_NAME = "Ali-Check"
}
}
| apache-2.0 |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.kt | 1 | 904 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL
aapsLogger.debug(LTag.PUMPCOMM, "Canceling temp basal")
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "BASAL__CANCEL_TEMPORARY_BASAL"
}
} | agpl-3.0 |
kohesive/kohesive-iac | cloudtrail-tool/src/main/kotlin/uy/kohesive/iac/model/aws/cloudtrail/preprocessing/CreateNetworkInterfacePreprocessor.kt | 1 | 650 | package uy.kohesive.iac.model.aws.cloudtrail.preprocessing
import uy.kohesive.iac.model.aws.cloudtrail.RequestMap
class CreateNetworkInterfacePreprocessor : RequestPreprocessor {
override val eventNames = listOf("CreateNetworkInterface")
override fun processRequestMap(requestMap: RequestMap): RequestMap {
// Fix group IDs/names
val groupSet = (requestMap["groupSet"] as? RequestMap).orEmpty()
val groupItems = groupSet["items"] as? List<RequestMap>
val groupIds = groupItems?.map { it["groupId"] }
return (requestMap - "groupSet") + mapOf(
"groups" to groupIds
)
}
} | mit |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/generator/GlslGenerator.kt | 1 | 23580 | package de.fabmax.kool.modules.ksl.generator
import de.fabmax.kool.modules.ksl.lang.*
import de.fabmax.kool.modules.ksl.model.KslState
/**
* Default GLSL shader code generator, generates glsl in version 300 es, which works for WebGL and OpenGL 3.3+
*/
open class GlslGenerator : KslGenerator() {
protected var glslVersionStr = "#version 300 es"
var blockIndent = " "
override fun generateProgram(program: KslProgram): GlslGeneratorOutput {
return GlslGeneratorOutput(generateVertexSrc(program.vertexStage), generateFragmentSrc(program.fragmentStage))
}
override fun constFloatVecExpression(vararg values: KslExpression<KslTypeFloat1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "vec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constIntVecExpression(vararg values: KslExpression<KslTypeInt1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "ivec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constUintVecExpression(vararg values: KslExpression<KslTypeUint1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "uvec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constBoolVecExpression(vararg values: KslExpression<KslTypeBool1>): String {
if (values.size !in 2..4) {
throw IllegalArgumentException("invalid number of values: ${values.size} (must be between 2 and 4)")
}
return "bvec${values.size}(${values.joinToString { it.generateExpression(this) }})"
}
override fun constMatExpression(vararg columns: KslVectorExpression<*, KslTypeFloat1>): String {
if (columns.size !in 2..4) {
throw IllegalArgumentException("invalid number of columns: ${columns.size} (must be between 2 and 4)")
}
return "mat${columns.size}(${columns.joinToString { it.generateExpression(this) }})"
}
override fun castExpression(castExpr: KslExpressionCast<*>): String {
return "${glslTypeName(castExpr.expressionType)}(${castExpr.value.generateExpression(this)})"
}
override fun <B: KslBoolType> compareExpression(expression: KslExpressionCompare<B>): String {
val lt = expression.left.generateExpression(this)
val rt = expression.right.generateExpression(this)
return if (expression.left.expressionType is KslVector<*>) {
when (expression.operator) {
KslCompareOperator.Equal -> "equal($lt, $rt)"
KslCompareOperator.NotEqual -> "notEqual($lt, $rt)"
KslCompareOperator.Less -> "lessThan($lt, $rt)"
KslCompareOperator.LessEqual -> "lessThanEqual($lt, $rt)"
KslCompareOperator.Greater -> "greaterThan($lt, $rt)"
KslCompareOperator.GreaterEqual -> "greaterThanEqual($lt, $rt)"
}
} else {
"($lt ${expression.operator.opString} $rt)"
}
}
override fun sampleColorTexture(sampleTexture: KslSampleColorTexture<*>): String {
val sampler = sampleTexture.sampler.generateExpression(this)
val coord = if (sampleTexture.sampler.expressionType is KslTypeSampler1d && sampleTexture.coord.expressionType is KslTypeFloat1) {
// for better OpenGL ES compatibility 1d textures actually are 2d textures...
"vec2(${sampleTexture.coord.generateExpression(this)}, 0.5)"
} else {
sampleTexture.coord.generateExpression(this)
}
return if (sampleTexture.lod != null) {
"textureLod(${sampler}, ${coord}, ${sampleTexture.lod.generateExpression(this)})"
} else {
"texture(${sampler}, ${coord})"
}
}
override fun sampleDepthTexture(sampleTexture: KslSampleDepthTexture<*>): String {
return "texture(${sampleTexture.sampler.generateExpression(this)}, ${sampleTexture.coord.generateExpression(this)})"
}
override fun textureSize(textureSize: KslTextureSize<*, *>): String {
return "textureSize(${textureSize.sampler.generateExpression(this)}, ${textureSize.lod.generateExpression(this)})"
}
override fun texelFetch(expression: KslTexelFetch<*>): String {
val sampler = expression.sampler.generateExpression(this)
val coords = expression.coord.generateExpression(this)
val lod = expression.lod?.generateExpression(this)
return "texelFetch($sampler, $coords, ${lod ?: 0})"
}
private fun generateVertexSrc(vertexStage: KslVertexStage): String {
val src = StringBuilder()
src.appendLine("""
$glslVersionStr
precision highp sampler3D;
/*
* ${vertexStage.program.name} - generated vertex shader
*/
""".trimIndent())
src.appendLine()
src.generateUbos(vertexStage)
src.generateUniformSamplers(vertexStage)
src.generateAttributes(vertexStage.attributes.values.filter { it.inputRate == KslInputRate.Instance }, "instance attributes")
src.generateAttributes(vertexStage.attributes.values.filter { it.inputRate == KslInputRate.Vertex }, "vertex attributes")
src.generateInterStageOutputs(vertexStage)
src.generateFunctions(vertexStage)
src.appendLine("void main() {")
src.appendLine(generateScope(vertexStage.main, blockIndent))
src.appendLine("}")
return src.toString()
}
private fun generateFragmentSrc(fragmentStage: KslFragmentStage): String {
val src = StringBuilder()
src.appendLine("""
$glslVersionStr
precision highp float;
precision highp sampler2DShadow;
precision highp sampler3D;
/*
* ${fragmentStage.program.name} - generated fragment shader
*/
""".trimIndent())
src.appendLine()
src.generateUbos(fragmentStage)
src.generateUniformSamplers(fragmentStage)
src.generateInterStageInputs(fragmentStage)
src.generateOutputs(fragmentStage.outColors)
src.generateFunctions(fragmentStage)
src.appendLine("void main() {")
src.appendLine(generateScope(fragmentStage.main, blockIndent))
src.appendLine("}")
return src.toString()
}
protected open fun StringBuilder.generateUniformSamplers(stage: KslShaderStage) {
val samplers = stage.getUsedSamplers()
if (samplers.isNotEmpty()) {
appendLine("// texture samplers")
for (u in samplers) {
val arraySuffix = if (u.value is KslArray<*>) { "[${u.arraySize}]" } else { "" }
appendLine("uniform ${glslTypeName(u.expressionType)} ${u.value.name()}${arraySuffix};")
}
appendLine()
}
}
protected open fun StringBuilder.generateUbos(stage: KslShaderStage) {
val ubos = stage.getUsedUbos()
if (ubos.isNotEmpty()) {
appendLine("// uniform buffer objects")
for (ubo in ubos) {
// if isShared is true, the underlying buffer is externally provided without the buffer layout
// being queried via OpenGL API -> use standardized std140 layout
val layoutPrefix = if (ubo.isShared) { "layout(std140) " } else { "" }
appendLine("${layoutPrefix}uniform ${ubo.name} {")
for (u in ubo.uniforms.values) {
val arraySuffix = if (u.value is KslArray<*>) { "[${u.arraySize}]" } else { "" }
appendLine(" highp ${glslTypeName(u.expressionType)} ${u.value.name()}${arraySuffix};")
}
appendLine("};")
}
appendLine()
}
}
protected open fun StringBuilder.generateAttributes(attribs: List<KslVertexAttribute<*>>, info: String) {
if (attribs.isNotEmpty()) {
appendLine("// $info")
attribs.forEach { a ->
appendLine("layout(location=${a.location}) in ${glslTypeName(a.expressionType)} ${a.value.name()};")
}
appendLine()
}
}
protected open fun StringBuilder.generateInterStageOutputs(vertexStage: KslVertexStage) {
if (vertexStage.interStageVars.isNotEmpty()) {
appendLine("// custom vertex stage outputs")
vertexStage.interStageVars.forEach { interStage ->
val value = interStage.input
val arraySuffix = if (value is KslArray<*>) { "[${value.arraySize}]" } else { "" }
appendLine("${interStage.interpolation.glsl()} out ${glslTypeName(value.expressionType)} ${value.name()}${arraySuffix};")
}
appendLine()
}
}
protected open fun StringBuilder.generateInterStageInputs(fragmentStage: KslFragmentStage) {
if (fragmentStage.interStageVars.isNotEmpty()) {
appendLine("// custom fragment stage inputs")
fragmentStage.interStageVars.forEach { interStage ->
val value = interStage.output
val arraySuffix = if (value is KslArray<*>) { "[${value.arraySize}]" } else { "" }
appendLine("${interStage.interpolation.glsl()} in ${glslTypeName(value.expressionType)} ${value.name()}${arraySuffix};")
}
appendLine()
}
}
protected open fun StringBuilder.generateOutputs(outputs: List<KslStageOutput<*>>) {
if (outputs.isNotEmpty()) {
appendLine("// stage outputs")
outputs.forEach { output ->
val loc = if (output.location >= 0) "layout(location=${output.location}) " else ""
appendLine("${loc}out ${glslTypeName(output.expressionType)} ${output.value.name()};")
}
appendLine()
}
}
private fun StringBuilder.generateFunctions(stage: KslShaderStage) {
if (stage.functions.isNotEmpty()) {
val funcList = stage.functions.values.toMutableList()
sortFunctions(funcList)
funcList.forEach { func ->
appendLine("${glslTypeName(func.returnType)} ${func.name}(${func.parameters.joinToString { p -> "${glslTypeName(p.expressionType)} ${p.stateName}" }}) {")
appendLine(generateScope(func.body, blockIndent))
appendLine("}")
appendLine()
}
}
}
override fun opDeclareVar(op: KslDeclareVar): String {
val initExpr = op.initExpression?.let { " = ${it.generateExpression(this)}" } ?: ""
val state = op.declareVar
return "${glslTypeName(state.expressionType)} ${state.name()}${initExpr};"
}
override fun opDeclareArray(op: KslDeclareArray): String {
val initExpr = op.elements.joinToString { it.generateExpression(this) }
val array = op.declareVar
val typeName = glslTypeName(array.expressionType.elemType)
return "$typeName ${array.name()}[${array.arraySize}] = ${typeName}[](${initExpr});"
}
override fun opAssign(op: KslAssign<*>): String {
return "${op.assignTarget.generateAssignable(this)} = ${op.assignExpression.generateExpression(this)};"
}
override fun opAugmentedAssign(op: KslAugmentedAssign<*>): String {
return "${op.assignTarget.generateAssignable(this)} ${op.augmentationMode.opChar}= ${op.assignExpression.generateExpression(this)};"
}
override fun opIf(op: KslIf): String {
val txt = StringBuilder("if (${op.condition.generateExpression(this)}) {\n")
txt.appendLine(generateScope(op.body, blockIndent))
txt.append("}")
op.elseIfs.forEach { elseIf ->
txt.appendLine(" else if (${elseIf.first.generateExpression(this)}) {")
txt.appendLine(generateScope(elseIf.second, blockIndent))
txt.append("}")
}
if (op.elseBody.isNotEmpty()) {
txt.appendLine(" else {")
txt.appendLine(generateScope(op.elseBody, blockIndent))
txt.append("}")
}
return txt.toString()
}
override fun opFor(op: KslLoopFor<*>): String {
return StringBuilder("for (; ")
.append(op.whileExpression.generateExpression(this)).append("; ")
.append(op.loopVar.generateAssignable(this)).append(" += ").append(op.incExpr.generateExpression(this))
.appendLine(") {")
.appendLine(generateScope(op.body, blockIndent))
.append("}")
.toString()
}
override fun opWhile(op: KslLoopWhile): String {
return StringBuilder("while (${op.whileExpression.generateExpression(this)}) {\n")
.appendLine(generateScope(op.body, blockIndent))
.append("}")
.toString()
}
override fun opDoWhile(op: KslLoopDoWhile): String {
return StringBuilder("do {\n")
.appendLine(generateScope(op.body, blockIndent))
.append("} while (${op.whileExpression.generateExpression(this)});")
.toString()
}
override fun opBreak(op: KslLoopBreak) = "break;"
override fun opContinue(op: KslLoopContinue) = "continue;"
override fun opDiscard(op: KslDiscard): String = "discard;"
override fun opReturn(op: KslReturn): String = "return ${op.returnValue.generateExpression(this)};"
override fun opBlock(op: KslBlock): String {
val txt = StringBuilder("{ // block: ${op.opName}\n")
txt.appendLine(generateScope(op.body, blockIndent))
txt.append("}")
return txt.toString()
}
private fun generateArgs(args: List<KslExpression<*>>, expectedArgs: Int): String {
check(args.size == expectedArgs)
return args.joinToString { it.generateExpression(this) }
}
override fun invokeFunction(func: KslInvokeFunction<*>) = "${func.function.name}(${generateArgs(func.args, func.args.size)})"
override fun builtinAbs(func: KslBuiltinAbsScalar<*>) = "abs(${generateArgs(func.args, 1)})"
override fun builtinAbs(func: KslBuiltinAbsVector<*, *>) = "abs(${generateArgs(func.args, 1)})"
override fun builtinAtan2(func: KslBuiltinAtan2Scalar) = "atan(${generateArgs(func.args, 2)})"
override fun builtinAtan2(func: KslBuiltinAtan2Vector<*>) = "atan(${generateArgs(func.args, 2)})"
override fun builtinCeil(func: KslBuiltinCeilScalar) = "ceil(${generateArgs(func.args, 1)})"
override fun builtinCeil(func: KslBuiltinCeilVector<*>) = "ceil(${generateArgs(func.args, 1)})"
override fun builtinClamp(func: KslBuiltinClampScalar<*>) = "clamp(${generateArgs(func.args, 3)})"
override fun builtinClamp(func: KslBuiltinClampVector<*, *>) = "clamp(${generateArgs(func.args, 3)})"
override fun builtinCross(func: KslBuiltinCross) = "cross(${generateArgs(func.args, 2)})"
override fun builtinDegrees(func: KslBuiltinDegreesScalar) = "degrees(${generateArgs(func.args, 1)})"
override fun builtinDegrees(func: KslBuiltinDegreesVector<*>) = "degrees(${generateArgs(func.args, 1)})"
override fun builtinDistance(func: KslBuiltinDistanceScalar<*>) = "distance(${generateArgs(func.args, 2)})"
override fun builtinDot(func: KslBuiltinDot<*>) = "dot(${generateArgs(func.args, 2)})"
override fun builtinExp(func: KslBuiltinExpScalar) = "exp(${generateArgs(func.args, 1)})"
override fun builtinExp(func: KslBuiltinExpVector<*>) = "exp(${generateArgs(func.args, 1)})"
override fun builtinExp2(func: KslBuiltinExp2Scalar) = "exp2(${generateArgs(func.args, 1)})"
override fun builtinExp2(func: KslBuiltinExp2Vector<*>) = "exp2(${generateArgs(func.args, 1)})"
override fun builtinFaceForward(func: KslBuiltinFaceForward<*>) = "faceforward(${generateArgs(func.args, 3)})"
override fun builtinFloor(func: KslBuiltinFloorScalar) = "floor(${generateArgs(func.args, 1)})"
override fun builtinFloor(func: KslBuiltinFloorVector<*>) = "floor(${generateArgs(func.args, 1)})"
override fun builtinFma(func: KslBuiltinFmaScalar) = "fma(${generateArgs(func.args, 3)})"
override fun builtinFma(func: KslBuiltinFmaVector<*>) = "fma(${generateArgs(func.args, 3)})"
override fun builtinFract(func: KslBuiltinFractScalar) = "fract(${generateArgs(func.args, 1)})"
override fun builtinFract(func: KslBuiltinFractVector<*>) = "fract(${generateArgs(func.args, 1)})"
override fun builtinInverseSqrt(func: KslBuiltinInverseSqrtScalar) = "inversesqrt(${generateArgs(func.args, 1)})"
override fun builtinInverseSqrt(func: KslBuiltinInverseSqrtVector<*>) = "inversesqrt(${generateArgs(func.args, 1)})"
override fun builtinLength(func: KslBuiltinLength<*>) = "length(${generateArgs(func.args, 1)})"
override fun builtinLog(func: KslBuiltinLogScalar) = "log(${generateArgs(func.args, 1)})"
override fun builtinLog(func: KslBuiltinLogVector<*>) = "log(${generateArgs(func.args, 1)})"
override fun builtinLog2(func: KslBuiltinLog2Scalar) = "log2(${generateArgs(func.args, 1)})"
override fun builtinLog2(func: KslBuiltinLog2Vector<*>) = "log2(${generateArgs(func.args, 1)})"
override fun builtinMax(func: KslBuiltinMaxScalar<*>) = "max(${generateArgs(func.args, 2)})"
override fun builtinMax(func: KslBuiltinMaxVector<*, *>) = "max(${generateArgs(func.args, 2)})"
override fun builtinMin(func: KslBuiltinMinScalar<*>) = "min(${generateArgs(func.args, 2)})"
override fun builtinMin(func: KslBuiltinMinVector<*, *>) = "min(${generateArgs(func.args, 2)})"
override fun builtinMix(func: KslBuiltinMixScalar) = "mix(${generateArgs(func.args, 3)})"
override fun builtinMix(func: KslBuiltinMixVector<*>) = "mix(${generateArgs(func.args, 3)})"
override fun builtinNormalize(func: KslBuiltinNormalize<*>) = "normalize(${generateArgs(func.args, 1)})"
override fun builtinReflect(func: KslBuiltinReflect<*>) = "reflect(${generateArgs(func.args, 2)})"
override fun builtinRefract(func: KslBuiltinRefract<*>) = "refract(${generateArgs(func.args, 3)})"
override fun builtinRound(func: KslBuiltinRoundScalar) = "round(${generateArgs(func.args, 1)})"
override fun builtinRound(func: KslBuiltinRoundVector<*>) = "round(${generateArgs(func.args, 1)})"
override fun builtinSign(func: KslBuiltinSignScalar<*>) = "sign(${generateArgs(func.args, 1)})"
override fun builtinSign(func: KslBuiltinSignVector<*, *>) = "sign(${generateArgs(func.args, 1)})"
override fun builtinPow(func: KslBuiltinPowScalar) = "pow(${generateArgs(func.args, 2)})"
override fun builtinPow(func: KslBuiltinPowVector<*>) = "pow(${generateArgs(func.args, 2)})"
override fun builtinRadians(func: KslBuiltinRadiansScalar) = "radians(${generateArgs(func.args, 1)})"
override fun builtinRadians(func: KslBuiltinRadiansVector<*>) = "radians(${generateArgs(func.args, 1)})"
override fun builtinSmoothStep(func: KslBuiltinSmoothStepScalar) = "smoothstep(${generateArgs(func.args, 3)})"
override fun builtinSmoothStep(func: KslBuiltinSmoothStepVector<*>) = "smoothstep(${generateArgs(func.args, 3)})"
override fun builtinSqrt(func: KslBuiltinSqrtScalar) = "sqrt(${generateArgs(func.args, 1)})"
override fun builtinSqrt(func: KslBuiltinSqrtVector<*>) = "sqrt(${generateArgs(func.args, 1)})"
override fun builtinStep(func: KslBuiltinStepScalar) = "step(${generateArgs(func.args, 2)})"
override fun builtinStep(func: KslBuiltinStepVector<*>) = "step(${generateArgs(func.args, 2)})"
override fun builtinTrigonometry(func: KslBuiltinTrigonometryScalar) = "${func.name}(${generateArgs(func.args, 1)})"
override fun builtinTrigonometry(func: KslBuiltinTrigonometryVector<*>) = "${func.name}(${generateArgs(func.args, 1)})"
override fun builtinTrunc(func: KslBuiltinTruncScalar) = "trunc(${generateArgs(func.args, 1)})"
override fun builtinTrunc(func: KslBuiltinTruncVector<*>) = "trunc(${generateArgs(func.args, 1)})"
override fun builtinDeterminant(func: KslBuiltinDeterminant<*, *>) = "determinant(${generateArgs(func.args, 1)})"
override fun builtinTranspose(func: KslBuiltinTranspose<*, *>) = "transpose(${generateArgs(func.args, 1)})"
protected fun KslInterStageInterpolation.glsl(): String {
return when (this) {
KslInterStageInterpolation.Smooth -> "smooth"
KslInterStageInterpolation.Flat -> "flat"
KslInterStageInterpolation.NoPerspective -> "noperspective"
}
}
override fun KslState.name(): String {
return when (stateName) {
KslVertexStage.NAME_IN_VERTEX_INDEX -> "gl_VertexID"
KslVertexStage.NAME_IN_INSTANCE_INDEX -> "gl_InstanceID"
KslVertexStage.NAME_OUT_POSITION -> "gl_Position"
KslVertexStage.NAME_OUT_POINT_SIZE -> "gl_PointSize"
KslFragmentStage.NAME_IN_FRAG_POSITION -> "gl_FragCoord"
KslFragmentStage.NAME_IN_IS_FRONT_FACING -> "gl_FrontFacing"
KslFragmentStage.NAME_OUT_DEPTH -> "gl_FragDepth"
else -> stateName
}
}
protected fun glslTypeName(type: KslType): String {
return when (type) {
KslTypeVoid -> "void"
KslTypeBool1 -> "bool"
KslTypeBool2 -> "bvec2"
KslTypeBool3 -> "bvec3"
KslTypeBool4 -> "bvec4"
KslTypeFloat1 -> "float"
KslTypeFloat2 -> "vec2"
KslTypeFloat3 -> "vec3"
KslTypeFloat4 -> "vec4"
KslTypeInt1 -> "int"
KslTypeInt2 -> "ivec2"
KslTypeInt3 -> "ivec3"
KslTypeInt4 -> "ivec4"
KslTypeUint1 -> "uint"
KslTypeUint2 -> "uvec2"
KslTypeUint3 -> "uvec3"
KslTypeUint4 -> "uvec4"
KslTypeMat2 -> "mat2"
KslTypeMat3 -> "mat3"
KslTypeMat4 -> "mat4"
KslTypeColorSampler1d -> "sampler2D" // in WebGL2, 1d textures are not supported, simply use 2d instead (with height = 1px)
KslTypeColorSampler2d -> "sampler2D"
KslTypeColorSampler3d -> "sampler3D"
KslTypeColorSamplerCube -> "samplerCube"
KslTypeColorSampler2dArray -> "sampler2DArray"
KslTypeColorSamplerCubeArray -> "samplerCubeArray"
KslTypeDepthSampler2d -> "sampler2DShadow"
KslTypeDepthSamplerCube -> "samplerCubeShadow"
KslTypeDepthSampler2dArray -> "sampler2DArrayShadow"
KslTypeDepthSamplerCubeArray -> "samplerCubeArrayShadow"
is KslTypeArray<*> -> glslTypeName(type.elemType)
}
}
class GlslGeneratorOutput(val vertexSrc: String, val fragmentSrc: String) : GeneratorOutput {
private fun linePrefix(line: Int): String {
var num = "$line"
while (num.length < 3) {
num = " $num"
}
return "$num "
}
fun dump() {
println("### vertex shader:")
vertexSrc.lineSequence().forEachIndexed { i, line -> println("${linePrefix(i)}${line}") }
println("### fragment shader:")
fragmentSrc.lineSequence().forEachIndexed { i, line -> println("${linePrefix(i)}${line}") }
}
}
} | apache-2.0 |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/component/AliBaseProjectComponent.kt | 2 | 1176 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.smartfox.idea.common.component
import com.alibaba.smartfox.idea.common.util.PluginVersions
import com.intellij.openapi.components.ProjectComponent
/**
*
*
* @author caikang
* @date 2017/04/28
*/
interface AliBaseProjectComponent : ProjectComponent {
override fun getComponentName(): String {
return "${PluginVersions.pluginId.idString}-${javaClass.name}"
}
override fun disposeComponent() {
}
override fun projectClosed() {
}
override fun initComponent() {
}
override fun projectOpened() {
}
} | apache-2.0 |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/AddOnViewHolderViewModel.kt | 1 | 9774 | package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.R
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.models.Country
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.RewardUtils
import com.kickstarter.libs.utils.extensions.negate
import com.kickstarter.models.Project
import com.kickstarter.models.Reward
import com.kickstarter.models.RewardsItem
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.ui.viewholders.RewardViewHolder
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import java.math.RoundingMode
interface AddOnViewHolderViewModel {
interface Inputs {
/** Configure with the current [ProjectData] and [Reward].
* @param projectData we get the Project for currency
* @param reward the actual reward, add on, no reward loading on the ViewHolder
*/
fun configureWith(projectData: ProjectData, reward: Reward)
}
interface Outputs {
/** Emits `true` if the title for addons should be hidden, `false` otherwise. */
fun isAddonTitleGone(): Observable<Boolean>
/** Emits the reward's minimum converted to the user's preference */
fun conversion(): Observable<String>
/** Emits `true` if the conversion should be hidden, `false` otherwise. */
fun conversionIsGone(): Observable<Boolean>
/** Emits the reward's description when `isNoReward` is true. */
fun descriptionForNoReward(): Observable<Int>
/** Emits the reward's description. */
fun descriptionForReward(): Observable<String?>
/** Emits the minimum pledge amount in the project's currency. */
fun minimumAmountTitle(): Observable<String>
/** Emits the reward's items. */
fun rewardItems(): Observable<List<RewardsItem>>
/** Emits `true` if the items section should be hidden, `false` otherwise. */
fun rewardItemsAreGone(): Observable<Boolean>
/** Emits the reward's title when `isReward` is true. */
fun titleForReward(): Observable<String?>
/** Emits the reward's title when `noReward` is true. */
fun titleForNoReward(): Observable<Int>
/** Emits a pait with the add on title and the quantity in order to build the stylized title */
fun titleForAddOn(): Observable<Pair<String, Int>>
/** Emits a boolean that determines if the local PickUp section should be hidden **/
fun localPickUpIsGone(): Observable<Boolean>
/** Emits the String with the Local Pickup Displayable name **/
fun localPickUpName(): Observable<String>
}
/**
* Logic to handle the UI for `Reward`, `No Reward` and `Add On`
* Configuring the View for [AddOnViewHolder]
* - No interaction with the user just displaying information
* - Loading in [AddOnViewHolder] -> [RewardAndAddOnsAdapter] -> [BackingFragment]
*/
class ViewModel(@NonNull environment: Environment) : ActivityViewModel<RewardViewHolder>(environment), Inputs, Outputs {
private val ksCurrency = requireNotNull(environment.ksCurrency())
private val isAddonTitleGone = BehaviorSubject.create<Boolean>()
private val projectDataAndReward = PublishSubject.create<Pair<ProjectData, Reward>>()
private val conversion = BehaviorSubject.create<String>()
private val conversionIsGone = BehaviorSubject.create<Boolean>()
private val descriptionForNoReward = BehaviorSubject.create<Int>()
private val titleForNoReward = BehaviorSubject.create<Int>()
private val descriptionForReward = BehaviorSubject.create<String?>()
private val minimumAmountTitle = PublishSubject.create<String>()
private val rewardItems = BehaviorSubject.create<List<RewardsItem>>()
private val rewardItemsAreGone = BehaviorSubject.create<Boolean>()
private val titleForReward = BehaviorSubject.create<String?>()
private val titleForAddOn = BehaviorSubject.create<Pair<String, Int>>()
private val titleIsGone = BehaviorSubject.create<Boolean>()
private val localPickUpIsGone = BehaviorSubject.create<Boolean>()
private val localPickUpName = BehaviorSubject.create<String>()
private val optimizely = environment.optimizely()
val inputs: Inputs = this
val outputs: Outputs = this
init {
val reward = this.projectDataAndReward
.map { it.second }
val projectAndReward = this.projectDataAndReward
.map { Pair(it.first.project(), it.second) }
projectAndReward
.map { buildCurrency(it.first, it.second) }
.compose(bindToLifecycle())
.subscribe(this.minimumAmountTitle)
projectAndReward
.map { it.first }
.map { it.currency() == it.currentCurrency() }
.compose(bindToLifecycle())
.subscribe(this.conversionIsGone)
projectAndReward
.map { getCurrency(it) }
.compose(bindToLifecycle())
.subscribe(this.conversion)
reward
.filter { RewardUtils.isReward(it) }
.map { it.description() }
.compose(bindToLifecycle())
.subscribe(this.descriptionForReward)
reward
.filter { !it.isAddOn() && RewardUtils.isNoReward(it) }
.compose(bindToLifecycle())
.subscribe {
this.descriptionForNoReward.onNext(R.string.Thanks_for_bringing_this_project_one_step_closer_to_becoming_a_reality)
this.titleForNoReward.onNext(R.string.You_pledged_without_a_reward)
}
reward
.filter { RewardUtils.isItemized(it) }
.map { if (it.isAddOn()) it.addOnsItems() else it.rewardsItems() }
.compose(bindToLifecycle())
.subscribe(this.rewardItems)
reward
.map { RewardUtils.isItemized(it) }
.map { it.negate() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.rewardItemsAreGone)
reward
.filter { !it.isAddOn() && RewardUtils.isReward(it) }
.map { it.title() }
.compose(bindToLifecycle())
.subscribe(this.titleForReward)
reward
.map { !it.isAddOn() }
.compose(bindToLifecycle())
.subscribe(this.titleIsGone)
reward
.filter { it.isAddOn() && it.quantity()?.let { q -> q > 0 } ?: false }
.map { reward -> parametersForTitle(reward) }
.compose(bindToLifecycle())
.subscribe(this.titleForAddOn)
reward
.filter { !RewardUtils.isShippable(it) }
.map {
RewardUtils.isLocalPickup(it)
}
.compose(bindToLifecycle())
.subscribe {
this.localPickUpIsGone.onNext(!it)
}
reward
.filter { !RewardUtils.isShippable(it) }
.filter { RewardUtils.isLocalPickup(it) }
.map { it.localReceiptLocation()?.displayableName() }
.filter { ObjectUtils.isNotNull(it) }
.compose(bindToLifecycle())
.subscribe(this.localPickUpName)
}
private fun getCurrency(it: Pair<Project, Reward>) =
this.ksCurrency.format(it.second.convertedMinimum(), it.first, true, RoundingMode.HALF_UP, true)
private fun buildCurrency(project: Project, reward: Reward): String {
val completeCurrency = ksCurrency.format(reward.minimum(), project, RoundingMode.HALF_UP)
val country = Country.findByCurrencyCode(project.currency()) ?: ""
return completeCurrency.removePrefix(country.toString())
}
private fun parametersForTitle(reward: Reward?): Pair<String, Int> {
val title = reward?.title()?.let { it } ?: ""
val quantity = reward?.quantity()?.let { it } ?: -1
return Pair(title, quantity)
}
override fun configureWith(projectData: ProjectData, reward: Reward) = this.projectDataAndReward.onNext(Pair.create(projectData, reward))
override fun isAddonTitleGone(): Observable<Boolean> = this.isAddonTitleGone
override fun conversion(): Observable<String> = this.conversion
override fun conversionIsGone(): Observable<Boolean> = this.conversionIsGone
override fun descriptionForNoReward(): Observable<Int> = this.descriptionForNoReward
override fun titleForNoReward(): Observable<Int> = this.titleForNoReward
override fun descriptionForReward(): Observable<String?> = this.descriptionForReward
override fun minimumAmountTitle(): Observable<String> = this.minimumAmountTitle
override fun rewardItems(): Observable<List<RewardsItem>> = this.rewardItems
override fun rewardItemsAreGone(): Observable<Boolean> = this.rewardItemsAreGone
override fun titleForReward(): Observable<String?> = this.titleForReward
override fun titleForAddOn(): Observable<Pair<String, Int>> = this.titleForAddOn
override fun localPickUpIsGone(): Observable<Boolean> = localPickUpIsGone
override fun localPickUpName(): Observable<String> = localPickUpName
}
}
| apache-2.0 |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Alarm.kt | 1 | 585 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_History_Alarm @JvmOverloads constructor(
injector: HasAndroidInjector,
from: Long = 0
) : DanaRS_Packet_History_(injector, from) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__ALARM
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__ALARM"
}
} | agpl-3.0 |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliEqualsAvoidNullInspection.kt | 2 | 4918 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.p3c.idea.inspection
import com.alibaba.p3c.idea.i18n.P3cBundle
import com.alibaba.p3c.idea.quickfix.DecorateInspectionGadgetsFix
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiField
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import com.siyeh.HardcodedMethodConstants
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import com.siyeh.ig.psiutils.TypeUtils
import com.siyeh.ig.style.LiteralAsArgToStringEqualsInspection
import org.jetbrains.annotations.NonNls
/**
*
* Batch QuickFix Supported
* @author caikang
* @date 2017/02/27
*/
class AliEqualsAvoidNullInspection : LiteralAsArgToStringEqualsInspection, AliBaseInspection {
constructor()
/**
* For Javassist
*/
constructor(any: Any?) : this()
override fun ruleName(): String {
return "EqualsAvoidNullRule"
}
override fun getDisplayName(): String {
return RuleInspectionUtils.getRuleMessage(ruleName())
}
override fun buildErrorString(vararg infos: Any?): String {
val methodName = infos[0] as String
return String.format(P3cBundle.getMessage("com.alibaba.p3c.idea.inspection.rule.AliEqualsAvoidNull.errMsg"),
methodName)
}
override fun getShortName(): String {
return "AliEqualsAvoidNull"
}
override fun getStaticDescription(): String? {
return RuleInspectionUtils.getRuleStaticDescription(ruleName())
}
override fun getDefaultLevel(): HighlightDisplayLevel {
return RuleInspectionUtils.getHighlightDisplayLevel(ruleName())
}
override fun buildVisitor(): BaseInspectionVisitor {
return LiteralAsArgToEqualsVisitor()
}
private class LiteralAsArgToEqualsVisitor : BaseInspectionVisitor() {
override fun visitMethodCallExpression(
expression: PsiMethodCallExpression) {
super.visitMethodCallExpression(expression)
val methodExpression = expression.methodExpression
@NonNls val methodName = methodExpression.referenceName
if (HardcodedMethodConstants.EQUALS != methodName && HardcodedMethodConstants.EQUALS_IGNORE_CASE != methodName) {
return
}
val argList = expression.argumentList
val args = argList.expressions
if (args.size != 1) {
return
}
val argument = args[0]
val argumentType = argument.type ?: return
if (argument !is PsiLiteralExpression && !isConstantField(argument)) {
return
}
if (!TypeUtils.isJavaLangString(argumentType)) {
return
}
val target = methodExpression.qualifierExpression
if (target is PsiLiteralExpression || isConstantField(argument)) {
return
}
registerError(argument, methodName)
}
private fun isConstantField(argument: PsiExpression): Boolean {
if (argument !is PsiReferenceExpression) {
return false
}
val psiField = argument.resolve() as? PsiField ?: return false
val modifierList = psiField.modifierList ?: return false
return modifierList.hasModifierProperty("final") && modifierList.hasModifierProperty("static")
}
}
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val fix = super.buildFix(*infos) ?: return null
return DecorateInspectionGadgetsFix(fix,
P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.AliEqualsAvoidNull"))
}
override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? {
return buildFix(psiElement)
}
override fun manualParsePsiElement(psiFile: PsiFile, manager: InspectionManager, start: Int, end: Int): PsiElement {
return psiFile.findElementAt(start)!!.parent.parent
}
}
| apache-2.0 |
Setekh/corvus-android-essentials | app/src/main/java/eu/corvus/essentials/core/tasks.kt | 1 | 3751 | package eu.corvus.essentials.core
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
/**
* Created by Vlad Cazacu on 05.05.2017.
*/
class Promise<T> {
var isSuccessful = false
var isCanceled = false
var future: Future<*>? = null
set(value) {
if(isCanceled)
value?.cancel(true)
field = value
}
internal val successHandlers = LinkedList<ResultCallbackHolder<T>>()
internal val failHandlers = LinkedList<ResultCallbackHolder<Throwable>>()
internal var alwaysHandler: ResultCallbackHolder<Unit>? = null
fun cancel(mayInterruptIfRunning: Boolean) {
isCanceled = true
future?.cancel(mayInterruptIfRunning)
}
fun doSuccess(returns: T) {
isSuccessful = true
successHandlers.forEach {
if(it.isUi)
threads.uiHandler.post { it.resultHandler.invoke(true, returns) }
else
it.resultHandler.invoke(true, returns)
}
}
fun doFail(returns: Throwable) {
isSuccessful = false
failHandlers.forEach {
if(it.isUi)
threads.uiHandler.post { it.resultHandler.invoke(false, returns) }
else
it.resultHandler.invoke(false, returns)
}
}
class ResultCallbackHolder<in E>(val isUi: Boolean, val resultHandler: (Boolean, E) -> Unit)
fun doFinally() {
successHandlers.clear()
failHandlers.clear()
val alwaysHandler = alwaysHandler ?: return
this.alwaysHandler = null
if(alwaysHandler.isUi)
threads.uiHandler.post { alwaysHandler.resultHandler.invoke(isSuccessful, Unit) }
else
alwaysHandler.resultHandler.invoke(isSuccessful, Unit)
}
fun get(): T {
if(isCanceled)
throw InterruptedException("Task interrupted!")
return future!!.get() as T
}
}
fun <V> task(body: () -> V): Promise<V> {
val promise = Promise<V>()
val futureTask = FutureTask<V>(Callable {
var value: V? = null
try {
val v = body.invoke()
value = v
promise.doSuccess(v)
} catch (e: Exception) {
promise.doFail(e)
} finally {
promise.doFinally()
}
value
})
promise.future = futureTask
threads.uiHandler.post { // on the next loop
threads.executionService.submit(futureTask)
}
return promise
}
infix fun <T> Promise<T>.success(callback: ((T) -> Unit)) : Promise<T> {
successHandlers += Promise.ResultCallbackHolder(false, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.fail(callback: ((Throwable) -> Unit)) : Promise<T> {
failHandlers += Promise.ResultCallbackHolder(false, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.successUi(callback: ((T) -> Unit)) : Promise<T> {
successHandlers += Promise.ResultCallbackHolder(true, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.failUi(callback: ((Throwable) -> Unit)) : Promise<T> {
failHandlers += Promise.ResultCallbackHolder(true, { _, returns -> callback.invoke(returns) })
return this
}
infix fun <T> Promise<T>.finally(callback: ((Boolean) -> Unit)) : Promise<T> {
alwaysHandler = Promise.ResultCallbackHolder(false, { success, _ -> callback.invoke(success) })
return this
}
infix fun <T> Promise<T>.finallyUi(callback: ((Boolean) -> Unit)) : Promise<T> {
alwaysHandler = Promise.ResultCallbackHolder(true, { success, _ -> callback.invoke(success) })
return this
}
| apache-2.0 |
mdaniel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/productInfo/ProductInfoGenerator.kt | 1 | 2848 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl.productInfo
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.BuiltinModulesFileData
internal const val PRODUCT_INFO_FILE_NAME = "product-info.json"
@OptIn(ExperimentalSerializationApi::class)
internal val jsonEncoder by lazy {
Json {
prettyPrint = true
prettyPrintIndent = " "
encodeDefaults = false
explicitNulls = false
}
}
/**
* Generates product-info.json file containing meta-information about product installation.
*/
internal fun generateMultiPlatformProductJson(relativePathToBin: String,
builtinModules: BuiltinModulesFileData?,
launch: List<ProductInfoLaunchData>,
context: BuildContext): String {
val appInfo = context.applicationInfo
val json = ProductInfoData(
name = appInfo.productName,
version = appInfo.fullVersion,
versionSuffix = appInfo.versionSuffix,
buildNumber = context.buildNumber,
productCode = appInfo.productCode,
dataDirectoryName = context.systemSelector,
svgIconPath = if (appInfo.svgRelativePath == null) null else "$relativePathToBin/${context.productProperties.baseFileName}.svg",
launch = launch,
customProperties = context.productProperties.generateCustomPropertiesForProductInfo(),
bundledPlugins = builtinModules?.bundledPlugins ?: emptyList(),
fileExtensions = builtinModules?.fileExtensions ?: emptyList(),
modules = builtinModules?.modules ?: emptyList(),
)
return jsonEncoder.encodeToString(serializer(), json)
}
/**
* Describes format of JSON file containing meta-information about a product installation. Must be consistent with 'product-info.schema.json' file.
*/
@Serializable
data class ProductInfoData(
val name: String,
val version: String,
val versionSuffix: String?,
val buildNumber: String,
val productCode: String,
val dataDirectoryName: String,
val svgIconPath: String?,
val launch: List<ProductInfoLaunchData> = emptyList(),
val customProperties: List<CustomProperty> = emptyList(),
val bundledPlugins: List<String>,
val modules: List<String>,
val fileExtensions: List<String>,
)
@Serializable
data class ProductInfoLaunchData(
val os: String,
val launcherPath: String,
val javaExecutablePath: String?,
val vmOptionsFilePath: String,
val startupWmClass: String? = null,
)
@Serializable
data class CustomProperty(
val key: String,
val value: String,
) | apache-2.0 |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/extensions/ObservableExtensions.kt | 1 | 641 | package acr.browser.lightning.extensions
import io.reactivex.Observable
import io.reactivex.Single
import java.io.IOException
/**
* Filters the [Observable] to only instances of [T].
*/
inline fun <reified T> Observable<out Any>.filterInstance(): Observable<T> {
return this.filter { it is T }.map { it as T }
}
/**
* On an [IOException], resume with the value provided by the [mapper].
*/
inline fun <T> Single<T>.onIOExceptionResumeNext(
crossinline mapper: (IOException) -> T
): Single<T> = this.onErrorResumeNext {
if (it is IOException) {
Single.just(mapper(it))
} else {
Single.error(it)
}
}
| mpl-2.0 |
leafclick/intellij-community | platform/indexing-impl/src/com/intellij/model/search/impl/DecomposableQuery.kt | 1 | 309 | // 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.model.search.impl
import com.intellij.util.Query
internal interface DecomposableQuery<R> : Query<R> {
fun decompose(): PrimitiveRequests<R>
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.