repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
WindSekirun/RichUtilsKt
RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RPickMedia.kt
1
10154
@file:JvmName("RPickMedia") package pyxis.uzuki.live.richutilskt.utils import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.net.Uri import android.provider.MediaStore import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import android.support.v4.app.FragmentManager import pyxis.uzuki.live.richutilskt.impl.F2 import pyxis.uzuki.live.richutilskt.module.image.OrientationFixer class RPickMedia private constructor() { private var mInternalStorage: Boolean = false private var fixPhotoOrientation: Boolean = false private val PERMISSION_ARRAY = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA) private lateinit var title: String private fun getActivity(context: Context): FragmentActivity? { var c = context while (c is ContextWrapper) { if (c is FragmentActivity) { return c } c = c.baseContext } return null } private fun Context.requestPermission(listener: (Boolean) -> Unit) { RPermission.instance.checkPermission(this, PERMISSION_ARRAY) { code, _ -> listener.invoke(code == RPermission.PERMISSION_GRANTED) } } /** * enable internal storage mode * * @param [isInternal] capture Image/Video in internal storage */ fun setInternalStorage(isInternal: Boolean) { mInternalStorage = isInternal } /** * enable fixing orientation * * @param [enable] fixing orientation */ fun setFixPhotoOrientation(enable: Boolean) { this.fixPhotoOrientation = enable } /** * set title of media when capture using PICK_FROM_CAMERA and PICK_FROM_CAMERA_VIDEO */ fun setTitle(title: String) { this.title = title } /** * pick image from Camera * * @param[callback] callback */ fun pickFromCamera(context: Context, callback: (Int, String) -> Unit) { context.requestPermission { if (!it) { callback.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_CAMERA, callback) } } /** * pick image from Camera * * @param[callback] callback */ fun pickFromCamera(context: Context, callback: F2<Int, String>?) { context.requestPermission { if (!it) { callback?.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_CAMERA) { code, uri -> callback?.invoke(code, uri) } } } /** * pick image from Gallery * * @param[callback] callback */ fun pickFromGallery(context: Context, callback: (Int, String) -> Unit) { context.requestPermission { if (!it) { callback.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_GALLERY, callback) } } /** * pick image from Gallery * * @param[callback] callback */ fun pickFromGallery(context: Context, callback: F2<Int, String>?) { context.requestPermission { if (!it) { callback?.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_GALLERY) { code, uri -> callback?.invoke(code, uri) } } } /** * pick image from Video * * @param[callback] callback */ fun pickFromVideo(context: Context, callback: (Int, String) -> Unit) { context.requestPermission { if (!it) { callback.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_VIDEO, callback) } } /** * pick image from Video * * @param[callback] callback */ fun pickFromVideo(context: Context, callback: F2<Int, String>?) { context.requestPermission { if (!it) { callback?.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_VIDEO, { code, uri -> callback?.invoke(code, uri) }) } } /** * pick image from Camera (Video Mode) * * @param[callback] callback */ fun pickFromVideoCamera(context: Context, callback: (Int, String) -> Unit) { context.requestPermission { if (!it) { callback.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_CAMERA_VIDEO, callback) } } /** * pick image from Camera (Video Mode) * * @param[callback] callback */ fun pickFromVideoCamera(context: Context, callback: F2<Int, String>?) { context.requestPermission { if (!it) { callback?.invoke(PICK_FAILED, "") return@requestPermission } requestPhotoPick(context, PICK_FROM_CAMERA_VIDEO, { code, uri -> callback?.invoke(code, uri) }) } } private var currentPhotoPath: String? = null private var currentVideoPath: String? = null @SuppressLint("ValidFragment") private fun requestPhotoPick(context: Context, pickType: Int, callback: (Int, String) -> Unit) { val fm = getActivity(context)?.supportFragmentManager val intent = Intent() if (!::title.isInitialized) { title = nowDateString() } when (pickType) { PICK_FROM_CAMERA -> { intent.action = MediaStore.ACTION_IMAGE_CAPTURE val captureUri = createUri(context, false, mInternalStorage, title) currentPhotoPath = captureUri.toString() intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri) } PICK_FROM_GALLERY -> { intent.action = Intent.ACTION_PICK intent.type = android.provider.MediaStore.Images.Media.CONTENT_TYPE } PICK_FROM_VIDEO -> { intent.action = Intent.ACTION_PICK intent.type = android.provider.MediaStore.Video.Media.CONTENT_TYPE } PICK_FROM_CAMERA_VIDEO -> { intent.action = MediaStore.ACTION_VIDEO_CAPTURE val captureUri = createUri(context, true, mInternalStorage, title) currentVideoPath = captureUri.toString() intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri) } } val fragment = ResultFragment(fm as FragmentManager, callback, currentPhotoPath ?: "", currentVideoPath ?: "") fragment.fixPhotoOrientation = fixPhotoOrientation fm.beginTransaction().add(fragment, "FRAGMENT_TAG").commitAllowingStateLoss() fm.executePendingTransactions() fragment.startActivityForResult(intent, pickType) } @SuppressLint("ValidFragment") class ResultFragment() : Fragment() { var fm: FragmentManager? = null var callback: ((Int, String) -> Unit)? = null var currentPhotoPath = "" var currentVideoPath = "" var fixPhotoOrientation: Boolean = false constructor(fm: FragmentManager, callback: (Int, String) -> Unit, currentPhotoPath: String, currentVideoPath: String) : this() { this.fm = fm this.callback = callback this.currentPhotoPath = currentPhotoPath this.currentVideoPath = currentVideoPath } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (callback == null) { return } val callback = callback!! // implicit cast to non-null cause checking pre-processing if (resultCode != Activity.RESULT_OK || context == null) { callback.invoke(PICK_FAILED, "") return } val context = context!! // implicit cast to non-null cause checking pre-processing var realPath: String? = "" if (requestCode == PICK_FROM_CAMERA) { val uri = Uri.parse(currentPhotoPath) realPath = uri getRealPath context if (fixPhotoOrientation) { realPath = OrientationFixer.execute(realPath, context) } } else if (requestCode == PICK_FROM_CAMERA_VIDEO && data != null && data.data != null) { realPath = data.data.getRealPath(context) if (realPath.isEmpty()) { realPath = Uri.parse(currentVideoPath) getRealPath context } } else if (requestCode == PICK_FROM_CAMERA_VIDEO) { realPath = Uri.parse(currentVideoPath) getRealPath context } else if (data != null && data.data != null) { realPath = data.data.getRealPath(context) if (fixPhotoOrientation) { realPath = OrientationFixer.execute(realPath, context) } } if (realPath?.isEmpty() != false) { callback.invoke(PICK_FAILED, "") return } callback.invoke(PICK_SUCCESS, realPath) fm?.beginTransaction()?.remove(this)?.commit() } } companion object { @JvmField var instance: RPickMedia = RPickMedia() val PICK_FROM_CAMERA = 0 val PICK_FROM_GALLERY = 1 val PICK_FROM_VIDEO = 2 val PICK_FROM_CAMERA_VIDEO = 3 @JvmField val PICK_SUCCESS = 1 @JvmField val PICK_FAILED = 0 } }
apache-2.0
e6aafad77c38e3d7053dd75c61a280ae
29.587349
136
0.578097
4.936315
false
false
false
false
MaKToff/Codename_Ghost
core/src/com/cypress/GameObjects/Enemies/Warrior.kt
1
6788
package com.cypress.GameObjects.Enemies import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.utils.Array import com.cypress.CGHelpers.AssetLoader import com.cypress.GameObjects.* /** */ class Warrior(public override val position : Vector2, private val player : Player) : Character() { public override val isEnemy = true public override val width = 115 public override val height = 180 public override val bounds = Rectangle(0f, 0f, width.toFloat(), height.toFloat()) public override val velocity = Vector2(4f, 12f) public override val offsetY = 18f public override val offsetX = 10f public override var health = 50 public override var shouldGoToLeft = false public override var delta = 0f public override var shouldJump = false public override var shouldGoToRight = false public override var stayRight = false public override var onGround = true public override var gunType = "uzi" public override var isDead = false private val assets = AssetLoader.getInstance() private val uziLeft = TextureRegion(assets.guns, 281, 95, 90, 58) private var warriorGoesLeft = Animation(0.1f, Array<TextureRegion>()) private var warriorGoesRight = Animation(0.1f, Array<TextureRegion>()) private var warriorStayRight = TextureRegion(assets.warrior, 25, 11, width, height) private var warriorStayLeft = TextureRegion(assets.warrior, 201, 11, width, height) private var counter = 0 private var canShoot = false private var startValue = 0f init { // setting animation val posR = arrayOf(Pair( 28, 235), Pair(350, 237), Pair(674, 236), Pair( 30, 445), Pair(361, 445), Pair(678, 445), Pair( 23, 662), Pair(349, 662), Pair(688, 663)) val posL = arrayOf(Pair(200, 236), Pair(529, 236), Pair(871, 236), Pair(199, 445), Pair(519, 442), Pair(864, 442), Pair(204, 662), Pair(528, 661), Pair(853, 661)) val warriorsRight = Array<TextureRegion>() val warriorsLeft = Array<TextureRegion>() warriorsRight.addAll( Array(9, {i -> TextureRegion(assets.warrior, posR[i].first, posR[i].second, width, height)}), 0, 8 ) warriorsLeft.addAll( Array(9, {i -> TextureRegion(assets.warrior, posL[i].first, posL[i].second, width, height)}), 0, 8 ) warriorGoesRight = Animation(0.1f, warriorsRight, Animation.PlayMode.LOOP) warriorGoesLeft = Animation(0.1f, warriorsLeft, Animation.PlayMode.LOOP) } /** Defines actions of warrior. */ public fun update(delta : Float) { counter++ // movement of warrior if (position.y <= 80f) { onGround = true position.y = 80f velocity.y = 12f } // falling else { if (velocity.y < -9) velocity.y = -9f position.y += velocity.y velocity.y -= 0.2f } val distanceX = player.getX() - position.x val distanceY = Math.abs(player.getY() - position.y) if (counter % 50 == 0) { canShoot = true counter = 0 } else canShoot = false // warrior pursues player if (stayRight && distanceX > 0 && distanceX < 300f && distanceY < 500) { shouldGoToRight = false shouldGoToLeft = false if (canShoot) { assets.bulletsList.add(Bullet(this)) assets.shot[0]?.stop() if (assets.musicOn) assets.shot[0]?.play() } } else if (stayRight && distanceX >= 300f && distanceX < 500f) { position.x += velocity.x shouldGoToRight = true shouldGoToLeft = false } else if (!stayRight && distanceX < 0 && distanceX > -300f && distanceY < 500) { shouldGoToRight = false shouldGoToLeft = false if (canShoot) { assets.bulletsList.add(Bullet(this)) assets.shot[0]?.stop() if (assets.musicOn) assets.shot[0]?.play() } } else if (!stayRight && distanceX <= -300f && distanceX > -500f) { position.x -= velocity.x shouldGoToRight = false shouldGoToLeft = true } else if (distanceX == 0f) stayRight = !stayRight // warrior can't find player and looks around else { shouldGoToRight = false shouldGoToLeft = false if (delta.hashCode() % 100 == 0) stayRight = !stayRight } } /** Draws warrior. */ public fun draw(delta : Float, batcher : SpriteBatch) { if (!isDead) startValue = delta batcher.begin() // warrior is dead if (isDead) { batcher.draw(death.getKeyFrame(delta - startValue), position.x, position.y, 155f, 155f) if (delta - startValue > 0.5f) isDead = false } else { if (shouldGoToLeft || !stayRight) batcher.draw(uziLeft, position.x - 55, position.y + 25, 90f, 58f) // warrior should stay still ... if (!shouldGoToLeft && !shouldGoToRight) { when (stayRight) { // ... turning to the right side true -> batcher.draw(warriorStayRight, position.x, position.y, width.toFloat(), height.toFloat()) // ... turning to the left side false -> batcher.draw(warriorStayLeft, position.x, position.y, width.toFloat(), height.toFloat()) } } // warrior should go to left else if (shouldGoToLeft) { stayRight = false batcher.draw(warriorGoesLeft.getKeyFrame(delta), position.x, position.y, width.toFloat(), height.toFloat()) } // warrior should go to right else if (shouldGoToRight) { stayRight = true batcher.draw(warriorGoesRight.getKeyFrame(delta), position.x, position.y, width.toFloat(), height.toFloat()) } } batcher.end() } /** Returns position of warrior on Ox axis. */ public override fun getX(): Float = position.x /** Returns position of warrior on Oy axis. */ public override fun getY(): Float = position.y /** Returns bounds of player. */ public fun getBound() : Rectangle = bounds }
apache-2.0
2a2e0767d319c1d18621d4350775357b
37.350282
124
0.574838
4.370895
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/fragments/FavedCommentFragment.kt
1
1460
package com.pr0gramm.app.ui.fragments import androidx.lifecycle.lifecycleScope import com.pr0gramm.app.R import com.pr0gramm.app.Settings import com.pr0gramm.app.api.pr0gramm.Message import com.pr0gramm.app.services.FavedCommentService import com.pr0gramm.app.services.UserService import com.pr0gramm.app.ui.MessageAdapter import com.pr0gramm.app.ui.Pagination import com.pr0gramm.app.ui.PaginationController import com.pr0gramm.app.util.di.instance /** */ class FavedCommentFragment : InboxFragment("FavedCommentFragment") { private val favedCommentService: FavedCommentService by instance() private val userService: UserService by instance() override fun getContentAdapter(): Pair<MessageAdapter, Pagination<Message>> { val loader = apiMessageLoader(requireContext()) { olderThan -> val username = userService.name if (username == null || !userService.isAuthorized) { return@apiMessageLoader listOf() } favedCommentService.list(Settings.contentType, username, olderThan).map { FavedCommentService.commentToMessage(it) } } // create and initialize the adapter val pagination = Pagination(lifecycleScope, loader) val adapter = MessageAdapter( R.layout.row_inbox_message, actionListener, null, PaginationController(pagination)) return Pair(adapter, pagination) } }
mit
23c895589775c4b75ccbdeed15864c7e
34.609756
85
0.710959
4.464832
false
false
false
false
android/android-studio-poet
aspoet/src/main/kotlin/com/google/androidstudiopoet/gradle/GradleLang.kt
1
1836
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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.androidstudiopoet.gradle interface Statement { fun toGroovy(indentNumber: Int): String } data class StringStatement(val value: String) : Statement { override fun toGroovy(indentNumber: Int): String = INDENT.repeat(indentNumber) + value } data class Expression(val left: String, val right: String) : Statement { override fun toGroovy(indentNumber: Int): String = "${INDENT.repeat(indentNumber)}$left $right" } class Closure(val name: String, val statements: List<Statement>) : Statement { override fun toGroovy(indentNumber: Int): String { val indent = INDENT.repeat(indentNumber) return """$indent$name { ${statements.joinToString(separator = "\n") { it.toGroovy(indentNumber + 1) }} $indent}""" } } data class Task(val name: String, val arguments: List<TaskParameter>, val statements: List<Statement>) : Statement { override fun toGroovy(indentNumber: Int): String { val indent = INDENT.repeat(indentNumber) return """${indent}task $name(${arguments.joinToString { "${it.name}: ${it.value}" }}) { ${statements.joinToString(separator = "\n") { it.toGroovy(indentNumber + 1) }} $indent}""" } } data class TaskParameter(val name: String, val value: String) private const val INDENT = " "
apache-2.0
32421ad684c6abf960a13810d11eef09
34.326923
116
0.724401
4.182232
false
false
false
false
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/util/StringUtils.kt
1
4191
/* * Copyright 2016-2019 Adrian Cotfas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.apps.adrcotfas.goodtime.util import java.time.* import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.time.temporal.TemporalAdjusters import java.util.* import kotlin.math.roundToInt object StringUtils { private val backUpFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm") private val dayOfWeekFormatter = DateTimeFormatter.ofPattern("E") private val suffixes: NavigableMap<Long, String> = TreeMap() /** * Shortens a value in minutes to a easier to read format of maximum 4 characters * Do not use this for anything else than the History chart before removing the extra left padding hack * @param value the value in minutes to be formatted * @return the formatted value */ fun formatLong(value: Long): String { //Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here if (value == Long.MIN_VALUE) return formatLong(Long.MIN_VALUE + 1) if (value < 0) return "-" + formatLong(-value) if (value < 1000) return value.toString() //deal with easy case val e = suffixes.floorEntry(value)!! val divideBy = e.key val suffix = e.value val truncated = value / (divideBy / 10) //the number part of the output times 10 val hasDecimal = truncated < 100 && truncated / 10.0 != (truncated / 10).toDouble() return if (hasDecimal) (truncated / 10.0).toString() + suffix else (truncated / 10).toString() + suffix } fun formatDateAndTime(millis: Long): String { return millis.toLocalDateTime().format(backUpFormatter) } @JvmStatic fun formatTimeForStatistics(millis: Long?): String { val date = LocalDateTime.ofInstant( Instant.ofEpochMilli( millis!! ), ZoneId.systemDefault() ) return date.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)) } @JvmStatic fun formatDateForStatistics(millis: Long?): String { val date = LocalDateTime.ofInstant( Instant.ofEpochMilli( millis!! ), ZoneId.systemDefault() ) return "${date.format(DateTimeFormatter.ofPattern("EEEE"))} ${date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))}" } fun toPercentage(value: Float): String { return (100 * value).roundToInt().toString() + "%" } fun toDayOfWeek(value: Int): String { return LocalDateTime.now().with(TemporalAdjusters.next(DayOfWeek.of(value))).format(dayOfWeekFormatter) } fun toHourOfDay(hour: Int, is24HourFormat: Boolean): String { val time = LocalTime.now().withHour(hour) return time.format( DateTimeFormatter.ofPattern( if (is24HourFormat) "HH" else "hh a" ) ).replace(" ", "\n") } init { suffixes[1000L] = "k" suffixes[1000000L] = "M" suffixes[1000000000L] = "G" suffixes[1000000000000L] = "T" suffixes[1000000000000000L] = "P" suffixes[1000000000000000000L] = "E" } fun formatMinutes(minutes: Long): String { val days = minutes / 1440 val hours = minutes / 60 % 24 val remMin = minutes % 60 val result: String = if (minutes != 0L) { ((if (days != 0L) "${days}d\n" else "") + (if (hours != 0L) "" + hours.toString() + "h" else "") + if (remMin != 0L) " " + remMin.toString() + "m" else "") } else { "0m" } return result } }
apache-2.0
0dedcb5ada57e9d384b725176456fcb3
36.765766
137
0.631592
4.316169
false
false
false
false
nextcloud/android
app/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt
1
7530
/* * ownCloud Android client application * * @author David A. Velasco * Copyright (C) 2015 ownCloud Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.owncloud.android.ui.preview import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.Player import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.di.Injectable import com.nextcloud.client.media.ExoplayerListener import com.nextcloud.client.media.NextcloudExoPlayer.createNextcloudExoplayer import com.nextcloud.client.network.ClientFactory import com.owncloud.android.R import com.owncloud.android.databinding.ActivityPreviewVideoBinding import com.owncloud.android.datamodel.OCFile import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.ui.activity.FileActivity import com.owncloud.android.utils.MimeTypeUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject /** * Activity implementing a basic video player. * */ @Suppress("TooManyFunctions") class PreviewVideoActivity : FileActivity(), Player.Listener, Injectable { @Inject lateinit var clientFactory: ClientFactory @Inject lateinit var accountManager: UserAccountManager private var mSavedPlaybackPosition: Long = -1 // in the unit time handled by MediaPlayer.getCurrentPosition() private var mAutoplay = false // when 'true', the playback starts immediately with the activity private var exoPlayer: ExoPlayer? = null // view to play the file; both performs and show the playback private var mStreamUri: Uri? = null private lateinit var binding: ActivityPreviewVideoBinding private lateinit var pauseButton: View private lateinit var playButton: View public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log_OC.v(TAG, "onCreate") binding = ActivityPreviewVideoBinding.inflate(layoutInflater) setContentView(binding.root) val extras = intent.extras if (savedInstanceState == null && extras != null) { mSavedPlaybackPosition = extras.getLong(EXTRA_START_POSITION) mAutoplay = extras.getBoolean(EXTRA_AUTOPLAY) mStreamUri = extras[EXTRA_STREAM_URL] as Uri? } else if (savedInstanceState != null) { mSavedPlaybackPosition = savedInstanceState.getLong(EXTRA_START_POSITION) mAutoplay = savedInstanceState.getBoolean(EXTRA_AUTOPLAY) mStreamUri = savedInstanceState[EXTRA_STREAM_URL] as Uri? } supportActionBar?.hide() } private fun setupPlayerView() { binding.videoPlayer.player = exoPlayer exoPlayer!!.addListener(this) binding.root.findViewById<View>(R.id.exo_exit_fs).setOnClickListener { onBackPressed() } pauseButton = binding.root.findViewById(R.id.exo_pause) pauseButton.setOnClickListener { exoPlayer!!.pause() } playButton = binding.root.findViewById(R.id.exo_play) playButton.setOnClickListener { exoPlayer!!.play() } if (mSavedPlaybackPosition >= 0) { exoPlayer?.seekTo(mSavedPlaybackPosition) } onIsPlayingChanged(exoPlayer!!.isPlaying) } override fun onIsPlayingChanged(isPlaying: Boolean) { super.onIsPlayingChanged(isPlaying) if (isPlaying) { playButton.visibility = View.GONE pauseButton.visibility = View.VISIBLE } else { playButton.visibility = View.VISIBLE pauseButton.visibility = View.GONE } } /** * {@inheritDoc} */ public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putLong(EXTRA_START_POSITION, currentPosition()) outState.putBoolean(EXTRA_AUTOPLAY, isPlaying()) outState.putParcelable(EXTRA_STREAM_URL, mStreamUri) } override fun onBackPressed() { Log_OC.v(TAG, "onBackPressed") val i = Intent() i.putExtra(EXTRA_AUTOPLAY, isPlaying()) i.putExtra(EXTRA_START_POSITION, currentPosition()) setResult(RESULT_OK, i) exoPlayer?.stop() exoPlayer?.release() super.onBackPressed() } private fun isPlaying() = exoPlayer?.isPlaying ?: false private fun currentPosition() = exoPlayer?.currentPosition ?: 0 private fun play(item: MediaItem) { exoPlayer?.addMediaItem(item) exoPlayer?.prepare() if (mAutoplay) { exoPlayer?.play() } } override fun onStart() { super.onStart() if (account != null) { require(file != null) { throw IllegalStateException("Instanced with a NULL OCFile") } var fileToPlay: OCFile? = file // Validate handled file (first image to preview) require(MimeTypeUtil.isVideo(fileToPlay)) { "Non-video file passed as argument" } fileToPlay = storageManager.getFileById(fileToPlay!!.fileId) if (fileToPlay != null) { val mediaItem = when { fileToPlay.isDown -> MediaItem.fromUri(fileToPlay.storageUri) else -> MediaItem.fromUri(mStreamUri!!) } if (exoPlayer != null) { setupPlayerView() play(mediaItem) } else { val context = this CoroutineScope(Dispatchers.IO).launch { val client = clientFactory.createNextcloudClient(accountManager.user) CoroutineScope(Dispatchers.Main).launch { exoPlayer = createNextcloudExoplayer(context, client).also { it.addListener(ExoplayerListener(context, binding.videoPlayer, it)) } setupPlayerView() play(mediaItem) } } } } else { finish() } } else { finish() } } override fun onStop() { super.onStop() if (exoPlayer?.isPlaying == true) { exoPlayer?.pause() } } companion object { /** Key to receive a flag signaling if the video should be started immediately */ const val EXTRA_AUTOPLAY = "AUTOPLAY" /** Key to receive the position of the playback where the video should be put at start */ const val EXTRA_START_POSITION = "START_POSITION" const val EXTRA_STREAM_URL = "STREAM_URL" private val TAG = PreviewVideoActivity::class.java.simpleName } }
gpl-2.0
8da7bc59f7d47b08897fe3575036ef91
34.687204
113
0.649402
4.921569
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/utils/PresentationUtils.kt
1
8000
package org.rust.ide.utils import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* class PresentationInfo( element: RsNamedElement, val type: String?, val name: String, private val declaration: DeclarationInfo ) { private val location: String? init { location = element.containingFile?.let { " [${it.name}]" }.orEmpty() } val typeNameText: String get() = if (type == null) { name } else "$type `$name`" val projectStructureItemText: String get() = "$name${declaration.suffix}" val projectStructureItemTextWithValue: String get() = "$projectStructureItemText${declaration.value}" val signatureText: String = "${declaration.prefix}<b>$name</b>${declaration.suffix.escaped}" val quickDocumentationText: String get() = if (declaration.isAmbiguous && type != null) { "<i>$type:</i> " } else { "" } + "$signatureText${valueText.escaped}$location" private val valueText: String get() = if (declaration.value.isEmpty()) { "" } else { " ${declaration.value}" } } data class DeclarationInfo( val prefix: String = "", val suffix: String = "", val value: String = "", val isAmbiguous: Boolean = false ) val RsNamedElement.presentationInfo: PresentationInfo? get() { val elementName = name ?: return null val declInfo = when (this) { is RsFunction -> Pair("function", createDeclarationInfo(this, identifier, false, listOf(whereClause, retType, valueParameterList))) is RsStructItem -> Pair("struct", createDeclarationInfo(this, identifier, false, if (blockFields != null) listOf(whereClause) else listOf(whereClause, tupleFields))) is RsFieldDecl -> Pair("field", createDeclarationInfo(this, identifier, false, listOf(typeReference))) is RsEnumItem -> Pair("enum", createDeclarationInfo(this, identifier, false, listOf(whereClause))) is RsEnumVariant -> Pair("enum variant", createDeclarationInfo(this, identifier, false, listOf(tupleFields))) is RsTraitItem -> Pair("trait", createDeclarationInfo(this, identifier, false, listOf(whereClause))) is RsTypeAlias -> Pair("type alias", createDeclarationInfo(this, identifier, false, listOf(typeReference, typeParamBounds, whereClause), eq)) is RsConstant -> Pair("constant", createDeclarationInfo(this, identifier, false, listOf(expr, typeReference), eq)) is RsSelfParameter -> Pair("parameter", createDeclarationInfo(this, self, false, listOf(typeReference))) is RsTypeParameter -> Pair("type parameter", createDeclarationInfo(this, identifier, true)) is RsLifetimeDecl -> Pair("lifetime", createDeclarationInfo(this, quoteIdentifier, true)) is RsModItem -> Pair("module", createDeclarationInfo(this, identifier, false)) is RsLabelDecl -> { val p = parent when (p) { is RsLoopExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.loop))) is RsForExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.expr, p.`in`, p.`for`))) is RsWhileExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.condition, p.`while`))) else -> Pair("label", createDeclarationInfo(this, quoteIdentifier, true)) } } is RsPatBinding -> { val patOwner = topLevelPattern.parent when (patOwner) { is RsLetDecl -> Pair("variable", createDeclarationInfo(patOwner, identifier, false, listOf(patOwner.typeReference))) is RsValueParameter -> Pair("value parameter", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.typeReference))) is RsMatchArm -> Pair("match arm binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.patList.lastOrNull()))) is RsCondition -> Pair("condition binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.lastChild))) else -> Pair("binding", createDeclarationInfo(this, identifier, true)) } } is RsFile -> { val mName = modName if (isCrateRoot) return PresentationInfo(this, "crate", "crate", DeclarationInfo()) else if (mName != null) return PresentationInfo(this, "mod", name.substringBeforeLast(".rs"), DeclarationInfo("mod ")) else Pair("file", DeclarationInfo()) } else -> Pair(javaClass.simpleName, createDeclarationInfo(this, navigationElement, true)) } return declInfo.second?.let { PresentationInfo(this, declInfo.first, elementName, it) } } fun presentableQualifiedName(element: RsDocAndAttributeOwner): String? { val qName = (element as? RsQualifiedNamedElement)?.qualifiedName if (qName != null) return qName if (element is RsMod) return element.modName return element.name } private fun createDeclarationInfo(decl: RsCompositeElement, name: PsiElement?, isAmbiguous: Boolean, stopAt: List<PsiElement?> = emptyList(), valueSeparator: PsiElement? = null): DeclarationInfo? { // Break an element declaration into elements. For example: // // pub const Foo: u32 = 100; // ^^^^^^^^^ signature prefix // ^^^ name // ^^^^^ signature suffix // ^^^^^ value // ^ end if (name == null) return null // Remove leading spaces, comments and attributes val signatureStart = generateSequence(decl.firstChild) { it.nextSibling } .dropWhile { it is PsiWhiteSpace || it is PsiComment || it is RsOuterAttr } .firstOrNull() ?.startOffsetInParent ?: return null val nameStart = name.offsetIn(decl) // pick (in order) elements we should stop at // if they all fail, drop down to the end of the name element val end = stopAt .filterNotNull().firstOrNull() ?.let { it.startOffsetInParent + it.textLength } ?: nameStart + name.textLength val valueStart = valueSeparator?.offsetIn(decl) ?: end val nameEnd = nameStart + name.textLength check(signatureStart <= nameStart && nameEnd <= valueStart && valueStart <= end && end <= decl.textLength) val prefix = decl.text.substring(signatureStart, nameStart).escaped val value = decl.text.substring(valueStart, end) val suffix = decl.text.substring(nameEnd, end - value.length) .replace("""\s+""".toRegex(), " ") .replace("( ", "(") .replace(" )", ")") .replace(" ,", ",") .trimEnd() return DeclarationInfo(prefix, suffix, value, isAmbiguous) } private fun PsiElement.offsetIn(owner: PsiElement): Int = ancestors.takeWhile { it != owner }.sumBy { it.startOffsetInParent } val String.escaped: String get() = StringUtil.escapeXml(this) fun breadcrumbName(e: RsCompositeElement): String? { fun lastComponentWithoutGenerics(path: RsPath) = path.referenceName return when (e) { is RsModItem, is RsStructOrEnumItemElement, is RsTraitItem, is RsConstant, is RsMacroDefinition -> (e as RsNamedElement).name is RsImplItem -> { val typeName = run { val typeReference = e.typeReference (typeReference as? RsBaseType)?.path?.let { lastComponentWithoutGenerics(it) } ?: typeReference?.text ?: return null } val traitName = e.traitRef?.path?.let { lastComponentWithoutGenerics(it) } val start = if (traitName != null) "$traitName for" else "impl" "$start $typeName" } is RsFunction -> e.name?.let { "$it()" } else -> null } }
mit
cbdabeae100ac09848216ec177c4dd8d
43.692737
197
0.64875
4.784689
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/servers/sitemaps/list/SitemapSelectFragment.kt
1
6551
package treehou.se.habit.ui.servers.sitemaps.list import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.GridLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.subjects.BehaviorSubject import kotlinx.android.synthetic.main.fragment_sitemaplist_list.* import se.treehou.ng.ohcommunicator.connector.models.OHServer import se.treehou.ng.ohcommunicator.connector.models.OHSitemap import treehou.se.habit.R import treehou.se.habit.core.db.model.ServerDB import treehou.se.habit.core.db.model.SitemapDB import treehou.se.habit.dagger.HasActivitySubcomponentBuilders import treehou.se.habit.dagger.ServerLoaderFactory import treehou.se.habit.dagger.fragment.SitemapSelectComponent import treehou.se.habit.dagger.fragment.SitemapSelectModule import treehou.se.habit.mvp.BaseDaggerFragment import treehou.se.habit.ui.adapter.SitemapListAdapter import treehou.se.habit.ui.servers.sitemaps.sitemapsettings.SitemapSettingsFragment import treehou.se.habit.util.Settings import javax.inject.Inject class SitemapSelectFragment : BaseDaggerFragment<SitemapSelectContract.Presenter>(), SitemapSelectContract.View { @Inject lateinit var settings: Settings @Inject lateinit var serverLoader: ServerLoaderFactory @Inject lateinit var sitemapPresenter: SitemapSelectContract.Presenter private var sitemapAdapter: SitemapListAdapter? = null private val serverBehaviorSubject = BehaviorSubject.create<OHServer>() private var serverId: Long = -1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) serverId = arguments!!.getLong(ARG_SHOW_SERVER) } override fun getPresenter(): SitemapSelectContract.Presenter? { return sitemapPresenter } override fun injectMembers(hasActivitySubcomponentBuilders: HasActivitySubcomponentBuilders) { (hasActivitySubcomponentBuilders.getFragmentComponentBuilder(SitemapSelectFragment::class.java) as SitemapSelectComponent.Builder) .fragmentModule(SitemapSelectModule(this)) .build().injectMembers(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_sitemaplist_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupActionBar() val gridLayoutManager = GridLayoutManager(activity, 1) listView.layoutManager = gridLayoutManager listView.itemAnimator = DefaultItemAnimator() sitemapAdapter = SitemapListAdapter() sitemapAdapter!!.setSitemapSelectedListener(object : SitemapListAdapter.SitemapSelectedListener { override fun onSelected(server: OHServer, sitemap: OHSitemap?) { val sitemapDB = realm.where(SitemapDB::class.java) .equalTo("server.id", serverId) .equalTo("name", sitemap?.name) .findFirst() if (sitemapDB != null) { openSitemap(sitemapDB) } } override fun onErrorSelected(server: OHServer) { serverBehaviorSubject.onNext(server) } override fun onCertificateErrorSelected(server: OHServer) {} }) listView.adapter = sitemapAdapter } /** * Open fragment showing sitemap. * * @param sitemap the name of sitemap to show. */ private fun openSitemap(sitemap: SitemapDB?) { val fragmentManager = activity!!.supportFragmentManager fragmentManager.beginTransaction() .replace(R.id.page_container, SitemapSettingsFragment.newInstance(sitemap!!.id)) .addToBackStack(null) .commit() } /** * Setup actionbar. */ private fun setupActionBar() { val actionBar = (activity as AppCompatActivity).supportActionBar actionBar?.setTitle(R.string.sitemaps) } /** * Clears list of sitemaps. */ private fun clearList() { emptyView.visibility = View.VISIBLE sitemapAdapter!!.clear() } override fun onResume() { super.onResume() clearList() loadSitemapsFromServers() } /** * Load servers from database and request their sitemaps. */ private fun loadSitemapsFromServers() { val context = context ?: return realm.where(ServerDB::class.java).equalTo("id", serverId).findAll().asFlowable().toObservable() .flatMap<ServerDB>({ Observable.fromIterable(it) }) .map<OHServer>({ it.toGeneric() }) .distinct() .compose<ServerLoaderFactory.ServerSitemapsResponse>(serverLoader.serverToSitemap(context)) .observeOn(AndroidSchedulers.mainThread()) .compose<ServerLoaderFactory.ServerSitemapsResponse>(bindToLifecycle<ServerLoaderFactory.ServerSitemapsResponse>()) .subscribe({ serverSitemaps -> emptyView.visibility = View.GONE val server = serverSitemaps.server val sitemaps = serverSitemaps.sitemaps if (sitemaps != null) { for (sitemap in sitemaps) { if (server != null) { sitemapAdapter!!.add(server, sitemap) } } } }) { logger.e(TAG, "Request sitemap failed", it) } } companion object { private val TAG = "SitemapSelectFragment" private val ARG_SHOW_SERVER = "ARG_SHOW_SERVER" /** * Load sitemaps for servers. * Open provided sitemap if loaded. * * @param serverId the server to load * @return Fragment */ fun newInstance(serverId: Long): SitemapSelectFragment { val fragment = SitemapSelectFragment() val args = Bundle() args.putLong(ARG_SHOW_SERVER, serverId) fragment.arguments = args return fragment } } }
epl-1.0
a3637368dab58e23975fd0ba8b35f0a9
35.394444
138
0.658525
5.295877
false
false
false
false
goodwinnk/intellij-community
platform/configuration-store-impl/src/ProjectStoreImpl.kt
1
15265
// 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.configurationStore import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.highlighter.WorkspaceFileType import com.intellij.notification.Notifications import com.intellij.notification.NotificationsManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.* import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.impl.stores.SaveSessionAndFile import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCoreUtil import com.intellij.openapi.project.ex.ProjectNameProvider import com.intellij.openapi.project.getProjectCachePath import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification import com.intellij.openapi.project.impl.ProjectStoreClassProvider import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.ReadonlyStatusHandler import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.containers.computeIfAny import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.io.* import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.text.nullize import java.nio.file.Path import java.nio.file.Paths internal const val PROJECT_FILE = "\$PROJECT_FILE$" internal const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$" val IProjectStore.nameFile: Path get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE) internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false) internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true) // cannot be `internal`, used in Upsource abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreWithExtraComponents(), IProjectStore { // protected setter used in upsource // Zelix KlassMaster - ERROR: Could not find method 'getScheme()' var scheme: StorageScheme = StorageScheme.DEFAULT override final var loadPolicy: StateLoadPolicy = StateLoadPolicy.LOAD override final fun isOptimiseTestLoadSpeed(): Boolean = loadPolicy != StateLoadPolicy.LOAD override final fun getStorageScheme(): StorageScheme = scheme override abstract val storageManager: StateStorageManagerImpl protected val isDirectoryBased: Boolean get() = scheme == StorageScheme.DIRECTORY_BASED override final fun setOptimiseTestLoadSpeed(value: Boolean) { // we don't load default state in tests as app store does because // 1) we should not do it // 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations) loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD } override fun getProjectFilePath(): String = storageManager.expandMacro(PROJECT_FILE) /** * `null` for default or non-directory based project. */ override fun getProjectConfigDir(): String? = if (isDirectoryBased) storageManager.expandMacro(PROJECT_CONFIG_DIR) else null override final fun getWorkspaceFilePath(): String = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE) override final fun clearStorages() { storageManager.clearStorages() } override final fun loadProjectFromTemplate(defaultProject: Project) { defaultProject.save() val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return LOG.runAndLogException { if (isDirectoryBased) { normalizeDefaultProjectElement(defaultProject, element, Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR))) } else { LOG.runAndLogException { moveComponentConfiguration(defaultProject, element) { if (it == "workspace.xml") Paths.get(workspaceFilePath) else Paths.get(projectFilePath) } } } } (storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element) } override final fun getProjectBasePath(): String { if (isDirectoryBased) { val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR)) if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) { return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path)) } return path } else { return PathUtilRt.getParentPath(projectFilePath) } } // used in upsource protected fun setPath(filePath: String, refreshVfs: Boolean) { val storageManager = storageManager val fs = LocalFileSystem.getInstance() if (filePath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) { scheme = StorageScheme.DEFAULT storageManager.addMacro(PROJECT_FILE, filePath) val workspacePath = composeFileBasedProjectWorkSpacePath(filePath) storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath) if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath)) } } if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !Paths.get(filePath).exists() } } else { scheme = StorageScheme.DIRECTORY_BASED val configDir = "$filePath/${Project.DIRECTORY_STORE_FOLDER}" storageManager.addMacro(PROJECT_CONFIG_DIR, configDir) storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml") storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml") if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !Paths.get(filePath).exists() } if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) } } } storageManager.addMacro(StoragePathMacros.CACHE_FILE, FileUtilRt.toSystemIndependentName(project.getProjectCachePath("workspace").toString()) + ".xml") } override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> { val storages = stateSpec.storages if (storages.isEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } if (isDirectoryBased) { var result: MutableList<Storage>? = null for (storage in storages) { if (storage.path != PROJECT_FILE) { if (result == null) { result = SmartList() } result.add(storage) } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { result!!.sortWith(deprecatedComparator) if (isDirectoryBased) { StreamProviderFactory.EP_NAME.getExtensions(project).computeIfAny { LOG.runAndLogException { it.customizeStorageSpecs(component, storageManager, stateSpec, result!!, operation) } }?.let { // yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case return it } } // if we create project from default, component state written not to own storage file, but to project file, // we don't have time to fix it properly, so, ancient hack restored if (result.first().path != StoragePathMacros.CACHE_FILE) { result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION) } return result } } else { var result: MutableList<Storage>? = null // FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry var hasOnlyDeprecatedStorages = true for (storage in storages) { @Suppress("DEPRECATION") if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE || storage.path == StoragePathMacros.CACHE_FILE) { if (result == null) { result = SmartList() } result.add(storage) if (!storage.deprecated) { hasOnlyDeprecatedStorages = false } } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { if (hasOnlyDeprecatedStorages) { result!!.add(PROJECT_FILE_STORAGE_ANNOTATION) } result!!.sortWith(deprecatedComparator) return result } } } override fun isProjectFile(file: VirtualFile): Boolean { if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) { return false } val filePath = file.path if (!isDirectoryBased) { return filePath == projectFilePath || filePath == workspaceFilePath } return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false) } override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean): String? = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize() override fun getDirectoryStoreFile(): VirtualFile? = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) } override fun getDirectoryStorePathOrBase(): String = PathUtilRt.getParentPath(projectFilePath) } private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) { private var lastSavedProjectName: String? = null init { assert(!project.isDefault) } override final fun getPathMacroManagerForDefaults() = pathMacroManager override val storageManager = ProjectStateStorageManager(TrackingPathMacroSubstitutorImpl(pathMacroManager), project) override fun setPath(path: String) { setPath(path, true) } override fun getProjectName(): String { if (!isDirectoryBased) { return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) } val baseDir = projectBasePath val nameFile = nameFile if (nameFile.exists()) { LOG.runAndLogException { nameFile.inputStream().reader().useLines { line -> line.firstOrNull { !it.isEmpty() }?.trim() }?.let { lastSavedProjectName = it return it } } } return ProjectNameProvider.EP_NAME.extensionList.computeIfAny { LOG.runAndLogException { it.getDefaultName(project) } } ?: PathUtilRt.getFileName(baseDir).replace(":", "") } private fun saveProjectName() { if (!isDirectoryBased) { return } val currentProjectName = project.name if (lastSavedProjectName == currentProjectName) { return } lastSavedProjectName = currentProjectName val basePath = projectBasePath if (currentProjectName == PathUtilRt.getFileName(basePath)) { // name equals to base path name - just remove name nameFile.delete() } else { if (Paths.get(basePath).isDirectory()) { nameFile.write(currentProjectName.toByteArray()) } } } override fun doSave(saveSession: SaveExecutor, readonlyFiles: MutableList<SaveSessionAndFile>, errors: MutableList<Throwable>) { try { saveProjectName() } catch (e: Throwable) { LOG.error("Unable to store project name", e) } beforeSave(readonlyFiles) super.doSave(saveSession, readonlyFiles, errors) val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (readonlyFiles.isEmpty()) { for (notification in notifications) { notification.expire() } return } if (!notifications.isEmpty()) { throw IComponentStore.SaveCancelledException() } val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) } if (status.hasReadonlyFiles()) { dropUnableToSaveProjectNotification(project, status.readonlyFiles) throw IComponentStore.SaveCancelledException() } val oldList = readonlyFiles.toTypedArray() readonlyFiles.clear() for (entry in oldList) { executeSave(entry.session, readonlyFiles, errors) } CompoundRuntimeException.throwIfNotEmpty(errors) if (!readonlyFiles.isEmpty()) { dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles)) throw IComponentStore.SaveCancelledException() } } protected open fun beforeSave(readonlyFiles: MutableList<SaveSessionAndFile>) { } } private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) { val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (notifications.isEmpty()) { Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project) } else { notifications[0].myFiles = readOnlyFiles } } private fun getFilesList(readonlyFiles: List<SaveSessionAndFile>) = Array(readonlyFiles.size) { readonlyFiles[it].file } private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) { override fun beforeSave(readonlyFiles: MutableList<SaveSessionAndFile>) { super.beforeSave(readonlyFiles) for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) { module.stateStore.save(readonlyFiles) } } } // used in upsource class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java } } @Suppress("unused") private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java } } private fun composeFileBasedProjectWorkSpacePath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}"
apache-2.0
27e12bfb69e2a62188cc319461b028ff
37.844784
200
0.739142
5.261979
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/utils/ClientUtil.kt
1
756
package de.xikolo.utils import de.xikolo.App import java.io.File import java.util.* object ClientUtil { private const val FILE_NAME = "INSTALLATION" var id: String? = null get() { if (field == null) { val installationFile = File(App.instance.filesDir, FILE_NAME) try { if (!installationFile.exists()) { installationFile.writeText( UUID.randomUUID().toString() ) } field = installationFile.readText() } catch (e: Exception) { throw RuntimeException(e) } } return field } }
bsd-3-clause
901a7b9c6ec917b79d5497b9427fed2a
26
77
0.460317
5.178082
false
false
false
false
mockk/mockk
modules/mockk-agent-android/src/main/kotlin/io/mockk/proxy/android/transformation/InliningClassTransformer.kt
2
2176
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mockk.proxy.android.transformation import io.mockk.proxy.MockKAgentException import io.mockk.proxy.common.transformation.ClassTransformationSpecMap import java.util.* internal class InliningClassTransformer( private val specMap: ClassTransformationSpecMap ) { val identifier = newId() @Suppress("unused") // JNI call fun transform(classBeingRedefined: Class<*>?, classfileBuffer: ByteArray): ByteArray? { if (classBeingRedefined == null) { return classfileBuffer } val spec = specMap[classBeingRedefined] ?: return classfileBuffer return synchronized(lock) { try { nativeRedefine( identifier, classfileBuffer, spec.shouldDoSimpleIntercept, spec.shouldDoStaticIntercept, spec.shouldDoConstructorIntercept ) } catch (ex: Exception) { throw MockKAgentException("Transformation issue", ex) } } } fun shouldTransform(classBeingRedefined: Class<*>) = specMap.shouldTransform(classBeingRedefined) private external fun nativeRedefine( identifier: String, original: ByteArray, mockk: Boolean, staticMockk: Boolean, constructorMockk: Boolean ): ByteArray companion object { private val lock = Any() private val rng = Random() private fun newId() = Math.abs(rng.nextLong()).toString(16) } }
apache-2.0
57d4f4e4d905e402c508801728cd6446
31.477612
101
0.650276
5.12
false
false
false
false
daviddenton/databob.kotlin
src/main/kotlin/io/github/databob/CollectionSizeRange.kt
1
853
package io.github.databob import java.util.* class CollectionSizeRange(private val min: Int, private val max: Int) { init { if (min > max) throw IllegalArgumentException("Cannot construct negative sized range") } object generators { val empty = Generators.ofType { -> CollectionSizeRange(0, 0) } fun exactly(value: Int): Generator = Generators.ofType { -> CollectionSizeRange(value, value) } fun between(min: Int, max: Int): Generator = Generators.ofType { -> CollectionSizeRange(min, max) } fun atMost(max: Int): Generator = Generators.ofType { -> CollectionSizeRange(0, max) } } fun toRandomRange(): IntRange = when { min == 0 && max == 0 -> IntRange.EMPTY min == max -> IntRange(0, max - 1) else -> IntRange(0, min - 1 + Random().nextInt(max - min)) } }
apache-2.0
893653e7b1801a33b4bd13c3f63e0010
31.807692
107
0.630715
4.181373
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/LoginActivity.kt
2
3221
package com.bennyhuo.github.view import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.Intent import android.os.Bundle import android.view.View import android.widget.EditText import com.bennyhuo.common.ext.hideSoftInput import com.bennyhuo.github.R import com.bennyhuo.github.common.ext.otherwise import com.bennyhuo.github.common.ext.yes import com.bennyhuo.github.presenter.LoginPresenter import com.bennyhuo.github.view.config.Themer import com.bennyhuo.mvp.impl.BaseActivity import com.bennyhuo.tieguanyin.annotations.ActivityBuilder import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.app_bar_simple.* import org.jetbrains.anko.sdk15.listeners.onClick import org.jetbrains.anko.toast @ActivityBuilder(flags = [Intent.FLAG_ACTIVITY_NO_HISTORY]) class LoginActivity : BaseActivity<LoginPresenter>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Themer.applyProperTheme(this) setContentView(R.layout.activity_login) setSupportActionBar(toolbar) signInButton.onClick { presenter.checkUserName(username.text.toString()) .yes { presenter.checkPasswd(password.text.toString()) .yes { hideSoftInput() presenter.doLogin(username.text.toString(), password.text.toString()) } .otherwise { showTips(password, "密码不合法") } } .otherwise { showTips(username, "用户名不合法") } } } private fun showProgress(show: Boolean) { val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime) loginForm.animate().setDuration(shortAnimTime.toLong()).alpha( (if (show) 0 else 1).toFloat()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { loginForm.visibility = if (show) View.GONE else View.VISIBLE } }) loginProgress.animate().setDuration(shortAnimTime.toLong()).alpha( (if (show) 1 else 0).toFloat()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { loginProgress.visibility = if (show) View.VISIBLE else View.GONE } }) } private fun showTips(view: EditText, tips: String){ view.requestFocus() view.error = tips } fun onLoginStart(){ showProgress(true) } fun onLoginError(e: Throwable){ e.printStackTrace() toast("登录失败") showProgress(false) } fun onLoginSuccess(){ toast("登录成功") showProgress(false) startMainActivity() } fun onDataInit(name: String, passwd: String){ username.setText(name) password.setText(passwd) } }
apache-2.0
185d7e3b31873bcb212eb24342325c98
33.978022
105
0.619541
4.919629
false
false
false
false
panpf/sketch
sample/src/main/java/com/github/panpf/sketch/sample/util/MmkvData.kt
1
2720
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.sample.util import com.tencent.mmkv.MMKV import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class StringMmkvData( mmkv: MMKV, key: String, defaultState: String ) : BaseMmkvData<String>(defaultState, StringMmkvAdapter(mmkv, key, defaultState)) class BooleanMmkvData( mmkv: MMKV, key: String, defaultState: Boolean ) : BaseMmkvData<Boolean>(defaultState, BooleanMmkvAdapter(mmkv, key, defaultState)) abstract class BaseMmkvData<T>(defaultState: T, private val mmkvAdapter: MmkvAdapter<T>) { private val _stateFlow = MutableStateFlow(defaultState) private val _sharedFlow = MutableSharedFlow<T>() private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) val stateFlow: StateFlow<T> get() = _stateFlow val sharedFlow: SharedFlow<T> get() = _sharedFlow init { _stateFlow.value = mmkvAdapter.state } var value: T get() = stateFlow.value set(value) { mmkvAdapter.state = value _stateFlow.value = value scope.launch { _sharedFlow.emit(value) } } } interface MmkvAdapter<T> { var state: T } class StringMmkvAdapter( private val mmkv: MMKV, private val key: String, private val defaultValue: String ) : MmkvAdapter<String> { override var state: String get() = mmkv.decodeString(key, defaultValue) ?: defaultValue set(value) { mmkv.encode(key, value) } } class BooleanMmkvAdapter( private val mmkv: MMKV, private val key: String, private val defaultValue: Boolean ) : MmkvAdapter<Boolean> { override var state: Boolean get() = mmkv.decodeBool(key, defaultValue) set(value) { mmkv.encode(key, value) } }
apache-2.0
10966ec468bdff0c6bf4f19cbfebaa3b
29.233333
90
0.7
4.204019
false
false
false
false
deskchanproject/DeskChanJava
src/main/kotlin/info/deskchan/notification_manager/Main.kt
2
5638
package info.deskchan.notification_manager; import info.deskchan.MessageData.Core.AddCommand import info.deskchan.MessageData.Core.SetEventLink import info.deskchan.MessageData.GUI.Control import info.deskchan.MessageData.GUI.SetPanel import info.deskchan.core.MessageDataMap import info.deskchan.core.MessageListener import info.deskchan.core.Plugin; import info.deskchan.core.PluginProxyInterface; import java.text.SimpleDateFormat import java.util.*; public class Main : Plugin { companion object { private lateinit var pluginProxy: PluginProxyInterface private var phraseIdCounter = 0 } /** Single phrase in notification. **/ private class NotificationPhrase { public val text: String public val sender: String? public val date: Date public val id: Int constructor(text: String, sender: String?){ this.text = text this.sender = sender date = Date() id = phraseIdCounter phraseIdCounter++ } public fun getAsControl(): Control { var dateString = "(" + SimpleDateFormat("HH:mm:ss").format(date) + ") " val map = Control( Control.ControlType.Button, "notification" + id, "X", "label", dateString + (if (sender != null) "[" + sender + "]: " else "") + text, "msgTag", "notification:delete", "msgData", id ) return map } } private var managerIsOpened = false private val history = mutableListOf<NotificationPhrase>() private val logLength = 12 private var currentQuery = "" private lateinit var EMPTY: Control private fun historyToNotification(): MutableList<Map<String, Any>>{ val ret = mutableListOf<Map<String, Any>>() val list = history.subList(Math.max(history.size - logLength, 0), history.size) if (list.isEmpty()){ ret.add(EMPTY) } else { list.forEach { it -> ret.add(it.getAsControl()) } } return ret } override fun initialize(pluginProxy: PluginProxyInterface): Boolean { Main.pluginProxy = pluginProxy pluginProxy.setConfigField("name", pluginProxy.getString("plugin.name")) EMPTY = Control( Control.ControlType.Label, null, pluginProxy.getString("no-notifications"), "width", 350 ) /* Open chat request. * Public message * Params: None * Returns: None */ pluginProxy.addMessageListener("notification:open", MessageListener { sender, tag, data -> pluginProxy.sendMessage(SetPanel( "notification", SetPanel.PanelType.WINDOW, SetPanel.ActionType.SHOW )) managerIsOpened = true; }) pluginProxy.sendMessage(AddCommand( "notification:open", "notifications.open-info" )) pluginProxy.sendMessage(SetEventLink( "gui:keyboard-handle", "notification:open", "ALT+N" )) /* Chat has been closed through GUI. */ pluginProxy.addMessageListener("notification:closed", MessageListener { sender, tag, data -> managerIsOpened = false; }) /* Updated textfield input. */ pluginProxy.addMessageListener("notification:update-textfield", MessageListener {sender, tag, data -> //currentQuery = data.toString(); }) /* Someone made request to clear all messages from notification window. We're clearing it. */ pluginProxy.addMessageListener("notification:clear", MessageListener {sender, tag, data -> history.clear() setPanel() }); pluginProxy.addMessageListener("notification:delete", MessageListener {sender, tag, data -> val id = data as Int history.removeIf { it -> it.id == id } setPanel() }) /* New notification occurred */ pluginProxy.addMessageListener("DeskChan:notify", MessageListener {sender, tag, data -> val map = MessageDataMap("message", data) if (map.containsKey("msgData")) map.put("message", map.getString("msgData")) if (!map.containsKey("message")) return@MessageListener history.add(NotificationPhrase(map.getString("message")!!, sender)) setPanel() }) /* Registering "Open Notification Manager" button in menu. */ pluginProxy.sendMessage(SetEventLink( "gui:menu-action", "notification:open", pluginProxy.getString("notifications.open") )) setPanel() pluginProxy.log("Notification Manager loading complete") return true } fun setPanel(){ val message = SetPanel( "notification", SetPanel.PanelType.WINDOW, SetPanel.ActionType.SET, pluginProxy.getString("window-name"), "notification:closed", null ) val controls = historyToNotification() controls.add(Control( Control.ControlType.Button, "clear", pluginProxy.getString("clear"), "msgTag", "notification:clear" )) message.controls = controls Main.pluginProxy.sendMessage(message) } }
lgpl-3.0
91e31de39da9d395c9feed893914e568
31.217143
109
0.576978
5.215541
false
false
false
false
JimSeker/AudioVideo
CameraXVideoDemo_kt/app/src/main/java/edu/cs4730/cameraxvideodemo_kt/MainActivity.kt
1
7987
package edu.cs4730.cameraxvideodemo_kt import android.Manifest import android.annotation.SuppressLint import android.content.ContentValues import android.content.pm.PackageManager import android.database.Cursor import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ImageCapture import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.video.* import androidx.camera.video.VideoRecordEvent.Finalize import androidx.core.content.ContextCompat import kotlinx.android.synthetic.main.activity_main.* import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * based on https://codelabs.developers.google.com/codelabs/camerax-getting-started#0 */ class MainActivity : AppCompatActivity() { private var videoCapture: VideoCapture<Recorder>? = null private var currentRecording: Recording? = null lateinit var rpl: ActivityResultLauncher<Array<String>> private lateinit var cameraExecutor: ExecutorService var recording: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) REQUIRED_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //For API 29+ (q), for 26 to 28. arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) } else { arrayOf( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO ) } rpl = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { if (allPermissionsGranted()) { startCamera() } else { Toast.makeText( applicationContext, "Permissions not granted by the user.", Toast.LENGTH_SHORT ).show() finish() } } // Request camera permissions if (allPermissionsGranted()) { startCamera() } else { rpl.launch(REQUIRED_PERMISSIONS) } // Set up the listener for take photo button camera_capture_button.setOnClickListener { takeVideo() } cameraExecutor = Executors.newSingleThreadExecutor() } @SuppressLint("RestrictedApi", "MissingPermission") private fun takeVideo() { Log.d(TAG, "start") // Get a stable reference of the modifiable image capture use case val videoCapture = videoCapture ?: return if (recording) { //ie already started. currentRecording?.stop() recording = false camera_capture_button.text = "Start Rec" } else { val name = "CameraX-" + SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) + ".mp4" val cv = ContentValues() cv.put(MediaStore.MediaColumns.DISPLAY_NAME, name) cv.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { cv.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CameraX-Video") } val mediaStoreOutputOptions = MediaStoreOutputOptions.Builder( contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI ) .setContentValues(cv) .build() currentRecording = videoCapture.output .prepareRecording(this@MainActivity, mediaStoreOutputOptions) .withAudioEnabled() .start( cameraExecutor ) { videoRecordEvent -> if (videoRecordEvent is Finalize) { val savedUri = videoRecordEvent.outputResults.outputUri //convert uri to useful name. var cursor: Cursor? = null var path: String try { cursor = contentResolver.query( savedUri, arrayOf(MediaStore.MediaColumns.DATA), null, null, null ) cursor!!.moveToFirst() path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)) } finally { cursor!!.close() } Log.wtf(TAG, path) if (path == "") { path = savedUri.toString() } val msg = "Video capture succeeded: $path" runOnUiThread { Toast.makeText( baseContext, msg, Toast.LENGTH_LONG ).show() } Log.d(TAG, msg) currentRecording = null } } recording = true camera_capture_button.text = "Stop Rec" } } @SuppressLint("RestrictedApi") private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener( { try { val cameraProvider = cameraProviderFuture.get() as ProcessCameraProvider val preview = Preview.Builder().build() preview.setSurfaceProvider(viewFinder.surfaceProvider) val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA val recorder = Recorder.Builder() .setQualitySelector( QualitySelector.from( Quality.HIGHEST, FallbackStrategy.higherQualityOrLowerThan(Quality.SD) ) ) .build() videoCapture = VideoCapture.withOutput(recorder) val imageCatpure = ImageCapture.Builder().build() // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera cameraProvider.bindToLifecycle( this@MainActivity, cameraSelector, preview, imageCatpure, videoCapture ) } catch (e: Exception) { Log.e(TAG, "Use case binding failed", e) } }, ContextCompat.getMainExecutor(this) ) } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it ) == PackageManager.PERMISSION_GRANTED } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } companion object { private const val TAG = "CameraXBasic" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" private lateinit var REQUIRED_PERMISSIONS: Array<String> } }
apache-2.0
876e55b9a5012e630d6cb7274aa57143
36.853081
108
0.548516
5.851282
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/RsDowngradeModuleToFile.kt
2
3307
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring import com.intellij.lang.Language import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.impl.file.PsiFileImplUtil import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.actions.BaseRefactoringAction import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import org.rust.RsBundle import org.rust.lang.RsConstants import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsFile import org.rust.openapiext.checkWriteAccessAllowed class RsDowngradeModuleToFile : BaseRefactoringAction() { override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean = elements.all { it.isDirectoryMod } override fun isAvailableOnElementInEditorAndFile( element: PsiElement, editor: Editor, file: PsiFile, context: DataContext ): Boolean { return file.isDirectoryMod } override fun getHandler(dataContext: DataContext): RefactoringActionHandler = Handler override fun isAvailableInEditorOnly(): Boolean = false override fun isAvailableForLanguage(language: Language): Boolean = language.`is`(RsLanguage) private object Handler : RefactoringActionHandler { override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) { invoke(project, arrayOf(file), dataContext) } override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) { runWriteCommandAction( project, RsBundle.message("action.Rust.RsDowngradeModuleToFile.text"), "action.Rust.RsDowngradeModuleToFile", { for (element in elements) { contractModule(element as PsiFileSystemItem) } } ) } } } private fun contractModule(fileOrDirectory: PsiFileSystemItem) { checkWriteAccessAllowed() val (file, dir) = when (fileOrDirectory) { is RsFile -> fileOrDirectory to fileOrDirectory.parent!! is PsiDirectory -> fileOrDirectory.children.single() as RsFile to fileOrDirectory else -> error("Can contract only files and directories") } val dst = dir.parent!! val fileName = "${dir.name}.rs" PsiFileImplUtil.setName(file, fileName) MoveFilesOrDirectoriesUtil.doMoveFile(file, dst) dir.delete() } private val PsiElement.isDirectoryMod: Boolean get() { return when (this) { is RsFile -> name == RsConstants.MOD_RS_FILE && containingDirectory?.children?.size == 1 is PsiDirectory -> { val child = children.singleOrNull() child is RsFile && child.name == RsConstants.MOD_RS_FILE } else -> false } }
mit
62e117ee4869e8f725f15e2529621acc
35.340659
115
0.698216
4.995468
false
false
false
false
TeamWizardry/LibrarianLib
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/registration/BlockSpec.kt
1
11936
package com.teamwizardry.librarianlib.foundation.registration import com.teamwizardry.librarianlib.foundation.block.BaseBlock import com.teamwizardry.librarianlib.foundation.block.BlockPropertiesBuilder import com.teamwizardry.librarianlib.foundation.block.FoundationBlockProperties import com.teamwizardry.librarianlib.foundation.block.IFoundationBlock import com.teamwizardry.librarianlib.foundation.item.IFoundationItem import com.teamwizardry.librarianlib.foundation.loot.BlockLootTableGenerator import net.minecraft.block.Block import net.minecraft.block.BlockState import net.minecraft.block.SoundType import net.minecraft.block.material.Material import net.minecraft.block.material.MaterialColor import net.minecraft.client.renderer.model.IBakedModel import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer import net.minecraft.item.* import net.minecraft.tags.ITag import net.minecraft.tags.Tag import net.minecraft.util.IItemProvider import net.minecraft.util.Identifier import net.minecraftforge.client.model.generators.BlockStateProvider import net.minecraftforge.client.model.generators.ItemModelProvider import net.minecraftforge.common.ToolType import java.util.concurrent.Callable import java.util.function.Consumer import java.util.function.Function import java.util.function.Supplier /** * The specs for creating and registering a block. The [BlockItem] instance is generated using the callback provided to * [blockItem], or the block if it's an [IFoundationBlock], or [BlockItem]. Item generation can be completely disabled * using [noItem]. */ public class BlockSpec( /** * The registry name, sans mod ID */ public var id: String ): IItemProvider, BlockPropertiesBuilder<BlockSpec> { /** * The mod ID to register this block under. This is populated by the [RegistrationManager]. */ public var modid: String = "" @JvmSynthetic internal set /** * The registry name of the block. The [mod ID][modid] is populated by the [RegistrationManager]. */ public val registryName: Identifier get() = Identifier(modid, id) /** * Whether a [BlockItem] should be registered for this block */ public var hasItem: Boolean = true private set /** * What render layer this block should be drawn in */ public var renderLayer: RenderLayerSpec = RenderLayerSpec.SOLID private set /** * What item group the [BlockItem] should be in */ public var itemGroup: ItemGroupSpec = ItemGroupSpec.DEFAULT private set /** * The information used during data generation */ public val datagen: DataGen = DataGen() private var blockConstructor: Function<BlockSpec, Block> = Function { BaseBlock(it.blockProperties) } private var itemConstructor: Function<BlockSpec, BlockItem>? = null /** Disables the registration of a [BlockItem] for this block */ public fun noItem(): BlockSpec = build { this.hasItem = false } /** Sets whether a [BlockItem] should be registered for this block */ public fun hasItem(value: Boolean): BlockSpec = build { this.hasItem = value } /** Sets the render layer this block should draw in */ public fun renderLayer(value: RenderLayerSpec): BlockSpec = build { this.renderLayer = value } /** * Sets the item group this block's item should be in */ public fun itemGroup(value: ItemGroupSpec): BlockSpec = build { this.itemGroup = value } /** * Sets the block constructor for deferred evaluation */ public fun block(constructor: Function<BlockSpec, Block>): BlockSpec = build { this.blockConstructor = constructor } /** * Sets the custom [BlockItem] constructor for deferred evaluation */ public fun blockItem(constructor: Function<BlockSpec, BlockItem>): BlockSpec = build { this.itemConstructor = constructor } public fun tileEntity(type: LazyTileEntityType<*>): BlockSpec = build { val tileSpec = type.spec ?: if (type.typeInstance == null) throw IllegalStateException("Can't add a block to a LazyTileEntityType that isn't initialized") else throw IllegalArgumentException("Can't add a block to a LazyTileEntityType that isn't backed by a Foundation TileEntitySpec") tileSpec._validBlocks.add(this.lazy) } /** * Configures the information used for data generation */ public fun datagen(data: Consumer<DataGen>): BlockSpec = build { data.accept(this.datagen) } /** * Configures the information used for data generation */ @JvmSynthetic public inline fun datagen(crossinline data: DataGen.() -> Unit): BlockSpec = datagen(Consumer { it.data() }) public override val blockProperties: FoundationBlockProperties = FoundationBlockProperties() //region item properties public var itemProperties: Item.Properties = Item.Properties() /** * Sets this item's food type */ public fun food(food: Food): BlockSpec = build { itemProperties.food(food) } /** * Sets the maximum stack size for this item */ public fun maxStackSize(maxStackSize: Int): BlockSpec = build { itemProperties.maxStackSize(maxStackSize) } /** * Sets the max damage (i.e. durability) of this item. This also implicitly sets the max stack size to 1. */ public fun maxDamage(maxDamage: Int): BlockSpec = build { itemProperties.maxDamage(maxDamage) } /** * Sets the container item for this item. e.g. bucket for a lava bucket, bottle for a dragon's breath, etc. This is * the item left behind in the crafting grid after a recipe completes. */ public fun containerItem(containerItem: Item): BlockSpec = build { itemProperties.containerItem(containerItem) } /** * Sets this item's rarity */ public fun rarity(rarity: Rarity): BlockSpec = build { itemProperties.rarity(rarity) } /** * Removes the ability to repair this item */ public fun setNoRepair(): BlockSpec = build { itemProperties.setNoRepair() } /** * Sets the tool level of this item */ public fun addToolType(type: ToolType, level: Int): BlockSpec = build { itemProperties.addToolType(type, level) } /** * Sets the [ItemStackTileEntityRenderer]. Note that [IBakedModel.isBuiltInRenderer] must return true for this to * be used. */ public fun setISTER(ister: Supplier<Callable<ItemStackTileEntityRenderer>>): BlockSpec = build { itemProperties.setISTER(ister) } //endregion /** * The lazily-evaluated [Block] instance */ public val blockInstance: Block by lazy { try { blockConstructor.apply(this).setRegistryName(registryName) } catch (e: Exception) { throw RuntimeException("Error instantiating block $registryName", e) } } /** * The lazily-evaluated [BlockItem] instance */ public val itemInstance: Item? by lazy { if (!hasItem) return@lazy null try { val item = itemConstructor?.apply(this) ?: (blockInstance as? IFoundationBlock)?.createBlockItem(itemProperties) ?: BlockItem(blockInstance, itemProperties) item.setRegistryName(registryName) } catch (e: Exception) { throw RuntimeException("Error instantiating block item $registryName", e) } } override fun asItem(): Item { return itemInstance ?: throw IllegalStateException("BlockSpec doesn't have an item") } public val lazy: LazyBlock = LazyBlock(this) /** * Information used when generating data */ public inner class DataGen { @get:JvmSynthetic internal var model: Consumer<BlockStateProvider>? = null private set @get:JvmSynthetic internal var itemModel: Consumer<ItemModelProvider>? = null private set @get:JvmSynthetic internal val names: MutableMap<String, String> = mutableMapOf() @get:JvmSynthetic internal val tags: MutableSet<ITag.INamedTag<Block>> = mutableSetOf() @get:JvmSynthetic internal val itemTags: MutableSet<ITag.INamedTag<Item>> = mutableSetOf() /** * The loot table generation options */ public val lootTable: LootDataGen = LootDataGen() /** * The block instance, for use in data generators */ public val block: Block get() = lazy.get() /** * The item instance, for use in data generators */ public val item: Item? get() = itemInstance /** * Sets the model generation function. Note: this will override [IFoundationBlock.generateBlockState]. */ public fun model(model: Consumer<BlockStateProvider>): DataGen { this.model = model return this } /** * Sets the model generation function. Note: this will override [IFoundationBlock.generateBlockState]. */ @JvmSynthetic public inline fun model(crossinline model: BlockStateProvider.() -> Unit): DataGen = model(Consumer { it.model() }) /** * Sets the item model generation function. Note: this will override [IFoundationItem.generateItemModel]. */ public fun itemModel(model: Consumer<ItemModelProvider>): DataGen { this.itemModel = model return this } /** * Sets the item model generation function. Note: this will override [IFoundationItem.generateItemModel]. */ @JvmSynthetic public inline fun itemModel(crossinline model: ItemModelProvider.() -> Unit): DataGen = itemModel(Consumer { it.model() }) /** * Sets the model generation function to create a simple cube block using the texture at * `yourmodid:block/blockid.png`. */ public fun simpleModel(): DataGen = model { simpleBlock(blockInstance) } /** * Sets the name of this block in the generated en_us lang file */ public fun name(name: String): DataGen = name("en_us", name) /** * Sets the name of this block in the generated lang file */ public fun name(locale: String, name: String): DataGen { this.names[locale] = name return this } /** * Adds the passed tags to this block */ public fun tags(vararg tags: ITag.INamedTag<Block>): DataGen { this.tags.addAll(tags) return this } /** * Adds the passed tags to this block's item */ public fun itemTags(vararg tags: ITag.INamedTag<Item>): DataGen { this.itemTags.addAll(tags) return this } } public inner class LootDataGen { @get:JvmSynthetic internal var generator: Consumer<BlockLootTableGenerator>? = null private set /** * Sets the loot table generation function. Note: this will override [IFoundationBlock.generateLootTable]. */ public fun custom(loot: Consumer<BlockLootTableGenerator>) { this.generator = loot } /** * Sets the loot table generation function. Note: this will override [IFoundationBlock.generateLootTable]. */ @JvmSynthetic public inline fun custom(crossinline loot: BlockLootTableGenerator.() -> Unit) { custom(Consumer { it.loot() }) } // shortcuts: // - drop self // - silk touch } private inline fun build(block: () -> Unit): BlockSpec { block() return this } }
lgpl-3.0
c34117cd9b214730f08ae3407a6cb815
33.005698
140
0.651056
4.91598
false
false
false
false
yzbzz/beautifullife
app/src/main/java/com/ddu/ui/fragment/work/FragmentA.kt
2
3366
package com.ddu.ui.fragment.work import android.content.Intent import android.net.Uri import android.os.Bundle import com.ddu.R import com.ddu.icore.common.ext.ctx import com.ddu.icore.ui.fragment.DefaultFragment import com.ddu.ui.activity.TestActivity import com.ddu.util.ToastUtils import kotlinx.android.synthetic.main.fragment_work_state.* import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import java.net.URLEncoder /** * Created by lhz on 16/4/6. */ class FragmentA : DefaultFragment() { private var schemeUrl: String? = null set(value) { startTo(value) } var yzbzzUrl: String? = null var httpUrl: String? = null var defaultData = "yzbzz://5" var login = "1" override fun initData(savedInstanceState: Bundle?) { yzbzzUrl = URLEncoder.encode("yzbzz://5?userId=3&phone=186xxx&t=张三", "utf-8") httpUrl = URLEncoder.encode("http://www.baidu.com?userId=3&phone=186xxx&t=张三", "utf-8") } override fun getLayoutId(): Int { return R.layout.fragment_work_state } override fun initView() { btn_ok.setOnClickListener { if (login.equals("1", ignoreCase = true)) { login = "0" ToastUtils.showToast("登录关闭") } else { login = "1" ToastUtils.showToast("登录开启") } } btn_yzbzz.setOnClickListener { schemeUrl = "yzbzz://3?login=$login" } btn_http.setOnClickListener { schemeUrl = "http://www.baidu.com" } btn_yzbzz_s_e.setOnClickListener { schemeUrl = "yzbzz://100?url=$yzbzzUrl&login=$login" } btn_yzbzz_s_h.setOnClickListener { schemeUrl = "yzbzz://100?url=$httpUrl&login=$login" } btn_yzbzz_s_d_e.setOnClickListener { defaultData = "yzbzz://2" schemeUrl = "yzbzz://101?login=$login" } btn_yzbzz_s_d_h.setOnClickListener { defaultData = "http://www.163.com" schemeUrl = "yzbzz://101?login=$login" } btn_yzbzz_s_d_error.setOnClickListener { defaultData = "yzbzz://102" schemeUrl = "yzbzz://101?login=$login" } btn_yzbzz_s_d_error_o.setOnClickListener { defaultData = "abc**102" schemeUrl = "yzbzz://101?login=$login" } } fun startTo(url: String?) { val intent = Intent(ctx, TestActivity::class.java) val uri = Uri.parse(url) intent.data = uri intent.putExtra("defaultData", defaultData) startActivity(intent) } companion object { fun newInstance(): FragmentA { val fragment = FragmentA() val args = Bundle() fragment.arguments = args return fragment } } fun appendUrl(url: String?, urlParams: Map<String, String>?): String { if (null == url) { return "" } if (urlParams == null || urlParams.size <= 0) { return url } val httpUrl = url!!.toHttpUrlOrNull() ?: return url val urlBuilder = httpUrl.newBuilder() for ((key, value) in urlParams) { urlBuilder.addQueryParameter(key, value) } return urlBuilder.build().toString() } }
apache-2.0
12060d9e7ee423fdf643af190b0664c6
28.839286
95
0.57301
4.136139
false
false
false
false
DSteve595/Put.io
app/src/main/java/com/stevenschoen/putionew/files/FileTitleBarView.kt
1
754
package com.stevenschoen.putionew.files import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.TextView import com.stevenschoen.putionew.R class FileTitleBarView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val titleView: TextView private val backView: View init { View.inflate(context, R.layout.file_title_bar, this) titleView = findViewById(R.id.file_title_bar_name) backView = findViewById(R.id.file_title_bar_back) } var title: CharSequence set(value) { titleView.text = value } get() = titleView.text }
mit
5bab16a14e1fd55c58d7d210ead815df
25.928571
72
0.748011
3.906736
false
false
false
false
androidx/androidx
activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/MainActivity.kt
3
8431
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.activity.integration.testapp import android.Manifest.permission.ACCESS_FINE_LOCATION import android.app.Activity import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.view.ViewManager import android.widget.Button import android.widget.LinearLayout import android.widget.LinearLayout.VERTICAL import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.IntentSenderRequest import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts.CaptureVideo import androidx.activity.result.contract.ActivityResultContracts.CreateDocument import androidx.activity.result.contract.ActivityResultContracts.GetContent import androidx.activity.result.contract.ActivityResultContracts.OpenMultipleDocuments import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia import androidx.activity.result.contract.ActivityResultContracts.PickMultipleVisualMedia import androidx.activity.result.contract.ActivityResultContracts.RequestPermission import androidx.activity.result.contract.ActivityResultContracts.TakePicture import androidx.activity.result.contract.ActivityResultContracts.TakePicturePreview import androidx.activity.result.launch import androidx.activity.result.registerForActivityResult import androidx.core.content.FileProvider import java.io.File class MainActivity : ComponentActivity() { val requestLocation = registerForActivityResult( RequestPermission(), ACCESS_FINE_LOCATION ) { isGranted -> toast("Location granted: $isGranted") } val takePicturePreview = registerForActivityResult(TakePicturePreview()) { bitmap -> toast("Got picture: $bitmap") } val takePicture = registerForActivityResult(TakePicture()) { success -> toast("Got picture: $success") } val captureVideo: ActivityResultLauncher<Uri> = registerForActivityResult( CaptureVideo() ) { success -> toast("Got video: $success") } val getContent: ActivityResultLauncher<String> = registerForActivityResult( GetContent() ) { uri -> toast("Got image: $uri") } lateinit var pickVisualMedia: ActivityResultLauncher<PickVisualMediaRequest> lateinit var pickMultipleVisualMedia: ActivityResultLauncher<PickVisualMediaRequest> lateinit var createDocument: ActivityResultLauncher<String> lateinit var openDocuments: ActivityResultLauncher<Array<String>> private val intentSender = registerForActivityResult( ActivityResultContracts .StartIntentSenderForResult() ) { toast("Received intent sender callback") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (android.os.Build.VERSION.SDK_INT >= 19) { pickVisualMedia = registerForActivityResult(PickVisualMedia()) { uri -> toast("Got image: $uri") } pickMultipleVisualMedia = registerForActivityResult(PickMultipleVisualMedia(5)) { uris -> var media = "" uris.forEach { media += "uri: $it \n" } toast("Got media files: $media") } createDocument = registerForActivityResult(CreateDocument("image/png")) { uri -> toast("Created document: $uri") } openDocuments = registerForActivityResult(OpenMultipleDocuments()) { uris -> var docs = "" uris.forEach { docs += "uri: $it \n" } toast("Got documents: $docs") } } setContentView { add(::LinearLayout) { orientation = VERTICAL button("Request location permission") { requestLocation.launch() } button("Get picture thumbnail") { takePicturePreview.launch() } button("Take pic") { val file = File(filesDir, "image") val uri = FileProvider.getUriForFile(this@MainActivity, packageName, file) takePicture.launch(uri) } button("Capture video") { val file = File(filesDir, "video") val uri = FileProvider.getUriForFile(this@MainActivity, packageName, file) captureVideo.launch(uri) } button("Pick an image (w/ GET_CONTENT)") { getContent.launch("image/*") } if (android.os.Build.VERSION.SDK_INT >= 19) { button("Pick an image (w/ photo picker)") { pickVisualMedia.launch( PickVisualMediaRequest(PickVisualMedia.ImageOnly) ) } button("Pick a GIF (w/ photo picker)") { pickVisualMedia.launch( PickVisualMediaRequest(PickVisualMedia.SingleMimeType("image/gif")) ) } button("Pick 5 visual media max (w/ photo picker)") { pickMultipleVisualMedia.launch( PickVisualMediaRequest(PickVisualMedia.ImageAndVideo) ) } button("Create document") { createDocument.launch("Temp") } button("Open documents") { openDocuments.launch(arrayOf("*/*")) } } button("Start IntentSender") { val request = IntentSenderRequest.Builder( PendingIntent.getActivity( context, 0, Intent(MediaStore.ACTION_IMAGE_CAPTURE), 0 ).intentSender ) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK, 1) .build() intentSender.launch(request) } } } } } fun Context.toast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show() } inline fun Activity.setContentView(ui: ViewManager.() -> Unit) = ActivityViewManager(this).apply(ui) class ActivityViewManager(val activity: Activity) : ViewManager { override fun addView(p0: View?, p1: ViewGroup.LayoutParams?) { activity.setContentView(p0) } override fun updateViewLayout(p0: View?, p1: ViewGroup.LayoutParams?) { TODO("not implemented") } override fun removeView(p0: View?) { TODO("not implemented") } } val ViewManager.context get() = when (this) { is View -> context is ActivityViewManager -> activity else -> TODO() } fun <VM : ViewManager, V : View> VM.add(construct: (Context) -> V, init: V.() -> Unit) { construct(context).apply(init).also { addView(it, ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) } } fun ViewManager.button(txt: String, listener: (View) -> Unit) { add(::Button) { text = txt setOnClickListener(listener) } }
apache-2.0
ccb6e8e5574bc2cd243226d95d6d55c0
36.642857
95
0.623295
5.332701
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/NV_blend_equation_advanced.kt
1
3526
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val NV_blend_equation_advanced = "NVBlendEquationAdvanced".nativeClassGL("NV_blend_equation_advanced", postfix = NV) { documentation = """ Native bindings to the $registryLink extension. This extension adds a number of "advanced" blending equations that can be used to perform new color blending operations, many of which are more complex than the standard blend modes provided by unextended OpenGL. Provides the new blending equations, but guarantees defined results only if each sample is touched no more than once in any single rendering pass. The command #BlendBarrierNV() is provided to indicate a boundary between passes. Requires ${GL20.core}. """ IntConstant( """ Accepted by the {@code pname} parameter of BlendParameteriNV, GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev. """, "BLEND_PREMULTIPLIED_SRC_NV"..0x9280, "BLEND_OVERLAP_NV"..0x9281 ) IntConstant( """ Accepted by the {@code value} parameter of BlendParameteriNV when {@code pname} is BLEND_OVERLAP_NV. """, "UNCORRELATED_NV"..0x8521, "DISJOINT_NV"..0x9283, "CONJOINT_NV"..0x9284 ) IntConstant( """ Accepted by the {@code mode} parameter of BlendEquation and BlendEquationi. """, "SRC_NV"..0x9286, "DST_NV"..0x9287, "SRC_OVER_NV"..0x9288, "DST_OVER_NV"..0x9289, "SRC_IN_NV"..0x928A, "DST_IN_NV"..0x928B, "SRC_OUT_NV"..0x928C, "DST_OUT_NV"..0x928D, "SRC_ATOP_NV"..0x928E, "DST_ATOP_NV"..0x928F, "XOR_NV"..0x1506, "MULTIPLY_NV"..0x9294, "SCREEN_NV"..0x9295, "OVERLAY_NV"..0x9296, "DARKEN_NV"..0x9297, "LIGHTEN_NV"..0x9298, "COLORDODGE_NV"..0x9299, "COLORBURN_NV"..0x929A, "HARDLIGHT_NV"..0x929B, "SOFTLIGHT_NV"..0x929C, "DIFFERENCE_NV"..0x929E, "EXCLUSION_NV"..0x92A0, "INVERT_RGB_NV"..0x92A3, "LINEARDODGE_NV"..0x92A4, "LINEARBURN_NV"..0x92A5, "VIVIDLIGHT_NV"..0x92A6, "LINEARLIGHT_NV"..0x92A7, "PINLIGHT_NV"..0x92A8, "HARDMIX_NV"..0x92A9, "HSL_HUE_NV"..0x92AD, "HSL_SATURATION_NV"..0x92AE, "HSL_COLOR_NV"..0x92AF, "HSL_LUMINOSITY_NV"..0x92B0, "PLUS_NV"..0x9291, "PLUS_CLAMPED_NV"..0x92B1, "PLUS_CLAMPED_ALPHA_NV"..0x92B2, "PLUS_DARKER_NV"..0x9292, "MINUS_NV"..0x929F, "MINUS_CLAMPED_NV"..0x92B3, "CONTRAST_NV"..0x92A1, "INVERT_OVG_NV"..0x92B4, "RED_NV"..0x1903, "GREEN_NV"..0x1904, "BLUE_NV"..0x1905 ) void( "BlendParameteriNV", "", GLenum.IN("pname", ""), GLint.IN("value", "") ) void( "BlendBarrierNV", "" ) } val NV_blend_equation_advanced_coherent = "NVBlendEquationAdvancedCoherent".nativeClassGL("NV_blend_equation_advanced_coherent", postfix = NV) { documentation = """ Native bindings to the ${registryLink("NV", "blend_equation_advanced")} extension. Similar to NV_blend_equation_advanced, but guarantees that blending is done coherently and in API primitive ordering. An enable is provided to allow implementations to opt out of fully coherent blending and instead behave as though only NV_blend_equation_advanced were supported. Requires ${GL20.core} and ${NV_blend_equation_advanced.link}. """ IntConstant( """ Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, and by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetFloatv, GetDoublev and GetInteger64v. """, "BLEND_ADVANCED_COHERENT_NV"..0x9285 ) }
bsd-3-clause
878913f583454ff809ffc128e82be2f5
26.341085
160
0.697107
2.789557
false
false
false
false
google/android-auto-companion-android
communication/src/com/google/android/libraries/car/communication/messagingsync/MessagingUtils.kt
1
2985
// Copyright 2021 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.libraries.car.communication.messagingsync import android.content.Context import android.content.SharedPreferences import com.google.android.libraries.car.notifications.NotificationAccessUtils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * Provides util methods for Messaging Sync Feature */ internal class MessagingUtils constructor(private val context: Context) { private val enabledCars get() = sharedPreferences .getStringSet(ENABLED_CARS_KEY, mutableSetOf()) ?: mutableSetOf() private val sharedPreferences get() = context.getSharedPreferences( MESSAGING_SYNC_SHARED_PREFERENCE_KEY, Context.MODE_PRIVATE ) fun isMessagingSyncEnabled(carId: String) = enabledCars.contains(carId) && NotificationAccessUtils.hasNotificationAccess(context) fun isNotificationAccessEnabled() = NotificationAccessUtils.hasNotificationAccess(context) /** * Handles the user flow to request user permissions and turn on messaging sync. */ fun enableMessagingSync(carId: String, onSuccess: () -> Unit, onFailure: (() -> Unit)?) = CoroutineScope(Dispatchers.Main).launch { val notificationGranted = NotificationAccessUtils.requestNotificationAccess(context) if (notificationGranted) { enableMessagingSyncSharedPreferences(carId) DebugLogs.logMessagingSyncFeatureEnabled() onSuccess() } else { onFailure?.let { it() } } } /** * Turns off messaging sync feature. */ fun disableMessagingSync(carId: String) = sharedPreferences.putStringSet( ENABLED_CARS_KEY, enabledCars.apply { remove(carId) } ).also { DebugLogs.logMessagingSyncFeatureDisabled() } private fun enableMessagingSyncSharedPreferences(carId: String) = sharedPreferences.putStringSet( ENABLED_CARS_KEY, enabledCars.apply { add(carId) } ) private fun SharedPreferences.putStringSet(key: String, set: Set<String>) = edit().putStringSet(key, set).apply() companion object { private const val MESSAGING_SYNC_SHARED_PREFERENCE_KEY = "TrustedDevice.MessagingSyncPreferences" private const val ENABLED_CARS_KEY = "enabledCars" private const val MESSAGING_APP_LIST_FEATURE_FLAG_ENABLED = false } }
apache-2.0
1c03601fdba5ca676523a0d81481da8b
31.096774
91
0.726968
4.642302
false
false
false
false
barinek/bigstar
components/metrics/tests/barinek/bigstar/metrics/MetricsControllerTest.kt
1
3272
package barinek.bigstar.metrics import com.fasterxml.jackson.databind.ObjectMapper import io.barinek.bigstar.jdbc.DataSourceConfig import io.barinek.bigstar.metrics.Metrics import io.barinek.bigstar.rest.BasicApp import io.barinek.bigstar.rest.RestTemplate import org.eclipse.jetty.server.Handler import org.eclipse.jetty.server.handler.HandlerList import org.eclipse.jetty.servlet.ServletContextHandler import org.eclipse.jetty.servlet.ServletHolder import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.springframework.context.annotation.Configuration import org.springframework.http.converter.HttpMessageConverter import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter import org.springframework.web.context.ContextLoaderListener import org.springframework.web.context.WebApplicationContext import org.springframework.web.context.support.AnnotationConfigWebApplicationContext import org.springframework.web.servlet.DispatcherServlet import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter open class MetricsControllerTest() { var app: TestApp = TestApp() @Before fun setUp() { DataSourceConfig().getJdbcTemplate().execute("delete from accounts") app.start() } @After fun tearDown() { app.stop() } @Test fun testGetMetrics() { DataSourceConfig().getJdbcTemplate().update(""" insert into accounts (name, total_contract_value) values ('John\'s Grocery, Inc.', 6000000), ('Hamburg Inn No. 2', 0), ('Record Collector', 1400000) """) val port = 8081 val response = RestTemplate().doGet("http://localhost:$port/api/metrics") val metrics = ObjectMapper().readValue(response, Metrics::class.java) assertEquals(3, metrics.numberOfAccounts) assertEquals(7400000.00, metrics.totalContractValue, 0.0) } /// class TestApp : BasicApp() { override fun getPort(): Int { return 8081 } override fun handlerList(): HandlerList { val list = HandlerList() list.addHandler(getServletContextHandler(getContext())) return list } private fun getServletContextHandler(context: WebApplicationContext): Handler { return ServletContextHandler().apply { contextPath = "/" addServlet(ServletHolder(DispatcherServlet(context)), "/*") addEventListener(ContextLoaderListener(context)) } } private fun getContext(): WebApplicationContext { return AnnotationConfigWebApplicationContext().apply { setConfigLocation("io.barinek.bigstar.metrics,io.barinek.bigstar.jdbc,barinek.bigstar.metrics") } } } @Configuration @EnableWebMvc open class WebConfig : WebMvcConfigurerAdapter() { override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) { converters.add(MappingJackson2HttpMessageConverter(ObjectMapper())) } } }
apache-2.0
f56989131935a0067708dcbfc101b725
34.193548
111
0.702017
4.950076
false
true
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/OsmNoteWithPhotosUploader.kt
1
2613
package de.westnordost.streetcomplete.data.osmnotes import android.util.Log import de.westnordost.streetcomplete.data.NotesApi import de.westnordost.osmapi.common.errors.OsmConflictException import de.westnordost.osmapi.common.errors.OsmNotFoundException import de.westnordost.osmapi.map.data.LatLon import de.westnordost.osmapi.notes.Note import de.westnordost.streetcomplete.data.osm.upload.ConflictException import javax.inject.Inject /** Uploads a new note or a note comment to OSM, with the option to attach a number of photos */ class OsmNoteWithPhotosUploader @Inject constructor( private val notesApi: NotesApi, private val imageUploader: StreetCompleteImageUploader ) { /** Creates a new note * * @throws ImageUploadException if any attached photo could not be uploaded */ fun create(pos: LatLon, text: String, imagePaths: List<String>?): Note { val attachedPhotosText = uploadAndGetAttachedPhotosText(imagePaths) val note = notesApi.create(pos, text + attachedPhotosText) if (!imagePaths.isNullOrEmpty()) { activateImages(note.id) } return note } /** Comments on an existing note * * @throws ImageUploadException if any attached photo could not be uploaded * @throws ConflictException if the note has already been closed or deleted */ fun comment(noteId: Long, text: String, imagePaths: List<String>?): Note { try { val attachedPhotosText = uploadAndGetAttachedPhotosText(imagePaths) val note = notesApi.comment(noteId, text + attachedPhotosText) if (!imagePaths.isNullOrEmpty()) { activateImages(note.id) } return note } catch (e: OsmNotFoundException) { // someone else already closed the note -> our contribution is probably worthless throw ConflictException(e.message, e) } catch (e: OsmConflictException) { throw ConflictException(e.message, e) } } private fun activateImages(noteId: Long) { try { imageUploader.activate(noteId) } catch (e: ImageActivationException) { Log.e("OsmNoteUploader", "Image activation failed", e) } } private fun uploadAndGetAttachedPhotosText(imagePaths: List<String>?): String { if (!imagePaths.isNullOrEmpty()) { val urls = imageUploader.upload(imagePaths) if (urls.isNotEmpty()) { return "\n\nAttached photo(s):\n" + urls.joinToString("\n") } } return "" } }
gpl-3.0
489b6196d5392695df8b9033245c7fc8
36.884058
96
0.665901
4.750909
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/functions/invoke/kt3772.kt
5
335
//KT-3772 Invoke and overload resolution ambiguity open class A { fun invoke(f: A.() -> Unit) = 1 } class B { operator fun invoke(f: B.() -> Unit) = 2 } open class C val C.attr: A get() = A() open class D: C() val D.attr: B get() = B() fun box(): String { val d = D() return if (d.attr {} == 2) "OK" else "fail" }
apache-2.0
49fe558a3c7782ea20f18ccb51617795
15
50
0.555224
2.745902
false
false
false
false
zlyne0/colonization
core/src/promitech/colonization/ai/BuyShipPlaner.kt
1
8183
package promitech.colonization.screen.debug import com.badlogic.gdx.utils.ObjectIntMap import net.sf.freecol.common.model.Specification import net.sf.freecol.common.model.UnitType import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.foreachMission import net.sf.freecol.common.model.ai.missions.goodsToSell.TransportGoodsToSellMissionPlaner import net.sf.freecol.common.model.ai.missions.pioneer.RequestGoodsMission import net.sf.freecol.common.model.ai.missions.transportunit.TransportUnitRequestMission import net.sf.freecol.common.model.player.Player import promitech.colonization.ai.MissionHandlerLogger.logger import promitech.colonization.ai.UnitTypeId import promitech.colonization.ai.calculateNavyTotalCargo import kotlin.LazyThreadSafetyMode.NONE sealed class BuyShipOrder { data class BuyShipNow(val unitType: UnitType): BuyShipOrder() { override fun toString(): String { return "BuyShipNow[${unitType.id}]" } } data class CollectGoldAndBuy(val unitType: UnitType): BuyShipOrder() { override fun toString(): String { return "CollectGoldAndBuy[${unitType.id}]" } } class NoNeedToBuy(): BuyShipOrder() class NoGoldToBuy(): BuyShipOrder() } class BuyShipPlaner( private val player: Player, private val specification: Specification, private val transportGoodsToSellMissionPlaner: TransportGoodsToSellMissionPlaner, private val playerMissionsContainer: PlayerMissionsContainer ) { private val cargoRequestToCapacityRatio = 1.8 private val transportShips = listOf( specification.unitTypes.getById(UnitType.CARAVEL), specification.unitTypes.getById(UnitType.MERCHANTMAN), specification.unitTypes.getById(UnitType.GALLEON), specification.unitTypes.getById(UnitType.FRIGATE) ) private val ownedShips by lazy(NONE) { calculateOwnedShips() } private val cargoAmountWaitingForTransport by lazy(NONE) { transportGoodsToSellMissionPlaner.potentialCargoAmountWaitingForTransport(player) } private val cargoSlotsRequest: CargoSlotsRequest by lazy(NONE) { calculateCargoSlotRequests() } fun createBuyShipPlan(): BuyShipOrder { val freeNavyCargoSlots = player.calculateNavyTotalCargo(transportShipsToSet()) if (cargoSlotsRequest.sum() > freeNavyCargoSlots * cargoRequestToCapacityRatio) { val lastOwnPlusOne = lastOwnPlusOne() val buyOrder = calculateBuyOrder(lastOwnPlusOne) if (logger.isDebug) { logger.debug("player[%s].buyShipPlan cargoSlotRequest > capacity [ %s > %s ] buy ship request, order: %s", player.id, cargoSlotsRequest.sum(), freeNavyCargoSlots * cargoRequestToCapacityRatio, buyOrder ) } return buyOrder } else { if (logger.isDebug) { logger.debug("player[%s].buyShipPlan cargoSlotRequest < capacity [ %s < %s ] do not need buy ship", player.id, cargoSlotsRequest.sum(), freeNavyCargoSlots * cargoRequestToCapacityRatio ) } return BuyShipOrder.NoNeedToBuy() } } fun handleBuyOrders(buyShipOrder: BuyShipOrder) { when (buyShipOrder) { is BuyShipOrder.BuyShipNow -> player.europe.buyUnitByAI(buyShipOrder.unitType) is BuyShipOrder.CollectGoldAndBuy -> return is BuyShipOrder.NoGoldToBuy -> return is BuyShipOrder.NoNeedToBuy -> return } } private fun calculateBuyOrder(shipType: UnitType): BuyShipOrder { if (player.hasGold(shipType.price)) { return BuyShipOrder.BuyShipNow(shipType) } if (player.gold + cargoAmountWaitingForTransport.cargoValue >= shipType.price) { return BuyShipOrder.CollectGoldAndBuy(shipType) } val cheaperVersionShipType = minusOne(shipType) if (player.hasGold(cheaperVersionShipType.price)) { return BuyShipOrder.BuyShipNow(cheaperVersionShipType) } if (player.gold + cargoAmountWaitingForTransport.cargoValue >= cheaperVersionShipType.price) { return BuyShipOrder.CollectGoldAndBuy(cheaperVersionShipType) } if (hasNotAnyShip()) { return BuyShipOrder.CollectGoldAndBuy(cheaperVersionShipType) } return BuyShipOrder.NoGoldToBuy() } private fun lastOwnPlusOne(): UnitType { var lastOwned = transportShips.first() for (transportShip in transportShips) { if (ownedShips.get(transportShip.id, 0) > 0) { lastOwned = transportShip } } return plusOne(lastOwned) } private fun plusOne(unitType: UnitType): UnitType { var found = false for (transportShip in transportShips) { if (transportShip.equalsId(unitType)) { found = true } else if (found) { return transportShip } } return unitType } private fun minusOne(unitType: UnitType): UnitType { var preview = unitType for (transportShip in transportShips) { if (transportShip.equalsId(unitType)) { return preview } preview = transportShip } return unitType } private fun hasNotAnyShip(): Boolean { for (transportShip in transportShips) { if (ownedShips.get(transportShip.id, 0) > 0) { return false } } return true } private fun calculateCargoSlotRequests(): CargoSlotsRequest { val cargoSlotsRequest = CargoSlotsRequest() cargoSlotsRequest.cargoAmountWaitingForTransport = cargoAmountWaitingForTransport.cargoSlots playerMissionsContainer.foreachMission(TransportUnitRequestMission::class.java, { transportUnitRequestMission -> if (transportUnitRequestMission.isWorthEmbark()) { cargoSlotsRequest.transportUnitRequest++ } }) playerMissionsContainer.foreachMission(RequestGoodsMission::class.java, { requestGoodsMission -> cargoSlotsRequest.requestGoods++ }) return cargoSlotsRequest } private fun calculateOwnedShips(): ObjectIntMap<UnitTypeId> { val ownedShips = ObjectIntMap<UnitTypeId>() for (unit in player.units) { if (unit.isNaval && !unit.isDamaged) { ownedShips.getAndIncrement(unit.unitType.id, 0, 1) } } return ownedShips } private fun transportShipsToSet(): Set<UnitTypeId> { val ids = mutableSetOf<UnitTypeId>() for (transportShip in transportShips) { ids.add(transportShip.id) } return ids } fun printDebugInfo() { for (ownShipEntry in ownedShips) { println("ownShipEntry[${ownShipEntry.key}] = ${ownShipEntry.value}") } println("CargoSlotsRequest.cargoAmountWaitingForTransport = ${cargoSlotsRequest.cargoAmountWaitingForTransport}") println("CargoSlotsRequest.requestGoods = ${cargoSlotsRequest.requestGoods}") println("CargoSlotsRequest.transportUnitRequest = ${cargoSlotsRequest.transportUnitRequest}") println("CargoSlotsRequest.sum = ${cargoSlotsRequest.sum()}") val freeNavyCargoSlots = player.calculateNavyTotalCargo(transportShipsToSet()) println("freeNavyCargoSlots = ${freeNavyCargoSlots}") val signal = cargoSlotsRequest.sum() > freeNavyCargoSlots * cargoRequestToCapacityRatio println("buy ship signal (${cargoSlotsRequest.sum()} > ${freeNavyCargoSlots * cargoRequestToCapacityRatio}) = ${signal}") } private class CargoSlotsRequest { var transportUnitRequest: Int = 0 var requestGoods: Int = 0 var cargoAmountWaitingForTransport: Int = 0 fun sum(): Int = transportUnitRequest + requestGoods + cargoAmountWaitingForTransport } }
gpl-2.0
9447c8e9f48b2cc01f060d6687f327e2
38.346154
146
0.666748
5.327474
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/domain/source/interactor/GetEnabledSources.kt
1
2092
package eu.kanade.domain.source.interactor import eu.kanade.domain.source.model.Pin import eu.kanade.domain.source.model.Pins import eu.kanade.domain.source.model.Source import eu.kanade.domain.source.repository.SourceRepository import eu.kanade.domain.source.service.SourcePreferences import eu.kanade.tachiyomi.source.LocalSource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged class GetEnabledSources( private val repository: SourceRepository, private val preferences: SourcePreferences, ) { fun subscribe(): Flow<List<Source>> { return combine( preferences.pinnedSources().changes(), preferences.enabledLanguages().changes(), preferences.disabledSources().changes(), preferences.lastUsedSource().changes(), repository.getSources(), ) { pinnedSourceIds, enabledLanguages, disabledSources, lastUsedSource, sources -> val duplicatePins = preferences.duplicatePinnedSources().get() sources .filter { it.lang in enabledLanguages || it.id == LocalSource.ID } .filterNot { it.id.toString() in disabledSources } .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name }) .flatMap { val flag = if ("${it.id}" in pinnedSourceIds) Pins.pinned else Pins.unpinned val source = it.copy(pin = flag) val toFlatten = mutableListOf(source) if (source.id == lastUsedSource) { toFlatten.add(source.copy(isUsedLast = true, pin = source.pin - Pin.Actual)) } if (duplicatePins && Pin.Pinned in source.pin) { toFlatten[0] = toFlatten[0].copy(pin = source.pin + Pin.Forced) toFlatten.add(source.copy(pin = source.pin - Pin.Actual)) } toFlatten } } .distinctUntilChanged() } }
apache-2.0
afa669309ea25ec59e46a93d471f0420
43.510638
100
0.618069
4.842593
false
false
false
false
Heiner1/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetCancelTemporaryBasal.kt
1
867
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.shared.logging.LTag class DanaRSPacketBasalSetCancelTemporaryBasal( injector: HasAndroidInjector ) : DanaRSPacket(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 val friendlyName: String = "BASAL__CANCEL_TEMPORARY_BASAL" }
agpl-3.0
45d59f3445fa98336da2d960430446fe
30
81
0.683968
4.587302
false
false
false
false
Heiner1/AndroidAPS
app/src/test/java/info/nightscout/androidaps/plugins/general/autotune/AutotunePrepTest.kt
1
19694
package info.nightscout.androidaps.plugins.general.autotune import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.LocalInsulin import info.nightscout.androidaps.data.ProfileSealed import info.nightscout.androidaps.data.PureProfile import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.data.Block import info.nightscout.androidaps.database.data.TargetBlock import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Carbs import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.extensions.shiftBlock import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.plugins.general.autotune.data.* import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONObject import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import java.io.File import java.util.* class AutotunePrepTest : TestBaseWithProfile() { @Mock lateinit var sp: SP @Mock lateinit var autotuneFS: AutotuneFS @Mock lateinit var injector: HasAndroidInjector @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var repository: AppRepository private lateinit var autotunePrep: AutotunePrep private lateinit var autotuneIob: TestAutotuneIob private var ts = 0 private var min5mCarbImpact = 0.0 private var autotuneMin = 0.0 private var autotuneMax = 0.0 private var startDayTime = 0L @Before fun initData() { ts = T.msecs(TimeZone.getDefault().getOffset(System.currentTimeMillis()).toLong()).hours().toInt() - 2 } @Test fun autotunePrepTest1() { // Test if categorisation with standard treatments with carbs is Ok val inputIobJson = File("src/test/res/autotune/test1/oaps-iobCalc.2022-05-21.json").readText() //json files build with iob/activity calculated by OAPS val iobOapsCalculation = buildIobOaps(JSONArray(inputIobJson)) autotuneIob = TestAutotuneIob(aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS, iobOapsCalculation) autotunePrep = AutotunePrep(aapsLogger, sp, dateUtil, autotuneFS, autotuneIob) val inputProfileJson = File("src/test/res/autotune/test1/profile.pump.json").readText() val inputProfile = atProfileFromOapsJson(JSONObject(inputProfileJson), dateUtil)!! val prepJson = File("src/test/res/autotune/test1/autotune.2022-05-21.json").readText() val oapsPreppedGlucose = PreppedGlucose(JSONObject(prepJson), dateUtil) //prep data calculated by OpenAPS autotune val oapsEntriesJson = File("src/test/res/autotune/test1/aaps-entries.2022-05-21.json").readText() autotuneIob.glucose = buildGlucose(JSONArray(oapsEntriesJson)) val oapsTreatmentsJson = File("src/test/res/autotune/test1/aaps-treatments.2022-05-21.json").readText() autotuneIob.meals = buildMeals(JSONArray(oapsTreatmentsJson)) //Only meals is used in unit test, Insulin only used for iob calculation autotuneIob.boluses = buildBoluses(oapsPreppedGlucose) //Values from oapsPrepData because linked to iob calculation method for TBR `when`(sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0)).thenReturn(min5mCarbImpact) `when`(sp.getBoolean(R.string.key_autotune_categorize_uam_as_basal, false)).thenReturn(false) val aapsPreppedGlucose = autotunePrep.categorizeBGDatums(inputProfile, inputProfile.localInsulin, false) try { aapsPreppedGlucose?.let { // compare all categorization calculated by aaps plugin (aapsPreppedGlucose) with categorization calculated by OpenAPS (oapsPreppedGlucose) for (i in aapsPreppedGlucose.crData.indices) Assert.assertTrue(oapsPreppedGlucose.crData[i].equals(aapsPreppedGlucose.crData[i])) for (i in aapsPreppedGlucose.csfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.csfGlucoseData[i].equals(aapsPreppedGlucose.csfGlucoseData[i])) oapsPreppedGlucose.isfGlucoseData = oapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } aapsPreppedGlucose.isfGlucoseData = aapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.isfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.isfGlucoseData[i].equals(aapsPreppedGlucose.isfGlucoseData[i])) oapsPreppedGlucose.basalGlucoseData = oapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } aapsPreppedGlucose.basalGlucoseData = aapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.basalGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.basalGlucoseData[i].equals(aapsPreppedGlucose.basalGlucoseData[i])) } ?: Assert.fail() } catch (e: Exception) { Assert.fail() } } @Test fun autotunePrepTest2() { // Test if categorisation without carbs (full UAM) and categorize UAM as basal false is Ok val inputIobJson = File("src/test/res/autotune/test2/oaps-iobCalc.2022-05-21.json").readText() //json files build with iob/activity calculated by OAPS val iobOapsCalculation = buildIobOaps(JSONArray(inputIobJson)) autotuneIob = TestAutotuneIob(aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS, iobOapsCalculation) autotunePrep = AutotunePrep(aapsLogger, sp, dateUtil, autotuneFS, autotuneIob) val inputProfileJson = File("src/test/res/autotune/test2/profile.pump.json").readText() val inputProfile = atProfileFromOapsJson(JSONObject(inputProfileJson), dateUtil)!! val prepJson = File("src/test/res/autotune/test2/autotune.2022-05-21.json").readText() val oapsPreppedGlucose = PreppedGlucose(JSONObject(prepJson), dateUtil) //prep data calculated by OpenAPS autotune val oapsEntriesJson = File("src/test/res/autotune/test2/aaps-entries.2022-05-21.json").readText() autotuneIob.glucose = buildGlucose(JSONArray(oapsEntriesJson)) val oapsTreatmentsJson = File("src/test/res/autotune/test2/aaps-treatments.2022-05-21.json").readText() autotuneIob.meals = buildMeals(JSONArray(oapsTreatmentsJson)) //Only meals is used in unit test, Insulin only used for iob calculation autotuneIob.boluses = buildBoluses(oapsPreppedGlucose) //Values from oapsPrepData because linked to iob calculation method for TBR `when`(sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0)).thenReturn(min5mCarbImpact) `when`(sp.getBoolean(R.string.key_autotune_categorize_uam_as_basal, false)).thenReturn(false) // CategorizeUAM as Basal = False val aapsPreppedGlucose = autotunePrep.categorizeBGDatums(inputProfile, inputProfile.localInsulin, false) try { aapsPreppedGlucose?.let { // compare all categorization calculated by aaps plugin (aapsPreppedGlucose) with categorization calculated by OpenAPS (oapsPreppedGlucose) for (i in aapsPreppedGlucose.crData.indices) Assert.assertTrue(oapsPreppedGlucose.crData[i].equals(aapsPreppedGlucose.crData[i])) for (i in aapsPreppedGlucose.csfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.csfGlucoseData[i].equals(aapsPreppedGlucose.csfGlucoseData[i])) oapsPreppedGlucose.isfGlucoseData = oapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } aapsPreppedGlucose.isfGlucoseData = aapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.isfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.isfGlucoseData[i].equals(aapsPreppedGlucose.isfGlucoseData[i])) oapsPreppedGlucose.basalGlucoseData = oapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } aapsPreppedGlucose.basalGlucoseData = aapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.basalGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.basalGlucoseData[i].equals(aapsPreppedGlucose.basalGlucoseData[i])) } ?: Assert.fail() } catch (e: Exception) { Assert.fail() } } @Test fun autotunePrepTest3() { // Test if categorisation without carbs (full UAM) and categorize UAM as basal true is Ok val inputIobJson = File("src/test/res/autotune/test3/oaps-iobCalc.2022-05-21.json").readText() //json files build with iob/activity calculated by OAPS val iobOapsCalculation = buildIobOaps(JSONArray(inputIobJson)) autotuneIob = TestAutotuneIob(aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS, iobOapsCalculation) autotunePrep = AutotunePrep(aapsLogger, sp, dateUtil, autotuneFS, autotuneIob) val inputProfileJson = File("src/test/res/autotune/test3/profile.pump.json").readText() val inputProfile = atProfileFromOapsJson(JSONObject(inputProfileJson), dateUtil)!! val prepJson = File("src/test/res/autotune/test3/autotune.2022-05-21.json").readText() val oapsPreppedGlucose = PreppedGlucose(JSONObject(prepJson), dateUtil) //prep data calculated by OpenAPS autotune val oapsEntriesJson = File("src/test/res/autotune/test3/aaps-entries.2022-05-21.json").readText() autotuneIob.glucose = buildGlucose(JSONArray(oapsEntriesJson)) val oapsTreatmentsJson = File("src/test/res/autotune/test3/aaps-treatments.2022-05-21.json").readText() autotuneIob.meals = buildMeals(JSONArray(oapsTreatmentsJson)) //Only meals is used in unit test, Insulin only used for iob calculation autotuneIob.boluses = buildBoluses(oapsPreppedGlucose) //Values from oapsPrepData because linked to iob calculation method for TBR `when`(sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0)).thenReturn(min5mCarbImpact) `when`(sp.getBoolean(R.string.key_autotune_categorize_uam_as_basal, false)).thenReturn(true) // CategorizeUAM as Basal = True val aapsPreppedGlucose = autotunePrep.categorizeBGDatums(inputProfile, inputProfile.localInsulin, false) try { aapsPreppedGlucose?.let { // compare all categorization calculated by aaps plugin (aapsPreppedGlucose) with categorization calculated by OpenAPS (oapsPreppedGlucose) for (i in aapsPreppedGlucose.crData.indices) Assert.assertTrue(oapsPreppedGlucose.crData[i].equals(aapsPreppedGlucose.crData[i])) for (i in aapsPreppedGlucose.csfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.csfGlucoseData[i].equals(aapsPreppedGlucose.csfGlucoseData[i])) oapsPreppedGlucose.isfGlucoseData = oapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } aapsPreppedGlucose.isfGlucoseData = aapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.isfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.isfGlucoseData[i].equals(aapsPreppedGlucose.isfGlucoseData[i])) oapsPreppedGlucose.basalGlucoseData = oapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } aapsPreppedGlucose.basalGlucoseData = aapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.basalGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.basalGlucoseData[i].equals(aapsPreppedGlucose.basalGlucoseData[i])) } ?: Assert.fail() } catch (e: Exception) { Assert.fail() } } /************************************************************************************************************************************************************************************* * OpenAPS profile for Autotune only have one ISF value and one IC value */ @Suppress("SpellCheckingInspection") private fun atProfileFromOapsJson(jsonObject: JSONObject, dateUtil: DateUtil, defaultUnits: String? = null): ATProfile? { try { min5mCarbImpact = JsonHelper.safeGetDoubleAllowNull(jsonObject, "min_5m_carbimpact") ?: return null autotuneMin = JsonHelper.safeGetDoubleAllowNull(jsonObject, "autosens_min") ?: return null autotuneMax = JsonHelper.safeGetDoubleAllowNull(jsonObject, "autosens_max") ?: return null val txtUnits = JsonHelper.safeGetStringAllowNull(jsonObject, "units", defaultUnits) ?: return null val units = GlucoseUnit.fromText(txtUnits) val dia = JsonHelper.safeGetDoubleAllowNull(jsonObject, "dia") ?: return null val peak = JsonHelper.safeGetIntAllowNull(jsonObject, "insulinPeakTime") ?: return null val localInsulin = LocalInsulin("insulin", peak, dia) val timezone = TimeZone.getTimeZone(JsonHelper.safeGetString(jsonObject, "timezone", "UTC")) val isfJson = jsonObject.getJSONObject("isfProfile") val isfBlocks = ArrayList<Block>(1).also { val isfJsonArray = isfJson.getJSONArray("sensitivities") val value = isfJsonArray.getJSONObject(0).getDouble("sensitivity") it.add(0, Block((T.hours(24).secs()) * 1000L, value)) } val icBlocks = ArrayList<Block>(1).also { val value = jsonObject.getDouble("carb_ratio") it.add(0, Block((T.hours(24).secs()) * 1000L, value)) } val basalBlocks = blockFromJsonArray(jsonObject.getJSONArray("basalprofile")) ?: return null val targetBlocks = ArrayList<TargetBlock>(1).also { it.add(0, TargetBlock((T.hours(24).secs()) * 1000L, 100.0, 100.0)) } val pure = PureProfile( jsonObject = jsonObject, basalBlocks = basalBlocks.shiftBlock(1.0,ts), isfBlocks = isfBlocks, icBlocks = icBlocks, targetBlocks = targetBlocks, glucoseUnit = units, timeZone = timezone, dia = dia ) return ATProfile(ProfileSealed.Pure(pure), localInsulin, profileInjector).also { it.dateUtil = dateUtil } } catch (ignored: Exception) { return null } } private fun blockFromJsonArray(jsonArray: JSONArray?): List<Block>? { val size = jsonArray?.length() ?: return null val ret = ArrayList<Block>(size) try { for (index in 0 until jsonArray.length() - 1) { val o = jsonArray.getJSONObject(index) val tas = o.getInt("minutes") * 60 val next = jsonArray.getJSONObject(index + 1) val nextTas = next.getInt("minutes") * 60 val value = o.getDouble("rate") if (tas % 3600 != 0) return null if (nextTas % 3600 != 0) return null ret.add(index, Block((nextTas - tas) * 1000L, value)) } val last: JSONObject = jsonArray.getJSONObject(jsonArray.length() - 1) val lastTas = last.getInt("minutes") * 60 val value = last.getDouble("rate") ret.add(jsonArray.length() - 1, Block((T.hours(24).secs() - lastTas) * 1000L, value)) } catch (e: Exception) { return null } return ret } private fun buildBoluses(preppedGlucose: PreppedGlucose): ArrayList<Bolus> { //if categorization is correct then I return for dose function the crInsulin calculated in Oaps val boluses: ArrayList<Bolus> = ArrayList() for (i in preppedGlucose.crData.indices) { boluses.add( Bolus( timestamp = preppedGlucose.crData[i].crEndTime, amount = preppedGlucose.crData[i].crInsulin, type = Bolus.Type.NORMAL ) ) } if (boluses.size == 0) //Add at least one insulin treatment for tests to avoid return null in categorization boluses.add( Bolus( timestamp = startDayTime, amount = 1.0, type = Bolus.Type.NORMAL ) ) return boluses } private fun buildMeals(jsonArray: JSONArray): ArrayList<Carbs> { val list: ArrayList<Carbs> = ArrayList() for (index in 0 until jsonArray.length()) { val json = jsonArray.getJSONObject(index) val value = JsonHelper.safeGetDouble(json, "carbs", 0.0) val timestamp = JsonHelper.safeGetLong(json, "date") if (value > 0.0 && timestamp > startDayTime) { list.add(Carbs(timestamp = timestamp, amount = value, duration = 0)) } } return list } private fun buildGlucose(jsonArray: JSONArray): List<GlucoseValue> { val list: ArrayList<GlucoseValue> = ArrayList() for (index in 0 until jsonArray.length()) { val json = jsonArray.getJSONObject(index) val value = JsonHelper.safeGetDouble(json, "sgv") val timestamp = JsonHelper.safeGetLong(json, "date") list.add(GlucoseValue(raw = value, noise = 0.0, value = value, timestamp = timestamp, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) } if (list.size > 0) startDayTime = list[list.size - 1].timestamp return list } private fun buildIobOaps(jsonArray: JSONArray): ArrayList<IobTotal> { //if categorization is correct then I return for dose function the crInsulin calculated in Oaps val list: ArrayList<IobTotal> = ArrayList() for (index in 0 until jsonArray.length()) { val json = jsonArray.getJSONObject(index) val time = JsonHelper.safeGetLong(json, "date") val iob = JsonHelper.safeGetDouble(json, "iob") val activity = JsonHelper.safeGetDouble(json, "activity") val iobTotal = IobTotal(time) iobTotal.iob = iob iobTotal.activity = activity list.add(iobTotal) } return list } class TestAutotuneIob( val aapsLogger: AAPSLogger, repository: AppRepository, val profileFunction: ProfileFunction, val sp: SP, val dateUtil: DateUtil, val activePlugin: ActivePlugin, autotuneFS: AutotuneFS, private val iobOapsCalculation: ArrayList<IobTotal> ) : AutotuneIob( aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS ) { override fun getIOB(time: Long, localInsulin: LocalInsulin): IobTotal { val bolusIob = IobTotal(time) iobOapsCalculation.forEach { if (it.time == time) return it } return bolusIob } } }
agpl-3.0
b5ba90391afa765d093481d66c0d82c5
58.141141
191
0.671524
4.944514
false
true
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/interfaces/Constraint.kt
1
3951
package info.nightscout.androidaps.interfaces import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import java.util.* class Constraint<T : Comparable<T>>(private var value: T) { private var originalValue: T private val reasons: MutableList<String> = ArrayList() private val mostLimiting: MutableList<String> = ArrayList() fun value(): T { return value } fun originalValue(): T { return originalValue } fun set(aapsLogger: AAPSLogger, value: T): Constraint<T> { this.value = value originalValue = value aapsLogger.debug(LTag.CONSTRAINTS, "Setting value $value") return this } fun set(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { aapsLogger.debug(LTag.CONSTRAINTS, "Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value addReason(reason, from) addMostLimingReason(reason, from) return this } fun setIfDifferent(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { if (this.value != value) { aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of different value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value addReason(reason, from) addMostLimingReason(reason, from) } return this } fun setIfSmaller(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { if (value < this.value) { aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of smaller value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value mostLimiting.clear() addMostLimingReason(reason, from) } if (value < originalValue) { addReason(reason, from) } return this } fun setIfGreater(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { if (value > this.value) { aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of greater value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value mostLimiting.clear() addMostLimingReason(reason, from) } if (value > originalValue) { addReason(reason, from) } return this } private fun translateFrom(from: Any): String { return from.javaClass.simpleName.replace("Plugin", "") } fun addReason(reason: String, from: Any) { reasons.add(translateFrom(from) + ": " + reason) } private fun addMostLimingReason(reason: String, from: Any) { mostLimiting.add(translateFrom(from) + ": " + reason) } fun getReasons(aapsLogger: AAPSLogger): String { val sb = StringBuilder() for ((count, r) in reasons.withIndex()) { if (count != 0) sb.append("\n") sb.append(r) } aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") return sb.toString() } val reasonList: List<String> get() = reasons fun getMostLimitedReasons(aapsLogger: AAPSLogger): String { val sb = StringBuilder() for ((count, r) in mostLimiting.withIndex()) { if (count != 0) sb.append("\n") sb.append(r) } aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") return sb.toString() } val mostLimitedReasonList: List<String> get() = mostLimiting fun copyReasons(another: Constraint<*>) { reasons.addAll(another.reasonList) } init { originalValue = value } }
agpl-3.0
066fe31ac8753822b4a74f1d4b8931c2
33.068966
166
0.595545
4.308615
false
false
false
false
laminr/aeroknow
app/src/main/java/biz/eventually/atpl/ui/questions/QuestionViewModel.kt
1
4736
package biz.eventually.atpl.ui.questions import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Transformations import android.arch.lifecycle.ViewModel import android.widget.ImageView import biz.eventually.atpl.AtplApplication import biz.eventually.atpl.BuildConfig import biz.eventually.atpl.data.NetworkStatus import biz.eventually.atpl.data.db.Question import biz.eventually.atpl.data.dto.SubjectView import com.squareup.picasso.Picasso import org.jetbrains.anko.doAsync import javax.inject.Inject import javax.inject.Singleton /** * Created by Thibault de Lambilly on 26/11/2017. * */ @Singleton class QuestionViewModel @Inject constructor(private val repository: QuestionRepository) : ViewModel() { // topicId: Long, isSync: Boolean, hasOffline: Boolean var updateLine: MutableLiveData<Triple<Long, Boolean, Boolean>> = MutableLiveData() var networkStatus: LiveData<NetworkStatus> = repository.networkStatus() private var mPosition: MutableLiveData<Int> = MutableLiveData() var question: LiveData<QuestionState> = Transformations.switchMap(mPosition) { mPosition.value?.let { mAnswerIndexTick = -1 val data = MutableLiveData<QuestionState>() mQuestionState = mQuestionState.copy( question = mQuestions[it], index = mPosition.value ?: 0 ) data.postValue(mQuestionState) return@switchMap data } } private var mQuestions: List<Question> = listOf() private var mQuestionState = QuestionState(Question(-1, -1, "", ""), 0, 0) private var mAnswerIndexTick = -1 fun launchTest(topicId: Long, starFist: Boolean) { repository.getQuestions(topicId, starFist, fun(data: List<Question>) { if (data.isNotEmpty()) { mQuestions = data mQuestionState.size = data.size mPosition.value = 0 doAsync { checkExistingPics(mQuestions) } } }) } private fun checkExistingPics(questions: List<Question>) { // https://www.codeday.top/2017/07/31/31373.html val withPics = questions.filter { q -> q.img.isNotEmpty() } val imageViewContainer = ImageView(AtplApplication.get()) withPics.forEach { Picasso.with(AtplApplication.get()).load(BuildConfig.API_ATPL_IMG + it).into(imageViewContainer) } } fun getDataForSubject(subjectId: Long, subjects: List<SubjectView>) { subjects.forEach { // here the topic is in fact a Subject, w/ idWeb = idWeb * -1 if (it.subject.idWeb == (subjectId * -1)) { it.topics.forEach { topic -> val id = topic.idWeb // show sync on the line updateLine.value = Triple(id, true, true) repository.getWebData(id, false, true, true) { // sync done for that line updateLine.value = Triple(id, false, true) // download offline image doAsync { checkExistingPics(repository.getTopicQuestionWithImage(id)) } } } // show the subject button download updateLine.postValue(Triple(subjectId, false, true)) } } } fun tickAnswer(tick: Int) { mAnswerIndexTick = tick } /** * change index position for previous question * returning if ever the answer to the question was good. */ fun previous(): Boolean? { var isGood: Boolean? = null // adding check size while investigating for a crash... if (mAnswerIndexTick > -1 && mAnswerIndexTick < mQuestionState.question.answers.size) { isGood = mQuestionState.question.answers[mAnswerIndexTick].good } mPosition.value?.let { if (it >= 1) mPosition.postValue(it - 1) } return isGood } /** * change index position for next question * returning if ever the answer to the question was good. */ fun next(): Boolean? { var isGood: Boolean? = null mPosition.value?.let { if (mAnswerIndexTick > -1 && it < mQuestionState.question.answers.size) { isGood = mQuestionState.question.answers[mAnswerIndexTick].good } if (it < mQuestions.size - 1) mPosition.postValue(it + 1) } return isGood } fun shuffle() { mQuestions = mQuestions.shuffled() mPosition.value = 0 } }
mit
8aa44ec358c89866c8b06cba1eb06040
31.445205
108
0.607475
4.798379
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/model/data/remote/parser/BaseParser.kt
1
1115
package forpdateam.ru.forpda.model.data.remote.parser import android.text.Spanned import forpdateam.ru.forpda.model.data.remote.api.ApiUtils import java.util.regex.Matcher open class BaseParser { fun String?.fromHtml(): String? = this?.let { ApiUtils.fromHtml(it) } fun String?.fromHtmlToColored(): Spanned? = this?.let { ApiUtils.coloredFromHtml(it) } fun String?.fromHtmlToSpanned(): Spanned? = this?.let { ApiUtils.spannedFromHtml(it) } inline fun Matcher.findOnce(action: (Matcher) -> Unit): Matcher { if (this.find()) action(this) return this } inline fun Matcher.findAll(action: (Matcher) -> Unit): Matcher { while (this.find()) action(this) return this } inline fun <R> Matcher.map(transform: (Matcher) -> R): List<R> { val data = mutableListOf<R>() findAll { data.add(transform(this)) } return data } inline fun <R> Matcher.mapOnce(transform: (Matcher) -> R): R? { var data: R? = null findOnce { data = transform(this) } return data } }
gpl-3.0
94f758fd11c98a8ea267f8e65f3ddbaf
29.135135
90
0.618834
3.871528
false
false
false
false
eugeis/ee-elastic
ee-elastic/src/test/kotlin/ee/es/ExportControllerTest.kt
1
1850
package ee.es import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import java.io.File class ExportControllerTest { @Disabled @Test fun testWriteExportConfig() { val config = exportConfig() val objectMapper: ObjectMapper = jacksonObjectMapper() objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.writeValue(exportConfigFile(), config) } @Disabled @Test fun testReadExportConfig() { val config = exportConfig() val objectMapper: ObjectMapper = jacksonObjectMapper() val loadedConfig = objectMapper.readValue(exportConfigFile(), ExportConfig::class.java) assertEquals(config, loadedConfig) } //@Disabled @Test fun testExport() { val config = exportConfig() val controller = ExportController(config) controller.export() } private fun exportConfig(): ExportConfig { val config = ExportConfig("D:/TC_CACHE/logs/export/tid1.log") config.indexes = arrayOf("logstash-2017.05.18") config.fields = arrayOf("logdate", "type", "level", "logger", "dur", "kind", "message") val thread: String = "0:ffff0a7f642d:912b6af:591c0cff:207dff" /*config.searchSource = SearchSourceBuilder.searchSource().query(match_phrase { "thread" to { query = thread } }).sort("@logdate", SortOrder.ASC).sort("sequence", SortOrder.ASC).toString() println(config.searchSource) */ return config } private fun exportConfigFile() = File("D:/TC_CACHE/logs/export/exportConfig.json") }
apache-2.0
e3351056eba86cb850c90378ae98d12c
32.035714
95
0.687027
4.332553
false
true
false
false
johnjohndoe/Umweltzone
Umweltzone/src/main/java/de/avpptr/umweltzone/details/DetailsFragment.kt
1
9500
/* * Copyright (C) 2020 Tobias Preuss * * 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 de.avpptr.umweltzone.details import android.app.Activity import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.LinearLayout.LayoutParams import android.widget.TextView import androidx.annotation.LayoutRes import androidx.core.os.bundleOf import androidx.core.view.isVisible import de.avpptr.umweltzone.BuildConfig import de.avpptr.umweltzone.R import de.avpptr.umweltzone.base.BaseFragment import de.avpptr.umweltzone.details.dataconverters.toDetailsViewModel import de.avpptr.umweltzone.details.dataconverters.toOtherDetailsViewModel import de.avpptr.umweltzone.details.viewmodels.DpzDetailsViewModel import de.avpptr.umweltzone.details.viewmodels.LezDetailsViewModel import de.avpptr.umweltzone.details.viewmodels.OtherDetailsViewModel import de.avpptr.umweltzone.extensions.textOrHide import de.avpptr.umweltzone.extensions.typeOrHide import de.avpptr.umweltzone.models.AdministrativeZone import de.avpptr.umweltzone.models.ChildZone import de.avpptr.umweltzone.models.DieselProhibitionZone import de.avpptr.umweltzone.models.LowEmissionZone import de.avpptr.umweltzone.utils.ViewHelper import info.metadude.kotlin.library.roadsigns.RoadSign import org.parceler.Parcels class DetailsFragment : BaseFragment() { private val zoneDetailsView by lazy { view?.findViewById(R.id.zoneDetailsView) as LinearLayout } private var administrativeZone: AdministrativeZone? = null public override fun getLayoutResource() = R.layout.fragment_zone_details override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val extras = arguments if (extras != null) { val parcelable = extras.getParcelable<Parcelable>(BUNDLE_KEY_ADMINISTRATIVE_ZONE) administrativeZone = Parcels.unwrap<AdministrativeZone>(parcelable) } } override fun onResume() { super.onResume() if (activity != null && administrativeZone != null) { updateDetails(activity!!, administrativeZone!!) updateSubTitle(administrativeZone!!.displayName) } } private fun updateDetails(activity: Activity, zone: AdministrativeZone) { zoneDetailsView.removeAllViews() zone.childZones.forEach { updateChildZoneDetails(activity, it) } addOtherDetails(zone.toOtherDetailsViewModel()) addVerticalSpace() } private fun updateChildZoneDetails(activity: Activity, childZone: ChildZone) { when (childZone) { is LowEmissionZone -> addLowEmissionZoneDetails(childZone.toDetailsViewModel(activity)) is DieselProhibitionZone -> addDieselProhibitionZoneDetails(childZone.toDetailsViewModel(activity)) } } private fun addLowEmissionZoneDetails(viewModel: LezDetailsViewModel) { val detailsView = layoutInflater.inflate(R.layout.details_low_emission_zone) updateLezDetails(detailsView, viewModel) zoneDetailsView.addChildView(detailsView) } private fun addDieselProhibitionZoneDetails(viewModel: DpzDetailsViewModel) { val detailsView = layoutInflater.inflate(R.layout.details_diesel_prohibition_zone) updateDpzDetails(detailsView, viewModel) zoneDetailsView.addChildView(detailsView) } private fun addOtherDetails(viewModel: OtherDetailsViewModel) { val detailsView = layoutInflater.inflate(R.layout.details_other) updateOtherDetails(detailsView, viewModel) zoneDetailsView.addChildView(detailsView) } private fun addVerticalSpace() { val detailsView = layoutInflater.inflate(R.layout.vertical_space) zoneDetailsView.addChildView(detailsView) } private fun LayoutInflater.inflate(@LayoutRes resource: Int) = inflate(resource, zoneDetailsView, false) private fun LinearLayout.addChildView(view: View) = addView(view, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) private fun updateLezDetails(rootView: View, model: LezDetailsViewModel) { val roadSignView = rootView.findViewById(R.id.detailsLezRoadSignView) as RoadSign val listOfCitiesView = rootView.findViewById(R.id.detailsLezListOfCitiesView) as TextView val zoneNumberSinceView = rootView.findViewById(R.id.detailsLezZoneNumberSinceView) as TextView val nextZoneNumberAsOfView = rootView.findViewById(R.id.detailsLezNextZoneNumberAsOfView) as TextView val abroadLicensedVehicleZoneInfoView = rootView.findViewById(R.id.detailsLezAbroadLicensedVehicleZoneInfoView) as TextView val geometryUpdatedAtView = rootView.findViewById(R.id.detailsLezGeometryUpdatedAtView) as TextView val geometrySourceView = rootView.findViewById(R.id.detailsLezGeometrySourceView) as TextView return with(model) { roadSignView.typeOrHide = roadSignType listOfCitiesView.textOrHide = listOfCitiesText zoneNumberSinceView.textOrHide = zoneNumberSinceText nextZoneNumberAsOfView.textOrHide = nextZoneNumberAsOfText abroadLicensedVehicleZoneInfoView.textOrHide = abroadLicensedVehicleZoneNumberText geometryUpdatedAtView.textOrHide = geometryUpdatedAtText geometrySourceView.textOrHide = geometrySourceText } } private fun updateDpzDetails(rootView: View, model: DpzDetailsViewModel) { val displayNameView = rootView.findViewById(R.id.detailsDpzDisplayNameView) as TextView val roadSignView = rootView.findViewById(R.id.detailsDpzRoadSignView) as RoadSign val allowedEmissionStandardInDpzView = rootView.findViewById(R.id.detailsDpzAllowedEmissionStandardInDpzView) as TextView val isCongruentWithLowEmissionZoneView = rootView.findViewById(R.id.detailsDpzIsCongruentWithLowEmissionZoneView) as TextView val zoneNumberForResidentsSinceView = rootView.findViewById(R.id.detailsDpzZoneNumberForResidentsSinceView) as TextView val zoneNumberForNonResidentsSinceView = rootView.findViewById(R.id.detailsDpzZoneNumberForNonResidentsSinceView) as TextView val prohibitedVehiclesView = rootView.findViewById(R.id.detailsDpzProhibitedVehiclesView) as TextView val geometrySourceView = rootView.findViewById(R.id.detailsDpzGeometrySourceView) as TextView val geometryUpdatedAtView = rootView.findViewById(R.id.detailsDpzGeometryUpdatedAtView) as TextView return with(model) { displayNameView.textOrHide = displayName roadSignView.typeOrHide = roadSignType allowedEmissionStandardInDpzView.textOrHide = allowedEmissionStandardInDpz isCongruentWithLowEmissionZoneView.textOrHide = isCongruentWithLowEmissionZone zoneNumberForResidentsSinceView.textOrHide = zoneNumberForResidentsSince zoneNumberForNonResidentsSinceView.textOrHide = zoneNumberForNonResidentsSince prohibitedVehiclesView.textOrHide = prohibitedVehicles geometrySourceView.textOrHide = geometrySource geometryUpdatedAtView.textOrHide = geometryUpdatedAt } } private fun updateOtherDetails(rootView: View, model: OtherDetailsViewModel) { val furtherInformationView = rootView.findViewById(R.id.detailsOtherFurtherInformationView) as TextView val badgeOnlineView = rootView.findViewById(R.id.detailsOtherBadgeOnlineView) as TextView val activity = requireActivity() return with(model) { ViewHelper.setupTextViewExtended(activity, furtherInformationView, R.string.city_info_further_information, furtherInformation) if (urlBadgeOnline.isEmpty()) { badgeOnlineView.isVisible = false } else { badgeOnlineView.isVisible = true ViewHelper.setupTextViewExtended(activity, badgeOnlineView, R.string.city_info_badge_online_title, urlBadgeOnline) } } } companion object { const val FRAGMENT_TAG = BuildConfig.APPLICATION_ID + ".DETAILS_FRAGMENT_TAG" const val BUNDLE_KEY_ADMINISTRATIVE_ZONE = BuildConfig.APPLICATION_ID + ".ADMINISTRATIVE_ZONE_BUNDLE_KEY" @JvmStatic fun newInstance(administrativeZone: AdministrativeZone): DetailsFragment { val fragment = DetailsFragment() val parcelable = Parcels.wrap(administrativeZone) val extras = bundleOf( BUNDLE_KEY_ADMINISTRATIVE_ZONE to parcelable ) fragment.arguments = extras return fragment } } }
gpl-3.0
77fda8daf825357fd136e3f5aadecb7b
46.738693
133
0.741789
5.055881
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/project/IdeaModuleStructureOracle.kt
3
4719
// 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.project import com.intellij.openapi.module.Module import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.base.facet.implementedModules import org.jetbrains.kotlin.idea.base.facet.implementingModules import org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.unwrapModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.* import org.jetbrains.kotlin.resolve.ModulePath import org.jetbrains.kotlin.resolve.ModuleStructureOracle import java.util.* class IdeaModuleStructureOracle : ModuleStructureOracle { override fun hasImplementingModules(module: ModuleDescriptor): Boolean { return module.implementingDescriptors.isNotEmpty() } override fun findAllReversedDependsOnPaths(module: ModuleDescriptor): List<ModulePath> { val currentPath: Stack<ModuleInfo> = Stack() return sequence<ModuleInfoPath> { val root = module.moduleInfo if (root != null) { yieldPathsFromSubgraph( root, currentPath, getChilds = { with(DependsOnGraphHelper) { it.unwrapModuleSourceInfo()?.predecessorsInDependsOnGraph() ?: emptyList() } } ) } }.map { it.toModulePath() }.toList() } override fun findAllDependsOnPaths(module: ModuleDescriptor): List<ModulePath> { val currentPath: Stack<ModuleInfo> = Stack() return sequence<ModuleInfoPath> { val root = module.moduleInfo if (root != null) { yieldPathsFromSubgraph( root, currentPath, getChilds = { with(DependsOnGraphHelper) { it.unwrapModuleSourceInfo()?.successorsInDependsOnGraph() ?: emptyList() } } ) } }.map { it.toModulePath() }.toList() } private suspend fun SequenceScope<ModuleInfoPath>.yieldPathsFromSubgraph( root: ModuleInfo, currentPath: Stack<ModuleInfo>, getChilds: (ModuleInfo) -> List<ModuleInfo> ) { currentPath.push(root) val childs = getChilds(root) if (childs.isEmpty()) { yield(ModuleInfoPath(currentPath.toList())) } else { childs.forEach { yieldPathsFromSubgraph(it, currentPath, getChilds) } } currentPath.pop() } private class ModuleInfoPath(val nodes: List<ModuleInfo>) private fun ModuleInfoPath.toModulePath(): ModulePath = ModulePath(nodes.mapNotNull { it.unwrapModuleSourceInfo()?.toDescriptor() }) } object DependsOnGraphHelper { fun ModuleDescriptor.predecessorsInDependsOnGraph(): List<ModuleDescriptor> { return moduleSourceInfo ?.predecessorsInDependsOnGraph() ?.mapNotNull { it.toDescriptor() } ?: emptyList() } fun ModuleSourceInfo.predecessorsInDependsOnGraph(): List<ModuleSourceInfo> { val sourceRootType = this.kotlinSourceRootType ?: return emptyList() return this.module.predecessorsInDependsOnGraph().mapNotNull { it.getModuleInfo(sourceRootType) } } fun Module.predecessorsInDependsOnGraph(): List<Module> { return implementingModules } fun ModuleDescriptor.successorsInDependsOnGraph(): List<ModuleDescriptor> { return moduleSourceInfo ?.successorsInDependsOnGraph() ?.mapNotNull { it.toDescriptor() } ?: emptyList() } fun ModuleSourceInfo.successorsInDependsOnGraph(): List<ModuleSourceInfo> { return module.successorsInDependsOnGraph().mapNotNull { module -> val sourceRootType = module.kotlinSourceRootType ?: return@mapNotNull null module.getModuleInfo(sourceRootType) } } fun Module.successorsInDependsOnGraph(): List<Module> { return implementedModules } } private val ModuleDescriptor.moduleInfo: ModuleInfo? get() = getCapability(ModuleInfo.Capability)?.unwrapModuleSourceInfo() private val ModuleDescriptor.moduleSourceInfo: ModuleSourceInfo? get() = moduleInfo as? ModuleSourceInfo
apache-2.0
957e466b28c4a5e4b6553f2a4e72c624
36.165354
158
0.667938
5.617857
false
false
false
false
mdaniel/intellij-community
plugins/gradle-maven/src/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/completion/MavenDependenciesGradleCompletionContributor.kt
11
11789
// 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.gradle.integrations.maven.codeInsight.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.completion.CompletionUtil.DUMMY_IDENTIFIER import com.intellij.codeInsight.completion.CompletionUtil.DUMMY_IDENTIFIER_TRIMMED import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.patterns.PatternCondition import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ProcessingContext import org.jetbrains.concurrency.Promise import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil import org.jetbrains.idea.maven.dom.model.completion.MavenVersionNegatingWeigher import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo import org.jetbrains.idea.reposearch.DependencySearchService import org.jetbrains.idea.reposearch.RepositoryArtifactData import org.jetbrains.idea.reposearch.SearchParameters import org.jetbrains.plugins.gradle.codeInsight.AbstractGradleCompletionContributor import org.jetbrains.plugins.groovy.lang.completion.GrDummyIdentifierProvider.DUMMY_IDENTIFIER_DECAPITALIZED import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.util.GrNamedArgumentsOwner import java.util.concurrent.ConcurrentLinkedDeque /** * @author Vladislav.Soroka */ class MavenDependenciesGradleCompletionContributor : AbstractGradleCompletionContributor() { init { // map-style notation: // e.g.: // compile group: 'com.google.code.guice', name: 'guice', version: '1.0' // runtime([group:'junit', name:'junit-dep', version:'4.7']) // compile(group:'junit', name:'junit-dep', version:'4.7') extend(CompletionType.BASIC, IN_MAP_DEPENDENCY_NOTATION, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(params: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val parent = params.position.parent?.parent if (parent !is GrNamedArgument || parent.parent !is GrNamedArgumentsOwner) { return } result.stopHere() val searchParameters = createSearchParameters(params) val cld = ConcurrentLinkedDeque<MavenRepositoryArtifactInfo>() val dependencySearch = DependencySearchService.getInstance(parent.project) result.restartCompletionOnAnyPrefixChange() if (GROUP_LABEL == parent.labelName) { val groupId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, GROUP_LABEL)) val searchPromise = dependencySearch.fulltextSearch(groupId, searchParameters) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } waitAndAdd(searchPromise, cld) { result.addElement(MavenDependencyCompletionUtil.lookupElement(it).withInsertHandler(GradleMapStyleInsertGroupHandler.INSTANCE)) } } else if (NAME_LABEL == parent.labelName) { val groupId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, GROUP_LABEL)) val artifactId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, NAME_LABEL)) val searchPromise = searchArtifactId(groupId, artifactId, dependencySearch, searchParameters) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } waitAndAdd(searchPromise, cld) { result.addElement( MavenDependencyCompletionUtil.lookupElement(it).withInsertHandler(GradleMapStyleInsertArtifactIdHandler.INSTANCE)) } } else if (VERSION_LABEL == parent.labelName) { val groupId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, GROUP_LABEL)) val artifactId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, NAME_LABEL)) val searchPromise = searchArtifactId(groupId, artifactId, dependencySearch, searchParameters) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } val newResult = result.withRelevanceSorter(CompletionService.getCompletionService().emptySorter().weigh( MavenVersionNegatingWeigher())) waitAndAdd(searchPromise, cld) { repo -> repo.items.forEach { newResult.addElement(MavenDependencyCompletionUtil.lookupElement(it, it.version)) } } } } }) // group:name:version notation // e.g.: // compile 'junit:junit:4.11' // compile('junit:junit:4.11') extend(CompletionType.BASIC, IN_METHOD_DEPENDENCY_NOTATION, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(params: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val element = params.position.parent if (element !is GrLiteral || element.parent !is GrArgumentList) { //try val parent = element?.parent if (parent !is GrLiteral || parent.parent !is GrArgumentList) return } result.stopHere() val completionPrefix = CompletionUtil.findReferenceOrAlphanumericPrefix(params) val quote = params.position.text.firstOrNull() ?: '\'' val suffix = params.originalPosition?.text?.let { StringUtil.unquoteString(it).substring(completionPrefix.length) } val cld = ConcurrentLinkedDeque<MavenRepositoryArtifactInfo>() val splitted = completionPrefix.split(":") val groupId = splitted[0] val artifactId = splitted.getOrNull(1) val version = splitted.getOrNull(2) val dependencySearch = DependencySearchService.getInstance(element.project) val searchPromise = searchStringDependency(groupId, artifactId, dependencySearch, createSearchParameters(params)) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } result.restartCompletionOnAnyPrefixChange() val additionalData = CompletionData(suffix, quote) if (version != null) { val newResult = result.withRelevanceSorter(CompletionSorter.emptySorter().weigh(MavenVersionNegatingWeigher())) waitAndAdd(searchPromise, cld, completeVersions(newResult, additionalData)) } else { waitAndAdd(searchPromise, cld, completeGroupAndArtifact(result, additionalData)) } } }) } private fun completeVersions(result: CompletionResultSet, data: CompletionData): (MavenRepositoryArtifactInfo) -> Unit = { info -> result.addAllElements(info.items.filter { it.version != null }.map { item -> LookupElementBuilder.create(item, MavenDependencyCompletionUtil.getLookupString(item)) .withPresentableText(item.version!!) .withInsertHandler(GradleStringStyleVersionHandler) .also { it.putUserData(COMPLETION_DATA_KEY, data) } }) } private fun completeGroupAndArtifact(result: CompletionResultSet, data: CompletionData): (MavenRepositoryArtifactInfo) -> Unit = { info -> result.addElement(MavenDependencyCompletionUtil.lookupElement(info) .withInsertHandler(GradleStringStyleGroupAndArtifactHandler) .also { it.putUserData(COMPLETION_DATA_KEY, data) }) } private fun searchStringDependency(groupId: String, artifactId: String?, service: DependencySearchService, searchParameters: SearchParameters, consumer: (RepositoryArtifactData) -> Unit): Promise<Int> { if (artifactId == null) { return service.fulltextSearch(groupId, searchParameters, consumer) } else { return service.suggestPrefix(groupId, artifactId, searchParameters, consumer) } } private fun searchArtifactId(groupId: String, artifactId: String, service: DependencySearchService, searchParameters: SearchParameters, consumer: (RepositoryArtifactData) -> Unit): Promise<Int> { if (groupId.isBlank()) { return service.fulltextSearch(artifactId, searchParameters, consumer) } return service.suggestPrefix(groupId, artifactId, searchParameters, consumer) } private fun waitAndAdd(searchPromise: Promise<Int>, cld: ConcurrentLinkedDeque<MavenRepositoryArtifactInfo>, handler: (MavenRepositoryArtifactInfo) -> Unit) { while (searchPromise.state == Promise.State.PENDING || !cld.isEmpty()) { ProgressManager.checkCanceled() val item = cld.poll() if (item != null) { handler.invoke(item) } } } companion object { internal const val GROUP_LABEL = "group" internal const val NAME_LABEL = "name" internal const val VERSION_LABEL = "version" internal const val DEPENDENCIES_SCRIPT_BLOCK = "dependencies" data class CompletionData(val suffix: String?, val quote: Char) val COMPLETION_DATA_KEY = Key.create<CompletionData>("COMPLETION_DATA") private val DEPENDENCIES_CALL_PATTERN = psiElement() .inside(true, psiElement(GrMethodCallExpression::class.java).with( object : PatternCondition<GrMethodCallExpression>("withInvokedExpressionText") { override fun accepts(expression: GrMethodCallExpression, context: ProcessingContext): Boolean { if (checkExpression(expression)) return true return checkExpression(PsiTreeUtil.getParentOfType(expression, GrMethodCallExpression::class.java)) } private fun checkExpression(expression: GrMethodCallExpression?): Boolean { if (expression == null) return false val grExpression = expression.invokedExpression return DEPENDENCIES_SCRIPT_BLOCK == grExpression.text } })) private val IN_MAP_DEPENDENCY_NOTATION = psiElement() .and(GRADLE_FILE_PATTERN) .withParent(GrLiteral::class.java) .withSuperParent(2, psiElement(GrNamedArgument::class.java)) .and(DEPENDENCIES_CALL_PATTERN) private val IN_METHOD_DEPENDENCY_NOTATION = psiElement() .and(GRADLE_FILE_PATTERN) .and(DEPENDENCIES_CALL_PATTERN) private fun createSearchParameters(params: CompletionParameters): SearchParameters { return SearchParameters(params.invocationCount < 2, ApplicationManager.getApplication().isUnitTestMode) } private fun trimDummy(value: String?): String { return if (value == null) { "" } else StringUtil.trim(value.replace(DUMMY_IDENTIFIER, "") .replace(DUMMY_IDENTIFIER_TRIMMED, "") .replace(DUMMY_IDENTIFIER_DECAPITALIZED, "")) } } }
apache-2.0
4431b5b24f4fd5ec2db4aa628d367f53
48.95339
140
0.692595
5.265297
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/ScriptingSupportChecker.kt
1
4102
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.script.configuration import com.intellij.ide.BrowserUtil import com.intellij.ide.scratch.ScratchUtil import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.util.KOTLIN_AWARE_SOURCE_ROOT_TYPES import org.jetbrains.kotlin.scripting.definitions.isNonScript import java.util.function.Function import javax.swing.JComponent class ScriptingSupportChecker: EditorNotificationProvider { override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> { if (!Registry.`is`("kotlin.scripting.support.warning") || file.isNonScript() || ScratchUtil.isScratch(file)) { return EditorNotificationProvider.CONST_NULL } // warning panel is hidden if (!KotlinScriptingSettings.getInstance(project).showSupportWarning) { return EditorNotificationProvider.CONST_NULL } val providers = ScriptingSupportCheckerProvider.CHECKER_PROVIDERS.getExtensionList(project) // if script file is under source root val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex if (projectFileIndex.isUnderSourceRootOfType( file, KOTLIN_AWARE_SOURCE_ROOT_TYPES ) && providers.none { it.isSupportedUnderSourceRoot(file) } ) { return Function { EditorNotificationPanel(it).apply { text = KotlinBundle.message("kotlin.script.in.project.sources") createActionLabel( KotlinBundle.message("kotlin.script.warning.more.info"), Runnable { BrowserUtil.browse(KotlinBundle.message("kotlin.script.in.project.sources.link")) }, false ) addHideAction(file, project) } } } if (providers.none { it.isSupportedScriptExtension(file) }) { return Function { EditorNotificationPanel(it).apply { text = KotlinBundle.message("kotlin.script.in.beta.stage") createActionLabel( KotlinBundle.message("kotlin.script.warning.more.info"), Runnable { BrowserUtil.browse(KotlinBundle.message("kotlin.script.in.beta.stage.link")) }, false ) addHideAction(file, project) } } } return EditorNotificationProvider.CONST_NULL } } private fun EditorNotificationPanel.addHideAction( file: VirtualFile, project: Project ) { createActionLabel( KotlinBundle.message("kotlin.script.in.project.sources.hide"), Runnable { KotlinScriptingSettings.getInstance(project).showSupportWarning = false val fileEditorManager = FileEditorManager.getInstance(project) fileEditorManager.getSelectedEditor(file)?.let { editor -> fileEditorManager.removeTopComponent(editor, this) } }, false ) } private fun VirtualFile.supportedScriptExtensions() = name.endsWith(".main.kts") || name.endsWith(".space.kts") || name.endsWith(".gradle.kts")
apache-2.0
e442064adca5d241aee00deee78ef4fb
41.739583
121
0.656997
5.272494
false
false
false
false
radiKal07/pc-notifications
mobile/app/src/main/kotlin/com/radikal/pcnotifications/model/persistence/impl/SqliteSmsDao.kt
1
2975
package com.radikal.pcnotifications.model.persistence.impl import android.content.ContentResolver import android.net.Uri import android.telephony.TelephonyManager import android.util.Log import com.radikal.pcnotifications.model.domain.Sms import com.radikal.pcnotifications.model.persistence.SmsDao import com.radikal.pcnotifications.utils.RECEIVED import com.radikal.pcnotifications.utils.SENT import java.util.* import javax.inject.Inject import com.github.tamir7.contacts.Contact import com.github.tamir7.contacts.Contacts /** * Created by tudor on 25.04.2017. */ class SqliteSmsDao @Inject constructor() : SmsDao { val TAG: String = javaClass.simpleName val smsInboxUri: Uri = Uri.parse("content://sms/inbox") val smsSentUri: Uri = Uri.parse("content://sms/sent") @Inject lateinit var contentResolver: ContentResolver @Inject lateinit var telephonyManager: TelephonyManager override fun getAllReceived(): List<Sms> { return getSms(smsInboxUri) } override fun getAllSent(): List<Sms> { return getSms(smsSentUri) } private fun getSms(uri: Uri): MutableList<Sms> { var smsType: Int if (uri == smsInboxUri) { smsType = RECEIVED } else if (uri == smsSentUri) { smsType = SENT } else { throw IllegalArgumentException("Provided URI is invalid") } var smsList: MutableList<Sms> = ArrayList() val cursor = contentResolver.query(uri, null, null, null, null) val allContacts = Contacts.getQuery().find() while (cursor.moveToNext()) { var sender = cursor.getString(cursor.getColumnIndex("address")).replace(" ", "") val contactsByPhoneNumber = Contacts.getQuery() contactsByPhoneNumber.whereEqualTo(Contact.Field.PhoneNumber, sender) val contacts = contactsByPhoneNumber.find() var displayName = sender if (contacts.size == 0) { Log.e(TAG, "Contact not found for number: " + sender) allContacts.forEach { val contact = it it.phoneNumbers.forEach { if (it.normalizedNumber?.replace(" ", "") == sender || it.number?.replace(" ", "") == sender) { Log.v(TAG, "Found contact for number $sender and display name: ${contact.displayName}") displayName = contact.displayName } } } } else { displayName = contacts[0].displayName } var message = cursor.getString(cursor.getColumnIndex("body")) var date = cursor.getString(cursor.getColumnIndex("date")) smsList.add(Sms(com.radikal.pcnotifications.model.domain.Contact(displayName, sender), message, Date(date.toLong()), smsType)) } cursor.close() return smsList } }
apache-2.0
8aefa39b076866711e8ed93cb884cd1d
33.206897
138
0.622521
4.612403
false
false
false
false
dmeybohm/chocolate-cakephp
src/main/kotlin/com/daveme/chocolateCakePHP/Cake.kt
1
5500
package com.daveme.chocolateCakePHP import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.jetbrains.php.lang.psi.elements.PhpClass sealed class Cake(val viewDirectory: String, val elementTop: String) { abstract fun templatePath(settings: Settings, controllerName: String, controllerAction: String): String abstract fun elementPath(settings: Settings, elementPath: String): String abstract fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean } fun topSourceDirectoryFromFile(settings: Settings, file: PsiFile): PsiDirectory? { val originalFile = file.originalFile return pluginDirectoryFromFile(settings, originalFile) ?: appDirectoryFromFile(settings, originalFile) ?: templateDirectoryFromFile(settings, originalFile) } private fun templateDirectoryFromFile(settings: Settings, originalFile: PsiFile): PsiDirectory? { if (!settings.cake3Enabled) { return null } var dir: PsiDirectory? = originalFile.containingDirectory while (dir != null) { if (dir.name == "templates") { return dir } dir = dir.parent } return null } fun isCakeViewFile(settings: Settings, file: PsiFile): Boolean { if (!settings.enabled) { return false } val hasCakeFour = if (settings.cake3Enabled) file.name.endsWith("php") else false val hasCakeThree = if (settings.cake3Enabled) file.name.endsWith(settings.cakeTemplateExtension) else false val hasCakeTwo = if (settings.cake2Enabled) file.name.endsWith(settings.cake2TemplateExtension) else false val topDir = topSourceDirectoryFromFile(settings, file) if (hasCakeFour && CakeFour.isCakeViewFile(settings, topDir, file)) { return true } if (hasCakeThree && CakeThree.isCakeViewFile(settings, topDir, file)) { return true } if (hasCakeTwo && CakeTwo.isCakeViewFile(settings, topDir, file)) { return true } return false } private fun pluginDirectoryFromFile(settings: Settings, file: PsiFile): PsiDirectory? { if (!settings.cake3Enabled) { return null } var first: PsiDirectory? = file.containingDirectory var second = first?.parent var third = second?.parent while (third != null && third.name != settings.pluginPath) { first = second second = third third = third.parent } if (third?.name == settings.pluginPath) { return first } return null } private fun appDirectoryFromFile(settings: Settings, file: PsiFile): PsiDirectory? { var dir: PsiDirectory? = file.containingDirectory while (dir != null) { if (settings.cake3Enabled) { if (dir.name == settings.appDirectory) { return dir } } if (settings.cake2Enabled) { if (dir.name == settings.cake2AppDirectory) { return dir } } dir = dir.parent } return null } object CakeFour : Cake(viewDirectory = "templates", elementTop = "element") { override fun templatePath(settings: Settings, controllerName: String, controllerAction: String) = "../$viewDirectory/$controllerName/$controllerAction.php" override fun elementPath(settings: Settings, elementPath: String): String = "../$viewDirectory/$elementTop/$elementPath.php" override fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean { return topDir?.name == viewDirectory } } object CakeThree : Cake(viewDirectory = "Template", elementTop = "Element") { override fun templatePath(settings: Settings, controllerName: String, controllerAction: String) = "$viewDirectory/$controllerName/$controllerAction.${settings.cakeTemplateExtension}" override fun elementPath(settings: Settings, elementPath: String): String = "$viewDirectory/$elementTop/$elementPath.${settings.cakeTemplateExtension}" override fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean { var dir = file.originalFile.containingDirectory while (dir != null && dir != topDir) { if (settings.cake3Enabled) { if (dir.name == viewDirectory && dir.parent == topDir) { return true } } dir = dir.parentDirectory } return false } } object CakeTwo : Cake(viewDirectory = "View", elementTop = "Elements") { override fun templatePath(settings: Settings, controllerName: String, controllerAction: String) = "${viewDirectory}/$controllerName/$controllerAction.${settings.cake2TemplateExtension}" override fun elementPath(settings: Settings, elementPath: String): String = "${viewDirectory}/${elementTop}/$elementPath.${settings.cake2TemplateExtension}" override fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean { var dir = file.originalFile.containingDirectory while (dir != null && dir != topDir) { if (dir.name == viewDirectory && dir.parent == topDir) { return true } dir = dir.parentDirectory } return false } fun isModelClass(classes: Collection<PhpClass>): Boolean { return classes.any { phpClass -> phpClass.superFQN == "\\AppModel" } } }
mit
16ccfec80a4bbe729982228920b8f1a8
33.167702
107
0.660909
4.737295
false
false
false
false
iPoli/iPoli-android
app/src/test/java/io/ipoli/android/pet/usecase/RevivePetUseCaseSpek.kt
1
2455
package io.ipoli.android.pet.usecase import io.ipoli.android.Constants import io.ipoli.android.TestUtil import io.ipoli.android.pet.Pet import io.ipoli.android.pet.PetAvatar import io.ipoli.android.player.data.Player import org.amshove.kluent.`should be equal to` import org.amshove.kluent.`should be instance of` import org.amshove.kluent.`should be` import org.amshove.kluent.shouldThrow import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it /** * Created by Venelin Valkov <[email protected]> * on 12/5/17. */ class RevivePetUseCaseSpek : Spek({ describe("RevivePetUseCase") { fun executeUseCase(player: Player) = RevivePetUseCase(TestUtil.playerRepoMock(player)).execute(Unit) it("should require dead pet") { val player = TestUtil.player.copy( pet = Pet( "", avatar = PetAvatar.ELEPHANT, healthPoints = 10, moodPoints = 10 ) ) val exec = { executeUseCase(player) } exec shouldThrow IllegalArgumentException::class } it("should not revive when not enough gems") { val pet = TestUtil.player.pet val player = TestUtil.player.copy( gems = Constants.REVIVE_PET_GEM_PRICE - 1, pet = pet.copy( healthPoints = 0, moodPoints = 0 ) ) val result = executeUseCase(player) result.`should be`(RevivePetUseCase.Result.TooExpensive) } it("should revive pet") { val pet = TestUtil.player.pet val player = TestUtil.player.copy( gems = Constants.REVIVE_PET_GEM_PRICE, pet = pet.copy( healthPoints = 0, moodPoints = 0 ) ) val result = executeUseCase(player) result.`should be instance of`(RevivePetUseCase.Result.PetRevived::class) val newPlayer = (result as RevivePetUseCase.Result.PetRevived).player newPlayer.gems.`should be equal to`(0) val newPet = newPlayer.pet newPet.healthPoints.`should be equal to`(Constants.DEFAULT_PET_HP) newPet.moodPoints.`should be equal to`(Constants.DEFAULT_PET_MP) } } })
gpl-3.0
c1b5f0ef1d98f85b3564a867d1a56c91
33.591549
85
0.584521
4.463636
false
true
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/schedule/addquest/AddQuestAnimationHelper.kt
1
5063
package io.ipoli.android.quest.schedule.addquest import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.res.ColorStateList import android.support.design.widget.FloatingActionButton import android.view.View import android.view.ViewGroup import android.view.animation.AccelerateDecelerateInterpolator import com.bluelinelabs.conductor.RestoreViewOnCreateController import io.ipoli.android.R import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.navigation.Navigator import io.ipoli.android.common.view.* import io.ipoli.android.common.view.changehandler.CircularRevealChangeHandler import org.threeten.bp.LocalDate /** * Created by Polina Zhelyazkova <[email protected]> * on 4/25/18. */ class AddQuestAnimationHelper( private val controller: RestoreViewOnCreateController, private val addContainer: ViewGroup, private val fab: FloatingActionButton, private val background: View ) { fun openAddContainer(currentDate: LocalDate? = LocalDate.now()) { fab.isClickable = false val halfWidth = addContainer.width / 2 val fabSet = createFabAnimator(fab, halfWidth.toFloat() - fab.width / 2) fabSet.start() fabSet.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { addContainer.visible() fab.invisible() animateShowAddContainer(background) val handler = CircularRevealChangeHandler( addContainer, addContainer, duration = controller.shortAnimTime ) val childRouter = controller.getChildRouter(addContainer, "add-quest") Navigator(childRouter) .setAddQuest( closeListener = { childRouter.popCurrentController() closeAddContainer() }, currentDate = currentDate, changeHandler = handler ) } }) } fun closeAddContainer(endListener: (() -> Unit)? = null) { background.gone() val duration = background.resources.getInteger(android.R.integer.config_shortAnimTime).toLong() val revealAnim = RevealAnimator().createWithEndRadius( view = addContainer, endRadius = (fab.width / 2).toFloat(), reverse = true ) revealAnim.duration = duration revealAnim.startDelay = 300 revealAnim.interpolator = AccelerateDecelerateInterpolator() revealAnim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { if (controller.view == null) { return } addContainer.invisible() addContainer.requestFocus() fab.visible() val fabSet = createFabAnimator( fab, (addContainer.width - fab.width - ViewUtils.dpToPx(16f, fab.context)), reverse = true ) fabSet.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { fab.isClickable = true endListener?.invoke() } }) fabSet.start() } }) revealAnim.start() } private fun createFabAnimator( fab: FloatingActionButton, x: Float, reverse: Boolean = false ): AnimatorSet { val duration = fab.resources.getInteger(android.R.integer.config_shortAnimTime) .toLong() val fabTranslation = ObjectAnimator.ofFloat(fab, "x", x) val fabColor = controller.attrData(R.attr.colorAccent) val transitionColor = controller.colorRes(controller.colorSurfaceResource) val startColor = if (reverse) transitionColor else fabColor val endColor = if (reverse) fabColor else transitionColor val rgbAnim = ObjectAnimator.ofArgb( fab, "backgroundTint", startColor, endColor ) rgbAnim.addUpdateListener { animation -> val value = animation.animatedValue as Int fab.backgroundTintList = ColorStateList.valueOf(value) } return AnimatorSet().also { it.playTogether(fabTranslation, rgbAnim) it.interpolator = AccelerateDecelerateInterpolator() it.duration = duration } } private fun animateShowAddContainer(background: View) { background.alpha = 0f background.visible() background.animate().alpha(1f).setDuration(controller.longAnimTime).start() } }
gpl-3.0
cb82debabd3e80948e54e80b89902f59
33.924138
92
0.608928
5.582139
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/FinalFieldsEntityImpl.kt
2
7984
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.deft.api.annotations.Default import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FinalFieldsEntityImpl(val dataSource: FinalFieldsEntityData) : FinalFieldsEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val descriptor: AnotherDataClass get() = dataSource.descriptor override var description: String = dataSource.description override var anotherVersion: Int = dataSource.anotherVersion override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: FinalFieldsEntityData?) : ModifiableWorkspaceEntityBase<FinalFieldsEntity, FinalFieldsEntityData>( result), FinalFieldsEntity.Builder { constructor() : this(FinalFieldsEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FinalFieldsEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDescriptorInitialized()) { error("Field FinalFieldsEntity#descriptor should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as FinalFieldsEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.descriptor != dataSource.descriptor) this.descriptor = dataSource.descriptor if (this.description != dataSource.description) this.description = dataSource.description if (this.anotherVersion != dataSource.anotherVersion) this.anotherVersion = dataSource.anotherVersion if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var descriptor: AnotherDataClass get() = getEntityData().descriptor set(value) { checkModificationAllowed() getEntityData(true).descriptor = value changedProperty.add("descriptor") } override var description: String get() = getEntityData().description set(value) { checkModificationAllowed() getEntityData(true).description = value changedProperty.add("description") } override var anotherVersion: Int get() = getEntityData().anotherVersion set(value) { checkModificationAllowed() getEntityData(true).anotherVersion = value changedProperty.add("anotherVersion") } override fun getEntityClass(): Class<FinalFieldsEntity> = FinalFieldsEntity::class.java } } class FinalFieldsEntityData : WorkspaceEntityData<FinalFieldsEntity>() { lateinit var descriptor: AnotherDataClass var description: String = "Default description" var anotherVersion: Int = 0 fun isDescriptorInitialized(): Boolean = ::descriptor.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<FinalFieldsEntity> { val modifiable = FinalFieldsEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): FinalFieldsEntity { return getCached(snapshot) { val entity = FinalFieldsEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FinalFieldsEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return FinalFieldsEntity(descriptor, entitySource) { this.description = [email protected] this.anotherVersion = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as FinalFieldsEntityData if (this.entitySource != other.entitySource) return false if (this.descriptor != other.descriptor) return false if (this.description != other.description) return false if (this.anotherVersion != other.anotherVersion) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as FinalFieldsEntityData if (this.descriptor != other.descriptor) return false if (this.description != other.description) return false if (this.anotherVersion != other.anotherVersion) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + descriptor.hashCode() result = 31 * result + description.hashCode() result = 31 * result + anotherVersion.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + descriptor.hashCode() result = 31 * result + description.hashCode() result = 31 * result + anotherVersion.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(AnotherDataClass::class.java) collector.sameForAllEntities = true } }
apache-2.0
0a7786bb5ea2d13d65a2171cdc91766c
33.713043
122
0.734344
5.43499
false
false
false
false
GunoH/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinElementDescriptionProvider.kt
4
10278
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.findUsages import com.intellij.codeInsight.highlighting.HighlightUsagesDescriptionLocation import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.ElementDescriptionLocation import com.intellij.psi.ElementDescriptionProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.RefactoringDescriptionLocation import com.intellij.usageView.UsageViewLongNameLocation import com.intellij.usageView.UsageViewShortNameLocation import com.intellij.usageView.UsageViewTypeLocation import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.util.collapseSpaces import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType open class KotlinElementDescriptionProviderBase : ElementDescriptionProvider { private tailrec fun KtNamedDeclaration.parentForFqName(): KtNamedDeclaration? { val parent = getStrictParentOfType<KtNamedDeclaration>() ?: return null if (parent is KtProperty && parent.isLocal) return parent.parentForFqName() return parent } private fun KtNamedDeclaration.name() = nameAsName ?: Name.special("<no name provided>") private fun KtNamedDeclaration.fqName(): FqNameUnsafe { containingClassOrObject?.let { if (it is KtObjectDeclaration && it.isCompanion()) { return it.fqName().child(name()) } return FqNameUnsafe("${it.name()}.${name()}") } val internalSegments = generateSequence(this) { it.parentForFqName() } .filterIsInstance<KtNamedDeclaration>() .map { it.name ?: "<no name provided>" } .toList() .asReversed() val packageSegments = containingKtFile.packageFqName.pathSegments() return FqNameUnsafe((packageSegments + internalSegments).joinToString(".")) } private fun KtTypeReference.renderShort(): String { return accept( object : KtVisitor<String, Unit>() { private val visitor get() = this override fun visitTypeReference(typeReference: KtTypeReference, data: Unit): String { val typeText = typeReference.typeElement?.accept(this, data) ?: "???" return if (typeReference.hasParentheses()) "($typeText)" else typeText } override fun visitIntersectionType(definitelyNotNullType: KtIntersectionType, data: Unit): String { return buildString { append(definitelyNotNullType.getLeftTypeRef()?.typeElement?.accept(visitor, data) ?: "???") append(" & ") append(definitelyNotNullType.getRightTypeRef()?.typeElement?.accept(visitor, data) ?: "???") } } override fun visitDynamicType(type: KtDynamicType, data: Unit) = type.text override fun visitFunctionType(type: KtFunctionType, data: Unit): String { return buildString { type.receiverTypeReference?.let { append(it.accept(visitor, data)).append('.') } type.parameters.joinTo(this, prefix = "(", postfix = ")") { it.accept(visitor, data) } append(" -> ") append(type.returnTypeReference?.accept(visitor, data) ?: "???") } } override fun visitNullableType(nullableType: KtNullableType, data: Unit): String { val innerTypeText = nullableType.innerType?.accept(this, data) ?: return "???" return "$innerTypeText?" } override fun visitSelfType(type: KtSelfType, data: Unit) = type.text override fun visitUserType(type: KtUserType, data: Unit): String { return buildString { append(type.referencedName ?: "???") val arguments = type.typeArguments if (arguments.isNotEmpty()) { arguments.joinTo(this, prefix = "<", postfix = ">") { it.typeReference?.accept(visitor, data) ?: it.text } } } } override fun visitParameter(parameter: KtParameter, data: Unit) = parameter.typeReference?.accept(this, data) ?: "???" }, Unit ) } //TODO: Implement in FIR protected open val PsiElement.isRenameJavaSyntheticPropertyHandler get() = false protected open val PsiElement.isRenameKotlinPropertyProcessor get() = false override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? { val shouldUnwrap = location !is UsageViewShortNameLocation && location !is UsageViewLongNameLocation val targetElement = if (shouldUnwrap) element.unwrapped ?: element else element fun elementKind() = when (targetElement) { is KtClass -> if (targetElement.isInterface()) KotlinBundle.message("find.usages.interface") else KotlinBundle.message("find.usages.class") is KtObjectDeclaration -> if (targetElement.isCompanion()) KotlinBundle.message("find.usages.companion.object") else KotlinBundle.message("find.usages.object") is KtNamedFunction -> KotlinBundle.message("find.usages.function") is KtPropertyAccessor -> KotlinBundle.message( "find.usages.for.property", (if (targetElement.isGetter) KotlinBundle.message("find.usages.getter") else KotlinBundle.message("find.usages.setter")) ) + " " is KtFunctionLiteral -> KotlinBundle.message("find.usages.lambda") is KtPrimaryConstructor, is KtSecondaryConstructor -> KotlinBundle.message("find.usages.constructor") is KtProperty -> if (targetElement.isLocal) KotlinBundle.message("find.usages.variable") else KotlinBundle.message("find.usages.property") is KtTypeParameter -> KotlinBundle.message("find.usages.type.parameter") is KtParameter -> KotlinBundle.message("find.usages.parameter") is KtDestructuringDeclarationEntry -> KotlinBundle.message("find.usages.variable") is KtTypeAlias -> KotlinBundle.message("find.usages.type.alias") is KtLabeledExpression -> KotlinBundle.message("find.usages.label") is KtImportAlias -> KotlinBundle.message("find.usages.import.alias") is KtLightClassForFacade -> KotlinBundle.message("find.usages.facade.class") else -> { //TODO Implement in FIR when { targetElement.isRenameJavaSyntheticPropertyHandler -> KotlinBundle.message("find.usages.property") targetElement.isRenameKotlinPropertyProcessor -> KotlinBundle.message("find.usages.property.accessor") else -> null } } } val namedElement = if (targetElement is KtPropertyAccessor) { targetElement.parent as? KtProperty } else targetElement as? PsiNamedElement if (namedElement == null) { return if (targetElement is KtElement) "'" + StringUtil.shortenTextWithEllipsis( targetElement.text.collapseSpaces(), 53, 0 ) + "'" else null } if (namedElement.language != KotlinLanguage.INSTANCE) return null return when (location) { is UsageViewTypeLocation -> elementKind() is UsageViewShortNameLocation, is UsageViewLongNameLocation -> namedElement.name is RefactoringDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null val renderFqName = location.includeParent() && namedElement !is KtTypeParameter && namedElement !is KtParameter && namedElement !is KtConstructor<*> @Suppress("HardCodedStringLiteral") val desc = when (namedElement) { is KtFunction -> { val baseText = buildString { append(namedElement.name ?: "") namedElement.valueParameters.joinTo(this, prefix = "(", postfix = ")") { (if (it.isVarArg) "vararg " else "") + (it.typeReference?.renderShort() ?: "") } namedElement.receiverTypeReference?.let { append(" on ").append(it.renderShort()) } } val parentFqName = if (renderFqName) namedElement.fqName().parent() else null if (parentFqName?.isRoot != false) baseText else "${parentFqName.asString()}.$baseText" } else -> (if (renderFqName) namedElement.fqName().asString() else namedElement.name) ?: "" } "$kind ${CommonRefactoringUtil.htmlEmphasize(desc)}" } is HighlightUsagesDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null "$kind ${namedElement.name}" } else -> null } } }
apache-2.0
92931ca61b49755bb2a75371d7326490
48.893204
134
0.604982
5.876501
false
false
false
false
knes1/kotao
src/main/kotlin/io/github/knes1/kotao/brew/util/SiteMap.kt
1
2398
package io.github.knes1.kotao.brew.util import java.io.StringWriter import java.io.Writer import java.time.Instant import java.time.LocalDate import java.time.ZoneOffset import java.time.format.DateTimeFormatter import javax.xml.stream.XMLOutputFactory /** * Utility Url data class and extension functions for generating sitemaps. * * Sitemap is a set of urls. Therefore, to generate sitemap xml, use toXml extension functions * on a set of sitemap urls. * * Example: * * setOf(Url("http://example.com", "2016-01-01")).toXml() * * @author knesek * Created on: 6/14/16 */ data class Url ( val loc: String, val lastmod: String ) { constructor(loc: String, lastmod: Instant = Instant.now()) : this(loc, lastmod.atOffset(ZoneOffset.UTC).toLocalDate()) constructor(loc: String, lastmod: LocalDate) : this(loc, DateTimeFormatter.ISO_DATE.format(lastmod)) } fun Collection<Url>.toXml(writer: Writer) { val factory = XMLOutputFactory.newInstance() val sitemapNS = "http://www.sitemaps.org/schemas/sitemap/0.9" val schemaNS = "http://www.w3.org/2001/XMLSchema-instance" factory.createXMLStreamWriter(writer).apply { try { writeStartDocument() writeStartElement("", "urlset", sitemapNS) writeNamespace("", sitemapNS) writeNamespace("xsi", schemaNS) writeAttribute(schemaNS, "schemaLocation", "$sitemapNS $sitemapNS/sitemap.xsd") forEach { writeStartElement("url") writeStartElement("loc") //collapse index.html in sitemap val loc = if (it.loc.endsWith("index.html")) { it.loc.substring(0, it.loc.length - "index.html".length) } else { it.loc } writeCharacters(loc) writeEndElement() writeStartElement("lastmod") writeCharacters(it.lastmod) writeEndElement() writeEndElement() //url } writeEndElement() //urlset writeEndDocument() } catch (e: Exception) { throw RuntimeException("Failed generating sitemap xml: ${e.message}", e) } finally { flush() close() } } } fun Collection<Url>.toXml() = StringWriter().apply { toXml(this) }.toString()
mit
4c5faeec56b373a3f299be030a056a90
29.74359
122
0.608424
4.259325
false
true
false
false
jk1/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/GlobalActionRecorder.kt
2
3187
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.recorder import com.intellij.ide.IdeEventQueue import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.diagnostic.Logger import com.intellij.testGuiFramework.recorder.ui.GuiScriptEditorPanel import java.awt.event.KeyEvent import java.awt.event.MouseEvent /** * @author Sergey Karashevich */ object GlobalActionRecorder { private val LOG = Logger.getInstance("#${GlobalActionRecorder::class.qualifiedName}") var isActive: Boolean = false private set private val globalActionListener = object : AnActionListener { override fun beforeActionPerformed(action: AnAction?, dataContext: DataContext?, event: AnActionEvent?) { if (event?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions if(action == null) return EventDispatcher.processActionEvent(action, event) LOG.info("IDEA is going to perform action ${action.templatePresentation.text}") } override fun beforeEditorTyping(c: Char, dataContext: DataContext?) { LOG.info("IDEA typing detected: ${c}") } override fun afterActionPerformed(action: AnAction?, dataContext: DataContext?, event: AnActionEvent?) { if (event?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions if (action == null) return LOG.info("IDEA action performed ${action.templatePresentation.text}") } } private val globalAwtProcessor = IdeEventQueue.EventDispatcher { awtEvent -> when (awtEvent) { is MouseEvent -> EventDispatcher.processMouseEvent(awtEvent) is KeyEvent -> EventDispatcher.processKeyBoardEvent(awtEvent) } false } fun activate() { if (isActive) return LOG.info("Global action recorder is active") ActionManager.getInstance().addAnActionListener(globalActionListener) IdeEventQueue.getInstance().addDispatcher(globalAwtProcessor, GuiRecorderManager.frame) //todo: add disposal dependency on component isActive = true } fun deactivate() { if (isActive) { LOG.info("Global action recorder is non active") ActionManager.getInstance().removeAnActionListener(globalActionListener) IdeEventQueue.getInstance().removeDispatcher(globalAwtProcessor) } isActive = false ContextChecker.clearContext() } }
apache-2.0
c9652e8f1b95e4b27400e57b33965b8b
36.069767
136
0.754628
4.673021
false
false
false
false
airbnb/lottie-android
sample-compose/src/main/java/com/airbnb/lottie/sample/compose/utils/ComposeExtensions.kt
1
1091
package com.airbnb.lottie.sample.compose.utils import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp fun Modifier.maybeBackground(color: Color?): Modifier { return if (color == null) { this } else { this.then(background(color)) } } fun Modifier.drawTopBorder(color: Color = Color.DarkGray) = this.then(drawBehind { drawRect(color, Offset.Zero, size = Size(size.width, 1f)) }) fun Modifier.drawBottomBorder(color: Color = Color.DarkGray) = this.then(drawBehind { drawRect(color, Offset(0f, size.height - 1f), size = Size(size.width, 1f)) }) fun Modifier.maybeDrawBorder(draw: Boolean, color: Color = Color.Black, width: Dp = 1.dp): Modifier { return if (draw) { this.then(border(width, color)) } else { this } }
apache-2.0
164cbbd28d2ca10062472bb5756b32f8
28.486486
101
0.724106
3.553746
false
false
false
false
iskandergaba/Botanist
app/src/main/java/com/scientists/happy/botanist/controller/EditPlantController.kt
1
10231
package com.scientists.happy.botanist.controller import android.app.Activity import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.* import com.bumptech.glide.Glide import com.firebase.ui.database.FirebaseListAdapter import com.firebase.ui.storage.images.FirebaseImageLoader import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ValueEventListener import com.google.firebase.storage.StorageReference import com.scientists.happy.botanist.R import com.scientists.happy.botanist.data.Plant import za.co.riggaroo.materialhelptutorial.TutorialItem import java.util.* class EditPlantController(activity: AppCompatActivity) : ActivityController(activity) { private val mPlantId: String = activity.intent.extras.getString("plant_id") private var mPlantName: String? = null private var mPhotoNum: Int = 0 private var mPhotoPointer = -1 private val mPlantReference = databaseManager.getPlantReference(mPlantId) private val mUserPhotosReference = databaseManager.userPhotosReference private val mUserStorage = databaseManager.userStorage init { mPlantReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { val plant = dataSnapshot.getValue(Plant::class.java) if (plant != null) { val nameTextView = activity.findViewById<TextView>(R.id.name_text_view) mPlantName = plant.name nameTextView.text = mPlantName mPhotoNum = plant.photoNum mPhotoPointer = plant.photoPointer } } } override fun onCancelled(databaseError: DatabaseError) { } }) } override fun load() { showProgressDialog(activity.getString(R.string.loading_text)) loadNameSection() val grid = activity.findViewById<GridView>(R.id.photo_grid_view) grid.emptyView = activity.findViewById(R.id.empty_grid_view) populatePhotoGrid(activity) hideProgressDialog() } override fun loadTutorialItems(): ArrayList<TutorialItem>? { return null } /** * populate a grid with plant photos * @param activity - the current activity */ private fun populatePhotoGrid(activity: Activity) { val grid = activity.findViewById<GridView>(R.id.photo_grid_view) val emptyGridView = activity.findViewById<TextView>(R.id.empty_grid_view) val loadingProgressBar = activity.findViewById<ProgressBar>(R.id.loading_indicator) loadingProgressBar.visibility = View.VISIBLE if (mUserPhotosReference != null) { // An SQL-like hack to retrieve only data with values that matches the query: "plantId*" // This is needed to query only images that correspond to the specific plant being edited val query = mUserPhotosReference.orderByValue().startAt(mPlantId).endAt(mPlantId + "\uf8ff") val adapter = object : FirebaseListAdapter<String>(activity, String::class.java, R.layout.grid_item_photo, query) { /** * Populate a photo grid item * @param view - the current view * * * @param photoName - the photo to display * * * @param position - the position */ override fun populateView(view: View, photoName: String, position: Int) { val profilePhotoRef = mPlantReference.child("profilePhoto") val storageReference = mUserStorage.child(photoName) val picture = view.findViewById<ImageView>(R.id.photo_image_view) val isProfilePicture = BooleanArray(1) Glide.with(activity).using(FirebaseImageLoader()).load(storageReference).dontAnimate() .placeholder(R.drawable.flowey).into(picture) val setButton = view.findViewById<View>(R.id.set_photo_btn) setButton.setOnClickListener { profilePhotoRef.setValue(photoName) notifyDataSetChanged() } view.findViewById<ImageView>(R.id.delete_photo_btn).setOnClickListener { buildDeletePhotoDialog(storageReference, profilePhotoRef, position, isProfilePicture[0]).show() } profilePhotoRef.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val profilePhoto = dataSnapshot.value as String? val isSetIndicator = view.findViewById<View>(R.id.is_set_indicator) isProfilePicture[0] = profilePhoto != null && profilePhoto == photoName if (isProfilePicture[0]) { setButton.visibility = View.GONE isSetIndicator.visibility = View.VISIBLE } else { setButton.visibility = View.VISIBLE isSetIndicator.visibility = View.GONE } } override fun onCancelled(databaseError: DatabaseError) { } }) } override fun onDataChanged() { super.onDataChanged() val photoNumRef = mPlantReference.child("photoNum") // Keep photoNum up to date. (photoNum is zero-based) photoNumRef.setValue(count - 1) } /** * Delete Photo dialog * @return Return the dialog window warning user of photo removal */ private fun buildDeletePhotoDialog(storageReference: StorageReference, profilePhotoRef: DatabaseReference, position: Int, isProfilePicture: Boolean): AlertDialog { //Instantiate an AlertDialog.Builder with its constructor val builder = AlertDialog.Builder(activity) //Chain together various setter methods to set the dialog characteristics builder.setTitle(R.string.dialog_delete_photo_title).setMessage(R.string.dialog_delete_photo_text) // Add the buttons builder.setPositiveButton(R.string.yes) { _, _ -> storageReference.delete().addOnCompleteListener { task -> if (task.isSuccessful) { getRef(position).removeValue() if (isProfilePicture) { profilePhotoRef.setValue("default") } // Keep photoCount up-to-date databaseManager.photoCount = databaseManager.photoCount - 1 } } } builder.setNegativeButton(R.string.no) { _, _ -> } // Get the AlertDialog from create() return builder.create() } } // After digging deep, I discovered that Firebase keeps some local information in ".info" val connectedRef = databaseManager.userConnectionReference connectedRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val connected = snapshot.value as Boolean if (connected) { emptyGridView.setText(R.string.loading_text) loadingProgressBar.visibility = View.VISIBLE } else { Toast.makeText(activity, R.string.msg_network_error, Toast.LENGTH_SHORT).show() emptyGridView.setText(R.string.msg_network_error) loadingProgressBar.visibility = View.GONE } } override fun onCancelled(error: DatabaseError) {} }) mUserPhotosReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { loadingProgressBar.visibility = View.GONE emptyGridView.setText(R.string.grid_photos_empty_text) } override fun onCancelled(databaseError: DatabaseError) { emptyGridView.setText(R.string.msg_unexpected_error) loadingProgressBar.visibility = View.GONE } }) grid.adapter = adapter } } private fun loadNameSection() { activity.findViewById<Button>(R.id.rename_button).setOnClickListener { val builder = AlertDialog.Builder(activity) val dialogView = View.inflate(activity, R.layout.dialog_name_input, null) val inputEditText = dialogView.findViewById<EditText>(R.id.name_edit_text) inputEditText.setText(mPlantName) builder.setView(dialogView).setTitle(R.string.rename) // Set up the buttons builder.setPositiveButton(R.string.mdtp_ok) { _, _ -> mPlantReference.child("name").setValue(inputEditText.text.toString()) } builder.setNegativeButton(R.string.mdtp_cancel) { dialog, _ -> dialog.cancel() } builder.create().show() } } }
apache-2.0
4e8ee9c95a73490e94860524660f3b83
47.488152
127
0.572085
5.67758
false
false
false
false
mdanielwork/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInstaller.kt
1
6709
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl import com.intellij.ide.IdeBundle import com.intellij.ide.util.DelegatingProgressIndicator import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ArrayUtil import com.intellij.util.Restarter import com.intellij.util.io.HttpRequests import java.io.File import java.io.IOException import java.net.URL import java.nio.file.Files import java.nio.file.Paths import javax.swing.UIManager object UpdateInstaller { const val UPDATER_MAIN_CLASS = "com.intellij.updater.Runner" private val patchesUrl: URL get() = URL(System.getProperty("idea.patches.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.patchesUrl) @JvmStatic @Throws(IOException::class) fun downloadPatchChain(chain: List<BuildNumber>, forceHttps: Boolean, indicator: ProgressIndicator): List<File> { indicator.text = IdeBundle.message("update.downloading.patch.progress") val files = mutableListOf<File>() val product = ApplicationInfo.getInstance().build.productCode val jdk = if (System.getProperty("idea.java.redist", "").lastIndexOf("NoJavaDistribution") >= 0) "-no-jdk" else "" val share = 1.0 / (chain.size - 1) for (i in 1 until chain.size) { val from = chain[i - 1].withoutProductCode().asString() val to = chain[i].withoutProductCode().asString() val patchName = "${product}-${from}-${to}-patch${jdk}-${PatchInfo.OS_SUFFIX}.jar" val patchFile = File(getTempDir(), "patch${i}.jar") val url = URL(patchesUrl, patchName).toString() val partIndicator = object : DelegatingProgressIndicator(indicator) { override fun setFraction(fraction: Double) { super.setFraction((i - 1) * share + fraction / share) } } HttpRequests.request(url).gzip(false).forceHttps(forceHttps).saveToFile(patchFile, partIndicator) files += patchFile } return files } @JvmStatic fun installPluginUpdates(downloaders: Collection<PluginDownloader>, indicator: ProgressIndicator): Boolean { indicator.text = IdeBundle.message("update.downloading.plugins.progress") UpdateChecker.saveDisabledToUpdatePlugins() val disabledToUpdate = UpdateChecker.disabledToUpdatePlugins val readyToInstall = mutableListOf<PluginDownloader>() for (downloader in downloaders) { try { if (downloader.pluginId !in disabledToUpdate && downloader.prepareToInstall(indicator)) { readyToInstall += downloader } indicator.checkCanceled() } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } var installed = false ProgressManager.getInstance().executeNonCancelableSection { for (downloader in readyToInstall) { try { downloader.install() installed = true } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } } return installed } @JvmStatic fun cleanupPatch() { val tempDir = getTempDir() if (tempDir.exists()) FileUtil.delete(tempDir) } @JvmStatic @Throws(IOException::class) fun preparePatchCommand(patchFile: File, indicator: ProgressIndicator): Array<String> = preparePatchCommand(listOf(patchFile), indicator) @JvmStatic @Throws(IOException::class) fun preparePatchCommand(patchFiles: List<File>, indicator: ProgressIndicator): Array<String> { indicator.text = IdeBundle.message("update.preparing.patch.progress") val log4j = findLib("log4j.jar") val jna = findLib("jna.jar") val jnaUtils = findLib("jna-platform.jar") val tempDir = getTempDir() if (FileUtil.isAncestor(PathManager.getHomePath(), tempDir.path, true)) { throw IOException("Temp directory inside installation: $tempDir") } if (!(tempDir.exists() || tempDir.mkdirs())) { throw IOException("Cannot create temp directory: $tempDir") } val log4jCopy = log4j.copyTo(File(tempDir, log4j.name), true) val jnaCopy = jna.copyTo(File(tempDir, jna.name), true) val jnaUtilsCopy = jnaUtils.copyTo(File(tempDir, jnaUtils.name), true) var java = System.getProperty("java.home") if (FileUtil.isAncestor(PathManager.getHomePath(), java, true)) { val javaCopy = File(tempDir, "jre") FileUtil.copyDir(File(java), javaCopy) java = javaCopy.path } val args = arrayListOf<String>() if (SystemInfo.isWindows && !Files.isWritable(Paths.get(PathManager.getHomePath()))) { val launcher = PathManager.findBinFile("launcher.exe") val elevator = PathManager.findBinFile("elevator.exe") // "launcher" depends on "elevator" if (launcher != null && elevator != null && launcher.canExecute() && elevator.canExecute()) { args += Restarter.createTempExecutable(launcher).path Restarter.createTempExecutable(elevator) } } args += File(java, if (SystemInfo.isWindows) "bin\\java.exe" else "bin/java").path args += "-Xmx900m" args += "-cp" args += arrayOf(patchFiles.last().path, log4jCopy.path, jnaCopy.path, jnaUtilsCopy.path).joinToString(File.pathSeparator) args += "-Djna.nosys=true" args += "-Djna.boot.library.path=" args += "-Djna.debug_load=true" args += "-Djna.debug_load.jna=true" args += "-Djava.io.tmpdir=${tempDir.path}" args += "-Didea.updater.log=${PathManager.getLogPath()}" args += "-Dswing.defaultlaf=${UIManager.getSystemLookAndFeelClassName()}" args += UPDATER_MAIN_CLASS args += if (patchFiles.size == 1) "install" else "batch-install" args += PathManager.getHomePath() if (patchFiles.size > 1) { args += patchFiles.joinToString(File.pathSeparator) } return ArrayUtil.toStringArray(args) } private fun findLib(libName: String): File { val libFile = File(PathManager.getLibPath(), libName) return if (libFile.exists()) libFile else throw IOException("Missing: ${libFile}") } private fun getTempDir() = File(PathManager.getTempPath(), "patch-update") }
apache-2.0
a06027164fcf4ce59b9b9a4d0c3e61e4
36.909605
140
0.705619
4.18789
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/dataset/internal/DataSetModuleDownloader.kt
1
4199
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.dataset.internal import dagger.Reusable import io.reactivex.Completable import javax.inject.Inject import org.hisp.dhis.android.core.arch.call.factories.internal.UidsCall import org.hisp.dhis.android.core.arch.call.factories.internal.UidsCallFactory import org.hisp.dhis.android.core.arch.db.stores.internal.LinkStore import org.hisp.dhis.android.core.arch.helpers.UidsHelper.getUids import org.hisp.dhis.android.core.arch.modules.internal.UntypedModuleDownloader import org.hisp.dhis.android.core.dataelement.DataElement import org.hisp.dhis.android.core.dataset.DataSet import org.hisp.dhis.android.core.dataset.DataSetOrganisationUnitLink import org.hisp.dhis.android.core.dataset.DataSetOrganisationUnitLinkTableInfo import org.hisp.dhis.android.core.option.Option import org.hisp.dhis.android.core.option.OptionSet import org.hisp.dhis.android.core.period.internal.PeriodHandler import org.hisp.dhis.android.core.validation.ValidationRule import org.hisp.dhis.android.core.validation.internal.ValidationRuleUidsCall @Reusable internal class DataSetModuleDownloader @Inject internal constructor( private val dataSetCallFactory: UidsCallFactory<DataSet>, private val dataElementCallFactory: UidsCallFactory<DataElement>, private val optionSetCall: UidsCall<OptionSet>, private val optionCall: UidsCall<Option>, private val validationRuleCall: UidsCall<ValidationRule>, private val validationRuleUidsCall: ValidationRuleUidsCall, private val periodHandler: PeriodHandler, private val dataSetOrganisationUnitLinkStore: LinkStore<DataSetOrganisationUnitLink> ) : UntypedModuleDownloader { override fun downloadMetadata(): Completable { return Completable.fromCallable { val orgUnitDataSetUids = dataSetOrganisationUnitLinkStore .selectDistinctSlaves(DataSetOrganisationUnitLinkTableInfo.Columns.DATA_SET) val dataSets = dataSetCallFactory.create(orgUnitDataSetUids).call() val dataElements = dataElementCallFactory.create( DataSetParentUidsHelper.getDataElementUids(dataSets) ).call() val optionSetUids = DataSetParentUidsHelper.getAssignedOptionSetUids(dataElements) optionSetCall.download(optionSetUids).blockingGet() optionCall.download(optionSetUids).blockingGet() val validationRuleUids = validationRuleUidsCall.download(getUids(dataSets)).blockingGet() validationRuleCall.download(getUids(validationRuleUids)).blockingGet() periodHandler.generateAndPersist() } } }
bsd-3-clause
5a5a524e0418043cc6ef07d533004245
52.151899
101
0.78352
4.639779
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/leetcode/first_missing_positive/FirstMissingPositive.kt
1
1907
package katas.kotlin.leetcode.first_missing_positive import datsok.shouldEqual import org.junit.jupiter.api.Test // // https://leetcode.com/problems/first-missing-positive // // Given an unsorted integer array, find the smallest missing positive integer. // // Example 1: // Input: [1,2,0] // Output: 3 // // Example 2: // Input: [3,4,-1,1] // Output: 2 // // Example 3: // Input: [7,8,9,11,12] // Output: 1 // // Follow up: // Your algorithm should run in O(n) time and uses constant extra space. // fun firstMissingPositive(nums: IntArray): Int { nums.indices.filter { nums[it] == 0 }.forEach { nums[it] = -1 } nums.filter { it - 1 in nums.indices }.forEach { nums[it - 1] = 0 } return (nums.indices.find { nums[it] != 0 } ?: nums.size) + 1 } fun firstMissingPositive_2(nums: IntArray): Int { val numbers = nums.sorted().filter { it > 0 }.toSet() numbers.forEachIndexed { i, n -> if (i + 1 != n) return i + 1 } return (numbers.lastOrNull() ?: 0) + 1 } fun firstMissingPositive_1(nums: IntArray): Int { val positiveNumbers = nums.filter { it > 0 } val max = positiveNumbers.maxOrNull() ?: 0 return 1.until(max).find { it !in positiveNumbers } ?: max + 1 } fun firstMissingPositive_0(nums: IntArray): Int { return (1..Int.MAX_VALUE).find { it !in nums } ?: -1 } class FirstMissingPositiveTests { private val f: (IntArray) -> Int = ::firstMissingPositive @Test fun `some examples`() { f(intArrayOf()) shouldEqual 1 f(intArrayOf(-1)) shouldEqual 1 f(intArrayOf(0)) shouldEqual 1 f(intArrayOf(123)) shouldEqual 1 f(intArrayOf(Int.MAX_VALUE)) shouldEqual 1 f(intArrayOf(1)) shouldEqual 2 f(intArrayOf(1, 2, 0)) shouldEqual 3 f(intArrayOf(1, 1, 2, 2, 0)) shouldEqual 3 f(intArrayOf(3, 4, -1, 1)) shouldEqual 2 f(intArrayOf(7, 8, 9, 11, 12)) shouldEqual 1 } }
unlicense
8e9ab193ce2d4ec7d771348a78e66bdc
27.058824
79
0.629261
3.369258
false
false
false
false
micgn/stock-charts
stock-api/src/main/java/de/mg/stock/dto/ChartItemDTO.kt
1
1998
/* * Copyright 2016 Michael Gnatz. * * 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 de.mg.stock.dto import de.mg.stock.util.LocalDateTimeAdapter import java.io.Serializable import java.time.LocalDateTime import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter class ChartItemDTO(@get:XmlJavaTypeAdapter(LocalDateTimeAdapter::class) var dateTime: LocalDateTime, var minLong: Long? = null, var maxLong: Long? = null, var averageLong: Long?, var instantPrice: Boolean) : Serializable { val min: Double? get() = if (minLong != null) minLong!! / 100.0 else null val max: Double? get() = if (maxLong != null) maxLong!! / 100.0 else null val average: Double? get() = if (averageLong != null) averageLong!! / 100.0 else null val isValid: Boolean get() { var valid = true if (minLong != null && maxLong != null) valid = minLong!! <= maxLong!! if (minLong != null && averageLong != null) valid = valid && minLong!! <= averageLong!! if (averageLong != null && maxLong != null) valid = valid && averageLong!! <= maxLong!! return valid } override fun toString(): String { return "ChartItemDTO(dateTime=$dateTime, minLong=$minLong, maxLong=$maxLong, averageLong=$averageLong, instantPrice=$instantPrice)" } }
apache-2.0
1ed22597fb196bf92072c365d7cbac18
35.327273
139
0.632132
4.449889
false
false
false
false
neilellis/kontrol
doclient/src/main/kotlin/DigitalOceanClient.kt
1
12640
/* * Kotlin version Copyright (c) 2014 Cazcade Limited (http://cazcade.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * * Original Java codes was MIT License https://github.com/jeevatkm/digitalocean-api-java * * Copyright (c) 2010-2013 Jeevanandam M. (myjeeva.com) * * 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 kontrol.doclient import com.google.gson.JsonObject import com.google.gson.JsonParser import kontrol.doclient.Action.* import kontrol.doclient.* import org.apache.http.client.methods.HttpGet import org.apache.http.client.utils.URIBuilder import org.apache.http.conn.scheme.Scheme import org.apache.http.conn.ssl.HackedSSLSocketFactory import org.apache.http.impl.client.DefaultHttpClient import org.slf4j.Logger import org.slf4j.LoggerFactory import java.lang.reflect.Type import java.net.URI import com.google.gson.JsonElement import com.google.gson.Gson import com.google.gson.reflect.TypeToken /** * DigitalOcean API client wrapper methods Implementation * * @author Jeevanandam M. ([email protected]) */ public class DigitalOceanClient(val clientId: String, val apiKey: String) : DigitalOcean { public val TYPE_DROPLET_LIST: Type = object : TypeToken<MutableList<Droplet>>() { }.getType()!! public val TYPE_IMAGE_LIST: Type = object : TypeToken<MutableList<DropletImage>>() { }.getType()!! public val TYPE_REGION_LIST: Type = object : TypeToken<MutableList<Region>>() { }.getType()!! public val TYPE_SIZE_LIST: Type = object : TypeToken<MutableList<DropletSize>>() { }.getType()!! public val TYPE_DOMAIN_LIST: Type = object : TypeToken<MutableList<Domain>>() { }.getType()!! public val TYPE_DOMAIN_RECORD_LIST: Type = object : TypeToken<MutableList<DomainRecord>>() { }.getType()!! public val TYPE_SSH_KEY_LIST: Type = object : TypeToken<MutableList<SshKey>>() { }.getType()!! private val LOG: Logger = LoggerFactory.getLogger(javaClass<DigitalOceanClient>())!! val gson: Gson = Gson() public fun JsonElement.asClass(clazz: Class<*>): Any = gson.fromJson(this.toString(), clazz)!! public fun JsonElement.asType(`type`: Type): Any = gson.fromJson(this.toString(), `type`)!! /** * Http client */ private var httpClient: DefaultHttpClient? = null /** * User's Client ID */ /** * DigitalOcean API Host is <code>api.digitalocean.com</code> */ private var apiHost: String = "api.digitalocean.com" public override fun droplets(): List<Droplet> = get(AVAILABLE_DROPLETS, TYPE_DROPLET_LIST) as List<Droplet> public override fun createDroplet(droplet: Droplet, sshKeyIds: String?, backupsEnabled: Boolean, privateNetworking: Boolean): Droplet = getWithParam(CREATE_DROPLET, javaClass<Droplet>(), hashMapOf( P_NAME to droplet.name, P_SIZE_ID to droplet.size_id, P_IMAGE_ID to droplet.image_id, P_REGION_ID to droplet.region_id, P_BACKUPS_ENABLED to backupsEnabled, P_PRIVATE_NETWORKING to privateNetworking, P_SSH_KEY_IDS to sshKeyIds ) ) as Droplet override fun getDropletInfo(id: Int): Droplet = get(GET_DROPLET_INFO, javaClass<Droplet>(), id) as Droplet override fun rebootDroplet(id: Int): Response = call(REBOOT_DROPLET, id) override fun powerCyleDroplet(id: Int): Response = call(POWER_CYCLE_DROPLET, id) override fun shutdownDroplet(id: Int): Response = call(SHUTDOWN_DROPLET, id) override fun powerOffDroplet(id: Int): Response = call(POWER_OFF_DROPLET, id) override fun powerOnDroplet(id: Int): Response = call(POWER_ON_DROPLET, id) override fun resetDropletPassword(id: Int): Response = call(RESET_PASSWORD_DROPLET, id) override fun resizeDroplet(id: Int, sizeId: Int): Response = callWithParam(RESIZE_DROPLET, hashMapOf(P_SIZE_ID to sizeId), id) override fun takeDropletSnapshot(id: Int): Response = takeDropletSnapshot(id, null) override fun takeDropletSnapshot(id: Int, name: String?): Response = when (name) { null -> call(TAKE_DROPLET_SNAPSHOT, id) else -> callWithParam(TAKE_DROPLET_SNAPSHOT, hashMapOf(P_NAME to name), id) } override fun restoreDroplet(id: Int, imageId: Int): Response = callWithParam(RESTORE_DROPLET, hashMapOf(P_IMAGE_ID to imageId), id) override fun rebuildDroplet(id: Int, imageId: Int): Response = callWithParam(REBUILD_DROPLET, hashMapOf(P_IMAGE_ID to imageId), id) override fun enableDropletBackups(id: Int): Response = call(ENABLE_AUTOMATIC_BACKUPS, id) override fun disableDropletBackups(id: Int): Response = call(DISABLE_AUTOMATIC_BACKUPS, id) override fun renameDroplet(id: Int, name: String): Response = callWithParam(RENAME_DROPLET, hashMapOf(P_NAME to name), id) override fun deleteDroplet(id: Int): Response = call(DELETE_DROPLET, id) override fun getAvailableRegions(): List<Region> = get(AVAILABLE_REGIONS, TYPE_REGION_LIST) as List<Region> override fun getAvailableImages(): List<DropletImage> = get(AVAILABLE_IMAGES, TYPE_IMAGE_LIST) as List<DropletImage> override fun getImageInfo(imageId: Int): DropletImage = get(GET_IMAGE_INFO, javaClass<DropletImage>(), imageId) as DropletImage override fun deleteImage(imageId: Int): Response = call(DELETE_IMAGE, imageId) override fun transferImage(imageId: Int, regionId: Int): Response = callWithParam(TRANSFER_IMAGE, hashMapOf(P_REGION_ID to regionId), imageId) override fun getAvailableSshKeys(): List<SshKey> = get(AVAILABLE_SSH_KEYS, TYPE_SSH_KEY_LIST) as List<SshKey> override fun getSshKeyInfo(sshKeyId: Int): SshKey = get(GET_SSH_KEY, javaClass<SshKey>(), sshKeyId) as SshKey override fun addSshKey(name: String, publicKey: String): SshKey = get(CREATE_SSH_KEY, javaClass<SshKey>(), hashMapOf(P_NAME to name, P_PUBLIC_KEY to publicKey)) as SshKey override fun editSshKey(sshKeyId: Int, newKey: String): SshKey = get(EDIT_SSH_KEY, javaClass<SshKey>(), hashMapOf(P_PUBLIC_KEY to newKey), sshKeyId) as SshKey override fun deleteSshKey(sshKeyId: Int): Response = call(DELETE_SSH_KEY, sshKeyId) override fun getAvailableSizes(): List<DropletSize> = get(AVAILABLE_SIZES, TYPE_SIZE_LIST) as List<DropletSize> override fun getAvailableDomains(): List<Domain> = get(AVAILABLE_DOMAINS, TYPE_DOMAIN_LIST) as List<Domain> override fun getDomainInfo(domainId: Int): Domain = get(GET_DOMAIN_INFO, javaClass<Domain>(), domainId) as Domain override fun createDomain(domainName: String, ipAddress: String): Domain = get(CREATE_DOMAIN, javaClass<Domain>(), hashMapOf(P_NAME to domainName, PARAM_IP_ADDRESS to ipAddress)) as Domain override fun deleteDomain(domainId: Int): Response = call(DELETE_DOMAIN, domainId) override fun getDomainRecords(domainId: Int): List<DomainRecord> = get(GET_DOMAIN_RECORDS, TYPE_DOMAIN_RECORD_LIST, domainId) as List<DomainRecord> override fun getDomainRecordInfo(domainId: Int, recordId: Int): DomainRecord = get(GET_DOMAIN_RECORD_INFO, javaClass<DomainRecord>(), array(domainId, recordId)) as DomainRecord override fun createDomainRecord(domainRecord: DomainRecord): DomainRecord = getWithParam(CREATE_DOMAIN_RECORD, javaClass<DomainRecord>(), domainRecord.asParams(), domainRecord.domain_id) as DomainRecord override fun editDomainRecord(domainRecord: DomainRecord): DomainRecord = (getWithParam(EDIT_DOMAIN_RECORD, javaClass<DomainRecord>(), domainRecord.asParams(), array<Any>(domainRecord.domain_id?:-1, domainRecord.id?:-1)) as DomainRecord) override fun deleteDomainRecord(domainId: Int, recordId: Int): Response = call(DELETE_DOMAIN_RECORD, array<Any>(domainId, recordId)) private fun performAction(action: Action, queryParams: Map<String, Any?>?, vararg pathParams: Any?): JsonObject { try { val uri = generateUri(action.mapPath, queryParams, *pathParams) val obj = JsonParser().parse(execute(uri))?.getAsJsonObject()!! if (obj.get(STATUS)?.getAsString()?.equalsIgnoreCase("OK")?:false) { LOG.debug("JSON Respose Data: " + obj.toString()) return obj } else { throw RequestUnsuccessfulException("DigitalOcean API request unsuccessful, possible reason could be incorrect values [$uri].") } } catch (e: RequestUnsuccessfulException) { throw e } catch (e: Exception) { throw RequestUnsuccessfulException(e.getMessage(), e) } } private fun generateUri(path: String, queryParams: Map<String, Any?>?, vararg pathParams: Any?): URI { val ub = URIBuilder() .setScheme(HTTPS_SCHEME) ?.setHost(apiHost) ?.setPath(path.format(*pathParams)) ?.setParameter(PARAM_CLIENT_ID, this.clientId) ?.setParameter(PARAM_API_KEY, this.apiKey) queryParams?.entrySet()?.forEach { if (it.value != null) ub?.setParameter(it.key, it.value.toString()) } return ub?.build()!! } private fun execute(uri: URI): String { val httpGet = HttpGet(uri) LOG.debug("DigitalOcean API Endpoint URI: " + uri) try { val httpResponse = httpClient?.execute(httpGet) return when(httpResponse?.getStatusLine()?.getStatusCode()) { 401 -> throw AccessDeniedException("Request failed to authenticate into the DigitalOcean API successfully") 404 -> throw ResourceNotFoundException("Requested resource is not available DigitalOcean $uri") else -> httpResponse?.getEntity()?.getContent()?.readFully()?:"" } } finally { httpGet.releaseConnection() } } private fun call(action: Action, vararg pathParams: Any?): Response { return performAction(action, null, *pathParams).asClass(javaClass<Response>()) as Response } private fun callWithParam(action: Action, queryParams: Map<String, Any?>?, vararg pathParams: Any?): Response { return performAction(action, queryParams, *pathParams).asClass(javaClass<Response>()) as Response } private fun get(action: Action, clazz: Class<*>, vararg pathParams: Any?): Any? { return performAction(action, null, *pathParams)[action.element]?.asClass(clazz) } private fun getWithParam(action: Action, clazz: Class<*>, queryParams: Map<String, Any?>?, vararg pathParams: Any?): Any? { return performAction(action, queryParams, *pathParams)[action.element]?.asClass(clazz) } private fun get(action: Action, classType: Type, vararg pathParams: Any?): Any? { return performAction(action, null, *pathParams)[action.element]?.asType(classType) } { val base = DefaultHttpClient() val ccm = base.getConnectionManager() ccm?.getSchemeRegistry()?.register(Scheme("https", HackedSSLSocketFactory.newInstance(), 443)) this.httpClient = DefaultHttpClient(ccm, base.getParams()) } }
apache-2.0
57ee62aa7a40189089f4dfb31b64dddb
53.482759
241
0.701187
4.27027
false
false
false
false
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/fragment/HistFragment.kt
1
1826
package com.cv4j.app.fragment import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.cv4j.app.R import com.cv4j.app.activity.CompareHistActivity import com.cv4j.app.activity.HistogramDemoActivity import com.cv4j.app.activity.HistogramEqualizationActivity import com.cv4j.app.activity.ProjectHistActivity import com.cv4j.app.app.BaseFragment import kotlinx.android.synthetic.main.fragment_hist.* /** * * @FileName: * com.cv4j.app.fragment.HistFragment * @author: Tony Shen * @date: 2020-05-04 11:43 * @version: V1.0 <描述当前版本功能> */ class HistFragment : BaseFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_hist, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) text1.setOnClickListener { val i = Intent(mContext, HistogramEqualizationActivity::class.java) i.putExtra("Title", text1.text.toString()) startActivity(i) } text2.setOnClickListener { val i = Intent(mContext, HistogramDemoActivity::class.java) i.putExtra("Title", text2.text.toString()) startActivity(i) } text3.setOnClickListener { val i = Intent(mContext, CompareHistActivity::class.java) i.putExtra("Title", text3.text.toString()) startActivity(i) } text4.setOnClickListener { val i = Intent(mContext, ProjectHistActivity::class.java) i.putExtra("Title", text4.text.toString()) startActivity(i) } } }
apache-2.0
78485f519aec04300544a3aa2ea14ff8
31.927273
174
0.687845
4.03118
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSemicolonInspection.kt
3
5624
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.util.isLineBreak import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class RedundantSemicolonInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) if (element.node.elementType == KtTokens.SEMICOLON && isRedundantSemicolon(element)) { holder.registerProblem( element, KotlinBundle.message("redundant.semicolon"), Fix ) } } } } } internal fun isRedundantSemicolon(semicolon: PsiElement): Boolean { val nextLeaf = semicolon.nextLeaf { it !is PsiWhiteSpace && it !is PsiComment || it.isLineBreak() } val isAtEndOfLine = nextLeaf == null || nextLeaf.isLineBreak() if (!isAtEndOfLine) { //when there is no imports parser generates empty import list with no spaces if (semicolon.parent is KtPackageDirective && (nextLeaf as? KtImportList)?.imports?.isEmpty() == true) { return true } if (semicolon.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment || it.isLineBreak() } is PsiWhiteSpace && !semicolon.isBeforeLeftBrace() ) { return true } return false } if (semicolon.prevLeaf()?.node?.elementType == KtNodeTypes.ELSE) return false if (semicolon.parent is KtEnumEntry) return false (semicolon.parent.parent as? KtClass)?.let { clazz -> if (clazz.isEnum() && clazz.getChildrenOfType<KtEnumEntry>().isEmpty()) { if (semicolon.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment && !it.isLineBreak() }?.node?.elementType == KtTokens.LBRACE && clazz.declarations.isNotEmpty() ) { //first semicolon in enum with no entries, but with some declarations return false } } } (semicolon.prevLeaf()?.parent as? KtLoopExpression)?.let { if (it !is KtDoWhileExpression && it.body == null) return false } semicolon.prevLeaf()?.parent?.safeAs<KtIfExpression>()?.also { ifExpression -> if (ifExpression.then == null) return false } if (nextLeaf.isBeforeLeftBrace()) { return false // case with statement starting with '{' and call on the previous line } return !isSemicolonRequired(semicolon) } private fun PsiElement?.isBeforeLeftBrace(): Boolean { return this?.nextLeaf { it !is PsiWhiteSpace && it !is PsiComment && it.getStrictParentOfType<KDoc>() == null && it.getStrictParentOfType<KtAnnotationEntry>() == null }?.node?.elementType == KtTokens.LBRACE } private fun isSemicolonRequired(semicolon: PsiElement): Boolean { if (isRequiredForCompanion(semicolon)) { return true } val prevSibling = semicolon.getPrevSiblingIgnoringWhitespaceAndComments() val nextSibling = semicolon.getNextSiblingIgnoringWhitespaceAndComments() if (prevSibling.safeAs<KtNameReferenceExpression>()?.text in softModifierKeywords && nextSibling is KtDeclaration) { // enum; class Foo return true } if (nextSibling is KtPrefixExpression && nextSibling.operationToken == KtTokens.EXCL) { val typeElement = semicolon.prevLeaf()?.getStrictParentOfType<KtTypeReference>()?.typeElement if (typeElement != null) { return typeElement !is KtNullableType // trailing '?' fixes parsing } } return false } private fun isRequiredForCompanion(semicolon: PsiElement): Boolean { val prev = semicolon.getPrevSiblingIgnoringWhitespaceAndComments() as? KtObjectDeclaration ?: return false if (!prev.isCompanion()) return false if (prev.nameIdentifier != null || prev.getChildOfType<KtClassBody>() != null) return false val next = semicolon.getNextSiblingIgnoringWhitespaceAndComments() ?: return false val firstChildNode = next.firstChild?.node ?: return false if (KtTokens.KEYWORDS.contains(firstChildNode.elementType)) return false return true } private object Fix : LocalQuickFix { override fun getName() = KotlinBundle.message("fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { descriptor.psiElement.delete() } } private val softModifierKeywords: List<String> = KtTokens.SOFT_KEYWORDS.types.mapNotNull { (it as? KtModifierKeywordToken)?.toString() }
apache-2.0
ece93f24e2542d79c7011956a15bf57a
38.328671
136
0.685455
5.192982
false
false
false
false
google/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/open/GradleOpenProjectProvider.kt
1
4462
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.service.project.open import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.importing.AbstractOpenProjectProvider import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjectInfo import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode.MODAL_SYNC import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl import com.intellij.openapi.externalSystem.service.ui.ExternalProjectDataSelectorDialog import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants.BUILD_FILE_EXTENSIONS import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID import org.jetbrains.plugins.gradle.util.updateGradleJvm import org.jetbrains.plugins.gradle.util.validateJavaHome internal class GradleOpenProjectProvider : AbstractOpenProjectProvider() { override val systemId = SYSTEM_ID override fun isProjectFile(file: VirtualFile): Boolean { return !file.isDirectory && BUILD_FILE_EXTENSIONS.any { file.name.endsWith(it) } } override fun linkToExistingProject(projectFile: VirtualFile, project: Project) { LOG.debug("Link Gradle project '$projectFile' to existing project ${project.name}") val projectPath = getProjectDirectory(projectFile).toNioPath() val settings = createLinkSettings(projectPath, project) validateJavaHome(project, projectPath, settings.resolveGradleVersion()) val externalProjectPath = settings.externalProjectPath ExternalSystemApiUtil.getSettings(project, SYSTEM_ID).linkProject(settings) if (!Registry.`is`("external.system.auto.import.disabled")) { ExternalSystemUtil.refreshProject( externalProjectPath, ImportSpecBuilder(project, SYSTEM_ID) .usePreviewMode() .use(MODAL_SYNC) ) ExternalProjectsManagerImpl.getInstance(project).runWhenInitialized { ExternalSystemUtil.refreshProject( externalProjectPath, ImportSpecBuilder(project, SYSTEM_ID) .callback(createFinalImportCallback(project, externalProjectPath)) ) } } } private fun createFinalImportCallback(project: Project, externalProjectPath: String): ExternalProjectRefreshCallback { return object : ExternalProjectRefreshCallback { override fun onSuccess(externalProject: DataNode<ProjectData>?) { if (externalProject == null) return selectDataToImport(project, externalProjectPath, externalProject) importData(project, externalProject) updateGradleJvm(project, externalProjectPath) } } } private fun selectDataToImport(project: Project, externalProjectPath: String, externalProject: DataNode<ProjectData>) { val settings = GradleSettings.getInstance(project) val showSelectiveImportDialog = settings.showSelectiveImportDialogOnInitialImport() val application = ApplicationManager.getApplication() if (showSelectiveImportDialog && !application.isHeadlessEnvironment) { application.invokeAndWait { val projectInfo = InternalExternalProjectInfo(SYSTEM_ID, externalProjectPath, externalProject) val dialog = ExternalProjectDataSelectorDialog(project, projectInfo) if (dialog.hasMultipleDataToSelect()) { dialog.showAndGet() } else { Disposer.dispose(dialog.disposable) } } } } private fun importData(project: Project, externalProject: DataNode<ProjectData>) { ProjectDataManager.getInstance().importData(externalProject, project, false) } }
apache-2.0
0657b597e4afedcf5367f0dffeb0d4eb
45.489583
121
0.788436
5.200466
false
false
false
false
google/intellij-community
plugins/kotlin/base/fe10/code-insight/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt
5
7390
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.SuppressIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.idea.base.fe10.codeInsight.KotlinBaseFe10CodeInsightBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.highlighter.AnnotationHostKind import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.replaceFileAnnotationList import org.jetbrains.kotlin.resolve.BindingContext class KotlinSuppressIntentionAction( suppressAt: KtElement, private val suppressionKey: String, private val kind: AnnotationHostKind ) : SuppressIntentionAction() { val pointer = suppressAt.createSmartPointer() val project = suppressAt.project override fun getFamilyName() = KotlinBaseFe10CodeInsightBundle.message("intention.suppress.family") override fun getText() = KotlinBaseFe10CodeInsightBundle.message("intention.suppress.text", suppressionKey, kind.kind, kind.name ?: "") override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = element.isValid override fun invoke(project: Project, editor: Editor?, element: PsiElement) { if (!element.isValid) return val suppressAt = pointer.element ?: return if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return val id = "\"$suppressionKey\"" when (suppressAt) { is KtModifierListOwner -> suppressAt.addAnnotation( StandardNames.FqNames.suppress, id, whiteSpaceText = if (kind.newLineNeeded) "\n" else " ", addToExistingAnnotation = { entry -> addArgumentToSuppressAnnotation( entry, id ); true }) is KtAnnotatedExpression -> suppressAtAnnotatedExpression(CaretBox(suppressAt, editor), id) is KtExpression -> suppressAtExpression(CaretBox(suppressAt, editor), id) is KtFile -> suppressAtFile(suppressAt, id) } } private fun suppressAtFile(ktFile: KtFile, id: String) { val psiFactory = KtPsiFactory(project) val fileAnnotationList: KtFileAnnotationList? = ktFile.fileAnnotationList if (fileAnnotationList == null) { val newAnnotationList = psiFactory.createFileAnnotationListWithAnnotation(suppressAnnotationText(id, false)) val packageDirective = ktFile.packageDirective val createAnnotationList = if (packageDirective != null && PsiTreeUtil.skipWhitespacesForward(packageDirective) == ktFile.importList) { // packageDirective could be empty but suppression still should be added before it to generate consistent PSI ktFile.addBefore(newAnnotationList, packageDirective) as KtFileAnnotationList } else { replaceFileAnnotationList(ktFile, newAnnotationList) } ktFile.addAfter(psiFactory.createWhiteSpace(kind), createAnnotationList) return } val suppressAnnotation: KtAnnotationEntry? = findSuppressAnnotation(fileAnnotationList) if (suppressAnnotation == null) { val newSuppressAnnotation = psiFactory.createFileAnnotation(suppressAnnotationText(id, false)) fileAnnotationList.add(psiFactory.createWhiteSpace(kind)) fileAnnotationList.add(newSuppressAnnotation) as KtAnnotationEntry return } addArgumentToSuppressAnnotation(suppressAnnotation, id) } private fun suppressAtAnnotatedExpression(suppressAt: CaretBox<KtAnnotatedExpression>, id: String) { val entry = findSuppressAnnotation(suppressAt.expression) if (entry != null) { // already annotated with @suppress addArgumentToSuppressAnnotation(entry, id) } else { suppressAtExpression(suppressAt, id) } } private fun suppressAtExpression(caretBox: CaretBox<KtExpression>, id: String) { val suppressAt = caretBox.expression assert(suppressAt !is KtDeclaration) { "Declarations should have been checked for above" } val placeholderText = "PLACEHOLDER_ID" val annotatedExpression = KtPsiFactory(suppressAt).createExpression(suppressAnnotationText(id) + "\n" + placeholderText) val copy = suppressAt.copy()!! val afterReplace = suppressAt.replace(annotatedExpression) as KtAnnotatedExpression val toReplace = afterReplace.findElementAt(afterReplace.textLength - 2)!! assert(toReplace.text == placeholderText) val result = toReplace.replace(copy)!! caretBox.positionCaretInCopy(result) } private fun addArgumentToSuppressAnnotation(entry: KtAnnotationEntry, id: String) { // add new arguments to an existing entry val args = entry.valueArgumentList val psiFactory = KtPsiFactory(entry) val newArgList = psiFactory.createCallArguments("($id)") when { args == null -> // new argument list entry.addAfter(newArgList, entry.lastChild) args.arguments.isEmpty() -> // replace '()' with a new argument list args.replace(newArgList) else -> args.addArgument(newArgList.arguments[0]) } } private fun suppressAnnotationText(id: String, withAt: Boolean = true): String { return "${if (withAt) "@" else ""}${StandardNames.FqNames.suppress.shortName()}($id)" } private fun findSuppressAnnotation(annotated: KtAnnotated): KtAnnotationEntry? { val context = annotated.analyze() return findSuppressAnnotation(context, annotated.annotationEntries) } private fun findSuppressAnnotation(annotationList: KtFileAnnotationList): KtAnnotationEntry? { val context = annotationList.analyze() return findSuppressAnnotation(context, annotationList.annotationEntries) } private fun findSuppressAnnotation(context: BindingContext, annotationEntries: List<KtAnnotationEntry>): KtAnnotationEntry? { return annotationEntries.firstOrNull { entry -> context.get(BindingContext.ANNOTATION, entry)?.fqName == StandardNames.FqNames.suppress } } } private fun KtPsiFactory.createWhiteSpace(kind: AnnotationHostKind): PsiElement { return if (kind.newLineNeeded) createNewLine() else createWhiteSpace() } private class CaretBox<out E : KtExpression>( val expression: E, private val editor: Editor? ) { private val offsetInExpression: Int = (editor?.caretModel?.offset ?: 0) - expression.textRange!!.startOffset fun positionCaretInCopy(copy: PsiElement) { if (editor == null) return editor.caretModel.moveToOffset(copy.textOffset + offsetInExpression) } }
apache-2.0
29c68756308f44738ef057c169a4cb5b
42.988095
147
0.701083
5.568953
false
false
false
false
Masterzach32/SwagBot
src/main/kotlin/SwagBot.kt
1
5135
@file:JvmName("SwagBot") package xyz.swagbot import discord4j.core.* import discord4j.core.`object`.presence.* import discord4j.core.event.* import discord4j.core.event.domain.message.* import discord4j.core.shard.* import discord4j.gateway.intent.* import discord4j.rest.response.* import io.facet.common.* import io.facet.common.dsl.* import io.facet.core.* import io.facet.core.features.* import kotlinx.coroutines.* import org.slf4j.* import xyz.swagbot.commands.* import xyz.swagbot.extensions.* import xyz.swagbot.features.* import xyz.swagbot.features.autoroles.* import xyz.swagbot.features.bgw.* import xyz.swagbot.features.games.* import xyz.swagbot.features.guilds.* import xyz.swagbot.features.music.* import xyz.swagbot.features.permissions.* import xyz.swagbot.features.system.* import xyz.swagbot.util.* val logger: Logger = LoggerFactory.getLogger(EnvVars.BOT_NAME) fun main() { logger.info("Starting SwagBot (v${EnvVars.CODE_VERSION})") val client = DiscordClient.builder(EnvVars.BOT_TOKEN) .onClientResponse(ResponseFunction.emptyIfNotFound()) .build() client.gateway() .setEnabledIntents(IntentSet.all()) .setSharding(ShardingStrategy.recommended()) .setInitialPresence { ClientPresence.online(ClientActivity.listening("~help")) } .withPlugins(EventDispatcher::configure) .withPlugins(GatewayDiscordClient::configure) .block() } @OptIn(ObsoleteCoroutinesApi::class) suspend fun EventDispatcher.configure(scope: CoroutineScope) { install(scope, PostgresDatabase) { databaseName = EnvVars.POSTGRES_DB databaseUsername = EnvVars.POSTGRES_USER databasePassword = EnvVars.POSTGRES_PASSWORD } install(scope, GuildStorage) install(scope, ChatCommands) { useDefaultHelpCommand = true commandPrefix { guildId -> feature(GuildStorage).commandPrefixFor(guildId) } registerCommands( BringCommand, CatCommand, ChangePrefixCommand, Clear, Crewlink, DogCommand, InfoCommand, JoinCommand, LeaveCommand, LeaverClear, LmgtfyCommand, NowPlayingCommand, PauseResumeCommand, Premium, Queue, SkipCommand, ) } install(scope, Permissions) { developers = setOf(97341976214511616, 212311415455744000, 98200921950920704) } install(scope, Music) install(scope, BotPresence) install(scope, AutoAssignRole) install(scope, ChatGames) install(scope, Market) install(scope, BestGroupWorldStuff) install(scope, AmongUs) } @OptIn(ObsoleteCoroutinesApi::class) suspend fun GatewayDiscordClient.configure(scope: CoroutineScope) { listener<MessageCreateEvent>(scope) { event -> if (event.message.userMentionIds.contains(selfId)) { val prefix = commandPrefixFor(null) event.message.reply(baseTemplate.and { description = "Hi **${event.message.author.get().username}**! My command prefix is `$prefix`. To " + "learn more about me, type `${prefix}info`, and to see my commands, type `${prefix}help`." }) } } install(scope, ApplicationCommands) { registerCommand( ChangePermissionCommand, DisconnectRouletteCommand, MigrateCommand, Ping, Play, Prune, YouTubeSearch, VolumeCommand, VoteSkipCommand ) } scope.launch { // logger.info( // restClient.applicationService.getGlobalApplicationCommands(selfId.asLong()).await().toString() // ) // logger.info( // restClient.applicationService.getGuildApplicationCommands(selfId.asLong(), 97342233241464832).await().toString() // ) } //ApplicationCommandRequ{name=search, description=Search YouTube and select a video to play using reaction buttons., options=[ApplicationCommandOptionData{type=3, name=query, description=The search term to look up on YouTube., required=Possible{true}, choices=null, options=null}, ApplicationCommandOptionData{type=4, name=count, description=The number of results to show., required=Possible{false}, choices=[ApplicationCommandOptionChoiceData{name=Five results, value=5}, ApplicationCommandOptionChoiceData{name=Ten results, value=10}], options=null}], defaultPermission=Possible{true}} //ApplicationCommandData{name=search, description=Search YouTube and select a video to play using reaction buttons., options=[ApplicationCommandOptionData{type=3, name=query, description=The search term to look up on YouTube., required=Possible{true}, choices=null, options=null}, ApplicationCommandOptionData{type=4, name=count, description=The number of results to show., required=Possible.absent, choices=[ApplicationCommandOptionChoiceData{name=Five results, value=5}, ApplicationCommandOptionChoiceData{name=Ten results, value=10}], options=null}], defaultPermission=Possible{true}} }
gpl-2.0
cab91e463664d53a79512b7a1fc19f7e
35.678571
591
0.694255
4.362787
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/personal_deadlines/interactor/DeadlinesInteractor.kt
2
2406
package org.stepik.android.domain.personal_deadlines.interactor import io.reactivex.Completable import io.reactivex.Maybe import io.reactivex.Single import ru.nobird.android.domain.rx.doCompletableOnSuccess import org.stepic.droid.web.storage.model.StorageRecord import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper import org.stepik.android.domain.personal_deadlines.model.LearningRate import org.stepik.android.domain.personal_deadlines.repository.DeadlinesBannerRepository import org.stepik.android.domain.personal_deadlines.repository.DeadlinesRepository import org.stepik.android.domain.personal_deadlines.resolver.DeadlinesResolver import org.stepik.android.view.personal_deadlines.notification.DeadlinesNotificationDelegate import javax.inject.Inject class DeadlinesInteractor @Inject constructor( private val deadlinesRepository: DeadlinesRepository, private val deadlinesBannerRepository: DeadlinesBannerRepository, private val deadlinesResolver: DeadlinesResolver, private val deadlinesNotificationDelegate: DeadlinesNotificationDelegate ) { fun createPersonalDeadlines(courseId: Long, learningRate: LearningRate): Single<StorageRecord<DeadlinesWrapper>> = deadlinesResolver .calculateDeadlinesForCourse(courseId, learningRate) .flatMap(deadlinesRepository::createDeadlineRecord) .doOnSuccess { deadlinesNotificationDelegate.scheduleDeadlinesNotifications() } fun updatePersonalDeadlines(record: StorageRecord<DeadlinesWrapper>): Single<StorageRecord<DeadlinesWrapper>> = deadlinesRepository .updateDeadlineRecord(record) .doOnSuccess { deadlinesNotificationDelegate.scheduleDeadlinesNotifications() } fun removePersonalDeadline(recordId: Long): Completable = deadlinesRepository .removeDeadlineRecord(recordId) .doOnComplete { deadlinesNotificationDelegate.scheduleDeadlinesNotifications() } fun getPersonalDeadlineByCourseId(courseId: Long): Maybe<StorageRecord<DeadlinesWrapper>> = deadlinesRepository .getDeadlineRecordByCourseId(courseId) fun shouldShowDeadlinesBannerForCourse(courseId: Long): Single<Boolean> = deadlinesBannerRepository .hasCourseId(courseId) .doCompletableOnSuccess { deadlinesBannerRepository.addCourseId(courseId) } }
apache-2.0
9cd484c0ab728f72994e1fb92efa97a1
47.14
118
0.792186
5.569444
false
false
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/entity/ping/ClyNextOfficeHours.kt
1
5356
package io.customerly.entity.ping import android.content.Context import io.customerly.R import io.customerly.utils.ggkext.STimestamp import io.customerly.utils.ggkext.getTyped import io.customerly.utils.ggkext.nullOnException import io.customerly.utils.ggkext.optTyped import org.json.JSONObject import java.util.* /** * Created by Gianni on 07/07/18. * Project: Customerly-KAndroid-SDK */ internal fun JSONObject.parseNextOfficeHours(): ClyNextOfficeHours? { return nullOnException { ClyNextOfficeHours( period = it.getTyped(name = "period"), startUtc = it.optTyped(name = "start_utc", fallback = 0), endUtc = it.optTyped(name = "end_utc", fallback = 0)) } } internal data class ClyNextOfficeHours( val period: String, @STimestamp private val startUtc: Int, @STimestamp private val endUtc: Int) { @Suppress("unused") companion object { private const val PERIOD_EVERYDAY = "everyday" private const val PERIOD_WEEKENDS = "weekends" private const val PERIOD_WEEKDAYS = "weekdays" private const val PERIOD_MONDAY = "monday" private const val PERIOD_TUESDAY = "tuesday" private const val PERIOD_WEDNESDAY = "wednesday" private const val PERIOD_THURSDAY = "thursday" private const val PERIOD_FRIDAY = "friday" private const val PERIOD_SATURDAY = "saturday" private const val PERIOD_SUNDAY = "sunday" private const val PERIOD_A_SINGLE_DAY = "a_day" } /** * returns null if the office is open, returns this otherwise */ internal fun isOfficeOpen(): Boolean = this.startUtc < (System.currentTimeMillis() / 1000) internal fun getBotMessage(context: Context): String? { if(this.isOfficeOpen()) { return null } val startLocalTz = Calendar.getInstance().also { it.timeInMillis = this.startUtc * 1000L } val endLocalTz = Calendar.getInstance().also { it.timeInMillis = this.endUtc * 1000L } val localDay = startLocalTz.get(Calendar.DAY_OF_WEEK) val periodLocalized = when(this.period) { PERIOD_WEEKENDS -> { when(localDay) { Calendar.SATURDAY,Calendar.SUNDAY -> PERIOD_WEEKENDS else -> PERIOD_A_SINGLE_DAY } } PERIOD_WEEKDAYS -> { when(localDay) { Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY -> PERIOD_WEEKDAYS else -> PERIOD_A_SINGLE_DAY } } else -> PERIOD_A_SINGLE_DAY } val startTimeString: String = String.format(Locale.ITALIAN, "%d:%02d", startLocalTz.get(Calendar.HOUR_OF_DAY), startLocalTz.get(Calendar.MINUTE)) val endTimeString: String = String.format(Locale.ITALIAN, "%d:%02d", endLocalTz.get(Calendar.HOUR_OF_DAY), endLocalTz.get(Calendar.MINUTE)) return when(periodLocalized) { PERIOD_WEEKENDS -> { context.getString(R.string.io_customerly__outofoffice_weekends_fromx_toy, startTimeString, endTimeString) } PERIOD_WEEKDAYS -> { context.getString(R.string.io_customerly__outofoffice_weekdays_fromx_toy, startTimeString, endTimeString) } else -> { val todayLocalTz = Calendar.getInstance() if(startLocalTz.get(Calendar.YEAR) == todayLocalTz.get(Calendar.YEAR) && startLocalTz.get(Calendar.MONTH) == todayLocalTz.get(Calendar.MONTH) && startLocalTz.get(Calendar.DAY_OF_MONTH) == todayLocalTz.get(Calendar.DAY_OF_MONTH)) { //Next opening = Today context.getString(R.string.io_customerly__outofoffice_today_atx, startTimeString) } else { val tomorrowLocalTz = todayLocalTz.apply { this.add(Calendar.DAY_OF_MONTH, 1) } if(startLocalTz.get(Calendar.YEAR) == tomorrowLocalTz.get(Calendar.YEAR) && startLocalTz.get(Calendar.MONTH) == tomorrowLocalTz.get(Calendar.MONTH) && startLocalTz.get(Calendar.DAY_OF_MONTH) == tomorrowLocalTz.get(Calendar.DAY_OF_MONTH)) { //Next opening = Tomorrow context.getString(R.string.io_customerly__outofoffice_tomorrow_atx, startTimeString) } else { context.getString(when(localDay) { Calendar.MONDAY -> R.string.io_customerly__outofoffice_monday_atx Calendar.TUESDAY -> R.string.io_customerly__outofoffice_tuesday_atx Calendar.WEDNESDAY -> R.string.io_customerly__outofoffice_wednesday_atx Calendar.THURSDAY -> R.string.io_customerly__outofoffice_thursday_atx Calendar.FRIDAY -> R.string.io_customerly__outofoffice_friday_atx Calendar.SATURDAY -> R.string.io_customerly__outofoffice_saturday_atx Calendar.SUNDAY -> R.string.io_customerly__outofoffice_sunday_atx else -> R.string.io_customerly__outofoffice_tomorrow_atx }, startTimeString) } } } } } }
apache-2.0
a5599c00b0ec9c94f1e4247ceb68c3c6
46.40708
259
0.610904
4.538983
false
false
false
false
spacecowboy/Feeder
app/src/androidTest/java/com/nononsenseapps/feeder/db/room/MigrationFrom13To14.kt
1
1833
package com.nononsenseapps.feeder.db.room import androidx.room.testing.MigrationTestHelper import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class MigrationFrom13To14 { private val dbName = "testDb" @Rule @JvmField val testHelper: MigrationTestHelper = MigrationTestHelper( InstrumentationRegistry.getInstrumentation(), AppDatabase::class.java.canonicalName, FrameworkSQLiteOpenHelperFactory() ) @Test fun migrate13to14() { var db = testHelper.createDatabase(dbName, 13) db.use { db.execSQL( """ INSERT INTO feeds(id, title, url, custom_title, tag, notify, last_sync, response_hash, fulltext_by_default) VALUES(1, 'feed', 'http://url', '', '', 0, 0, 666, 0) """.trimIndent() ) db.execSQL( """ INSERT INTO feed_items(id, guid, title, plain_title, plain_snippet, unread, notified, feed_id, first_synced_time, primary_sort_time) VALUES(8, 'http://item', 'title', 'ptitle', 'psnippet', 1, 0, 1, 0, 0) """.trimIndent() ) } db = testHelper.runMigrationsAndValidate(dbName, 14, true, MIGRATION_13_14) db.query( """ SELECT open_articles_with FROM feeds """.trimIndent() )!!.use { assert(it.count == 1) assert(it.moveToFirst()) assertEquals(0L, it.getLong(0)) } } }
gpl-3.0
fa139f6ea0d6900737786ee7b5f19565
30.603448
144
0.619203
4.302817
false
true
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/injection/step_quiz/StepQuizPresentationModule.kt
1
3993
package org.stepik.android.view.injection.step_quiz import androidx.lifecycle.ViewModel import dagger.Module import dagger.Provides import dagger.multibindings.IntoMap import org.stepik.android.presentation.base.injection.ViewModelKey import org.stepik.android.presentation.step_quiz.StepQuizFeature import org.stepik.android.presentation.step_quiz.StepQuizViewModel import org.stepik.android.presentation.step_quiz.dispatcher.StepQuizActionDispatcher import org.stepik.android.presentation.step_quiz.reducer.StepQuizReducer import org.stepik.android.presentation.step_quiz_review.StepQuizReviewFeature import org.stepik.android.presentation.step_quiz_review.StepQuizReviewTeacherFeature import org.stepik.android.presentation.step_quiz_review.StepQuizReviewTeacherViewModel import org.stepik.android.presentation.step_quiz_review.StepQuizReviewViewModel import org.stepik.android.presentation.step_quiz_review.dispatcher.StepQuizReviewActionDispatcher import org.stepik.android.presentation.step_quiz_review.dispatcher.StepQuizReviewTeacherActionDispatcher import org.stepik.android.presentation.step_quiz_review.reducer.StepQuizReviewReducer import org.stepik.android.presentation.step_quiz_review.reducer.StepQuizReviewTeacherReducer import ru.nobird.app.core.model.safeCast import ru.nobird.app.presentation.redux.container.wrapWithViewContainer import ru.nobird.app.presentation.redux.dispatcher.transform import ru.nobird.app.presentation.redux.dispatcher.wrapWithActionDispatcher import ru.nobird.app.presentation.redux.feature.ReduxFeature @Module object StepQuizPresentationModule { /** * Presentation */ @Provides @IntoMap @ViewModelKey(StepQuizViewModel::class) internal fun provideStepQuizPresenter( stepQuizReducer: StepQuizReducer, stepQuizActionDispatcher: StepQuizActionDispatcher ): ViewModel = StepQuizViewModel( ReduxFeature(StepQuizFeature.State.Idle, stepQuizReducer) .wrapWithActionDispatcher(stepQuizActionDispatcher) .wrapWithViewContainer() ) @Provides @IntoMap @ViewModelKey(StepQuizReviewViewModel::class) internal fun provideStepQuizReviewPresenter( stepQuizReviewReducer: StepQuizReviewReducer, stepQuizReviewActionDispatcher: StepQuizReviewActionDispatcher, stepQuizActionDispatcher: StepQuizActionDispatcher ): ViewModel = StepQuizReviewViewModel( ReduxFeature(StepQuizReviewFeature.State.Idle, stepQuizReviewReducer) .wrapWithActionDispatcher(stepQuizReviewActionDispatcher) .wrapWithActionDispatcher( stepQuizActionDispatcher.transform( transformAction = { it.safeCast<StepQuizReviewFeature.Action.StepQuizAction>()?.action }, transformMessage = StepQuizReviewFeature.Message::StepQuizMessage ) ) .wrapWithViewContainer() ) @Provides @IntoMap @ViewModelKey(StepQuizReviewTeacherViewModel::class) internal fun provideStepQuizReviewTeacherViewModel( stepQuizReviewTeacherReducer: StepQuizReviewTeacherReducer, stepQuizReviewTeacherActionDispatcher: StepQuizReviewTeacherActionDispatcher, stepQuizActionDispatcher: StepQuizActionDispatcher ): ViewModel = StepQuizReviewTeacherViewModel( ReduxFeature(StepQuizReviewTeacherFeature.State.Idle, stepQuizReviewTeacherReducer) .wrapWithActionDispatcher(stepQuizReviewTeacherActionDispatcher) .wrapWithActionDispatcher( stepQuizActionDispatcher.transform( transformAction = { it.safeCast<StepQuizReviewTeacherFeature.Action.StepQuizAction>()?.action }, transformMessage = StepQuizReviewTeacherFeature.Message::StepQuizMessage ) ) .wrapWithViewContainer() ) }
apache-2.0
d08653187d3602895ececf47fd02fc1f
47.120482
120
0.756073
5.915556
false
false
false
false
android/wear-os-samples
AlwaysOnKotlin/compose/src/main/java/com/example/android/wearable/wear/alwayson/AlwaysOnApp.kt
1
8592
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wearable.wear.alwayson import android.app.AlarmManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.core.content.getSystemService import androidx.lifecycle.Lifecycle import androidx.lifecycle.repeatOnLifecycle import androidx.wear.compose.material.MaterialTheme import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import java.time.Clock import java.time.Duration import java.time.Instant import java.time.LocalTime /** * Duration between updates while in active mode. */ val ACTIVE_INTERVAL: Duration = Duration.ofSeconds(1) /** * Duration between updates while in ambient mode. */ val AMBIENT_INTERVAL: Duration = Duration.ofSeconds(10) const val AMBIENT_UPDATE_ACTION = "com.example.android.wearable.wear.alwayson.action.AMBIENT_UPDATE" /** * Create a PendingIntent which we'll give to the AlarmManager to send ambient mode updates * on an interval which we've define. */ private val ambientUpdateIntent = Intent(AMBIENT_UPDATE_ACTION) @Composable fun AlwaysOnApp( ambientState: AmbientState, ambientUpdateTimestamp: Instant, clock: Clock, activeDispatcher: CoroutineDispatcher ) { val ambientUpdateAlarmManager = rememberAlarmManager() val context = LocalContext.current /** * Retrieves a PendingIntent that will perform a broadcast. You could also use getActivity() * to retrieve a PendingIntent that will start a new activity, but be aware that actually * triggers onNewIntent() which causes lifecycle changes (onPause() and onResume()) which * might trigger code to be re-executed more often than you want. * * If you do end up using getActivity(), also make sure you have set activity launchMode to * singleInstance in the manifest. * * Otherwise, it is easy for the AlarmManager launch Intent to open a new activity * every time the Alarm is triggered rather than reusing this Activity. */ val ambientUpdatePendingIntent = remember(context) { PendingIntent.getBroadcast( context, 0, ambientUpdateIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) } /** * A ping used to set up a loopback side-effect loop, to continuously update the time. */ var updateDataTrigger by remember { mutableStateOf(0L) } /** * The current instant to display */ var currentInstant by remember { mutableStateOf(Instant.now(clock)) } /** * The current time to display */ var currentTime by remember { mutableStateOf(LocalTime.now(clock)) } /** * The number of times the current time and instant have been updated */ var drawCount by remember { mutableStateOf(0) } fun updateData() { updateDataTrigger++ currentInstant = Instant.now(clock) currentTime = LocalTime.now(clock) drawCount++ } val lifecycleOwner = LocalLifecycleOwner.current /** * Construct a boolean indicating if we are resumed. */ val isResumed by produceState(initialValue = false) { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) { value = true try { awaitCancellation() } finally { value = false } } } if (isResumed) { when (ambientState) { is AmbientState.Ambient -> { // When we are resumed and ambient, setup the broadcast receiver SystemBroadcastReceiver(systemAction = AMBIENT_UPDATE_ACTION) { updateData() } DisposableEffect(ambientUpdateAlarmManager, ambientUpdatePendingIntent) { onDispose { // Upon leaving resumption or ambient, cancel any ongoing pending intents ambientUpdateAlarmManager.cancel(ambientUpdatePendingIntent) } } } AmbientState.Interactive -> Unit } // Whenever we change ambient state (and initially) update the data. LaunchedEffect(ambientState) { updateData() } // Then, setup a ping to refresh data again: either via the alarm manager, or simply // after a delay LaunchedEffect(updateDataTrigger, ambientState) { when (ambientState) { is AmbientState.Ambient -> { val triggerTime = currentInstant.getNextInstantWithInterval( AMBIENT_INTERVAL ) ambientUpdateAlarmManager.setExact( AlarmManager.RTC_WAKEUP, triggerTime.toEpochMilli(), ambientUpdatePendingIntent ) } AmbientState.Interactive -> { val delay = currentInstant.getDelayToNextInstantWithInterval( ACTIVE_INTERVAL ) withContext(activeDispatcher) { // Delay on the active dispatcher for testability delay(delay.toMillis()) } updateData() } } } } MaterialTheme { AlwaysOnScreen( ambientState = ambientState, ambientUpdateTimestamp = ambientUpdateTimestamp, drawCount = drawCount, currentInstant = currentInstant, currentTime = currentTime ) } } /** * Returns the delay from this [Instant] to the next one that is aligned with the given [interval]. */ private fun Instant.getDelayToNextInstantWithInterval(interval: Duration): Duration = Duration.ofMillis(interval.toMillis() - toEpochMilli() % interval.toMillis()) /** * Returns the next [Instant] that is aligned with the given [interval]. */ private fun Instant.getNextInstantWithInterval(interval: Duration): Instant = plus(getDelayToNextInstantWithInterval(interval)) @Composable fun rememberAlarmManager(): AlarmManager { val context = LocalContext.current return remember(context) { context.getSystemService()!! } } @Composable fun SystemBroadcastReceiver( systemAction: String, onSystemEvent: (intent: Intent?) -> Unit ) { // Grab the current context in this part of the UI tree val context = LocalContext.current // Safely use the latest onSystemEvent lambda passed to the function val currentOnSystemEvent by rememberUpdatedState(onSystemEvent) // If either context or systemAction changes, unregister and register again DisposableEffect(context, systemAction) { val intentFilter = IntentFilter(systemAction) val broadcast = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { currentOnSystemEvent(intent) } } context.registerReceiver(broadcast, intentFilter) // When the effect leaves the Composition, remove the callback onDispose { context.unregisterReceiver(broadcast) } } }
apache-2.0
06d891386816719c881e4f35e2319363
33.506024
100
0.667831
5.31026
false
false
false
false
Kotlin/kotlinx.coroutines
benchmarks/src/jmh/kotlin/benchmarks/flow/FlatMapMergeBenchmark.kt
1
1215
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package benchmarks.flow import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import org.openjdk.jmh.annotations.* import java.util.concurrent.* @Warmup(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) @Fork(value = 1) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) @State(Scope.Benchmark) open class FlatMapMergeBenchmark { // Note: tests only absence of contention on downstream @Param("10", "100", "1000") private var iterations = 100 @Benchmark fun flatMapUnsafe() = runBlocking { benchmarks.flow.scrabble.flow { repeat(iterations) { emit(it) } }.flatMapMerge { value -> flowOf(value) }.collect { if (it == -1) error("") } } @Benchmark fun flatMapSafe() = runBlocking { kotlinx.coroutines.flow.flow { repeat(iterations) { emit(it) } }.flatMapMerge { value -> flowOf(value) }.collect { if (it == -1) error("") } } }
apache-2.0
9b83e28849da6aec97526fa0ad52d8e6
24.851064
102
0.621399
4.009901
false
false
false
false
udevbe/westford
compositor/src/main/kotlin/org/westford/nativ/glibc/termios.kt
3
1558
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.nativ.glibc import org.freedesktop.jaccall.CType import org.freedesktop.jaccall.Field import org.freedesktop.jaccall.Struct @Struct(Field(name = "c_iflag", type = CType.UNSIGNED_INT), Field(name = "c_oflag", type = CType.UNSIGNED_INT), Field(name = "c_cflag", type = CType.UNSIGNED_INT), Field(name = "c_lflag", type = CType.UNSIGNED_INT), Field(name = "c_line", type = CType.UNSIGNED_CHAR), Field(name = "c_cc", type = CType.UNSIGNED_CHAR, cardinality = Libc.NCCS), Field(name = "c_ispeed", type = CType.UNSIGNED_INT), Field(name = "c_ospeed", type = CType.UNSIGNED_INT)) class termios : Struct_termios()
agpl-3.0
137f6a082974e4ad5a4ea35691324bfa
37.95
75
0.648267
3.964377
false
false
false
false
zdary/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/network/status/WebServiceStatusManager.kt
12
1565
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.stats.completion.network.status import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.registry.Registry object WebServiceStatusManager { private const val USE_ANALYTICS_PLATFORM_REGISTRY = "completion.stats.analytics.platform.send" private const val ANALYTICS_PLATFORM_URL_REGISTRY = "completion.stats.analytics.platform.url" private val LOG = logger<WebServiceStatusManager>() private val statuses: MutableMap<String, WebServiceStatus> = mutableMapOf() init { if (Registry.`is`(USE_ANALYTICS_PLATFORM_REGISTRY, false)) { registerAnalyticsPlatformStatus() } } fun getAllStatuses(): List<WebServiceStatus> = statuses.values.toList() private fun registerAnalyticsPlatformStatus() { try { val registry = Registry.get(ANALYTICS_PLATFORM_URL_REGISTRY) if (registry.isChangedFromDefault) { register(AnalyticsPlatformServiceStatus(registry.asString())) return } } catch (e: Throwable) { LOG.error("No url for Analytics Platform web status. Set registry: $ANALYTICS_PLATFORM_URL_REGISTRY") } register(AnalyticsPlatformServiceStatus.withDefaultUrl()) } private fun register(status: WebServiceStatus) { val old = statuses[status.id] if (old != null) { LOG.warn("Service status with id [${old.id}] already created.") return } statuses[status.id] = status } }
apache-2.0
04650679324ff0e064f9081de024d13b
34.590909
140
0.729073
4.371508
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/LogExtensions.kt
1
4966
@file:Suppress("unused") package com.jetbrains.packagesearch.intellij.plugin.util import com.intellij.openapi.diagnostic.Logger import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment internal val logger = Logger.getInstance("#${PluginEnvironment.PLUGIN_ID}") internal fun logError(contextName: String? = null, messageProvider: () -> String) { logError(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } internal fun logError(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logError(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } internal fun logError(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logError(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } internal fun logError(message: String, throwable: Throwable? = null) { logger.error(message, throwable) } internal fun logWarn(contextName: String? = null, messageProvider: () -> String) { logWarn(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } internal fun logWarn(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logWarn(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } internal fun logWarn(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logWarn(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } internal fun logWarn(message: String, throwable: Throwable? = null) { logger.warn(message, throwable) } internal fun logInfo(contextName: String? = null, messageProvider: () -> String) { logInfo(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } internal fun logInfo(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logInfo(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } internal fun logInfo(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logInfo(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } internal fun logInfo(message: String, throwable: Throwable? = null) { logger.info(message, throwable) } internal fun logDebug(contextName: String? = null, messageProvider: () -> String) { logDebug(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } internal fun logDebug(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logDebug(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } internal fun logDebug(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logDebug(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } internal fun logDebug(message: String, throwable: Throwable? = null) { if (!FeatureFlags.useDebugLogging) return if (!logger.isDebugEnabled) warnNotLoggable() logger.debug(message, throwable) } internal fun logTrace(contextName: String? = null, messageProvider: () -> String) { logTrace(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } internal fun logTrace(traceInfo: TraceInfo? = null, contextName: String? = null, messageProvider: () -> String) { logTrace(buildMessageFrom(traceInfo, contextName, messageProvider)) } internal fun logTrace(message: String) { if (!FeatureFlags.useDebugLogging) return if (!logger.isTraceEnabled) warnNotLoggable() logger.trace(message) } internal fun logTrace(throwable: Throwable) { if (!FeatureFlags.useDebugLogging) return if (!logger.isTraceEnabled) warnNotLoggable() logger.trace(throwable) } private fun warnNotLoggable() { logger.warn( """ |!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |Debug logging not enabled. Make sure you have a line like this: | #${PluginEnvironment.PLUGIN_ID}:trace |in your debug log settings (Help | Diagnostic Tools | Debug Log Settings) |then restart the IDE. |!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |""".trimMargin() ) } private fun buildMessageFrom( traceInfo: TraceInfo?, contextName: String?, messageProvider: () -> String ) = buildString { if (traceInfo != null) { append(traceInfo) append(' ') } if (!contextName.isNullOrBlank()) { append(contextName) append(' ') } if (count() > 0) append("— ") append(messageProvider()) }
apache-2.0
892a7c9d5102e32d1ba98f23f0c165a9
37.48062
143
0.699436
4.661033
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/compatibility/RFPowerProxy.kt
1
1282
package net.ndrei.teslacorelib.compatibility import cofh.redstoneflux.api.IEnergyReceiver import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraftforge.fml.common.Optional /** * Created by CF on 2017-07-10. */ object RFPowerProxy { const val MODID = "redstoneflux" var isRFAvailable: Boolean = false @Optional.Method(modid = RFPowerProxy.MODID) fun isRFAcceptor(te: TileEntity, facing: EnumFacing) = (te is IEnergyReceiver) && te.canConnectEnergy(facing) @Optional.Method(modid = RFPowerProxy.MODID) fun givePowerTo(te: TileEntity, facing: EnumFacing, power: Long, simulate: Boolean = false): Long { val receiver = (te as? IEnergyReceiver) ?: return 0 return if (receiver.canConnectEnergy(facing)) receiver.receiveEnergy(facing, power.toInt(), simulate).toLong() else 0 } fun getEnergyStored(te: TileEntity, facing: EnumFacing): Int { val receiver = (te as? IEnergyReceiver) ?: return 0 return receiver.getEnergyStored(facing) } fun getMaxEnergyStored(te: TileEntity, facing: EnumFacing): Int { val receiver = (te as? IEnergyReceiver) ?: return 0 return receiver.getMaxEnergyStored(facing) } }
mit
e8e5fb11efc9ca967d3c93c4418d412d
33.648649
103
0.697348
4.108974
false
false
false
false
AndroidX/androidx
glance/glance-appwidget/integration-tests/demos/src/main/java/androidx/glance/appwidget/demos/ExactAppWidget.kt
3
2632
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.demos import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.glance.GlanceModifier import androidx.glance.LocalContext import androidx.glance.LocalSize import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.SizeMode import androidx.glance.appwidget.background import androidx.glance.appwidget.cornerRadius import androidx.glance.color.ColorProvider import androidx.glance.layout.Column import androidx.glance.layout.fillMaxSize import androidx.glance.layout.padding import androidx.glance.text.FontWeight import androidx.glance.text.Text import androidx.glance.text.TextDecoration import androidx.glance.text.TextStyle import java.text.DecimalFormat class ExactAppWidget : GlanceAppWidget() { override val sizeMode: SizeMode = SizeMode.Exact @Composable override fun Content() { val context = LocalContext.current Column( modifier = GlanceModifier .fillMaxSize() .background(day = Color.LightGray, night = Color.DarkGray) .padding(R.dimen.external_padding) .cornerRadius(R.dimen.corner_radius) ) { Text( context.getString(R.string.exact_widget_title), style = TextStyle( color = ColorProvider(day = Color.DarkGray, night = Color.LightGray), fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline ), ) val size = LocalSize.current val dec = DecimalFormat("#.##") val width = dec.format(size.width.value) val height = dec.format(size.height.value) Text("Current layout: ${width}dp x ${height}dp") } } } class ExactAppWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget = ExactAppWidget() }
apache-2.0
76ebb003f0c8cdc8fbc3409e71eb5fa4
36.070423
89
0.701368
4.7
false
false
false
false
smmribeiro/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/ui/proofreading/component/list/GrazieLanguagesPopupStep.kt
12
1173
// 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.grazie.ide.ui.proofreading.component.list import com.intellij.grazie.jlanguage.Lang import com.intellij.openapi.ui.popup.ListSeparator import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe class GrazieLanguagesPopupStep(@NlsContexts.PopupTitle title: String, available: List<Lang>, toDownload: List<Lang>, private val download: (Lang) -> Boolean, private val onResult: (Lang) -> Unit) : BaseListPopupStep<Lang>(title, available + toDownload) { private val firstOther = toDownload.firstOrNull() override fun getSeparatorAbove(value: Lang) = if (value == firstOther) ListSeparator() else null @NlsSafe override fun getTextFor(value: Lang) = value.nativeName override fun onChosen(selectedValue: Lang, finalChoice: Boolean): PopupStep<*>? { return doFinalStep { if (download(selectedValue)) onResult(selectedValue) } } }
apache-2.0
f989feaf2c320a2af9fb4910052986fb
47.875
140
0.763853
4.265455
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinStringTemplateUPolyadicExpression.kt
2
1442
// 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.uast.kotlin import com.intellij.psi.PsiLanguageInjectionHost import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.uast.* import org.jetbrains.uast.expressions.UInjectionHost class KotlinStringTemplateUPolyadicExpression( override val sourcePsi: KtStringTemplateExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UPolyadicExpression, KotlinUElementWithType, KotlinEvaluatableUElement, UInjectionHost { override val operands: List<UExpression> by lz { sourcePsi.entries.map { KotlinConverter.convertEntry( it, this, DEFAULT_EXPRESSION_TYPES_LIST )!! }.takeIf { it.isNotEmpty() } ?: listOf(KotlinStringULiteralExpression(sourcePsi, this, "")) } override val operator = UastBinaryOperator.PLUS override val psiLanguageInjectionHost: PsiLanguageInjectionHost get() = sourcePsi override val isString: Boolean get() = true override fun asRenderString(): String = if (operands.isEmpty()) "\"\"" else super<UPolyadicExpression>.asRenderString() override fun asLogString(): String = if (operands.isEmpty()) "UPolyadicExpression (value = \"\")" else super.asLogString() }
apache-2.0
a55cd1e9f1c1b990e2beb24f4786befd
41.411765
158
0.728155
5.301471
false
false
false
false
smmribeiro/intellij-community
java/idea-ui/src/com/intellij/ide/starters/remote/wizard/WebStarterInitialStep.kt
1
24916
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.starters.remote.wizard import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.ide.starters.JavaStartersBundle import com.intellij.ide.starters.local.StarterModuleBuilder import com.intellij.ide.starters.remote.* import com.intellij.ide.starters.shared.* import com.intellij.ide.starters.shared.ValidationFunctions.* import com.intellij.ide.util.PropertiesComponent import com.intellij.ide.util.projectWizard.ModuleNameGenerator import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.wizard.AbstractWizard import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.observable.properties.map import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel import com.intellij.openapi.roots.ui.configuration.sdkComboBox import com.intellij.openapi.roots.ui.configuration.validateJavaVersion import com.intellij.openapi.roots.ui.configuration.validateSdk import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.InputValidator import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.IconButton import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.Ref import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.InplaceButton import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.UIBundle import com.intellij.ui.components.ActionLink import com.intellij.ui.dsl.builder.EMPTY_LABEL import com.intellij.ui.dsl.builder.SegmentedButton import com.intellij.ui.layout.* import com.intellij.util.concurrency.Semaphore import com.intellij.util.ui.AsyncProcessIcon import com.intellij.util.ui.UIUtil import java.awt.event.ActionListener import java.io.File import java.io.IOException import java.net.MalformedURLException import java.net.URL import java.util.concurrent.Future import javax.swing.DefaultComboBoxModel import javax.swing.JComponent import javax.swing.JTextField import javax.swing.SwingUtilities open class WebStarterInitialStep(contextProvider: WebStarterContextProvider) : ModuleWizardStep() { protected val moduleBuilder: WebStarterModuleBuilder = contextProvider.moduleBuilder protected val wizardContext: WizardContext = contextProvider.wizardContext protected val starterContext: WebStarterContext = contextProvider.starterContext protected val starterSettings: StarterWizardSettings = contextProvider.settings protected val parentDisposable: Disposable = contextProvider.parentDisposable private val validatedTextComponents: MutableList<JTextField> = mutableListOf() protected val propertyGraph: PropertyGraph = PropertyGraph() private val entityNameProperty: GraphProperty<String> = propertyGraph.graphProperty(::suggestName) private val locationProperty: GraphProperty<String> = propertyGraph.graphProperty(::suggestLocationByName) private val groupIdProperty: GraphProperty<String> = propertyGraph.graphProperty { starterContext.group } private val artifactIdProperty: GraphProperty<String> = propertyGraph.graphProperty { entityName } private val packageNameProperty: GraphProperty<String> = propertyGraph.graphProperty { starterContext.packageName } private val sdkProperty: GraphProperty<Sdk?> = propertyGraph.graphProperty { null } private val projectTypeProperty: GraphProperty<StarterProjectType?> = propertyGraph.graphProperty { starterContext.projectType } private val languageProperty: GraphProperty<StarterLanguage> = propertyGraph.graphProperty { starterContext.language } private val packagingProperty: GraphProperty<StarterAppPackaging?> = propertyGraph.graphProperty { starterContext.packaging } private val testFrameworkProperty: GraphProperty<StarterTestRunner?> = propertyGraph.graphProperty { starterContext.testFramework } private val languageLevelProperty: GraphProperty<StarterLanguageLevel?> = propertyGraph.graphProperty { starterContext.languageLevel } private val applicationTypeProperty: GraphProperty<StarterAppType?> = propertyGraph.graphProperty { starterContext.applicationType } private val exampleCodeProperty: GraphProperty<Boolean> = propertyGraph.graphProperty { starterContext.includeExamples } private val gitProperty: GraphProperty<Boolean> = propertyGraph.graphProperty { false } private var entityName: String by entityNameProperty.map { it.trim() } private var location: String by locationProperty private var groupId: String by groupIdProperty.map { it.trim() } private var artifactId: String by artifactIdProperty.map { it.trim() } private var languageLevel: StarterLanguageLevel? by languageLevelProperty private var packageName: String by packageNameProperty.map { it.trim() } private val contentPanel: DialogPanel by lazy { createComponent() } private val progressIcon: AsyncProcessIcon by lazy { AsyncProcessIcon(moduleBuilder.builderId + "ServerOptions") } private val serverUrlLink: ActionLink by lazy { createServerUrlLink() } private val retryButton: InplaceButton by lazy { createRetryButton() } private val sdkModel: ProjectSdksModel = ProjectSdksModel() private val languageLevelsModel: DefaultComboBoxModel<StarterLanguageLevel> = DefaultComboBoxModel<StarterLanguageLevel>() private val applicationTypesModel: DefaultComboBoxModel<StarterAppType> = DefaultComboBoxModel<StarterAppType>() private lateinit var projectTypesSelector: SegmentedButton<StarterProjectType?> private lateinit var packagingTypesSelector: SegmentedButton<StarterAppPackaging?> private lateinit var languagesSelector: SegmentedButton<StarterLanguage> private var languages: List<StarterLanguage> = starterSettings.languages private var applicationTypes: List<StarterAppType> = starterSettings.applicationTypes private var projectTypes: List<StarterProjectType> = starterSettings.projectTypes private var packagingTypes: List<StarterAppPackaging> = starterSettings.packagingTypes @Volatile private var serverOptions: WebStarterServerOptions? = null @Volatile private var currentRequest: Future<*>? = null @Volatile private var isDisposed: Boolean = false private val serverOptionsLoadingSemaphore: Semaphore = Semaphore() private val serverSettingsButton: InplaceButton = InplaceButton( IconButton(JavaStartersBundle.message("button.tooltip.configure"), AllIcons.General.Gear, AllIcons.General.GearHover), ActionListener { configureServer() } ) init { Disposer.register(parentDisposable, Disposable { isDisposed = true sdkModel.disposeUIResources() currentRequest?.cancel(true) }) } override fun getComponent(): JComponent = contentPanel override fun getHelpId(): String? = moduleBuilder.getHelpId() override fun updateDataModel() { starterContext.serverOptions = this.serverOptions!! starterContext.projectType = projectTypeProperty.get() starterContext.language = languageProperty.get() starterContext.group = groupId starterContext.artifact = artifactId starterContext.name = entityName starterContext.packageName = packageName starterContext.packaging = packagingProperty.get() starterContext.languageLevel = languageLevel starterContext.testFramework = testFrameworkProperty.get() starterContext.applicationType = applicationTypeProperty.get() starterContext.includeExamples = exampleCodeProperty.get() starterContext.gitIntegration = gitProperty.get() wizardContext.projectName = entityName wizardContext.setProjectFileDirectory(FileUtil.join(location, entityName)) val sdk = sdkProperty.get() if (wizardContext.project == null) { wizardContext.projectJdk = sdk } else { moduleBuilder.moduleJdk = sdk } } private fun suggestName(): String { return suggestName(starterContext.artifact) } private fun suggestName(prefix: String): String { val projectFileDirectory = File(wizardContext.projectFileDirectory) return FileUtil.createSequentFileName(projectFileDirectory, prefix, "") } private fun suggestLocationByName(): String { return wizardContext.projectFileDirectory } private fun suggestPackageName(): String { return StarterModuleBuilder.suggestPackageName(groupId, artifactId) } private fun createComponent(): DialogPanel { entityNameProperty.dependsOn(artifactIdProperty) { artifactId } artifactIdProperty.dependsOn(entityNameProperty) { entityName } packageNameProperty.dependsOn(artifactIdProperty, ::suggestPackageName) packageNameProperty.dependsOn(groupIdProperty, ::suggestPackageName) progressIcon.toolTipText = JavaStartersBundle.message("message.state.connecting.and.retrieving.options") return panel { row { cell(isFullWidth = true) { label(JavaStartersBundle.message("title.project.server.url.label")) component(serverUrlLink) component(serverSettingsButton) component(retryButton) component(progressIcon) } }.largeGapAfter() row(JavaStartersBundle.message("title.project.name.label")) { textField(entityNameProperty) .growPolicy(GrowPolicy.SHORT_TEXT) .withSpecialValidation(listOf(CHECK_NOT_EMPTY, CHECK_SIMPLE_NAME_FORMAT), createLocationWarningValidator(locationProperty)) .focused() for (nameGenerator in ModuleNameGenerator.EP_NAME.extensionList) { val nameGeneratorUi = nameGenerator.getUi(moduleBuilder.builderId) { entityNameProperty.set(it) } if (nameGeneratorUi != null) { component(nameGeneratorUi).constraints(pushX) } } }.largeGapAfter() addProjectLocationUi() addFieldsBefore(this) if (starterSettings.languages.size > 1) { row(JavaStartersBundle.message("title.project.language.label")) { languagesSelector = segmentedButton(starterSettings.languages, languageProperty) { it.title } }.largeGapAfter() } if (starterSettings.projectTypes.isNotEmpty()) { val messages = starterSettings.customizedMessages row(messages?.projectTypeLabel ?: JavaStartersBundle.message("title.project.type.label")) { projectTypesSelector = segmentedButton(starterSettings.projectTypes, projectTypeProperty) { it?.title ?: "" } }.largeGapAfter() } if (starterSettings.testFrameworks.isNotEmpty()) { row(JavaStartersBundle.message("title.project.test.framework.label")) { segmentedButton(starterSettings.testFrameworks, testFrameworkProperty) { it?.title ?: "" } }.largeGapAfter() } row(JavaStartersBundle.message("title.project.group.label")) { textField(groupIdProperty) .growPolicy(GrowPolicy.SHORT_TEXT) .withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_GROUP_FORMAT, CHECK_NO_RESERVED_WORDS) }.largeGapAfter() row(JavaStartersBundle.message("title.project.artifact.label")) { textField(artifactIdProperty) .growPolicy(GrowPolicy.SHORT_TEXT) .withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_ARTIFACT_SIMPLE_FORMAT, CHECK_NO_RESERVED_WORDS) }.largeGapAfter() if (starterSettings.isPackageNameEditable) { row(JavaStartersBundle.message("title.project.package.label")) { textField(packageNameProperty) .growPolicy(GrowPolicy.SHORT_TEXT) .withSpecialValidation(CHECK_NOT_EMPTY, CHECK_NO_WHITESPACES, CHECK_NO_RESERVED_WORDS, CHECK_PACKAGE_NAME) }.largeGapAfter() } if (starterSettings.applicationTypes.isNotEmpty()) { row(JavaStartersBundle.message("title.project.app.type.label")) { applicationTypesModel.addAll(starterSettings.applicationTypes) comboBox(applicationTypesModel, applicationTypeProperty, SimpleListCellRenderer.create("") { it?.title ?: "" }) .growPolicy(GrowPolicy.SHORT_TEXT) }.largeGapAfter() } row(JavaStartersBundle.message("title.project.sdk.label")) { sdkComboBox(sdkModel, sdkProperty, wizardContext.project, moduleBuilder) .growPolicy(GrowPolicy.SHORT_TEXT) }.largeGapAfter() if (starterSettings.languageLevels.isNotEmpty()) { row(JavaStartersBundle.message("title.project.java.version.label")) { languageLevelsModel.addAll(starterSettings.languageLevels) comboBox(languageLevelsModel, languageLevelProperty, SimpleListCellRenderer.create("") { it?.title ?: "" }) }.largeGapAfter() } if (starterSettings.packagingTypes.isNotEmpty()) { row(JavaStartersBundle.message("title.project.packaging.label")) { packagingTypesSelector = segmentedButton(starterSettings.packagingTypes, packagingProperty) { it?.title ?: "" } }.largeGapAfter() } if (starterSettings.isExampleCodeProvided) { row { checkBox(JavaStartersBundle.message("title.project.examples.label"), exampleCodeProperty) } } addFieldsAfter(this) }.withVisualPadding() } private fun createServerUrlLink(): ActionLink { val result = ActionLink(urlPreview(starterContext.serverUrl)) { BrowserUtil.browse(starterContext.serverUrl) } UIUtil.applyStyle(UIUtil.ComponentStyle.REGULAR, result) return result } private fun createRetryButton(): InplaceButton { return InplaceButton(IconButton(JavaStartersBundle.message("button.tooltip.retry"), AllIcons.Nodes.ErrorIntroduction, AllIcons.Actions.ForceRefresh), ActionListener { requestServerOptions() }).apply { isVisible = false } } @NlsSafe private fun urlPreview(serverUrl: String): String { val url = serverUrl .removePrefix("https://") .removeSuffix("/") if (url.length > 35) { return url.take(30) + "..." } return url } override fun getPreferredFocusedComponent(): JComponent? { return contentPanel.preferredFocusedComponent } override fun validate(): Boolean { if (!validateFormFields(component, contentPanel, validatedTextComponents)) { return false } if (!validateSdk(sdkProperty, sdkModel)) { return false } val passTechnologyName = if (starterSettings.languageLevels.size > 1) null else moduleBuilder.presentableName if (!validateJavaVersion(sdkProperty, languageLevel?.javaVersion, passTechnologyName)) { return false } return checkServerOptionsLoaded() } private fun checkServerOptionsLoaded(): Boolean { val request = currentRequest if (serverOptions != null && request == null) { return true } if (request == null) { // failure? retry server options loading requestServerOptions() } val newOptionsRef: Ref<WebStarterServerOptions> = Ref.create() ProgressManager.getInstance().runProcessWithProgressSynchronously(Runnable { val progressIndicator = ProgressManager.getInstance().progressIndicator progressIndicator.isIndeterminate = true for (i in 0 until 30) { progressIndicator.checkCanceled() if (serverOptionsLoadingSemaphore.waitFor(500)) { serverOptions?.let { newOptionsRef.set(it) } return@Runnable } } }, JavaStartersBundle.message("message.state.connecting.and.retrieving.options"), true, wizardContext.project) if (!newOptionsRef.isNull) { updatePropertiesWithServerOptions(newOptionsRef.get()) } return serverOptions != null } private fun LayoutBuilder.addProjectLocationUi() { val locationRow = row(JavaStartersBundle.message("title.project.location.label")) { projectLocationField(locationProperty, wizardContext) .withSpecialValidation(CHECK_NOT_EMPTY, CHECK_LOCATION_FOR_ERROR) } if (wizardContext.isCreatingNewProject) { // Git should not be enabled for single module row(EMPTY_LABEL) { checkBox(UIBundle.message("label.project.wizard.new.project.git.checkbox"), gitProperty) }.largeGapAfter() } else { locationRow.largeGapAfter() } } protected open fun addFieldsBefore(layout: LayoutBuilder) {} protected open fun addFieldsAfter(layout: LayoutBuilder) {} override fun _init() { super._init() if (serverOptions == null && currentRequest == null) { @Suppress("HardCodedStringLiteral") val serverUrlFromSettings = PropertiesComponent.getInstance().getValue(getServerUrlPropertyName()) if (serverUrlFromSettings != null) { setServerUrl(serverUrlFromSettings) } // required on dialog opening to get correct modality state SwingUtilities.invokeLater(this::requestServerOptions) } } private fun setServerUrl(@NlsSafe url: String) { starterContext.serverUrl = url serverUrlLink.text = urlPreview(url) serverUrlLink.toolTipText = url } private fun requestServerOptions() { progressIcon.isVisible = true retryButton.isVisible = false progressIcon.resume() serverOptionsLoadingSemaphore.down() currentRequest = ApplicationManager.getApplication().executeOnPooledThread { val readyServerOptions = try { moduleBuilder.getServerOptions(starterContext.serverUrl) } catch (e: Exception) { if (e is IOException || e is IllegalStateException) { logger<WebStarterInitialStep>().info("Unable to get server options for " + moduleBuilder.builderId, e) } else { logger<WebStarterInitialStep>().error("Unable to get server options for " + moduleBuilder.builderId, e) } ApplicationManager.getApplication().invokeLater( { if (component.isShowing) { // only if the wizard is visible Messages.showErrorDialog( JavaStartersBundle.message("message.no.connection.with.error.content", starterContext.serverUrl, e.message), JavaStartersBundle.message("message.title.error")) } }, getModalityState()) null } setServerOptions(readyServerOptions) } } private fun setServerOptions(serverOptions: WebStarterServerOptions?) { this.serverOptions = serverOptions this.currentRequest = null this.serverOptionsLoadingSemaphore.up() ApplicationManager.getApplication().invokeLater(Runnable { progressIcon.suspend() progressIcon.isVisible = false retryButton.isVisible = serverOptions == null if (serverOptions != null) { updatePropertiesWithServerOptions(serverOptions) } }, getModalityState(), getDisposed()) } private fun getModalityState(): ModalityState { return ModalityState.stateForComponent(wizardContext.getUserData(AbstractWizard.KEY)!!.contentComponent) } private fun getDisposed(): Condition<Any> = Condition<Any> { isDisposed } private fun configureServer() { val currentServerUrl = starterContext.serverUrl val serverUrlTitle = starterSettings.customizedMessages?.serverUrlDialogTitle ?: JavaStartersBundle.message("title.server.url.dialog") val newUrl = Messages.showInputDialog(component, null, serverUrlTitle, null, currentServerUrl, object : InputValidator { override fun canClose(inputString: String?): Boolean = checkInput(inputString) override fun checkInput(inputString: String?): Boolean { try { URL(inputString) } catch (e: MalformedURLException) { return false } return true } }) // update if (newUrl != null && starterContext.serverUrl != newUrl) { setServerUrl(newUrl) PropertiesComponent.getInstance().setValue(getServerUrlPropertyName(), newUrl) requestServerOptions() } } private fun getServerUrlPropertyName(): String { return moduleBuilder.builderId + ".service.url.last" } protected open fun updatePropertiesWithServerOptions(serverOptions: WebStarterServerOptions) { starterContext.frameworkVersion = serverOptions.frameworkVersions.find { it.isDefault } ?: serverOptions.frameworkVersions.firstOrNull() val currentPackageName = packageName // remember package name before applying group and artifact serverOptions.extractOption(SERVER_NAME_KEY) { if (entityName == suggestName(DEFAULT_MODULE_NAME)) { val newName = suggestName(it) if (entityName != newName) { entityNameProperty.set(newName) } } } serverOptions.extractOption(SERVER_GROUP_KEY) { if (groupId == DEFAULT_MODULE_GROUP && groupId != it) { groupIdProperty.set(it) } } serverOptions.extractOption(SERVER_ARTIFACT_KEY) { if (artifactId == DEFAULT_MODULE_ARTIFACT && artifactId != it) { artifactIdProperty.set(it) } } serverOptions.extractOption(SERVER_PACKAGE_NAME_KEY) { if (currentPackageName == DEFAULT_PACKAGE_NAME && currentPackageName != it) { packageNameProperty.set(it) } } serverOptions.extractOption(SERVER_VERSION_KEY) { starterContext.version = it } serverOptions.extractOption(SERVER_LANGUAGE_LEVELS_KEY) { levels -> val selectedItem = languageLevelsModel.selectedItem languageLevelsModel.removeAllElements() languageLevelsModel.addAll(levels) if (levels.contains(selectedItem)) { languageLevelsModel.selectedItem = selectedItem } else { languageLevel = levels.firstOrNull() languageLevelsModel.selectedItem = languageLevel } } serverOptions.extractOption(SERVER_LANGUAGE_LEVEL_KEY) { level -> if (languageLevel == starterSettings.defaultLanguageLevel && languageLevel != level) { languageLevelProperty.set(level) } } serverOptions.extractOption(SERVER_PROJECT_TYPES) { types -> if (types.isNotEmpty() && types != this.projectTypes && ::projectTypesSelector.isInitialized) { val correspondingOption = types.find { it.id == projectTypeProperty.get()?.id } projectTypeProperty.set(correspondingOption ?: types.first()) projectTypesSelector.items(types) this.projectTypes = types } } serverOptions.extractOption(SERVER_APPLICATION_TYPES) { types -> if (types.isNotEmpty() && types != applicationTypes) { applicationTypesModel.removeAllElements() applicationTypesModel.addAll(types) applicationTypesModel.selectedItem = types.firstOrNull() this.applicationTypes = types } } serverOptions.extractOption(SERVER_PACKAGING_TYPES) { types -> if (types.isNotEmpty() && types != this.packagingTypes && ::packagingTypesSelector.isInitialized) { val correspondingOption = types.find { it.id == packagingProperty.get()?.id } packagingProperty.set(correspondingOption ?: types.first()) packagingTypesSelector.items(types) this.packagingTypes = types } } serverOptions.extractOption(SERVER_LANGUAGES) { languages -> if (languages.isNotEmpty() && languages != this.languages && ::languagesSelector.isInitialized) { val correspondingOption = languages.find { it.id == languageProperty.get().id } languageProperty.set(correspondingOption ?: languages.first()) languagesSelector.items(languages) this.languages = languages } } contentPanel.revalidate() } @Suppress("SameParameterValue") private fun <T : JComponent> CellBuilder<T>.withSpecialValidation(vararg errorValidations: TextValidationFunction): CellBuilder<T> { return this.withSpecialValidation(errorValidations.asList(), null) } private fun <T : JComponent> CellBuilder<T>.withSpecialValidation(errorValidations: List<TextValidationFunction>, warningValidation: TextValidationFunction?): CellBuilder<T> { return withValidation(this, errorValidations, warningValidation, validatedTextComponents, parentDisposable) } }
apache-2.0
31d745d120764893d8c8a2e1e9b213fd
39.845902
140
0.733264
5.311447
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/AbstractCallChainChecker.kt
2
4849
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall abstract class AbstractCallChainChecker : AbstractKotlinInspection() { protected fun findQualifiedConversion( expression: KtQualifiedExpression, conversionGroups: Map<ConversionId, List<Conversion>>, additionalCallCheck: (Conversion, ResolvedCall<*>, ResolvedCall<*>, BindingContext) -> Boolean ): Conversion? { val firstExpression = expression.receiverExpression val firstCallExpression = getCallExpression(firstExpression) ?: return null val firstCalleeExpression = firstCallExpression.calleeExpression ?: return null val secondCallExpression = expression.selectorExpression as? KtCallExpression ?: return null val secondCalleeExpression = secondCallExpression.calleeExpression ?: return null val apiVersion by lazy { expression.languageVersionSettings.apiVersion } val actualConversions = conversionGroups[ConversionId(firstCalleeExpression, secondCalleeExpression)]?.filter { it.replaceableApiVersion == null || apiVersion >= it.replaceableApiVersion }?.sortedByDescending { it.removeNotNullAssertion } ?: return null val context = expression.analyze() val firstResolvedCall = firstExpression.getResolvedCall(context) ?: return null val secondResolvedCall = expression.getResolvedCall(context) ?: return null val conversion = actualConversions.firstOrNull { firstResolvedCall.isCalling(FqName(it.firstFqName)) && additionalCallCheck(it, firstResolvedCall, secondResolvedCall, context) } ?: return null // Do not apply for lambdas with return inside val lambdaArgument = firstCallExpression.lambdaArguments.firstOrNull() if (lambdaArgument?.anyDescendantOfType<KtReturnExpression>() == true) return null if (!secondResolvedCall.isCalling(FqName(conversion.secondFqName))) return null if (secondResolvedCall.valueArguments.any { (parameter, resolvedArgument) -> parameter.type.isFunctionOfAnyKind() && resolvedArgument !is DefaultValueArgument } ) return null return conversion } protected fun List<Conversion>.group(): Map<ConversionId, List<Conversion>> = groupBy { conversion -> conversion.id } data class ConversionId(val firstFqName: String, val secondFqName: String) { constructor(first: KtExpression, second: KtExpression) : this(first.text, second.text) } data class Conversion( @NonNls val firstFqName: String, @NonNls val secondFqName: String, @NonNls val replacement: String, @NonNls val additionalArgument: String? = null, val addNotNullAssertion: Boolean = false, val enableSuspendFunctionCall: Boolean = true, val removeNotNullAssertion: Boolean = false, val replaceableApiVersion: ApiVersion? = null, ) { private fun String.convertToShort() = takeLastWhile { it != '.' } val id: ConversionId get() = ConversionId(firstName, secondName) val firstName = firstFqName.convertToShort() val secondName = secondFqName.convertToShort() fun withArgument(argument: String) = Conversion(firstFqName, secondFqName, replacement, argument) } companion object { fun KtQualifiedExpression.firstCalleeExpression(): KtExpression? { val firstExpression = receiverExpression val firstCallExpression = getCallExpression(firstExpression) ?: return null return firstCallExpression.calleeExpression } fun getCallExpression(firstExpression: KtExpression) = (firstExpression as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: firstExpression as? KtCallExpression } }
apache-2.0
c645c260a531ac9ee76699c3197b517f
47.5
158
0.738915
5.516496
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/viewholders/discoverydrawer/ChildFilterViewHolder.kt
1
2527
package com.kickstarter.ui.viewholders.discoverydrawer import androidx.core.content.res.ResourcesCompat import com.kickstarter.R import com.kickstarter.databinding.DiscoveryDrawerChildFilterViewBinding import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.ui.adapters.data.NavigationDrawerData import com.kickstarter.ui.viewholders.KSViewHolder import timber.log.Timber class ChildFilterViewHolder( private val binding: DiscoveryDrawerChildFilterViewBinding, private val delegate: Delegate ) : KSViewHolder(binding.root) { private val ksString = requireNotNull(environment().ksString()) private var item: NavigationDrawerData.Section.Row? = null interface Delegate { fun childFilterViewHolderRowClick(viewHolder: ChildFilterViewHolder, row: NavigationDrawerData.Section.Row) } @Throws(Exception::class) override fun bindData(data: Any?) { item = ObjectUtils.requireNonNull(data as NavigationDrawerData.Section.Row?, NavigationDrawerData.Section.Row::class.java) } override fun onBind() { val context = context() val category = item?.params()?.category() if (category?.isRoot == true) { binding.filterTextView.text = item?.params()?.filterString(context, ksString) } else { binding.filterTextView.text = item?.params()?.filterString(context, ksString) } val textColor = if (item?.selected() == true) context.resources.getColor(R.color.accent, null) else context.resources.getColor(R.color.kds_support_700, null) val iconDrawable = if (item?.selected() == true) ResourcesCompat.getDrawable(context.resources, R.drawable.ic_label_green, null) else ResourcesCompat.getDrawable(context.resources, R.drawable.ic_label, null) val backgroundDrawable = if (item?.selected() == true) ResourcesCompat.getDrawable(context.resources, R.drawable.drawer_selected, null) else null binding.filterTextView.apply { setCompoundDrawablesRelativeWithIntrinsicBounds(iconDrawable, null, null, null) setTextColor(textColor) background = backgroundDrawable setOnClickListener { textViewClick() } } } fun textViewClick() { Timber.d("DiscoveryDrawerChildParamsViewHolder topFilterViewHolderRowClick") item?.let { delegate.childFilterViewHolderRowClick(this, it) } } }
apache-2.0
1d0f7ec46dfdfe97721918af8b0df14e
37.287879
130
0.696082
4.859615
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/customization/AvatarOverviewFragment.kt
1
6785
package com.habitrpg.android.habitica.ui.fragments.inventory.customization import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.databinding.FragmentAvatarOverviewBinding import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import io.reactivex.functions.Consumer class AvatarOverviewFragment : BaseMainFragment(), AdapterView.OnItemSelectedListener { private lateinit var binding: FragmentAvatarOverviewBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) binding = FragmentAvatarOverviewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.avatarSizeSpinner.onItemSelectedListener = this binding.avatarShirtView.setOnClickListener { displayCustomizationFragment("shirt", null) } binding.avatarSkinView.setOnClickListener { displayCustomizationFragment("skin", null) } binding.avatarChairView.setOnClickListener { displayCustomizationFragment("chair", null) } binding.avatarGlassesView.setOnClickListener { displayEquipmentFragment("eyewear", "glasses") } binding.avatarAnimalEarsView.setOnClickListener { displayEquipmentFragment("headAccessory", "animal") } binding.avatarAnimalTailView.setOnClickListener { displayEquipmentFragment("back", "animal") } binding.avatarHeadbandView.setOnClickListener { displayEquipmentFragment("headAccessory", "headband") } binding.avatarHairColorView.setOnClickListener { displayCustomizationFragment("hair", "color") } binding.avatarHairBangsView.setOnClickListener { displayCustomizationFragment("hair", "bangs") } binding.avatarHairBaseView.setOnClickListener { displayCustomizationFragment("hair", "base") } binding.avatarAccentView.setOnClickListener { displayCustomizationFragment("hair", "flower") } binding.avatarHairBeardView.setOnClickListener { displayCustomizationFragment("hair", "beard") } binding.avatarHairMustacheView.setOnClickListener { displayCustomizationFragment("hair", "mustache") } binding.avatarBackgroundView.setOnClickListener { displayCustomizationFragment("background", null) } compositeSubscription.add(userRepository.getUser().subscribeWithErrorHandler(Consumer { updateUser(it) })) } override fun injectFragment(component: UserComponent) { component.inject(this) } private fun displayCustomizationFragment(type: String, category: String?) { MainNavigationController.navigate(AvatarOverviewFragmentDirections.openAvatarDetail(type, category ?: "")) } private fun displayEquipmentFragment(type: String, category: String?) { MainNavigationController.navigate(AvatarOverviewFragmentDirections.openAvatarEquipment(type, category ?: "")) } fun updateUser(user: User) { this.setSize(user.preferences?.size) setCustomizations(user) } private fun setCustomizations(user: User) { binding.avatarShirtView.customizationIdentifier = user.preferences?.size + "_shirt_" + user.preferences?.shirt binding.avatarSkinView.customizationIdentifier = "skin_" + user.preferences?.skin val chair = user.preferences?.chair binding.avatarChairView.customizationIdentifier = if (chair?.startsWith("handleless") == true) "chair_$chair" else chair binding.avatarGlassesView.equipmentIdentifier = user.equipped?.eyeWear binding.avatarAnimalEarsView.equipmentIdentifier = user.equipped?.headAccessory binding.avatarHeadbandView.equipmentIdentifier = user.equipped?.headAccessory binding.avatarAnimalTailView.equipmentIdentifier = user.equipped?.back binding.avatarHairColorView.customizationIdentifier = if (user.preferences?.hair?.color != null && user.preferences?.hair?.color != "") "hair_bangs_1_" + user.preferences?.hair?.color else "" binding.avatarHairBangsView.customizationIdentifier = if (user.preferences?.hair?.bangs != null && user.preferences?.hair?.bangs != 0) "hair_bangs_" + user.preferences?.hair?.bangs + "_" + user.preferences?.hair?.color else "" binding.avatarHairBaseView.customizationIdentifier = if (user.preferences?.hair?.base != null && user.preferences?.hair?.base != 0) "hair_base_" + user.preferences?.hair?.base + "_" + user.preferences?.hair?.color else "" binding.avatarAccentView.customizationIdentifier = if (user.preferences?.hair?.flower != null && user.preferences?.hair?.flower != 0) "hair_flower_" + user.preferences?.hair?.flower else "" binding.avatarHairBeardView.customizationIdentifier = if (user.preferences?.hair?.beard != null && user.preferences?.hair?.beard != 0) "hair_beard_" + user.preferences?.hair?.beard + "_" + user.preferences?.hair?.color else "" binding.avatarHairMustacheView.customizationIdentifier = if (user.preferences?.hair?.mustache != null && user.preferences?.hair?.mustache != 0) "hair_mustache_" + user.preferences?.hair?.mustache + "_" + user.preferences?.hair?.color else "" binding.avatarBackgroundView.customizationIdentifier = "background_" + user.preferences?.background } private fun setSize(size: String?) { if (size == null) { return } if (size == "slim") { binding.avatarSizeSpinner.setSelection(0, false) } else { binding.avatarSizeSpinner.setSelection(1, false) } } override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { val newSize: String = if (position == 0) "slim" else "broad" if (this.user?.isValid == true && this.user?.preferences?.size != newSize) { compositeSubscription.add(userRepository.updateUser(user, "preferences.size", newSize) .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) } } override fun onNothingSelected(parent: AdapterView<*>) { /* no-on */ } }
gpl-3.0
b3bb79261fed2e50804dd8da85aa3732
59.681818
249
0.722771
5.140152
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/libs/ActivityRequestCodes.kt
1
385
package com.kickstarter.libs object ActivityRequestCodes { const val LOGIN_FLOW = 5921 const val RESET_FLOW = 5922 const val CHECKOUT_ACTIVITY_WALLET_REQUEST = 59210 const val CHECKOUT_ACTIVITY_WALLET_CHANGE_REQUEST = 59211 const val CHECKOUT_ACTIVITY_WALLET_OBTAINED_FULL = 59212 const val SAVE_NEW_PAYMENT_METHOD = 59213 const val SHOW_REWARDS = 59214 }
apache-2.0
ca40c1096496fb2891cd2ab76d977708
34
61
0.745455
3.85
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterDialog.kt
1
13563
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter import com.intellij.openapi.command.impl.FinishMarkAction import com.intellij.openapi.command.impl.StartMarkAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.refactoring.ui.NameSuggestionsField import com.intellij.refactoring.ui.RefactoringDialog import com.intellij.ui.NonFocusableCheckBox import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.core.util.isMultiLine import org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction.ui.ExtractFunctionParameterTablePanel import org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction.ui.KotlinExtractFunctionDialog import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.* import org.jetbrains.kotlin.idea.refactoring.validateElement import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.types.KotlinType import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets import java.util.* import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class KotlinIntroduceParameterDialog private constructor( project: Project, val editor: Editor, val descriptor: IntroduceParameterDescriptor, val lambdaExtractionDescriptor: ExtractableCodeDescriptor?, nameSuggestions: Array<String>, typeSuggestions: List<KotlinType>, val helper: KotlinIntroduceParameterHelper ) : RefactoringDialog(project, true) { constructor( project: Project, editor: Editor, descriptor: IntroduceParameterDescriptor, nameSuggestions: Array<String>, typeSuggestions: List<KotlinType>, helper: KotlinIntroduceParameterHelper ) : this(project, editor, descriptor, null, nameSuggestions, typeSuggestions, helper) constructor( project: Project, editor: Editor, introduceParameterDescriptor: IntroduceParameterDescriptor, lambdaExtractionDescriptor: ExtractableCodeDescriptor, helper: KotlinIntroduceParameterHelper ) : this( project, editor, introduceParameterDescriptor, lambdaExtractionDescriptor, lambdaExtractionDescriptor.suggestedNames.toTypedArray(), listOf(lambdaExtractionDescriptor.returnType), helper ) private val typeNameSuggestions = typeSuggestions.map { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it) }.toTypedArray() private val nameField = NameSuggestionsField(nameSuggestions, project, KotlinFileType.INSTANCE) private val typeField = NameSuggestionsField(typeNameSuggestions, project, KotlinFileType.INSTANCE) private var replaceAllCheckBox: JCheckBox? = null private var defaultValueCheckBox: JCheckBox? = null private val removeParamsCheckBoxes = LinkedHashMap<JCheckBox, KtElement>(descriptor.parametersToRemove.size) private var parameterTablePanel: ExtractFunctionParameterTablePanel? = null private val commandName = if (lambdaExtractionDescriptor != null) INTRODUCE_LAMBDA_PARAMETER else INTRODUCE_PARAMETER init { title = commandName init() nameField.addDataChangedListener { validateButtons() } typeField.addDataChangedListener { validateButtons() } } override fun getPreferredFocusedComponent() = nameField.focusableComponent private fun updateRemoveParamCheckBoxes() { val enableParamRemove = (replaceAllCheckBox?.isSelected ?: true) && (!defaultValueCheckBox!!.isSelected) removeParamsCheckBoxes.keys.forEach { it.isEnabled = enableParamRemove it.isSelected = enableParamRemove } } override fun createNorthPanel(): JComponent? { val gbConstraints = GridBagConstraints() val panel = JPanel(GridBagLayout()) gbConstraints.anchor = GridBagConstraints.WEST gbConstraints.fill = GridBagConstraints.NONE gbConstraints.gridx = 0 gbConstraints.insets = Insets(4, 4, 4, 0) gbConstraints.gridwidth = 1 gbConstraints.weightx = 0.0 gbConstraints.weighty = 0.0 gbConstraints.gridy = 0 val nameLabel = JLabel(KotlinBundle.message("text.parameter.name")) nameLabel.labelFor = nameField panel.add(nameLabel, gbConstraints) gbConstraints.insets = Insets(4, 4, 4, 8) gbConstraints.gridx++ gbConstraints.weightx = 1.0 gbConstraints.fill = GridBagConstraints.BOTH panel.add(nameField, gbConstraints) gbConstraints.insets = Insets(4, 4, 4, 8) gbConstraints.gridwidth = 1 gbConstraints.weightx = 0.0 gbConstraints.gridx = 0 gbConstraints.gridy++ gbConstraints.fill = GridBagConstraints.NONE val typeLabel = JLabel( if (lambdaExtractionDescriptor != null) KotlinBundle.message("text.lambda.return.type") else KotlinBundle.message("text.parameter.type") ) typeLabel.labelFor = typeField panel.add(typeLabel, gbConstraints) gbConstraints.gridx++ gbConstraints.insets = Insets(4, 4, 4, 8) gbConstraints.weightx = 1.0 gbConstraints.fill = GridBagConstraints.BOTH panel.add(typeField, gbConstraints) if (lambdaExtractionDescriptor != null && (lambdaExtractionDescriptor.parameters .isNotEmpty() || lambdaExtractionDescriptor.receiverParameter != null) ) { val parameterTablePanel = object : ExtractFunctionParameterTablePanel() { override fun onEnterAction() { doOKAction() } override fun onCancelAction() { doCancelAction() } } parameterTablePanel.init(lambdaExtractionDescriptor.receiverParameter, lambdaExtractionDescriptor.parameters) gbConstraints.insets = Insets(4, 4, 4, 8) gbConstraints.gridwidth = 1 gbConstraints.weightx = 0.0 gbConstraints.gridx = 0 gbConstraints.gridy++ gbConstraints.fill = GridBagConstraints.NONE val parametersLabel = JLabel(KotlinBundle.message("text.lambda.parameters")) parametersLabel.labelFor = parameterTablePanel panel.add(parametersLabel, gbConstraints) gbConstraints.gridx++ gbConstraints.insets = Insets(4, 4, 4, 8) gbConstraints.weightx = 1.0 gbConstraints.fill = GridBagConstraints.BOTH panel.add(parameterTablePanel, gbConstraints) this.parameterTablePanel = parameterTablePanel } gbConstraints.fill = GridBagConstraints.HORIZONTAL gbConstraints.gridx = 0 gbConstraints.insets = Insets(4, 0, 4, 8) gbConstraints.gridwidth = 2 gbConstraints.gridy++ val defaultValueCheckBox = NonFocusableCheckBox(KotlinBundle.message("text.introduce.default.value")) defaultValueCheckBox.isSelected = descriptor.withDefaultValue defaultValueCheckBox.addActionListener { updateRemoveParamCheckBoxes() } panel.add(defaultValueCheckBox, gbConstraints) this.defaultValueCheckBox = defaultValueCheckBox val occurrenceCount = descriptor.occurrencesToReplace.size if (occurrenceCount > 1) { gbConstraints.gridy++ val replaceAllCheckBox = NonFocusableCheckBox( KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount) ) replaceAllCheckBox.isSelected = true replaceAllCheckBox.addActionListener { updateRemoveParamCheckBoxes() } panel.add(replaceAllCheckBox, gbConstraints) this.replaceAllCheckBox = replaceAllCheckBox } if (replaceAllCheckBox != null) { gbConstraints.insets = Insets(0, 16, 4, 8) } for (parameter in descriptor.parametersToRemove) { val removeWhat = if (parameter is KtParameter) KotlinBundle.message("text.parameter.0", parameter.name.toString()) else KotlinBundle.message("text.receiver") val cb = NonFocusableCheckBox( KotlinBundle.message("text.remove.0.no.longer.used", removeWhat) ) removeParamsCheckBoxes[cb] = parameter cb.isSelected = true gbConstraints.gridy++ panel.add(cb, gbConstraints) } return panel } override fun createCenterPanel() = null override fun canRun() { val psiFactory = KtPsiFactory(myProject) psiFactory.createExpressionIfPossible(nameField.enteredName.quoteIfNeeded()).validateElement( KotlinBundle.message("error.text.invalid.parameter.name")) psiFactory.createTypeIfPossible(typeField.enteredName).validateElement( KotlinBundle.message("error.text.invalid.parameter.type")) } override fun doAction() { performRefactoring() } fun performRefactoring() { close(DialogWrapper.OK_EXIT_CODE) project.executeCommand(commandName) { fun createLambdaForArgument(function: KtFunction): KtExpression { val statement = function.bodyBlockExpression!!.statements.single() val space = if (statement.isMultiLine()) "\n" else " " val parameters = function.valueParameters val parametersText = if (parameters.isNotEmpty()) { " " + parameters.asSequence().map { it.name }.joinToString() + " ->" } else "" val text = "{$parametersText$space${statement.text}$space}" return KtPsiFactory(myProject).createExpression(text) } val chosenName = nameField.enteredName.quoteIfNeeded() var chosenType = typeField.enteredName var newArgumentValue = descriptor.newArgumentValue var newReplacer = descriptor.occurrenceReplacer val startMarkAction = StartMarkAction.start(editor, myProject, [email protected]) lambdaExtractionDescriptor?.let { oldDescriptor -> val newDescriptor = KotlinExtractFunctionDialog.createNewDescriptor( oldDescriptor, chosenName, null, parameterTablePanel?.selectedReceiverInfo, parameterTablePanel?.selectedParameterInfos ?: listOf(), null ) val options = ExtractionGeneratorOptions.DEFAULT.copy( target = ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION, allowExpressionBody = false ) runWriteAction { with(ExtractionGeneratorConfiguration(newDescriptor, options).generateDeclaration()) { val function = declaration as KtFunction val receiverType = function.receiverTypeReference?.text val parameterTypes = function .valueParameters.joinToString { it.typeReference!!.text } val returnType = function.typeReference?.text ?: "Unit" chosenType = (receiverType?.let { "$it." } ?: "") + "($parameterTypes) -> $returnType" if (KtTokens.SUSPEND_KEYWORD in newDescriptor.modifiers) { chosenType = "${KtTokens.SUSPEND_KEYWORD} $chosenType" } newArgumentValue = createLambdaForArgument(function) newReplacer = { } processDuplicates(duplicateReplacers, myProject, editor) } } } val descriptorToRefactor = descriptor.copy( newParameterName = chosenName, newParameterTypeText = chosenType, argumentValue = newArgumentValue, withDefaultValue = defaultValueCheckBox!!.isSelected, occurrencesToReplace = with(descriptor) { if (replaceAllCheckBox?.isSelected != false) { occurrencesToReplace } else { Collections.singletonList(originalOccurrence) } }, parametersToRemove = removeParamsCheckBoxes.filter { it.key.isEnabled && it.key.isSelected }.map { it.value }, occurrenceReplacer = newReplacer ) helper.configure(descriptorToRefactor).performRefactoring( editor, onExit = { FinishMarkAction.finish(myProject, editor, startMarkAction) } ) } } }
apache-2.0
67ef1d9194327ff9b4e8c528b82d2508
41.785489
158
0.658999
5.838571
false
false
false
false
Stealth2800/MCMarkupLanguage2
src/main/kotlin/com/stealthyone/mcml2/BukkitJsonSerializer.kt
1
3308
/** * Copyright 2017 Stealth2800 <http://stealthyone.com/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stealthyone.mcml2 import org.bukkit.Bukkit import org.bukkit.inventory.ItemStack import java.lang.Exception import java.lang.reflect.Method /** * Handles the conversion of a Bukkit ItemStack to JSON via reflection. */ object BukkitItemJsonSerializer : JsonSerializer(ItemStack::class.java) { private const val FAIL_MESSAGE = "(failed to convert item to JSON)" /** * Serializes an ItemStack to JSON via reflection. * * This method will not throw an exception on failure. Rather, it will return [FAIL_MESSAGE]. */ override fun serialize(obj: Any): String { val item = obj as ItemStack // NMS ItemStack val nmsItem = cb_CraftItemStack_asNMSCopy?.invoke(null, item) ?: return FAIL_MESSAGE // Empty NBTTagCompound val compound = nms_NBTTagCompound?.newInstance() ?: return FAIL_MESSAGE // Save ItemStack to compound and call toString to convert to JSON return nms_ItemStack_save?.invoke(nmsItem, compound)?.toString() ?: FAIL_MESSAGE } //region Reflection Utilities private fun getBukkitVersion(): String { return Bukkit.getServer().javaClass.canonicalName.split(".")[3] } private fun getNMSClassName(name: String): String { return "net.minecraft.server.${getBukkitVersion()}.$name" } private fun getNMSClass(name: String): Class<*> = Class.forName(getNMSClassName(name)) private fun getCBClassName(name: String): String { return "org.bukkit.craftbukkit.${getBukkitVersion()}.$name" } private fun getCBClass(name: String): Class<*> = Class.forName(getCBClassName(name)) //endregion //region Reflection Classes and Methods private val cb_CraftItemStack_asNMSCopy: Method? by lazy { try { getCBClass("inventory.CraftItemStack").getMethod("asNMSCopy", ItemStack::class.java) } catch (ex: Exception) { ex.printStackTrace() null } } private val nms_NBTTagCompound: Class<*>? by lazy { try { getNMSClass("NBTTagCompound") } catch (ex: Exception) { ex.printStackTrace() null } } private val nms_ItemStack: Class<*>? by lazy { try { getNMSClass("ItemStack") } catch (ex: Exception) { ex.printStackTrace() null } } private val nms_ItemStack_save: Method? by lazy { try { nms_ItemStack?.getMethod("save", nms_NBTTagCompound) } catch (ex: Exception) { ex.printStackTrace() null } } //endregion }
apache-2.0
632399a446de0ee4d8a14aabeafe9fc3
28.801802
97
0.641475
4.581717
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/runtime/workers/freeze2.kt
2
2255
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package runtime.workers.freeze2 import kotlin.test.* import kotlin.native.concurrent.* data class Data(var int: Int) @Test fun runTest() { // Ensure that we can not mutate frozen objects and arrays. val a0 = Data(2) a0.int++ a0.freeze() assertFailsWith<InvalidMutabilityException> {a0.int++ } val a1 = ByteArray(2) a1[1]++ a1.freeze() assertFailsWith<InvalidMutabilityException> { a1[1]++ } val a2 = ShortArray(2) a2[1]++ a2.freeze() assertFailsWith<InvalidMutabilityException> { a2[1]++ } val a3 = IntArray(2) a3[1]++ a3.freeze() assertFailsWith<InvalidMutabilityException> { a3[1]++ } val a4 = LongArray(2) a4[1]++ a4.freeze() assertFailsWith<InvalidMutabilityException> { a4[1]++ } val a5 = BooleanArray(2) a5[1] = true a5.freeze() assertFailsWith<InvalidMutabilityException> { a5[1] = false } val a6 = CharArray(2) a6[1] = 'a' a6.freeze() assertFailsWith<InvalidMutabilityException> { a6[1] = 'b' } val a7 = FloatArray(2) a7[1] = 1.0f a7.freeze() assertFailsWith<InvalidMutabilityException> { a7[1] = 2.0f } val a8 = DoubleArray(2) a8[1] = 1.0 a8.freeze() assertFailsWith<InvalidMutabilityException> { a8[1] = 2.0 } // Ensure that String and integral boxes are frozen by default, by passing local to the worker. val worker = Worker.start() var data: Any = "Hello" + " " + "world" assert(data.isFrozen) worker.execute(TransferMode.SAFE, { data } ) { input -> println("Worker 1: $input") }.result data = 42 assert(data.isFrozen) worker.execute(TransferMode.SAFE, { data } ) { input -> println("Worker2: $input") }.result data = 239.0 assert(data.isFrozen) worker.execute(TransferMode.SAFE, { data } ) { input -> println("Worker3: $input") }.result data = 'a' assert(data.isFrozen) worker.execute(TransferMode.SAFE, { data } ) { input -> println("Worker4: $input") }.result worker.requestTermination().result println("OK") }
apache-2.0
66c4c89af161f06def27a188ee7f3a08
24.066667
101
0.627494
3.528951
false
false
false
false
ebean-orm/avaje-ebeanorm-examples
e-kotlin-maven/src/test/java/org/example/domain/ExampleUsingPathProperties.kt
2
1779
package org.example.domain import org.example.service.LoadAgentAtRuntime public class ExampleUsingPathProperties : LoadAgentAtRuntime() { // public static void main(String[] args) { // //// new ExampleUsingPathProperties().runExample(); // new ExampleUsingPathProperties().runExampleUsingOrders(); // } // // public void runExample() { // // // // LoadExampleData.load(); // // List<Customer> list2 = Customer.find // .select("name") // .fetch("contacts") // .findList(); // // // PathProperties pathProperties = PathProperties.parse("(id,version,name,contacts(id,email,version))"); // // // Query<Customer> query = Customer.find.query(); // pathProperties.apply(query); // // List<Customer> list = query.findList(); // // JsonContext jsonContext = Customer.find.db().createJsonContext(); // // String jsonString = jsonContext.toJsonString(list, true); // System.out.println(jsonString); // // // for (Customer customer : list2) { // customer.getName(); // List<Contact> contacts = customer.getContacts(); // if (contacts != null) { // for (Contact contact : contacts) { // System.out.println("contact: "+contact.getFirstName()+" "+contact.getLastName()); // } // } // // } // } // // public void runExampleUsingOrders() { // // LoadExampleData.load(); // // PathProperties pathProperties = PathProperties.parse("(id,status,orderDate,customer(id,name),details(*,product(sku)))"); // // Query<Order> query = Ebean.createQuery(Order.class); // pathProperties.apply(query); // // List<Order> orders = query.where().gt("id", 1).findList(); // // String rawJson = Ebean.createJsonContext().toJsonString(orders, true); // System.out.println(rawJson); // } }
apache-2.0
e403fa38479fe3b67e511f8ae7eaa860
25.969697
126
0.639123
3.495088
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/platform/DesktopPlatformInput.desktop.kt
3
9135
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import androidx.compose.ui.geometry.Rect import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.CommitTextCommand import androidx.compose.ui.text.input.DeleteSurroundingTextInCodePointsCommand import androidx.compose.ui.text.input.EditCommand import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeOptions import androidx.compose.ui.text.input.PlatformTextInputService import androidx.compose.ui.text.input.SetComposingTextCommand import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.substring import androidx.compose.ui.unit.Density import java.awt.Point import java.awt.Rectangle import java.awt.event.InputMethodEvent import java.awt.font.TextHitInfo import java.awt.im.InputMethodRequests import java.text.AttributedCharacterIterator import java.text.AttributedString import java.text.CharacterIterator import java.util.Locale import kotlin.math.max import kotlin.math.min internal actual interface PlatformInputComponent { fun enableInput(inputMethodRequests: InputMethodRequests) fun disableInput() // Input service needs to know this information to implement Input Method support val locationOnScreen: Point val density: Density } internal actual class PlatformInput actual constructor(val component: PlatformComponent) : PlatformTextInputService { data class CurrentInput( var value: TextFieldValue, val onEditCommand: ((List<EditCommand>) -> Unit), val onImeActionPerformed: ((ImeAction) -> Unit), val imeAction: ImeAction, var focusedRect: Rect? = null ) var currentInput: CurrentInput? = null // This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264). // JDK currently properly supports this functionality only for TextComponent/JTextComponent descendants. // For our editor component we need this workaround. // After https://bugs.openjdk.java.net/browse/JDK-8074882 is fixed, this workaround should be replaced with a proper solution. var charKeyPressed: Boolean = false var needToDeletePreviousChar: Boolean = false override fun startInput( value: TextFieldValue, imeOptions: ImeOptions, onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit ) { val input = CurrentInput( value, onEditCommand, onImeActionPerformed, imeOptions.imeAction ) currentInput = input component.enableInput(methodRequestsForInput(input)) } override fun stopInput() { component.disableInput() currentInput = null } override fun showSoftwareKeyboard() { } override fun hideSoftwareKeyboard() { } override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) { currentInput?.let { input -> input.value = newValue } } @Deprecated("This method should not be called, used BringIntoViewRequester instead.") override fun notifyFocusedRect(rect: Rect) { currentInput?.let { input -> input.focusedRect = rect } } internal fun inputMethodCaretPositionChanged( @Suppress("UNUSED_PARAMETER") event: InputMethodEvent ) { // Which OSes and which input method could produce such events? We need to have some // specific cases in mind before implementing this } internal fun replaceInputMethodText(event: InputMethodEvent) { currentInput?.let { input -> if (event.text == null) { return } val committed = event.text.toStringUntil(event.committedCharacterCount) val composing = event.text.toStringFrom(event.committedCharacterCount) val ops = mutableListOf<EditCommand>() if (needToDeletePreviousChar && isMac && input.value.selection.min > 0) { needToDeletePreviousChar = false ops.add(DeleteSurroundingTextInCodePointsCommand(1, 0)) } // newCursorPosition == 1 leads to effectively ignoring of this parameter in EditCommands // processing. the cursor will be set after the inserted text. if (committed.isNotEmpty()) { ops.add(CommitTextCommand(committed, 1)) } if (composing.isNotEmpty()) { ops.add(SetComposingTextCommand(composing, 1)) } input.onEditCommand.invoke(ops) } } fun methodRequestsForInput(input: CurrentInput) = object : InputMethodRequests { override fun getLocationOffset(x: Int, y: Int): TextHitInfo? { if (input.value.composition != null) { // TODO: to properly implement this method we need to somehow have access to // Paragraph at this point return TextHitInfo.leading(0) } return null } override fun cancelLatestCommittedText( attributes: Array<AttributedCharacterIterator.Attribute>? ): AttributedCharacterIterator? { return null } override fun getInsertPositionOffset(): Int { val composedStartIndex = input.value.composition?.start ?: 0 val composedEndIndex = input.value.composition?.end ?: 0 val caretIndex = input.value.selection.start if (caretIndex < composedStartIndex) { return caretIndex } if (caretIndex < composedEndIndex) { return composedStartIndex } return caretIndex - (composedEndIndex - composedStartIndex) } override fun getCommittedTextLength() = input.value.text.length - (input.value.composition?.length ?: 0) override fun getSelectedText( attributes: Array<AttributedCharacterIterator.Attribute>? ): AttributedCharacterIterator { if (charKeyPressed) { needToDeletePreviousChar = true } val str = input.value.text.substring(input.value.selection) return AttributedString(str).iterator } override fun getTextLocation(offset: TextHitInfo): Rectangle? { return input.focusedRect?.let { val x = (it.right / component.density.density).toInt() + component.locationOnScreen.x val y = (it.top / component.density.density).toInt() + component.locationOnScreen.y Rectangle(x, y, it.width.toInt(), it.height.toInt()) } } override fun getCommittedText( beginIndex: Int, endIndex: Int, attributes: Array<AttributedCharacterIterator.Attribute>? ): AttributedCharacterIterator { val comp = input.value.composition val text = input.value.text val range = TextRange(beginIndex, endIndex.coerceAtMost(text.length)) if (comp == null) { val res = text.substring(range) return AttributedString(res).iterator } val committed = text.substring( TextRange( min(range.min, comp.min), max(range.max, comp.max).coerceAtMost(text.length) ) ) return AttributedString(committed).iterator } } } private fun AttributedCharacterIterator.toStringUntil(index: Int): String { val strBuf = StringBuffer() var i = index if (i > 0) { var c: Char = setIndex(0) while (i > 0) { strBuf.append(c) c = next() i-- } } return String(strBuf) } private fun AttributedCharacterIterator.toStringFrom(index: Int): String { val strBuf = StringBuffer() var c: Char = setIndex(index) while (c != CharacterIterator.DONE) { strBuf.append(c) c = next() } return String(strBuf) } private val isMac = System.getProperty("os.name").lowercase(Locale.ENGLISH).startsWith("mac")
apache-2.0
657e3aa618257f57b6a5fc1cffbe2122
36.438525
130
0.633169
5.02199
false
false
false
false
jwren/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/SpecialMethod.kt
3
26317
// 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.j2k import com.intellij.psi.* import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING import com.intellij.psi.impl.PsiExpressionEvaluator import org.jetbrains.kotlin.j2k.ast.* import java.io.PrintStream import java.util.* enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String, val parameterCount: Int?) { CHAR_SEQUENCE_LENGTH(CharSequence::class.java.name, "length", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse() }, COLLECTION_SIZE(Collection::class.java.name, "size", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse() }, COLLECTION_TO_ARRAY(Collection::class.java.name, "toArray", 0) { override fun ConvertCallData.convertCall() = convertWithChangedName("toTypedArray", argumentsNotNull()) }, COLLECTION_TO_ARRAY_WITH_ARG(Collection::class.java.name, "toArray", 1) { override fun ConvertCallData.convertCall() = copy(arguments = emptyList()).convertWithChangedName("toTypedArray", emptyList()) }, MAP_SIZE(Map::class.java.name, "size", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse() }, MAP_KEY_SET(Map::class.java.name, "keySet", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("keys") }, MAP_PUT_IF_ABSENT(Map::class.java.name, "putIfAbsent", 2) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_REMOVE(Map::class.java.name, "remove", 2) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_REPLACE(Map::class.java.name, "replace", 3) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_REPLACE_ALL(Map::class.java.name, "replaceAll", 1) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_COMPUTE(Map::class.java.name, "compute", 2) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_COMPUTE_IF_ABSENT(Map::class.java.name, "computeIfAbsent", 2) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_COMPUTE_IF_PRESENT(Map::class.java.name, "computeIfPresent", 2) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_MERGE(Map::class.java.name, "merge", 3) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_GET_OR_DEFAULT(Map::class.java.name, "getOrDefault", 2) { override fun ConvertCallData.convertCall() = convertWithReceiverCast() }, MAP_VALUES(Map::class.java.name, "values", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse() }, MAP_ENTRY_SET(Map::class.java.name, "entrySet", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("entries") }, ENUM_NAME(Enum::class.java.name, "name", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("name") }, ENUM_ORDINAL(Enum::class.java.name, "ordinal", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse() }, CHAR_AT(CharSequence::class.java.name, "charAt", 1) { override fun ConvertCallData.convertCall() = convertWithChangedName("get", argumentsNotNull()) }, NUMBER_BYTE_VALUE(Number::class.java.name, "byteValue", 0) { override fun ConvertCallData.convertCall() = convertWithChangedName("toByte", argumentsNotNull()) }, NUMBER_SHORT_VALUE(Number::class.java.name, "shortValue", 0) { override fun ConvertCallData.convertCall() = convertWithChangedName("toShort", argumentsNotNull()) }, NUMBER_INT_VALUE(Number::class.java.name, "intValue", 0) { override fun ConvertCallData.convertCall() = convertWithChangedName("toInt", argumentsNotNull()) }, NUMBER_LONG_VALUE(Number::class.java.name, "longValue", 0) { override fun ConvertCallData.convertCall() = convertWithChangedName("toLong", argumentsNotNull()) }, NUMBER_FLOAT_VALUE(Number::class.java.name, "floatValue", 0) { override fun ConvertCallData.convertCall() = convertWithChangedName("toFloat", argumentsNotNull()) }, NUMBER_DOUBLE_VALUE(Number::class.java.name, "doubleValue", 0) { override fun ConvertCallData.convertCall() = convertWithChangedName("toDouble", argumentsNotNull()) }, LIST_REMOVE(List::class.java.name, "remove", 1) { override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher) = super.matches(method, superMethodsSearcher) && method.parameterList.parameters.single().type.canonicalText == "int" override fun ConvertCallData.convertCall() = convertWithChangedName("removeAt", argumentsNotNull()) }, THROWABLE_GET_MESSAGE(Throwable::class.java.name, "getMessage", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("message") }, THROWABLE_GET_CAUSE(Throwable::class.java.name, "getCause", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("cause") }, MAP_ENTRY_GET_KEY(Map::class.java.name + ".Entry", "getKey", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("key") }, MAP_ENTRY_GET_VALUE(Map::class.java.name + ".Entry", "getValue", 0) { override fun ConvertCallData.convertCall() = convertMethodCallToPropertyUse("value") }, OBJECT_EQUALS(null, "equals", 1) { override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean = super.matches(method, superMethodsSearcher) && method.parameterList.parameters.single().type.canonicalText == JAVA_LANG_OBJECT override fun ConvertCallData.convertCall(): Expression? { if (qualifier == null || qualifier is PsiSuperExpression) return null return BinaryExpression(codeConverter.convertExpression(qualifier), codeConverter.convertExpression(arguments.single()), Operator.EQEQ) } }, OBJECT_GET_CLASS(JAVA_LANG_OBJECT, "getClass", 0) { override fun ConvertCallData.convertCall(): Expression { val identifier = Identifier.withNoPrototype("javaClass", isNullable = false) return if (qualifier != null) QualifiedExpression(codeConverter.convertExpression(qualifier), identifier, null) else identifier } }, OBJECTS_EQUALS("java.util.Objects", "equals", 2) { override fun ConvertCallData.convertCall() = BinaryExpression(codeConverter.convertExpression(arguments[0]), codeConverter.convertExpression(arguments[1]), Operator.EQEQ) }, COLLECTIONS_EMPTY_LIST(Collections::class.java.name, "emptyList", 0) { override fun ConvertCallData.convertCall() = MethodCallExpression.buildNonNull(null, "emptyList", ArgumentList.withNoPrototype(), typeArgumentsConverted) }, COLLECTIONS_EMPTY_SET(Collections::class.java.name, "emptySet", 0) { override fun ConvertCallData.convertCall() = MethodCallExpression.buildNonNull(null, "emptySet", ArgumentList.withNoPrototype(), typeArgumentsConverted) }, COLLECTIONS_EMPTY_MAP(Collections::class.java.name, "emptyMap", 0) { override fun ConvertCallData.convertCall() = MethodCallExpression.buildNonNull(null, "emptyMap", ArgumentList.withNoPrototype(), typeArgumentsConverted) }, COLLECTIONS_SINGLETON_LIST(Collections::class.java.name, "singletonList", 1) { override fun ConvertCallData.convertCall(): MethodCallExpression { val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpression(arguments.single())) return MethodCallExpression.buildNonNull(null, "listOf", argumentList, typeArgumentsConverted) } }, COLLECTIONS_SINGLETON(Collections::class.java.name, "singleton", 1) { override fun ConvertCallData.convertCall(): MethodCallExpression { val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpression(arguments.single())) return MethodCallExpression.buildNonNull(null, "setOf", argumentList, typeArgumentsConverted) } }, STRING_TRIM(JAVA_LANG_STRING, "trim", 0) { override fun ConvertCallData.convertCall(): Expression? { val comparison = BinaryExpression(Identifier.withNoPrototype("it", isNullable = false), LiteralExpression("' '").assignNoPrototype(), Operator(JavaTokenType.LE).assignNoPrototype()).assignNoPrototype() val argumentList = ArgumentList.withNoPrototype(LambdaExpression(null, Block.of(comparison).assignNoPrototype())) return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "trim", argumentList, dotPrototype = dot) } }, STRING_REPLACE_ALL(JAVA_LANG_STRING, "replaceAll", 2) { override fun ConvertCallData.convertCall(): MethodCallExpression { val argumentList = ArgumentList.withNoPrototype( codeConverter.convertToRegex(arguments[0]), codeConverter.convertExpression(arguments[1]) ) return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "replace", argumentList, dotPrototype = dot) } }, STRING_REPLACE_FIRST(JAVA_LANG_STRING, "replaceFirst", 2) { override fun ConvertCallData.convertCall(): MethodCallExpression { return MethodCallExpression.buildNonNull( codeConverter.convertExpression(qualifier), "replaceFirst", ArgumentList.withNoPrototype( codeConverter.convertToRegex(arguments[0]), codeConverter.convertExpression(arguments[1]) ), dotPrototype = dot ) } }, STRING_MATCHES(JAVA_LANG_STRING, "matches", 1) { override fun ConvertCallData.convertCall(): MethodCallExpression { val argumentList = ArgumentList.withNoPrototype(codeConverter.convertToRegex(arguments.single())) return MethodCallExpression.buildNonNull(codeConverter.convertExpression(qualifier), "matches", argumentList, dotPrototype = dot) } }, STRING_SPLIT(JAVA_LANG_STRING, "split", 1) { override fun ConvertCallData.convertCall(): Expression? { val splitCall = MethodCallExpression.buildNonNull( codeConverter.convertExpression(qualifier), "split", ArgumentList.withNoPrototype(codeConverter.convertToRegex(arguments.single())), dotPrototype = dot ).assignNoPrototype() val isEmptyCall = MethodCallExpression.buildNonNull(Identifier.withNoPrototype("it", isNullable = false), "isEmpty").assignNoPrototype() val isEmptyCallBlock = Block.of(isEmptyCall).assignNoPrototype() val dropLastCall = MethodCallExpression.buildNonNull( splitCall, "dropLastWhile", ArgumentList.withNoPrototype(LambdaExpression(null, isEmptyCallBlock).assignNoPrototype()) ).assignNoPrototype() return MethodCallExpression.buildNonNull(dropLastCall, "toTypedArray") } }, STRING_SPLIT_LIMIT(JAVA_LANG_STRING, "split", 2) { override fun ConvertCallData.convertCall(): Expression? { val patternArgument = codeConverter.convertToRegex(arguments[0]) val limitArgument = codeConverter.convertExpression(arguments[1]) val evaluator = PsiExpressionEvaluator() val limit = evaluator.computeConstantExpression(arguments[1], /* throwExceptionOnOverflow = */ false) as? Int val splitArguments = when { limit == null -> // not a constant listOf(patternArgument, MethodCallExpression.buildNonNull(limitArgument, "coerceAtLeast", ArgumentList.withNoPrototype(LiteralExpression("0").assignNoPrototype())).assignNoPrototype()) limit < 0 -> // negative, same behavior as split(regex) in kotlin listOf(patternArgument) limit == 0 -> { // zero, same replacement as for split without limit val newCallData = copy(arguments = listOf(arguments[0])) return STRING_SPLIT.convertCall(newCallData) } else -> // positive, same behavior as split(regex, limit) in kotlin listOf(patternArgument, limitArgument) } val splitCall = MethodCallExpression.buildNonNull( codeConverter.convertExpression(qualifier), "split", ArgumentList.withNoPrototype(splitArguments), dotPrototype = dot ).assignNoPrototype() return MethodCallExpression.buildNonNull(splitCall, "toTypedArray") } }, STRING_JOIN(JAVA_LANG_STRING, "join", 2) { override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean = super.matches(method, superMethodsSearcher) && method.parameterList.parameters.last().type.canonicalText == "java.lang.Iterable<? extends java.lang.CharSequence>" override fun ConvertCallData.convertCall(): Expression? { val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.take(1))) return MethodCallExpression.buildNonNull(codeConverter.convertExpression(arguments[1]), "joinToString", argumentList) } }, STRING_JOIN_VARARG(JAVA_LANG_STRING, "join", null) { override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean = super.matches(method, superMethodsSearcher) && method.parameterList.let { it.parametersCount == 2 && it.parameters.last().isVarArgs } override fun ConvertCallData.convertCall(): Expression? { return if (arguments.size == 2 && arguments.last().isAssignableToCharSequenceArray()) { STRING_JOIN.convertCall(this) } else { MethodCallExpression.buildNonNull( MethodCallExpression.buildNonNull(null, "arrayOf", ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.drop(1)))).assignNoPrototype(), "joinToString", ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.take(1))) ) } } private fun PsiExpression.isAssignableToCharSequenceArray(): Boolean { val charSequenceType = PsiType.getTypeByName("java.lang.CharSequence", project, resolveScope) return (type as? PsiArrayType)?.componentType?.let { charSequenceType.isAssignableFrom(it) } ?: false } }, STRING_CONCAT(JAVA_LANG_STRING, "concat", 1) { override fun ConvertCallData.convertCall() = BinaryExpression(codeConverter.convertExpression(qualifier), codeConverter.convertExpression(arguments.single()), Operator(JavaTokenType.PLUS).assignNoPrototype()) }, STRING_COMPARE_TO_IGNORE_CASE(JAVA_LANG_STRING, "compareToIgnoreCase", 1) { override fun ConvertCallData.convertCall() = convertWithIgnoreCaseArgument("compareTo") }, STRING_EQUALS_IGNORE_CASE(JAVA_LANG_STRING, "equalsIgnoreCase", 1) { override fun ConvertCallData.convertCall() = convertWithIgnoreCaseArgument("equals") }, STRING_REGION_MATCHES(JAVA_LANG_STRING, "regionMatches", 5) { override fun ConvertCallData.convertCall() = copy(arguments = arguments.drop(1)).convertWithIgnoreCaseArgument("regionMatches", ignoreCaseArgument = arguments.first()) }, STRING_GET_BYTES(JAVA_LANG_STRING, "getBytes", null) { override fun ConvertCallData.convertCall(): MethodCallExpression { val charsetArg = arguments.lastOrNull()?.takeIf { it.type?.canonicalText == JAVA_LANG_STRING } val convertedArguments = codeConverter.convertExpressionsInList(arguments).map { if (charsetArg != null && it.prototypes?.singleOrNull()?.element == charsetArg) MethodCallExpression.buildNonNull(null, "charset", ArgumentList.withNoPrototype(it)).assignNoPrototype() else it } return MethodCallExpression.buildNonNull( codeConverter.convertExpression(qualifier), "toByteArray", ArgumentList.withNoPrototype(convertedArguments), dotPrototype = dot ) } }, STRING_GET_CHARS(JAVA_LANG_STRING, "getChars", 4) { override fun ConvertCallData.convertCall(): MethodCallExpression { // reorder parameters: srcBegin(0), srcEnd(1), dst(2), dstOffset(3) -> destination(2), destinationOffset(3), startIndex(0), endIndex(1) val argumentList = ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments.slice(listOf(2, 3, 0, 1)))) return MethodCallExpression.buildNonNull( codeConverter.convertExpression(qualifier), "toCharArray", argumentList, dotPrototype = dot ) } }, STRING_VALUE_OF_CHAR_ARRAY(JAVA_LANG_STRING, "valueOf", null) { override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean { return super.matches(method, superMethodsSearcher) && method.parameterList.parametersCount.let { it == 1 || it == 3} && method.parameterList.parameters.first().type.canonicalText == "char[]" } override fun ConvertCallData.convertCall() = MethodCallExpression.buildNonNull(null, "String", ArgumentList.withNoPrototype(codeConverter.convertExpressionsInList(arguments))) }, STRING_COPY_VALUE_OF_CHAR_ARRAY(JAVA_LANG_STRING, "copyValueOf", null) { override fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean { return super.matches(method, superMethodsSearcher) && method.parameterList.parametersCount.let { it == 1 || it == 3 } && method.parameterList.parameters.first().type.canonicalText == "char[]" } override fun ConvertCallData.convertCall() = STRING_VALUE_OF_CHAR_ARRAY.convertCall(this) }, STRING_VALUE_OF(JAVA_LANG_STRING, "valueOf", 1) { override fun ConvertCallData.convertCall() = MethodCallExpression.buildNonNull(codeConverter.convertExpression(arguments.single(), shouldParenthesize = true), "toString") }, SYSTEM_OUT_PRINTLN(PrintStream::class.java.name, "println", null) { override fun ConvertCallData.convertCall() = convertSystemOutMethodCall(methodName) }, SYSTEM_OUT_PRINT(PrintStream::class.java.name, "print", null) { override fun ConvertCallData.convertCall() = convertSystemOutMethodCall(methodName) }; open fun matches(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean = method.name == methodName && matchesClass(method, superMethodsSearcher) && matchesParameterCount(method) protected fun matchesClass(method: PsiMethod, superMethodsSearcher: SuperMethodsSearcher): Boolean { if (qualifiedClassName == null) return true val superMethods = superMethodsSearcher.findDeepestSuperMethods(method) return if (superMethods.isEmpty()) method.containingClass?.qualifiedName == qualifiedClassName else superMethods.any { it.containingClass?.qualifiedName == qualifiedClassName } } protected fun matchesParameterCount(method: PsiMethod) = parameterCount == null || parameterCount == method.parameterList.parametersCount data class ConvertCallData( val qualifier: PsiExpression?, @Suppress("ArrayInDataClass") val arguments: List<PsiExpression>, val typeArgumentsConverted: List<Type>, val dot: PsiElement?, val lPar: PsiElement?, val rPar: PsiElement?, val codeConverter: CodeConverter ) @JvmName("convertCallPublic") fun convertCall(data: ConvertCallData): Expression? = data.convertCall() protected abstract fun ConvertCallData.convertCall(): Expression? protected fun ConvertCallData.convertMethodCallToPropertyUse(propertyName: String = methodName): Expression { val identifier = Identifier.withNoPrototype(propertyName, isNullable = false) return if (qualifier != null) QualifiedExpression(codeConverter.convertExpression(qualifier), identifier, dot) else identifier } protected fun ConvertCallData.argumentsNotNull() = arguments.map { Nullability.NotNull } protected fun ConvertCallData.convertWithChangedName(name: String, argumentNullabilities: List<Nullability>): MethodCallExpression { assert(argumentNullabilities.size == arguments.size) val argumentsConverted = arguments.zip(argumentNullabilities).map { codeConverter.convertExpression(it.first, null, it.second).assignPrototype(it.first, CommentsAndSpacesInheritance.LINE_BREAKS) } val argumentList = ArgumentList(argumentsConverted, LPar.withPrototype(lPar), RPar.withPrototype(rPar)).assignNoPrototype() return MethodCallExpression.buildNonNull( codeConverter.convertExpression(qualifier), name, argumentList, typeArgumentsConverted, dot) } protected fun ConvertCallData.convertWithReceiverCast(): MethodCallExpression? { val convertedArguments = codeConverter.convertExpressionsInList(arguments) val qualifierWithCast = castQualifierToType(codeConverter, qualifier!!, qualifiedClassName!!) ?: return null return MethodCallExpression.buildNonNull( qualifierWithCast, methodName, ArgumentList.withNoPrototype(convertedArguments), typeArgumentsConverted, dot) } private fun castQualifierToType(codeConverter: CodeConverter, qualifier: PsiExpression, type: String): TypeCastExpression? { val convertedQualifier = codeConverter.convertExpression(qualifier) val qualifierType = codeConverter.typeConverter.convertType(qualifier.type) val typeArgs = (qualifierType as? ClassType)?.referenceElement?.typeArgs ?: emptyList() val referenceElement = ReferenceElement(Identifier.withNoPrototype(type), typeArgs).assignNoPrototype() val newType = ClassType(referenceElement, Nullability.Default, codeConverter.settings).assignNoPrototype() return TypeCastExpression(newType, convertedQualifier).assignNoPrototype() } protected fun ConvertCallData.convertWithIgnoreCaseArgument(methodName: String, ignoreCaseArgument: PsiExpression? = null): Expression { val ignoreCaseExpression = ignoreCaseArgument?.let { codeConverter.convertExpression(it) } ?: LiteralExpression("true").assignNoPrototype() val ignoreCaseArgumentExpression = AssignmentExpression(Identifier.withNoPrototype("ignoreCase"), ignoreCaseExpression, Operator.EQ).assignNoPrototype() val convertedArguments = arguments.map { codeConverter.convertExpression(it, null, Nullability.NotNull).assignPrototype(it, CommentsAndSpacesInheritance.LINE_BREAKS) } + ignoreCaseArgumentExpression val argumentList = ArgumentList(convertedArguments, LPar.withPrototype(lPar), RPar.withPrototype(rPar)).assignNoPrototype() return MethodCallExpression.buildNonNull( codeConverter.convertExpression(qualifier), methodName, argumentList, typeArgumentsConverted, dot) } protected fun ConvertCallData.convertSystemOutMethodCall(methodName: String): Expression? { if (qualifier !is PsiReferenceExpression) return null val qqualifier = qualifier.qualifierExpression as? PsiReferenceExpression ?: return null if (qqualifier.canonicalText != "java.lang.System") return null if (qualifier.referenceName != "out") return null if (typeArgumentsConverted.isNotEmpty()) return null val argumentList = ArgumentList( codeConverter.convertExpressionsInList(arguments), LPar.withPrototype(lPar), RPar.withPrototype(rPar) ).assignNoPrototype() return MethodCallExpression.buildNonNull(null, methodName, argumentList) } protected fun CodeConverter.convertToRegex(expression: PsiExpression?): Expression = MethodCallExpression.buildNonNull(convertExpression(expression, shouldParenthesize = true), "toRegex").assignNoPrototype() companion object { private val valuesByName = values().groupBy { it.methodName } fun match(method: PsiMethod, argumentCount: Int, services: JavaToKotlinConverterServices): SpecialMethod? { val candidates = valuesByName[method.name] ?: return null return candidates .firstOrNull { it.matches(method, services.superMethodsSearcher) } ?.takeIf { it.parameterCount == null || it.parameterCount == argumentCount } // if parameterCount is specified we should make sure that argument count is correct } } }
apache-2.0
5895fe39924c41fbb608425a91b00f7e
50.100971
213
0.679143
5.548598
false
false
false
false
dpapathanasiou/ARMS
src/main/kotlin/org/papathanasiou/denis/ARMS/AnotherRESTfulMongoService.kt
1
1087
package org.papathanasiou.denis.ARMS import org.glassfish.jersey.netty.httpserver.NettyHttpContainerProvider import org.glassfish.jersey.server.ResourceConfig import java.net.URI import com.fasterxml.jackson.module.kotlin.* import java.io.IOException object AnotherRESTfulMongoService { @JvmStatic fun main(args: Array<String>) { val mapper = jacksonObjectMapper() val json = AnotherRESTfulMongoService.javaClass.classLoader.getResource(CONF_JSON) ?: throw IOException("Could not find or load $CONF_JSON from src/main/resources") val conf = mapper.readValue<ARMSConfiguration>(json) val connection = MongoConnection(conf.mongoURI) val resourceConfig = ResourceConfig.forApplication(JaxRSApplication(RESTfulEndpoints(connection.getConnection(), conf.authenticate, conf.authSeeds, TimeBasedOneTimePassword.TOTP))) val server = NettyHttpContainerProvider.createHttp2Server(URI.create(conf.serviceURI), resourceConfig, null) Runtime.getRuntime().addShutdownHook(Thread(Runnable { server.close() })) } }
mit
3deede703a83293ef43bb6df36864f16
44.333333
188
0.765409
4.330677
false
true
false
false
smmribeiro/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/VcsShowLogAction.kt
12
963
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.ui.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.vcs.VcsShowToolWindowTabAction import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.impl.VcsLogContentProvider import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.util.VcsLogUtil class VcsShowLogAction : VcsShowToolWindowTabAction() { override val tabName: String get() = VcsLogContentProvider.TAB_NAME override fun update(e: AnActionEvent) { super.update(e) val project = e.project if (project != null) { val providers = VcsProjectLog.getLogProviders(project) val vcsName = VcsLogUtil.getVcsDisplayName(project, providers.values) e.presentation.text = VcsLogBundle.message("action.Vcs.Show.Log.text.template", vcsName) } } }
apache-2.0
673e20d56b40b2dea39b5d2847d3b6c6
40.913043
140
0.777778
4.080508
false
false
false
false
NlRVANA/Unity
app/src/main/java/com/zwq65/unity/data/network/retrofit/interceptor/MyInterceptor.kt
1
1677
/* * Copyright [2017] [NIRVANA PRIVATE LIMITED] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zwq65.unity.data.network.retrofit.interceptor import android.util.Log import com.zwq65.unity.utils.LogUtils import okhttp3.Interceptor import okhttp3.Response import okhttp3.ResponseBody import java.io.IOException /** * ================================================ * 自定义拦截器(log request and response data) * <p> * Created by NIRVANA on 2017/10/12 * Contact with <[email protected]> * ================================================ */ class MyInterceptor : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val response = chain.proceed(chain.request()) LogUtils.d("request", "request:" + chain.request().url()) val body: ResponseBody try { body = response.peekBody((1024 * 1024).toLong()) } catch (e: IOException) { e.printStackTrace() throw e } val ss = body.string() Log.d("retrofitResponse", ss) return response } }
apache-2.0
5b67d77200a948d48c987979ae6697c4
31.038462
78
0.632432
4.280206
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SendMQTTMessagesAction.kt
1
1992
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.framework.extensions.applyIfNotNull import ch.rmy.android.framework.extensions.logException import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.exceptions.ActionException import ch.rmy.android.http_shortcuts.scripting.ExecutionContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.eclipse.paho.client.mqttv3.MqttClient import org.eclipse.paho.client.mqttv3.MqttConnectOptions import org.eclipse.paho.client.mqttv3.MqttException import org.eclipse.paho.client.mqttv3.MqttMessage class SendMQTTMessagesAction( private val serverUri: String, private val username: String?, private val password: String?, private val messages: List<Message>, ) : BaseAction() { override suspend fun execute(executionContext: ExecutionContext) { withContext(Dispatchers.IO) { try { val client = MqttClient(serverUri, MqttClient.generateClientId(), null) val options = MqttConnectOptions() .apply { isCleanSession = true } .applyIfNotNull(username) { userName = it } .applyIfNotNull(password) { password = it.toCharArray() } client.connect(options) messages.forEach { message -> client.publish(message.topic, MqttMessage(message.payload)) } client.disconnect() client.close() } catch (e: MqttException) { logException(e) throw ActionException { getString(R.string.error_failed_to_send_mqtt, e.message ?: e.toString()) } } } } data class Message(val topic: String, val payload: ByteArray) }
mit
b78def1b0d994d58d861976ed7d12144
37.307692
92
0.615462
4.942928
false
false
false
false
Archinamon/AndroidGradleSwagger
src/main/kotlin/com/archinamon/utils/aar.kt
2
1187
package com.archinamon.utils import java.io.File import javax.xml.bind.JAXBContext import javax.xml.bind.annotation.* internal fun findPackageNameIfAar(input: File): String { if (!input.absolutePath.contains("build-cache")) return input.absolutePath if (!input.exists()) return "[empty]" var f: File? = input do { f = f?.parentFile } while (f?.isDirectory!! && !f.listFiles().any(::findManifest)) val manifest = f.listFiles().find(::findManifest) if (manifest != null) { val xml = readXml(manifest, Manifest::class.java) return xml.libPackage } return input.name } private fun findManifest(f: File): Boolean { return f.name.equals("androidmanifest.xml", true) } private inline fun <reified T> readXml(file: File, clazz: Class<T>): T { val jc = JAXBContext.newInstance(clazz) val unmarshaller = jc.createUnmarshaller() val data = unmarshaller.unmarshal(file) ?: error("Marshalling failed. Get null object") return data as T } @XmlRootElement(name = "manifest") @XmlAccessorType(XmlAccessType.FIELD) internal class Manifest { @XmlAttribute(name = "package") lateinit var libPackage: String }
apache-2.0
14930bde59ed280ec6b08fd398be6b39
26.627907
91
0.69166
3.768254
false
false
false
false
nebula-plugins/nebula-bintray-plugin
src/main/kotlin/nebula/plugin/bintray/BintrayClient.kt
1
6690
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nebula.plugin.bintray import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import net.jodah.failsafe.RetryPolicy import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.gradle.api.GradleException import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.io.IOException import java.time.Duration import net.jodah.failsafe.Failsafe import org.slf4j.LoggerFactory import java.util.concurrent.TimeUnit class BintrayClient(var bintrayService: BintrayService, retryConfig: RetryConfig) { var retryPolicy : RetryPolicy<Any> val logger = LoggerFactory.getLogger(BintrayClient::class.java) init { this.retryPolicy = RetryPolicy<Any>() .handle(IOException::class.java) .withDelay(Duration.ofSeconds(retryConfig.retryDelayInSeconds)) .withMaxRetries(retryConfig.maxRetries) .onFailedAttempt { e -> logger.error( "Trying to publish a new version to Bintray failed.", e.lastFailure ) } .onRetry { _ -> logger.info("Retrying to publish a new version to Bintray.") } } data class Builder( var user: String? = null, var apiKey: String? = null, var apiUrl: String? = null, var maxRetries: Int = 3, var retryDelayInSeconds: Long = 15, var readTimeoutInSeconds: Long = 240, var connectionTimeoutInSeconds: Long = 240) { fun user(user: String) = apply { this.user = user } fun apiKey(apiKey: String) = apply { this.apiKey = apiKey } fun apiUrl(apiUrl: String) = apply { this.apiUrl = apiUrl } fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries } fun retryDelayInSeconds(retryDelayInSeconds: Long) = apply { this.retryDelayInSeconds = retryDelayInSeconds } fun readTimeoutInSeconds(readTimeoutInSeconds: Long) = apply { this.readTimeoutInSeconds = readTimeoutInSeconds } fun connectionTimeoutInSeconds(connectionTimeoutInSeconds: Long) = apply { this.connectionTimeoutInSeconds = connectionTimeoutInSeconds } fun build() = BintrayClient(bintray(apiUrl!!, user!!, apiKey!!, readTimeoutInSeconds, connectionTimeoutInSeconds), RetryConfig(this.maxRetries, this.retryDelayInSeconds)) } data class RetryConfig(val maxRetries: Int, val retryDelayInSeconds: Long) fun createOrUpdatePackage(subject: String, repo: String, pkg: String, packageRequest: PackageRequest) { val getPackageResult = Failsafe.with(retryPolicy).get( { -> bintrayService.getPackage(subject, repo, pkg).execute() } ) if(getPackageResult.isSuccessful) { return } if(getPackageResult.code() != 404) { throw GradleException("Could not obtain information for package $repo/$subject/$pkg - ${getPackageResult.errorBody()?.string()}") } val createPackageResult = Failsafe.with(retryPolicy).get( { -> bintrayService.createPackage(subject, repo, packageRequest).execute() } ) if(!createPackageResult.isSuccessful) { throw GradleException("Could not create or update information for package $repo/$subject/$pkg - ${getPackageResult.errorBody()?.string()}") } } fun publishVersion(subject: String, repo: String, pkg: String, version: String, publishRequest: PublishRequest) { val publishVersionResult = Failsafe.with(retryPolicy).get( { -> bintrayService.publishVersion(subject, repo, pkg, version, publishRequest).execute() } ) if(!publishVersionResult.isSuccessful) { throw GradleException("Could not publish $version version for package $repo/$subject/$pkg - ${publishVersionResult.errorBody()?.string()}") } } fun syncVersionToMavenCentral(subject: String, repo: String, pkg: String, version: String, mavenCentralSyncRequest: MavenCentralSyncRequest) { val syncVersionToMavenCentralResult = Failsafe.with(retryPolicy).get( { -> bintrayService.syncVersionToMavenCentral(subject, repo, pkg, version, mavenCentralSyncRequest).execute() } ) if(!syncVersionToMavenCentralResult.isSuccessful) { logger.error("Could not sync $version version for package $repo/$subject/$pkg to maven central - ${syncVersionToMavenCentralResult.errorBody()?.string()}") } } fun gpgSignVersion(subject: String, repo: String, pkg: String, version: String, passphrase: String?) { val headers = mutableMapOf<String, String>() if(!passphrase.isNullOrEmpty()) { headers.put("X-GPG-PASSPHRASE", passphrase) } val gppSignVersionResult = Failsafe.with(retryPolicy).get( { -> bintrayService.gpgSign(subject, repo, pkg, version, headers).execute() } ) if(!gppSignVersionResult.isSuccessful) { throw GradleException("Could not gpg sign $version version for package $repo/$subject/$pkg - ${gppSignVersionResult.errorBody()?.string()}") } } } fun bintray(apiUrl: String, user: String, apiKey: String, readTimeoutInSeconds: Long, connectionTimeoutInSeconds: Long): BintrayService = Retrofit.Builder() .baseUrl(apiUrl) .client(OkHttpClient.Builder() .readTimeout(readTimeoutInSeconds, TimeUnit.SECONDS) .connectTimeout(connectionTimeoutInSeconds, TimeUnit.SECONDS) .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)) .addInterceptor({ chain -> chain.proceed(chain.request().newBuilder() .header("Authorization", Credentials.basic(user, apiKey)) .build()) }) .build()) .addConverterFactory(MoshiConverterFactory.create(Moshi.Builder().add(KotlinJsonAdapterFactory()).build())) .build() .create(BintrayService::class.java)
apache-2.0
91e1f44e8ceed282d9bf6a1c008f0dcd
48.932836
178
0.683857
4.926362
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/internal/adapter/PageAdapter.kt
2
1389
package me.proxer.library.internal.adapter import com.squareup.moshi.FromJson import com.squareup.moshi.JsonDataException import com.squareup.moshi.ToJson import me.proxer.library.entity.manga.Page /** * @author Ruben Gees */ internal class PageAdapter { private companion object { private const val FIELD_AMOUNT = 3 private const val NAME_FIELD_LOCATION = 0 private const val HEIGHT_FIELD_LOCATION = 1 private const val WIDTH_FIELD_LOCATION = 2 } @FromJson @Suppress("ThrowsCount") fun fromJson(json: Array<Array<String>>): List<Page> { return json.map { jsonPage -> if (jsonPage.size != FIELD_AMOUNT) { throw JsonDataException("Page array length is " + json.size + " instead of 3.") } val height = jsonPage[HEIGHT_FIELD_LOCATION].let { it.toIntOrNull() ?: throw JsonDataException("Expected an Int for the height but was $it") } val width = jsonPage[WIDTH_FIELD_LOCATION].let { it.toIntOrNull() ?: throw JsonDataException("Expected an Int for the width but was $it") } Page(jsonPage[NAME_FIELD_LOCATION], height, width) } } @ToJson fun toJson(value: Page): Array<String> { return arrayOf(value.name, value.width.toString(), value.height.toString()) } }
gpl-3.0
cb3ce77d72ed6a9c8c32d02dacd8d5e9
29.866667
105
0.62923
4.340625
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/chatdetails/presentation/ChatDetailsPresenter.kt
2
3650
package chat.rocket.android.chatdetails.presentation import chat.rocket.android.chatdetails.domain.ChatDetails import chat.rocket.android.chatroom.presentation.ChatRoomNavigator import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.server.domain.GetCurrentServerInteractor import chat.rocket.android.server.infrastructure.ConnectionManagerFactory import chat.rocket.android.util.extension.launchUI import chat.rocket.android.util.retryIO import chat.rocket.common.RocketChatException import chat.rocket.common.model.roomTypeOf import chat.rocket.common.util.ifNull import chat.rocket.core.internal.rest.favorite import chat.rocket.core.internal.rest.getInfo import chat.rocket.core.model.Room import timber.log.Timber import javax.inject.Inject class ChatDetailsPresenter @Inject constructor( private val view: ChatDetailsView, private val navigator: ChatRoomNavigator, private val strategy: CancelStrategy, serverInteractor: GetCurrentServerInteractor, factory: ConnectionManagerFactory ) { private val currentServer = serverInteractor.get()!! private val manager = factory.create(currentServer) private val client = manager?.client fun toggleFavoriteChatRoom(roomId: String, isFavorite: Boolean) { launchUI(strategy) { try { // Note: If it is favorite then the user wants to remove the favorite - and vice versa. retryIO("favorite($roomId, ${!isFavorite})") { client?.favorite(roomId, !isFavorite) } view.showFavoriteIcon(!isFavorite) } catch (e: RocketChatException) { Timber.e( e, "Error while trying to favorite or removing the favorite of a chat room." ) e.message?.let { view.showMessage(it) }.ifNull { view.showGenericErrorMessage() } } } } fun toVideoConference(roomId: String, chatRoomType: String) = navigator.toVideoConference(roomId, chatRoomType) fun getDetails(chatRoomId: String, chatRoomType: String) { launchUI(strategy) { try { retryIO("getInfo($chatRoomId, null, $chatRoomType") { client?.getInfo(chatRoomId, null, roomTypeOf(chatRoomType))?.let { room -> view.displayDetails(roomToChatDetails(room)) } } } catch (exception: Exception) { Timber.e(exception) exception.message?.let { view.showMessage(it) }.ifNull { view.showGenericErrorMessage() } } } } fun toFiles(chatRoomId: String) { navigator.toFileList(chatRoomId) } fun toMembers(chatRoomId: String) { navigator.toMembersList(chatRoomId) } fun toMentions(chatRoomId: String) { navigator.toMentions(chatRoomId) } fun toPinned(chatRoomId: String) { navigator.toPinnedMessageList(chatRoomId) } fun toFavorites(chatRoomId: String) { navigator.toFavoriteMessageList(chatRoomId) } private fun roomToChatDetails(room: Room): ChatDetails { return with(room) { ChatDetails( name = name, fullName = fullName, type = type.toString(), topic = topic, description = description, announcement = announcement ) } } }
mit
072204a1b8c6184d49b068babeb4352e
33.443396
103
0.619452
5.034483
false
false
false
false
guyca/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/views/element/SharedElementTransition.kt
1
1734
package com.reactnativenavigation.views.element import android.animation.AnimatorSet import android.view.View import com.reactnativenavigation.parse.SharedElementTransitionOptions import com.reactnativenavigation.viewcontrollers.ViewController import com.reactnativenavigation.views.element.animators.* class SharedElementTransition(appearing: ViewController<*>, private val options: SharedElementTransitionOptions) : Transition() { val fromId: String = options.fromId.get() val toId: String = options.toId.get() lateinit var from: View lateinit var to: View override var viewController: ViewController<*> = appearing override val view: View get() = to override val topInset: Int get() = viewController.topInset fun isValid(): Boolean = this::from.isInitialized override fun createAnimators(): AnimatorSet { val animators = animators() .filter { it.shouldAnimateProperty() } .map { it.create(options).apply { duration = options.getDuration() startDelay = options.getStartDelay() interpolator = options.getInterpolator() } } val set = AnimatorSet() set.playTogether(animators) return set } private fun animators(): List<PropertyAnimatorCreator<*>> { return listOf( MatrixAnimator(from, to), XAnimator(from, to), YAnimator(from, to), RotationAnimator(from, to), ScaleXAnimator(from, to), ScaleYAnimator(from, to), BackgroundColorAnimator(from, to), TextChangeAnimator(from, to) ) } }
mit
70b97395b6446ca2d0226f291d0307af
35.914894
129
0.636678
5.385093
false
false
false
false
carlbenson/Pinch
library/src/main/java/guru/benson/pinch/KMPMatch.kt
1
1205
package guru.benson.pinch /** * Knuth-Morris-Pratt Algorithm for Pattern Matching http://stackoverflow.com/questions/1507780/searching-for-a-sequence-of-bytes-in-a-binary-file-with-java */ /** * Finds the first occurrence of the pattern in the text. */ internal fun indexOf(data: ByteArray, pattern: ByteArray): Int { val failure = computeFailure(pattern) var j = 0 if (data.isEmpty()) { return -1 } for (i in data.indices) { while (j > 0 && pattern[j] != data[i]) { j = failure[j - 1] } if (pattern[j] == data[i]) { j++ } if (j == pattern.size) { return i - pattern.size + 1 } } return -1 } /** * Computes the failure function using a boot-strapping process, where the pattern is matched * against itself. */ private fun computeFailure(pattern: ByteArray): IntArray { val failure = IntArray(pattern.size) var j = 0 for (i in 1 until pattern.size) { while (j > 0 && pattern[j] != pattern[i]) { j = failure[j - 1] } if (pattern[j] == pattern[i]) { j++ } failure[i] = j } return failure }
apache-2.0
2fda030803040a554e82956feb1139de
22.627451
156
0.556846
3.575668
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/glNext/tut05/depthClamping.kt
2
7734
package glNext.tut05 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL2ES3.GL_DEPTH import com.jogamp.opengl.GL3 import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP import glNext.* import glm.* import main.framework.Framework import uno.buffer.* import uno.gl.gl3 import uno.glsl.programOf import glm.vec._3.Vec3 /** * Created by GBarbieri on 23.02.2017. */ fun main(args: Array<String>) { DepthClamping_Next().setup("Tutorial 05 - Depth Clamping") } class DepthClamping_Next : Framework() { object Buffer { val VERTEX = 0 val INDEX = 1 val MAX = 2 } var theProgram = 0 var offsetUniform = 0 var perspectiveMatrixUnif = 0 val numberOfVertices = 36 val perspectiveMatrix = FloatArray(16) val frustumScale = 1.0f val bufferObject = intBufferBig(Buffer.MAX) val vao = intBufferBig(1) var depthClampingActive = false override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeBuffers(gl) initVertexArray(vao) { val colorData = Vec3.SIZE * numberOfVertices array(bufferObject[Buffer.VERTEX], glf.pos3_col4, 0, colorData) element(bufferObject[Buffer.INDEX]) } cullFace { enable() cullFace = back frontFace = cw } depth { test = true mask = true func = less range = 0.0 .. 1.0 } } fun initializeProgram(gl: GL3) = with(gl) { theProgram = programOf(gl, javaClass, "tut05", "standard.vert", "standard.frag") withProgram(theProgram) { offsetUniform = "offset".location perspectiveMatrixUnif = "perspectiveMatrix".location val zNear = 1.0f val zFar = 3.0f perspectiveMatrix[0] = frustumScale perspectiveMatrix[5] = frustumScale perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar) perspectiveMatrix[14] = 2f * zFar * zNear / (zNear - zFar) perspectiveMatrix[11] = -1.0f use { glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix) } } } fun initializeBuffers(gl: GL3) = with(gl) { glGenBuffers(bufferObject) withArrayBuffer(bufferObject[Buffer.VERTEX]) { data(vertexData, GL_STATIC_DRAW) } withElementBuffer(bufferObject[Buffer.INDEX]) { data(indexData, GL_STATIC_DRAW) } } override fun display(gl: GL3) = with(gl) { glClearBufferf(GL_COLOR, 0) glClearBufferf(GL_DEPTH) usingProgram(theProgram) { withVertexArray(vao) { glUniform3f(offsetUniform, 0.0f, 0.0f, 0.5f) glDrawElements(indexData.size, GL_UNSIGNED_SHORT) glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f) glDrawElementsBaseVertex(indexData.size, GL_UNSIGNED_SHORT, 0, numberOfVertices / 2) } } } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { perspectiveMatrix[0] = frustumScale * (h / w.f) perspectiveMatrix[5] = frustumScale usingProgram(theProgram) { glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix) } glViewport(w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(bufferObject) glDeleteVertexArray(vao) destroyBuffers(vao, bufferObject, vertexData, indexData) } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> quit() KeyEvent.VK_SPACE -> window.gl3 { if (depthClampingActive) glDisable(GL_DEPTH_CLAMP) else glEnable(GL_DEPTH_CLAMP) depthClampingActive = !depthClampingActive } } } val RIGHT_EXTENT = 0.8f val LEFT_EXTENT = -RIGHT_EXTENT val TOP_EXTENT = 0.20f val MIDDLE_EXTENT = 0.0f val BOTTOM_EXTENT = -TOP_EXTENT val FRONT_EXTENT = -1.25f val REAR_EXTENT = -1.75f val GREEN_COLOR = floatArrayOf(0.75f, 0.75f, 1.0f, 1.0f) val BLUE_COLOR = floatArrayOf(0.0f, 0.5f, 0.0f, 1.0f) val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f) val GREY_COLOR = floatArrayOf(0.8f, 0.8f, 0.8f, 1.0f) val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f) val vertexData = floatBufferOf( //Object 1 positions LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT, RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT, //Object 2 positions TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT, TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT, BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT, //Object 1 colors *GREEN_COLOR, *GREEN_COLOR, *GREEN_COLOR, *GREEN_COLOR, *BLUE_COLOR, *BLUE_COLOR, *BLUE_COLOR, *BLUE_COLOR, *RED_COLOR, *RED_COLOR, *RED_COLOR, *GREY_COLOR, *GREY_COLOR, *GREY_COLOR, *BROWN_COLOR, *BROWN_COLOR, *BROWN_COLOR, *BROWN_COLOR, //Object 2 colors *RED_COLOR, *RED_COLOR, *RED_COLOR, *RED_COLOR, *BROWN_COLOR, *BROWN_COLOR, *BROWN_COLOR, *BROWN_COLOR, *BLUE_COLOR, *BLUE_COLOR, *BLUE_COLOR, *BLUE_COLOR, *GREEN_COLOR, *GREEN_COLOR, *GREEN_COLOR, *GREY_COLOR, *GREY_COLOR, *GREY_COLOR, *GREY_COLOR) val indexData = shortBufferOf( 0, 2, 1, 3, 2, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 11, 13, 12, 14, 16, 15, 17, 16, 14) }
mit
76689d019ddb53db0f7fae2118a97082
26.429078
100
0.562064
3.982492
false
false
false
false
ontherunvaro/adb-awake
studio/app/src/main/java/nl/renedegroot/android/adbawake/AppModule.kt
2
921
package nl.renedegroot.android.adbawake import dagger.Module import dagger.Provides import nl.renedegroot.android.adbawake.providers.PowerManagerProvider import nl.renedegroot.android.adbawake.providers.SharedPreferencesProvider import nl.renedegroot.android.adbawake.providers.SystemTextProvider import nl.renedegroot.android.adbawake.businessmodel.LockControl import nl.renedegroot.android.adbawake.businessmodel.Preferences import javax.inject.Singleton @Module class AppModule { @Provides fun systemTextProvider(): SystemTextProvider = SystemTextProvider() @Provides fun sharedPreferencesProvider(): SharedPreferencesProvider = SharedPreferencesProvider() @Provides fun powerManagerProvider(): PowerManagerProvider = PowerManagerProvider() @Provides fun preferences(): Preferences = Preferences() @Provides @Singleton fun lockControl(): LockControl = LockControl() }
gpl-3.0
74abe2602dd8e89cf46b7386813ed7c3
29.733333
92
0.809989
5.323699
false
false
false
false
a642500/Ybook
app/src/main/kotlin/com/ybook/app/net/NetConfigure.kt
1
1074
/* Copyright 2015 Carlos 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.ybook.app.net import java.net.InetAddress /** * Created by carlos on 11/12/14. */ val MSG_ERROR = 0 val MSG_SUCCESS = 1 val MSG_PASSWORD_WRONG = 2 val MSG_ONE_SEARCH_RESULT = 3 val oldUrl = "http://whitepanda.org:2333"//TODO add url fun getMainUrl(): String? { try { val s = "http://" + InetAddress.getByName("www.ybook.me").getHostAddress() + ":2333" return s } catch (e: Exception) { e.printStackTrace() } return null }
apache-2.0
647a08e1b752a47e3f70f78d02f722b3
24.571429
92
0.68622
3.877256
false
false
false
false
androidx/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/FlowDslDemo.kt
2
7647
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstrainedLayoutReference import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintLayoutBaseScope import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Dimension import androidx.constraintlayout.compose.FlowStyle import androidx.constraintlayout.compose.LayoutReference import androidx.constraintlayout.compose.Wrap import java.util.Arrays @Preview(group = "flow1") @Composable public fun FlowDslDemo1() { // Currently, we still have problem with positioning the Flow Helper // and/or setting the width/height properly. ConstraintLayout( ConstraintSet { val a = createRefFor("1") val b = createRefFor("2") val c = createRefFor("3") val d = createRefFor("4") val g1 = createFlow(a, b, c, d) constrain(g1) { centerVerticallyTo(parent) centerHorizontallyTo(parent) } }, modifier = Modifier.fillMaxSize() ) { val numArray = arrayOf("1", "2", "3", "4") for (num in numArray) { Button( modifier = Modifier.layoutId(num), onClick = {}, ) { Text(text = num) } } } } @Preview(group = "flow2") @Composable public fun FlowDslDemo2() { ConstraintLayout( ConstraintSet { val a = createRefFor("1") val b = createRefFor("2") val c = createRefFor("3") val d = createRefFor("4") val g1 = createFlow( a, b, c, d, flowVertically = true ) constrain(g1) { centerVerticallyTo(parent) centerHorizontallyTo(parent) } }, modifier = Modifier.fillMaxSize() ) { val numArray = arrayOf("1", "2", "3", "4") for (num in numArray) { Button( modifier = Modifier.layoutId(num), onClick = {}, ) { Text(text = num) } } } } @Preview(group = "flow3") @Composable public fun FlowDslDemo3() { val numArray = arrayOf("1", "2", "3", "4", "5", "6", "7") ConstraintLayout( ConstraintSet { val elem = arrayOfNulls<LayoutReference>(numArray.size) for (i in numArray.indices) { elem[i] = createRefFor(numArray[i]) } val g1 = createFlow( elements = *elem, flowVertically = true, padding = 30.dp, wrapMode = Wrap.Chain, verticalFlowBias = 0.1f, horizontalFlowBias = 0.8f, maxElement = 4, ) constrain(g1) { centerVerticallyTo(parent) centerHorizontallyTo(parent) } }, modifier = Modifier.fillMaxSize() ) { for (num in numArray) { Button( modifier = Modifier.layoutId(num), onClick = {}, ) { Text(text = num) } } } } @Preview(group = "flow4") @Composable public fun FlowDslDemo4() { val chArray = arrayOf("a", "b", "c", "d", "e", "f", "g", "h") ConstraintLayout( ConstraintSet { val elem = arrayOfNulls<LayoutReference>(chArray.size) for (i in chArray.indices) { elem[i] = createRefFor(chArray[i]) } val g1 = createFlow( elements = * elem, wrapMode = Wrap.None, verticalGap = 32.dp, horizontalGap = 32.dp, horizontalFlowBias = 0.8f, maxElement = 4, ) constrain(g1) { centerVerticallyTo(parent) centerHorizontallyTo(parent) } }, modifier = Modifier.fillMaxSize() ) { for (ch in chArray) { Button( modifier = Modifier.layoutId(ch), onClick = {}, ) { Text(text = ch) } } } } @Preview(group = "flow5") @Composable public fun FlowDslDemo5() { ConstraintLayout( modifier = Modifier .fillMaxSize() ) { val (a, b, c, d) = createRefs() val g1 = createFlow(a, b, c, d, horizontalGap = 20.dp) constrain(g1) { centerVerticallyTo(parent) centerHorizontallyTo(parent) } Button( modifier = Modifier.constrainAs(a) {}, onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Button( modifier = Modifier.constrainAs(b) {}, onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Button( modifier = Modifier.constrainAs(c) {}, onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Button( modifier = Modifier.constrainAs(d) {}, onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } } } // verticalStyle and horizontalStyle don't work properly // Need to figure out the the reason. @Preview(group = "flow-invalid") @Composable public fun FlowDslDemo6() { val numArray = arrayOf("1", "2", "3", "4", "5", "6", "7") ConstraintLayout( ConstraintSet { val elem = arrayOfNulls<LayoutReference>(numArray.size) for (i in numArray.indices) { elem[i] = createRefFor(numArray[i]) } val g1 = createFlow( elements = *elem, flowVertically = true, wrapMode = Wrap.Aligned, verticalStyle = FlowStyle.Packed, horizontalStyle = FlowStyle.Packed, maxElement = 2, ) constrain(g1) { width = Dimension.matchParent height = Dimension.matchParent } }, modifier = Modifier.fillMaxSize() ) { for (num in numArray) { Button( modifier = Modifier.layoutId(num), onClick = {}, ) { Text(text = num) } } } }
apache-2.0
6b38a1474c58afddbc799a216b8f8754
26.606498
75
0.53485
4.72037
false
false
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/BoostedCandyChannels.kt
1
325
package net.perfectdreams.loritta.cinnamon.pudding.tables import org.jetbrains.exposed.dao.id.LongIdTable object BoostedCandyChannels : LongIdTable() { val user = reference("user", Profiles) val guildId = long("guild") val channelId = long("channel") val givenAt = long("given_at") val expiresAt = long("expires_at") }
agpl-3.0
27fc9931f3d162ee429172b2e385f038
28.636364
57
0.753846
3.421053
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/TerminatorCommand.kt
1
3377
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.utils.extensions.drawStringWithOutline import net.perfectdreams.loritta.common.commands.ArgumentType import net.perfectdreams.loritta.common.utils.extensions.enableFontAntiAliasing import net.perfectdreams.loritta.common.utils.image.JVMImage import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.vanilla.images.base.ImageAbstractCommandBase import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils import java.awt.Color import java.awt.Font import java.awt.image.BufferedImage import java.io.File class TerminatorCommand(m: LorittaBot) : ImageAbstractCommandBase( m, listOf("terminator", "animeterminator", "terminatoranime") ) { override fun command() = create { localizedDescription("commands.command.terminator.description") localizedExamples("commands.command.terminator.examples") usage { argument(ArgumentType.TEXT) {} } needsToUploadFiles = true executes { OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "terminatoranime") // TODO: Multiplatform loritta as LorittaBot val args = args.joinToString(" ") val split = args.split("|") if (2 > split.size) { explain() return@executes } val mppImage = validate(image(0)) mppImage as JVMImage val mppTerminatorAnime = loritta.assets.loadImage("terminator_anime.png", loadFromCache = true) val terminatorAnime = (mppTerminatorAnime as JVMImage).handle as BufferedImage val input1 = split[0] val input2 = split[1] val graphics = terminatorAnime.createGraphics() graphics.enableFontAntiAliasing() val lato = Font.createFont(Font.TRUETYPE_FONT, File(LorittaBot.ASSETS, "fonts/Lato-Bold.ttf")) val font = lato.deriveFont(24f) graphics.color = Color(255, 251, 0) graphics.font = font fun drawTextCentralizedNewLines(text: String, startAtX: Int, startAtY: Int) { var startAtX = startAtX var startAtY = startAtY val splitInput1 = text.split("((?<= )|(?= ))".toRegex()).dropLastWhile { it.isEmpty() } var input1FitInLine = "" for (split in splitInput1) { val old = input1FitInLine input1FitInLine += split println("${startAtX - (graphics.getFontMetrics(font).stringWidth(old) / 2)}") if (0 >= startAtX - (graphics.getFontMetrics(font).stringWidth(input1FitInLine) / 2) || startAtX + (graphics.getFontMetrics(font).stringWidth(input1FitInLine) / 2) >= terminatorAnime.width) { println((graphics.getFontMetrics(font).stringWidth(old))) val drawAtX = startAtX - (graphics.getFontMetrics(font).stringWidth(old) / 2) graphics.drawStringWithOutline(old, drawAtX, startAtY, Color.BLACK, 2) startAtY += 26 input1FitInLine = "" input1FitInLine += split } } val drawAtX = startAtX - (graphics.getFontMetrics(font).stringWidth(input1FitInLine) / 2) graphics.drawStringWithOutline(input1FitInLine, drawAtX, startAtY, Color.BLACK, 2) } val centerInput1X = 98 val centerInput1Y = 138 val centerInput2X = 286 val centerInput2Y = 254 drawTextCentralizedNewLines(input1, centerInput1X, centerInput1Y) drawTextCentralizedNewLines(input2, centerInput2X, centerInput2Y) sendImage(JVMImage(terminatorAnime), "terminator_anime.png") } } }
agpl-3.0
fb8b5939cd53fe3d4a705a2a10a8c762
33.469388
196
0.745928
3.890553
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/forum/PostAdapter.kt
1
5306
package me.proxer.app.forum import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.view.ViewCompat import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.LayoutManager import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.jakewharton.rxbinding3.view.clicks import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import com.uber.autodispose.autoDisposable import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import kotterknife.bindView import me.proxer.app.GlideRequests import me.proxer.app.R import me.proxer.app.base.AutoDisposeViewHolder import me.proxer.app.base.BaseAdapter import me.proxer.app.forum.PostAdapter.ViewHolder import me.proxer.app.ui.view.bbcode.BBCodeView import me.proxer.app.util.extension.distanceInWordsToNow import me.proxer.app.util.extension.logErrors import me.proxer.app.util.extension.mapBindingAdapterPosition import me.proxer.app.util.extension.setIconicsImage import me.proxer.library.util.ProxerUrls import java.util.concurrent.ConcurrentHashMap /** * @author Ruben Gees */ class PostAdapter : BaseAdapter<ParsedPost, ViewHolder>() { var glide: GlideRequests? = null val profileClickSubject: PublishSubject<Pair<ImageView, ParsedPost>> = PublishSubject.create() private val heightMap = ConcurrentHashMap<String, Int>() private var layoutManager: LayoutManager? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_post, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(data[position]) } override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { layoutManager = recyclerView.layoutManager } override fun onViewRecycled(holder: ViewHolder) { glide?.clear(holder.image) holder.post.destroyWithRetainingViews() holder.signature.destroyWithRetainingViews() } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { layoutManager = null glide = null } inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) { internal val userContainer by bindView<ViewGroup>(R.id.userContainer) internal val image by bindView<ImageView>(R.id.image) internal val user by bindView<TextView>(R.id.user) internal val post by bindView<BBCodeView>(R.id.post) internal val signatureDivider by bindView<View>(R.id.signatureDivider) internal val signature by bindView<BBCodeView>(R.id.signature) internal val date by bindView<TextView>(R.id.date) internal val thankYouIcon by bindView<ImageView>(R.id.thankYouIcon) internal val thankYou by bindView<TextView>(R.id.thankYou) init { post.glide = glide post.enableEmotions = true post.heightMap = heightMap signature.glide = glide signature.enableEmotions = true signature.heightMap = heightMap thankYouIcon.setIconicsImage(CommunityMaterial.Icon3.cmd_thumb_up, 32) } fun bind(item: ParsedPost) { userContainer.clicks() .mapBindingAdapterPosition({ bindingAdapterPosition }) { image to data[it] } .autoDisposable(this) .subscribe(profileClickSubject) Observable.merge(post.heightChanges.map { post }, signature.heightChanges.map { signature }) .autoDisposable(this) .subscribe { it.requestLayout() layoutManager?.requestSimpleAnimationsInNextLayout() } ViewCompat.setTransitionName(image, "post_${item.id}") user.text = item.username date.text = item.date.distanceInWordsToNow(date.context) thankYou.text = item.thankYouAmount.toString() post.userId = item.userId post.tree = item.parsedMessage item.signature.let { signature.userId = item.userId if (it == null) { signatureDivider.isGone = true signature.isGone = true signature.tree = null } else { signatureDivider.isVisible = true signature.isVisible = true signature.tree = it } } bindImage(item) } private fun bindImage(item: ParsedPost) { if (item.image.isBlank()) { image.setIconicsImage(CommunityMaterial.Icon.cmd_account, 32, 4, R.attr.colorSecondary) } else { glide?.load(ProxerUrls.userImage(item.image).toString()) ?.transition(DrawableTransitionOptions.withCrossFade()) ?.circleCrop() ?.logErrors() ?.into(image) } } } }
gpl-3.0
6fed0f024c974a30d306e369cb586a70
36.104895
105
0.671127
4.88582
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/adapters/ForceStopAppsAdapter.kt
1
2259
package com.androidvip.hebf.adapters import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.CompoundButton import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.androidvip.hebf.R import com.androidvip.hebf.models.App class ForceStopAppsAdapter(private val activity: Activity, private val apps: List<App>) : RecyclerView.Adapter<ForceStopAppsAdapter.ViewHolder>() { val selectedApps: MutableSet<App> = mutableSetOf() class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { var label: TextView = v.findViewById(R.id.app_nome) var icon: ImageView = v.findViewById(R.id.icon) var checkBox: CheckBox = v.findViewById(R.id.force_stop_apps_check) init { setIsRecyclable(false) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(activity).inflate(R.layout.list_item_small_app, parent, false) return ViewHolder(v).apply { setIsRecyclable(false) } } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val app = apps[holder.adapterPosition] fun selectionChange(isChecked: Boolean) { if (isChecked) { selectedApps.add(app) } else { selectedApps.remove(app) } app.isChecked = isChecked } holder.checkBox.setOnCheckedChangeListener(null) if (app.isChecked) { holder.checkBox.isChecked = true selectedApps.add(app) } else { holder.checkBox.isChecked = false selectedApps.remove(app) } holder.checkBox.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean -> selectionChange(isChecked) } holder.itemView.setOnClickListener { selectionChange(!holder.checkBox.isChecked) } holder.label.text = app.label holder.icon.setImageDrawable(app.icon) } override fun getItemCount(): Int { return apps.size } }
apache-2.0
cd5041345af740d485285de3158a59cf
30.388889
147
0.660912
4.629098
false
false
false
false