repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Rin-Da/UCSY-News
|
app/src/main/java/io/github/rin_da/ucsynews/presentation/base/view/login_utils.kt
|
1
|
2070
|
package io.github.rin_da.ucsynews.presentation.base.view
import android.content.ActivityNotFoundException
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import io.github.rin_da.ucsynews.presentation.login.activity.GOOGLE_SIGN_IN
/**
* Created by user on 12/13/16.
*/
internal fun AppCompatActivity.downloadGooglePlay() {
val appPackageName = GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)))
} catch (anfe: ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)))
}
}
internal fun AppCompatActivity.isGooglePlayServicesAvailable(): Boolean {
val apiAvailability = GoogleApiAvailability.getInstance()
val connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(this)
return connectionStatusCode == ConnectionResult.SUCCESS
}
/**
* Attempt to resolve a missing, out-of-date, invalid or disabled Google
* Play Services installation via a user dialog, if possible.
*/
internal fun AppCompatActivity.acquireGooglePlayServices() {
val apiAvailability = GoogleApiAvailability.getInstance()
val connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(this)
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode)
}
}
internal fun AppCompatActivity.showGooglePlayServicesAvailabilityErrorDialog(
connectionStatusCode: Int) {
val apiAvailability = GoogleApiAvailability.getInstance()
val dialog = apiAvailability.getErrorDialog(
this,
connectionStatusCode,
GOOGLE_SIGN_IN, DialogInterface.OnCancelListener { v -> finish() })
dialog.show()
}
|
mit
|
2b4303e0c0098bbc681d2f54443792a3
| 38.807692 | 126 | 0.778744 | 4.870588 | false | false | false | false |
fashare2015/MVVM-JueJin
|
app/src/main/kotlin/com/fashare/mvvm_juejin/view/detail/ArticleActivity.kt
|
1
|
5313
|
package com.fashare.mvvm_juejin.view.detail
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.webkit.WebView
import com.fashare.adapter.OnItemClickListener
import com.fashare.adapter.ViewHolder
import com.fashare.base_ui.BaseActivity
import com.fashare.mvvm_juejin.JueJinApp
import com.fashare.mvvm_juejin.R
import com.fashare.mvvm_juejin.databinding.ActivityArticleBinding
import com.fashare.mvvm_juejin.model.BannerListBean
import com.fashare.mvvm_juejin.model.article.ArticleBean
import com.fashare.mvvm_juejin.model.notify.NotifyBean
import com.fashare.mvvm_juejin.repo.Composers
import com.fashare.mvvm_juejin.repo.JueJinApis
import com.fashare.mvvm_juejin.viewmodel.ArticleVM
import com.fashare.net.ApiFactory
import kotlinx.android.synthetic.main.g_two_way_list.*
import java.io.*
class ArticleActivity : BaseActivity() {
companion object{
private val PARAMS_ARTICLE_ID = "PARAMS_ARTICLE_ID"
val LOCAL_TEMPLATE by lazy{
openAssets(JueJinApp.instance, "www/template.html")?: ""
}
val LOCAL_CSS by lazy{
com.daimajia.gold.utils.d.b.a(com.daimajia.gold.utils.g.b())
}
val LOCAL_JS by lazy{
com.daimajia.gold.utils.d.b.b(com.daimajia.gold.utils.g.c())
}
fun openAssets(context: Context, filePath: String): String? {
try {
return openAssets(context.resources.assets.open(filePath))
} catch (e: IOException) {
e.printStackTrace()
return null
}
}
@Throws(IOException::class)
fun openAssets(inputStream: InputStream): String {
val stringWriter = StringWriter()
val cArr = CharArray(2048)
try {
val bufferedReader = BufferedReader(InputStreamReader(inputStream, "utf-8"))
while (true) {
val read = bufferedReader.read(cArr)
if (read == -1) {
break
}
stringWriter.write(cArr, 0, read)
}
return stringWriter.toString()
} finally {
inputStream.close()
}
}
fun start(from: Context, article: ArticleBean?){
Intent(from, ArticleActivity::class.java)
.putExtra(PARAMS_ARTICLE_ID, article?: ArticleBean("", "")).apply {
from.startActivity(this)
}
}
val START = object : OnItemClickListener<ArticleBean>() {
override fun onItemClick(holder: ViewHolder, data: ArticleBean, position: Int) {
ArticleActivity.start(holder.itemView.context, data)
}
}
val START_FROM_NOTIFY = object : OnItemClickListener<NotifyBean>() {
override fun onItemClick(holder: ViewHolder, data: NotifyBean, position: Int) {
ArticleActivity.start(holder.itemView.context, data.entry?.toArticle())
}
}
val START_FROM_BANNER = object : OnItemClickListener<BannerListBean.Item>() {
override fun onItemClick(holder: ViewHolder, data: BannerListBean.Item, position: Int) {
ArticleActivity.start(holder.itemView.context, data.toArticle())
}
}
}
lateinit var binding : ActivityArticleBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DataBindingUtil.setContentView<ActivityArticleBinding>(this, R.layout.activity_article).apply{
binding = this
this.articleVM = ArticleVM(rv)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true)
}
val article = intent?.getSerializableExtra(PARAMS_ARTICLE_ID) as ArticleBean
loadArticleHtml(article)
}
private fun loadArticleHtml(article: ArticleBean) {
binding.articleVM.article.set(article)
binding.articleVM.headerData.article.set(article)
ApiFactory.getApi(JueJinApis.Article.Html::class.java)
.getHtml(article.objectId?: "")
.compose(Composers.handleError())
.subscribe({
// 以下代码来自反编译的掘金app
var template = LOCAL_TEMPLATE
var screenshot = article.screenshot?: ""
if (TextUtils.isEmpty(template)) {
template = "<h1>404</h1>"
} else {
template = template.replace("{gold-toolbar-height}", "0px")
.replace("{gold-css-js}", LOCAL_CSS)
.replace("{gold-js-replace}", LOCAL_JS)
.replace("{gold-header}", com.daimajia.gold.utils.d.b.a(screenshot, article.originalUrl, article.title, article.user?.username?: ""))
.replace("{gold-content}", it.content?: "")
}
binding.articleVM.headerData.html.set(template)
}, {})
}
}
|
mit
|
87941e3190366ed6808bb97e59be5484
| 37.889706 | 165 | 0.599357 | 4.345933 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/test/java/org/wordpress/android/ui/posts/prepublishing/home/usecases/GetButtonUiStateUseCaseTest.kt
|
1
|
4474
|
package org.wordpress.android.ui.posts.prepublishing.home.usecases
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.post.PostStatus.DRAFT
import org.wordpress.android.ui.posts.EditPostRepository
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ButtonUiState.PublishButtonUiState
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ButtonUiState.SaveButtonUiState
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ButtonUiState.ScheduleButtonUiState
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ButtonUiState.SubmitButtonUiState
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ButtonUiState.UpdateButtonUiState
import org.wordpress.android.ui.posts.editor.EditorActionsProvider
import org.wordpress.android.ui.posts.editor.PrimaryEditorAction.CONTINUE
import org.wordpress.android.ui.posts.editor.PrimaryEditorAction.PUBLISH_NOW
import org.wordpress.android.ui.posts.editor.PrimaryEditorAction.SAVE
import org.wordpress.android.ui.posts.editor.PrimaryEditorAction.SCHEDULE
import org.wordpress.android.ui.posts.editor.PrimaryEditorAction.SUBMIT_FOR_REVIEW
import org.wordpress.android.ui.posts.editor.PrimaryEditorAction.UPDATE
import org.wordpress.android.ui.uploads.UploadUtilsWrapper
class GetButtonUiStateUseCaseTest : BaseUnitTest() {
private lateinit var useCase: GetButtonUiStateUseCase
@Mock lateinit var editorActionsProvider: EditorActionsProvider
@Mock lateinit var uploadUtilsWrapper: UploadUtilsWrapper
@Mock lateinit var editPostRepository: EditPostRepository
@Mock lateinit var site: SiteModel
@Before
fun setup() {
useCase = GetButtonUiStateUseCase(editorActionsProvider, uploadUtilsWrapper)
whenever(editPostRepository.status).thenReturn(DRAFT)
}
@Test
fun `verify that PUBLISH_NOW EditorAction returns PublishButtonUiState`() {
// arrange
whenever(editorActionsProvider.getPrimaryAction(any(), any(), any())).thenReturn(PUBLISH_NOW)
// act
val uiState = useCase.getUiState(editPostRepository, mock()) {}
// assert
assertThat(uiState).isInstanceOf(PublishButtonUiState::class.java)
}
@Test
fun `verify that SCHEDULE EditorAction returns ScheduleButtonUiState`() {
// arrange
whenever(editorActionsProvider.getPrimaryAction(any(), any(), any())).thenReturn(SCHEDULE)
// act
val uiState = useCase.getUiState(editPostRepository, mock()) {}
// assert
assertThat(uiState).isInstanceOf(ScheduleButtonUiState::class.java)
}
@Test
fun `verify that UPDATE EditorAction returns UpdateButtonUiState`() {
// arrange
whenever(editorActionsProvider.getPrimaryAction(any(), any(), any())).thenReturn(UPDATE)
// act
val uiState = useCase.getUiState(editPostRepository, mock()) {}
// assert
assertThat(uiState).isInstanceOf(UpdateButtonUiState::class.java)
}
@Test
fun `verify that CONTINUE EditorAction returns UpdateButtonUiState`() {
// arrange
whenever(editorActionsProvider.getPrimaryAction(any(), any(), any())).thenReturn(CONTINUE)
// act
val uiState = useCase.getUiState(editPostRepository, mock()) {}
// assert
assertThat(uiState).isInstanceOf(UpdateButtonUiState::class.java)
}
@Test
fun `verify that SUBMIT_FOR_REVIEW EditorAction returns SubmitButtonUiState`() {
// arrange
whenever(editorActionsProvider.getPrimaryAction(any(), any(), any())).thenReturn(SUBMIT_FOR_REVIEW)
// act
val uiState = useCase.getUiState(editPostRepository, mock()) {}
// assert
assertThat(uiState).isInstanceOf(SubmitButtonUiState::class.java)
}
@Test
fun `verify that SAVE EditorAction returns SaveButtonUiState`() {
// arrange
whenever(editorActionsProvider.getPrimaryAction(any(), any(), any())).thenReturn(SAVE)
// act
val uiState = useCase.getUiState(editPostRepository, mock()) {}
// assert
assertThat(uiState).isInstanceOf(SaveButtonUiState::class.java)
}
}
|
gpl-2.0
|
dfdd3ce17e2b38326ff10fcbc4c783fe
| 38.946429 | 107 | 0.748547 | 4.841991 | false | true | false | false |
LittleLightCz/SheepsGoHome
|
core/src/com/sheepsgohome/steerable/SteerableHungryWolfBody.kt
|
1
|
2875
|
package com.sheepsgohome.steerable
import com.badlogic.gdx.ai.steer.behaviors.FollowPath
import com.badlogic.gdx.ai.steer.behaviors.Pursue
import com.badlogic.gdx.ai.steer.utils.paths.LinePath
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Body
import com.badlogic.gdx.utils.Array
import com.sheepsgohome.gameobjects.HungryWolf
import com.sheepsgohome.gameobjects.Sheep
import com.sheepsgohome.shared.GameData.CAMERA_HEIGHT
import com.sheepsgohome.shared.GameData.CAMERA_WIDTH
class SteerableHungryWolfBody(wolfBody: Body, private val sheep: Sheep) : SteerableBody(wolfBody) {
private val steeringPursue = Pursue(this, sheep.steerableBody).apply {
isEnabled = true
}
private val steeringFollowPath: FollowPath<Vector2, LinePath.LinePathParam>
private val huntDistance = 70f
init {
val waypoints = generateWaypoints(5)
val linePath = LinePath(waypoints)
steeringFollowPath = FollowPath(this, linePath).apply {
isEnabled = true
pathOffset = 10f
}
maxLinearAcceleration = HungryWolf.HUNGRY_WOLF_SPEED
maxLinearSpeed = HungryWolf.HUNGRY_WOLF_SPEED
}
private fun generateWaypoints(count: Int): Array<Vector2> {
var failures = 0
val waypoints = Array<Vector2>()
val minimumDistance = 20f
for (i in 1..count) {
if (waypoints.size == 0) {
waypoints.add(generateRandomVector())
} else {
val vec = generateRandomVector()
while (findMinimumDistance(waypoints, vec) < minimumDistance) {
failures++
if (failures > 5) {
break
}
}
waypoints.add(vec)
}
}
return waypoints
}
private fun findMinimumDistance(waypoints: Array<Vector2>, vec: Vector2): Float {
return waypoints.asSequence()
.map { it.dst(vec) }
.min() ?: Float.MAX_VALUE
}
private fun generateRandomVector(): Vector2 {
val vec = Vector2()
vec.x = (Math.random() * CAMERA_WIDTH - CAMERA_WIDTH / 2f).toFloat()
vec.y = (Math.random() * CAMERA_HEIGHT - CAMERA_HEIGHT / 2f).toFloat()
return vec
}
override fun calculateSteeringBehaviour() {
val sheepPosition = sheep.steerableBody.position
val distance = body.position.dst(sheepPosition)
if (distance < huntDistance) {
//Hunt the sheep
steeringPursue.maxPredictionTime = distance / 40f
steeringPursue.calculateSteering(steeringAcceleration)
} else {
//Wander
steeringFollowPath.calculateSteering(steeringAcceleration)
}
body.linearVelocity = steeringAcceleration.linear
}
}
|
gpl-3.0
|
989c1113ccea93a2408bf804a6e4d931
| 30.944444 | 99 | 0.630957 | 4.178779 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/j2k/old/tests/testData/fileOrElement/detectProperties/FieldUsagesInFactoryMethods.kt
|
13
|
355
|
internal class C(val arg1: Int) {
var arg2: Int = 0
var arg3: Int = 0
constructor(arg1: Int, arg2: Int, arg3: Int) : this(arg1) {
this.arg2 = arg2
this.arg3 = arg3
}
constructor(arg1: Int, arg2: Int) : this(arg1) {
this.arg2 = arg2
arg3 = 0
}
init {
arg2 = 0
arg3 = 0
}
}
|
apache-2.0
|
8cad6bae6249234671810b5e4d3b2a2f
| 17.684211 | 63 | 0.490141 | 2.886179 | false | false | false | false |
byu-oit/android-byu-suite-v2
|
support/src/main/java/edu/byu/support/payment/controller/PaymentReviewActivity.kt
|
2
|
2291
|
package edu.byu.support.payment.controller
import android.app.AlertDialog
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import edu.byu.support.R
import edu.byu.support.activity.ByuActivity
import edu.byu.support.payment.model.PaymentAccount
import edu.byu.support.utils.orFalse
import edu.byu.support.utils.setPositiveButton
import kotlinx.android.synthetic.main.payment_method_list_item.*
import kotlinx.android.synthetic.main.payment_review_activity.*
/**
* Created by geogor37 on 2/16/18
*/
abstract class PaymentReviewActivity: ByuActivity() {
companion object {
const val PAYMENT_ACCOUNT_TAG = "paymentAccount"
const val PAYMENT_VALUE_TAG = "charges"
}
protected var paymentAccount: PaymentAccount? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.payment_review_activity)
makePaymentHeader.findViewById<TextView>(R.id.textView).text = getString(R.string.make_payment_header)
withAccountHeader.findViewById<TextView>(R.id.textView).text = getString(R.string.with_account_header)
termsAndConditionsHeader.findViewById<TextView>(R.id.textView).text = getString(R.string.terms_and_conditions_header)
paymentTypeLayout.findViewById<ImageView>(R.id.listIndicatorImage).visibility = View.GONE
cancelButton.setOnClickListener { onBackPressed() }
payNowButton.setOnClickListener { onPayNow() }
paymentAccount = intent.getParcelableExtra(PAYMENT_ACCOUNT_TAG)
accountNickNameText.text = paymentAccount?.nickname
financialInstitutionText.text = paymentAccount?.financialInstitution
accountNumberText.text = paymentAccount?.getFormattedAccountNumber()
accountTypeImage.setImageResource(paymentAccount?.getImage() ?: R.drawable.icon_bank)
processingFeeText.visibility = if (paymentAccount?.isCreditCard().orFalse()) View.VISIBLE else View.GONE
startPayment()
}
private fun onPayNow() {
AlertDialog.Builder(this)
.setTitle("Confirm Payment")
.setMessage("I agree to the terms and conditions")
.setPositiveButton { _, _ -> completePayment() }
.setNegativeButton(android.R.string.no, null)
.show()
}
abstract fun startPayment()
abstract fun completePayment()
abstract fun backToMain()
}
|
apache-2.0
|
8f802b6d6eb175a3b9bf2dba8eafbae5
| 35.967742 | 119 | 0.79354 | 3.896259 | false | false | false | false |
Major-/Vicis
|
common/src/main/kotlin/rs/emulate/common/config/varbit/VarbitDefinitionDecoder.kt
|
1
|
1114
|
package rs.emulate.common.config.varbit
import io.netty.buffer.ByteBuf
import rs.emulate.common.config.Config
import rs.emulate.common.config.ConfigDecoder
import rs.emulate.util.readAsciiString
object VarbitDefinitionDecoder : ConfigDecoder<VarbitDefinition> {
override fun decode(id: Int, buffer: ByteBuf): VarbitDefinition {
val definition = VarbitDefinition(id)
var opcode = buffer.readUnsignedByte().toInt()
while (opcode != Config.DEFINITION_TERMINATOR) {
definition.decode(buffer, opcode)
opcode = buffer.readUnsignedByte().toInt()
}
return definition
}
private fun VarbitDefinition.decode(buffer: ByteBuf, opcode: Int) {
when (opcode) {
1 -> {
varp = buffer.readUnsignedShort()
low = buffer.readUnsignedByte().toInt()
high = buffer.readUnsignedByte().toInt()
}
3 -> buffer.readUnsignedInt()
4 -> buffer.readUnsignedInt()
5 -> /* unused */ return
10 -> buffer.readAsciiString()
}
}
}
|
isc
|
311a8db58e2b2662f492247cd69253df
| 29.944444 | 71 | 0.61939 | 4.603306 | false | true | false | false |
ianhanniballake/ContractionTimer
|
mobile/src/main/java/com/ianhanniballake/contractiontimer/appwidget/ControlAppWidgetProvider.kt
|
1
|
8089
|
package com.ianhanniballake.contractiontimer.appwidget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.preference.PreferenceManager
import android.provider.BaseColumns
import android.text.format.DateUtils
import android.util.Log
import android.view.View
import android.widget.RemoteViews
import com.ianhanniballake.contractiontimer.BuildConfig
import com.ianhanniballake.contractiontimer.R
import com.ianhanniballake.contractiontimer.extensions.closeable
import com.ianhanniballake.contractiontimer.extensions.goAsync
import com.ianhanniballake.contractiontimer.provider.ContractionContract
import com.ianhanniballake.contractiontimer.ui.MainActivity
import com.ianhanniballake.contractiontimer.ui.Preferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Handles updates of the 'Control' style App Widgets
*/
class ControlAppWidgetProvider : AppWidgetProvider() {
companion object {
private const val TAG = "CtrlAppWidgetProvider"
/**
* Identifier for this widget to be used in Analytics
*/
private const val WIDGET_IDENTIFIER = "widget_control"
internal suspend fun updateControlAppWidget(
context: Context,
appWidgetIds: IntArray? = null
) = withContext(Dispatchers.IO) {
if (BuildConfig.DEBUG)
Log.d(TAG, "Updating Control App Widgets")
val projection = arrayOf(BaseColumns._ID,
ContractionContract.Contractions.COLUMN_NAME_START_TIME,
ContractionContract.Contractions.COLUMN_NAME_END_TIME)
val selection = ContractionContract.Contractions.COLUMN_NAME_START_TIME + ">?"
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
val appwidgetBackground = preferences.getString(
Preferences.APPWIDGET_BACKGROUND_PREFERENCE_KEY,
context.getString(R.string.pref_appwidget_background_default))
val views = if (appwidgetBackground == "light")
RemoteViews(context.packageName, R.layout.control_appwidget_light)
else
RemoteViews(context.packageName, R.layout.control_appwidget_dark)
// Add the intent to the Application Launch button
val applicationLaunchIntent = Intent(context, MainActivity::class.java).apply {
putExtra(MainActivity.LAUNCHED_FROM_WIDGET_EXTRA, WIDGET_IDENTIFIER)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
val applicationLaunchPendingIntent = PendingIntent.getActivity(context, 0,
applicationLaunchIntent, PendingIntent.FLAG_UPDATE_CURRENT)
views.setOnClickPendingIntent(R.id.application_launch, applicationLaunchPendingIntent)
val averagesTimeFrame = preferences.getString(
Preferences.AVERAGE_TIME_FRAME_PREFERENCE_KEY,
context.getString(R.string.pref_average_time_frame_default))!!.toLong()
val timeCutoff = System.currentTimeMillis() - averagesTimeFrame
val selectionArgs = arrayOf(timeCutoff.toString())
context.contentResolver.query(ContractionContract.Contractions.CONTENT_URI, projection,
selection, selectionArgs, null)?.closeable()?.use { data ->
// Set the average duration and frequency
if (data.moveToFirst()) {
var averageDuration = 0.0
var averageFrequency = 0.0
var numDurations = 0
var numFrequencies = 0
while (!data.isAfterLast) {
val startTimeColumnIndex = data
.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME)
val startTime = data.getLong(startTimeColumnIndex)
val endTimeColumnIndex = data
.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_END_TIME)
if (!data.isNull(endTimeColumnIndex)) {
val endTime = data.getLong(endTimeColumnIndex)
val curDuration = endTime - startTime
averageDuration = (curDuration + numDurations * averageDuration) / (numDurations + 1)
numDurations++
}
if (data.moveToNext()) {
val prevContractionStartTimeColumnIndex = data
.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME)
val prevContractionStartTime = data.getLong(prevContractionStartTimeColumnIndex)
val curFrequency = startTime - prevContractionStartTime
averageFrequency = (curFrequency + numFrequencies * averageFrequency) / (numFrequencies + 1)
numFrequencies++
}
}
val averageDurationInSeconds = (averageDuration / 1000).toLong()
views.setTextViewText(R.id.average_duration, DateUtils.formatElapsedTime(averageDurationInSeconds))
val averageFrequencyInSeconds = (averageFrequency / 1000).toLong()
views.setTextViewText(R.id.average_frequency, DateUtils.formatElapsedTime(averageFrequencyInSeconds))
} else {
views.setTextViewText(R.id.average_duration, "")
views.setTextViewText(R.id.average_frequency, "")
}
}
// Set the status of the contraction toggle button
// Need to use a separate cursor as there could be running contractions
// outside of the average time frame
context.contentResolver.query(ContractionContract.Contractions.CONTENT_URI, projection,
null, null, null)?.closeable()?.use { allData ->
val contractionOngoing = (allData.moveToFirst() &&
allData.isNull(allData.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_END_TIME)))
val toggleContractionIntent = Intent(context, AppWidgetToggleReceiver::class.java).apply {
putExtra(AppWidgetToggleReceiver.WIDGET_NAME_EXTRA, WIDGET_IDENTIFIER)
}
val toggleContractionPendingIntent = PendingIntent.getBroadcast(context, 0,
toggleContractionIntent, PendingIntent.FLAG_UPDATE_CURRENT)
if (contractionOngoing) {
views.setViewVisibility(R.id.contraction_toggle_on, View.VISIBLE)
views.setOnClickPendingIntent(R.id.contraction_toggle_on, toggleContractionPendingIntent)
views.setViewVisibility(R.id.contraction_toggle_off, View.GONE)
} else {
views.setViewVisibility(R.id.contraction_toggle_off, View.VISIBLE)
views.setOnClickPendingIntent(R.id.contraction_toggle_off, toggleContractionPendingIntent)
views.setViewVisibility(R.id.contraction_toggle_on, View.GONE)
}
}
// Update the widgets
val appWidgetManager = AppWidgetManager.getInstance(context)
if (appWidgetIds != null)
appWidgetManager.updateAppWidget(appWidgetIds, views)
else
appWidgetManager.updateAppWidget(ComponentName(context, ControlAppWidgetProvider::class.java), views)
}
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) = goAsync {
updateControlAppWidget(context, appWidgetIds)
}
}
|
bsd-3-clause
|
fe5c3f4ff7986df5f435d408939e841a
| 53.655405 | 121 | 0.636543 | 5.567103 | false | false | false | false |
YutaKohashi/FakeLineApp
|
app/src/main/java/jp/yuta/kohashi/fakelineapp/utils/Util.kt
|
1
|
9171
|
package jp.yuta.kohashi.fakelineapp.utils
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.annotation.StringRes
import android.support.v4.content.FileProvider
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import jp.yuta.kohashi.fakelineapp.App
import jp.yuta.kohashi.fakelineapp.BuildConfig
import jp.yuta.kohashi.fakelineapp.Const
import java.io.File
import java.io.IOException
/**
* Author : yutakohashi
* Project name : FakeLineApp
* Date : 20 / 08 / 2017
*/
@SuppressLint("NewApi")
@Suppress("DEPRECATION")
object Util {
/**
* Drawableリソース取得
* @param id
* @return
*/
fun getString(@StringRes id: Int): String {
return App.sContext.resources.getString(id)
}
/**
* Drawableリソース取得
* @param id
* @return
*/
fun getDrawable(@DrawableRes id: Int): Drawable {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
App.sContext.resources.getDrawable(id, null)
else
App.sContext.resources.getDrawable(id)
}
/**
* colorリソース取得
* @param id
* @return
*/
fun getColor(@ColorRes id: Int): Int {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
App.sContext.resources.getColor(id, null)
else
App.sContext.resources.getColor(id)
}
/**
* Glideを使用してDrawableリソースをimageviewに適用
* @param id
* @param targetImageView
*/
fun setImageByGlide(@DrawableRes id: Int, targetImageView: ImageView) {
Glide.with(App.sContext).load(id).into(targetImageView)
}
fun setImageByGlide(uri: String, targetImageView: ImageView) {
strToUri(uri, "file")?.let { setImageByGlide(it, targetImageView) }
}
fun setImageByGlide(uri: Uri, targetImageView: ImageView) {
Glide.with(App.sContext).load(uri).into(targetImageView)
}
fun setImageByGlide(bmp: Bitmap, targetImageView: ImageView) {
Glide.with(App.sContext).load(bmp).into(targetImageView)
}
fun getDefaultImagePathFromImageName(imgName: String): String {
return getPathExternalStrage() + Const.PATH_IMAGES + imgName
}
fun getPathExternalStrage() = Environment.getExternalStorageDirectory().absolutePath.toString()
fun getUnixTime() = System.currentTimeMillis()
fun strToUri(target: String, protocol: String = ""): Uri? {
var parsed: Uri? = null
if (!TextUtils.isEmpty(protocol)) {
parsed = if (!target.contains(protocol + "://")) {
if (target.startsWith("/")) Uri.parse(protocol + "://" + target)
else Uri.parse(protocol + ":///" + target)
} else {
Uri.parse(target)
}
} else {
parsed = Uri.parse(target)
}
return parsed
}
fun imagePathToContentUri(path: String): Uri? {
return Util.strToUri(path, "file")?.let {
protocolFileToContent(it)
}
}
fun protocolFileToContent(uri: Uri): Uri? {
return uriToFile(uri)?.let {
FileProvider.getUriForFile(App.sContext, BuildConfig.APPLICATION_ID + ".fileprovider", it)
}
}
fun uriToFile(uri: Uri): File? {
if (!"file".equals(uri.scheme)) return null
else return File(Uri.parse(uri.toString()).path)
}
fun loadBitmapFromAssets(fileName: String): Bitmap? {
return try {
BitmapFactory.decodeStream(App.sContext.resources.assets.open(fileName))
} catch (e: IOException) {
null
} catch(e:OutOfMemoryError){
null
} catch(e:Exception){
null
}
}
fun textToClipBoard(text: String) {
//クリップボードに格納するItemを作成
val item = ClipData.Item(text)
//MIMETYPEの作成
val mimeType = arrayOfNulls<String>(1)
mimeType[0] = ClipDescription.MIMETYPE_TEXT_URILIST
//クリップボードに格納するClipDataオブジェクトの作成
val cd = ClipData(ClipDescription("text_data", mimeType), item)
//クリップボードにデータを格納
val cm = App.sContext.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
cm.primaryClip = cd
}
private val KEYBOARD_DETECT_BOTTOM_THRESHOLD_DP = 100f
fun isKeyboardShowing(view: View): Boolean {
val context = view.context ?: return false
val rootView = view.rootView ?: return false
val appRect = Rect()
rootView.getWindowVisibleDisplayFrame(appRect)
val screenHeight = context.getResources().displayMetrics.heightPixels
val bottomMargin = Math.abs(appRect.bottom - screenHeight)
val density = context.resources.displayMetrics.density
return bottomMargin > KEYBOARD_DETECT_BOTTOM_THRESHOLD_DP * density
}
}
//
//package jp.yuta.kohashi.fakelineapp.utils
//
//import android.annotation.SuppressLint
//import android.graphics.Bitmap
//import android.os.Build
//import android.support.annotation.ColorRes
//import android.support.annotation.DrawableRes
//import android.graphics.drawable.Drawable
//import android.net.Uri
//import android.os.Environment
//import com.bumptech.glide.Glide
//import android.widget.ImageView
//import com.bumptech.glide.load.DataSource
//import com.bumptech.glide.load.engine.GlideException
//import com.bumptech.glide.request.RequestListener
//import com.bumptech.glide.request.target.Target
//import jp.yuta.kohashi.fakelineapp.App
//import jp.yuta.kohashi.fakelineapp.Const
//
//
///**
// * Author : yutakohashi
// * Project name : FakeLineApp
// * Date : 20 / 08 / 2017
// */
//
//@SuppressLint("NewApi")
//object Util {
// /**
// * Drawableリソース取得
// * @param id
// * @return
// */
// fun getDrawable(@DrawableRes id: Int): Drawable {
// return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// App.sContext.resources.getDrawable(id, null)
// else
// App.sContext.resources.getDrawable(id)
// }
//
// /**
// * colorリソース取得
// * @param id
// * @return
// */
// fun getColor(@ColorRes id: Int): Int {
// return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
// App.sContext.resources.getColor(id, null)
// else
// App.sContext.resources.getColor(id)
// }
//
// /**
// * Glideを使用してDrawableリソースをimageviewに適用
// * @param id
// * @param targetImageView
// */
// fun setImageByGlide(@DrawableRes id: Int, targetImageView: ImageView) {
// Glide.with(App.sContext).load(id).into(targetImageView)
// }
//
// fun setImageByGlide(uri: String, targetImageView: ImageView, action: (() -> Unit?)? = null) {
// var fixUri = uri
// Uri.parse(fixUri)?.let {
// if (!uri.contains("file://") && uri.startsWith("/")) fixUri = "file://" + fixUri
// else if (!uri.contains("file://")) fixUri = "file:/" + fixUri
// setImageByGlide(Uri.parse(fixUri), targetImageView, action)
// }
// }
//
//// fun setImageByGlide(uri: Uri, targetImageView: ImageView) {
//// Glide.with(App.sContext).load(uri).into(targetImageView)
//// }
//
// fun setImageByGlide(bmp: Bitmap, targetImageView: ImageView) {
// Glide.with(App.sContext).load(bmp).into(targetImageView)
// }
//
//
// fun setImageByGlide(uri: Uri, targetImageView: ImageView, action: (() -> Unit?)? = null) {
// Glide.with(App.sContext).
// load(uri).
// listener(object : RequestListener<Drawable> {
// override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
// action?.invoke()
// return false
// }
//
// override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
// action?.invoke()
// return false
// }
// }).into(targetImageView)
// }
//
// fun getDefaultImagePathFromImageName(imgName: String): String {
// return getPathExternalStrage() + Const.PATH_IMAGES + imgName
// }
//
// fun getPathExternalStrage() = Environment.getExternalStorageDirectory().absolutePath.toString()
//
// fun getUnixTime() = System.currentTimeMillis()
//}
|
mit
|
f9c88bba843b02bd5a2a573ae82bd46c
| 31.208633 | 173 | 0.637328 | 3.877436 | false | false | false | false |
GunoH/intellij-community
|
platform/analysis-impl/src/com/intellij/lang/PerFileMappingState.kt
|
10
|
1429
|
// 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.lang
import com.intellij.openapi.util.text.StringUtil
import org.jdom.Element
internal class PerFileMappingState(var url: String, var value: String? = null) {
companion object {
@JvmStatic
fun write(list: List<PerFileMappingState>, valueAttributeName: String): Element {
val element = Element("state")
for (entry in list) {
val value = entry.value
if (value == null) {
continue
}
val entryElement = Element("file")
entryElement.setAttribute("url", entry.url)
entryElement.setAttribute(valueAttributeName, value)
element.addContent(entryElement)
}
return element
}
@JvmStatic
fun read(element: Element, valueAttributeName: String): List<PerFileMappingState> {
val entries = element.getChildren("file")
if (entries.isEmpty()) {
return emptyList()
}
val result = ArrayList<PerFileMappingState>()
for (child in entries) {
val url = child.getAttributeValue("url")
val value = child.getAttributeValue(valueAttributeName)
if (StringUtil.isEmpty(url) || value == null) {
continue
}
result.add(PerFileMappingState(url!!, value))
}
return result
}
}
}
|
apache-2.0
|
4b90ce3d3ef68ad08bf9ac29ee5db41a
| 29.404255 | 140 | 0.648705 | 4.479624 | false | false | false | false |
jk1/intellij-community
|
platform/platform-api/src/com/intellij/credentialStore/CredentialAttributes.kt
|
3
|
6620
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.ExceptionUtil
import com.intellij.util.io.toByteArray
import com.intellij.util.text.CharArrayCharSequence
import com.intellij.util.text.nullize
import org.jetbrains.annotations.Contract
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.CodingErrorAction
import java.util.concurrent.atomic.AtomicReference
const val SERVICE_NAME_PREFIX: String = "IntelliJ Platform"
fun generateServiceName(subsystem: String, key: String): String = "$SERVICE_NAME_PREFIX $subsystem — $key"
/**
* requestor is deprecated. Never use it in new code.
*/
data class CredentialAttributes @JvmOverloads constructor(val serviceName: String, val userName: String? = null, val requestor: Class<*>? = null, val isPasswordMemoryOnly: Boolean = false)
fun CredentialAttributes.toPasswordStoreable(): CredentialAttributes = if (isPasswordMemoryOnly) CredentialAttributes(serviceName, userName, requestor) else this
// user cannot be empty, but password can be
class Credentials(user: String?, val password: OneTimeString? = null) {
constructor(user: String?, password: String?) : this(user, password?.let(::OneTimeString))
constructor(user: String?, password: CharArray?) : this(user, password?.let { OneTimeString(it) })
constructor(user: String?, password: ByteArray?) : this(user, password?.let { OneTimeString(password) })
val userName: String? = user.nullize()
fun getPasswordAsString(): String? = password?.toString()
override fun equals(other: Any?): Boolean {
if (other !is Credentials) return false
return userName == other.userName && password == other.password
}
override fun hashCode(): Int = (userName?.hashCode() ?: 0) * 37 + (password?.hashCode() ?: 0)
}
@Suppress("FunctionName")
/**
* DEPRECATED. Never use it in a new code.
*/
fun CredentialAttributes(requestor: Class<*>, userName: String?): CredentialAttributes = CredentialAttributes(requestor.name, userName, requestor)
@Contract("null -> false")
fun Credentials?.isFulfilled(): Boolean = this != null && userName != null && !password.isNullOrEmpty()
fun Credentials?.hasOnlyUserName(): Boolean = this != null && userName != null && password.isNullOrEmpty()
fun Credentials?.isEmpty(): Boolean = this == null || (userName == null && password.isNullOrEmpty())
/**
* Tries to get credentials both by `newAttributes` and `oldAttributes`, and if they are available by `oldAttributes` migrates old to new,
* i.e. removes `oldAttributes` from the credentials store, and adds `newAttributes` instead.
*/
fun getAndMigrateCredentials(oldAttributes: CredentialAttributes, newAttributes: CredentialAttributes): Credentials? {
val safe = PasswordSafe.instance
var credentials = safe.get(newAttributes)
if (credentials == null) {
credentials = safe.get(oldAttributes)
if (credentials != null) {
safe.set(oldAttributes, null)
safe.set(newAttributes, credentials)
}
}
return credentials
}
@Suppress("FunctionName")
@JvmOverloads
fun OneTimeString(value: ByteArray, offset: Int = 0, length: Int = value.size - offset, clearable: Boolean = false): OneTimeString {
if (length == 0) {
return OneTimeString(ArrayUtil.EMPTY_CHAR_ARRAY)
}
// jdk decodes to heap array, but since this code is very critical, we cannot rely on it, so, we don't use Charsets.UTF_8.decode()
val charsetDecoder = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)
val charArray = CharArray((value.size * charsetDecoder.maxCharsPerByte().toDouble()).toInt())
charsetDecoder.reset()
val charBuffer = CharBuffer.wrap(charArray)
var cr = charsetDecoder.decode(ByteBuffer.wrap(value, offset, length), charBuffer, true)
if (!cr.isUnderflow) {
cr.throwException()
}
cr = charsetDecoder.flush(charBuffer)
if (!cr.isUnderflow) {
cr.throwException()
}
value.fill(0, offset, offset + length)
return OneTimeString(charArray, 0, charBuffer.position(), clearable = clearable)
}
/**
* clearable only if specified explicitly.
*
* Case
* 1) you create OneTimeString manually on user input.
* 2) you store it in CredentialStore
* 3) you consume it... BUT native credentials store do not store credentials immediately - write is postponed, so, will be an critical error.
*
* so, currently - only credentials store implementations should set this flag on get.
*/
@Suppress("EqualsOrHashCode")
class OneTimeString @JvmOverloads constructor(value: CharArray, offset: Int = 0, length: Int = value.size, private var clearable: Boolean = false) : CharArrayCharSequence(value, offset, offset + length) {
private val consumed = AtomicReference<String?>()
constructor(value: String): this(value.toCharArray())
private fun consume(willBeCleared: Boolean) {
if (!clearable) {
return
}
if (!willBeCleared) {
consumed.get()?.let { throw IllegalStateException("Already consumed: $it\n---\n") }
}
else if (!consumed.compareAndSet(null, ExceptionUtil.currentStackTrace())) {
throw IllegalStateException("Already consumed at ${consumed.get()}")
}
}
fun toString(clear: Boolean = false): String {
consume(clear)
val result = super.toString()
clear()
return result
}
// string will be cleared and not valid after
@JvmOverloads
fun toByteArray(clear: Boolean = true): ByteArray {
consume(clear)
val result = Charsets.UTF_8.encode(CharBuffer.wrap(myChars, myStart, length))
if (clear) {
clear()
}
return result.toByteArray()
}
private fun clear() {
if (clearable) {
myChars.fill('\u0000', myStart, myEnd)
}
}
@JvmOverloads
fun toCharArray(clear: Boolean = true): CharArray {
consume(clear)
if (clear) {
val result = CharArray(length)
getChars(result, 0)
clear()
return result
}
else {
return chars
}
}
fun clone(clear: Boolean, clearable: Boolean): OneTimeString = OneTimeString(toCharArray(clear), clearable = clearable)
override fun equals(other: Any?): Boolean {
if (other is CharSequence) {
return StringUtil.equals(this, other)
}
return super.equals(other)
}
fun appendTo(builder: StringBuilder) {
consume(false)
builder.append(myChars, myStart, length)
}
}
|
apache-2.0
|
4bd37c791c10ab22a82a226efc67087c
| 34.972826 | 204 | 0.723179 | 4.170132 | false | false | false | false |
AsamK/TextSecure
|
app/src/androidTest/java/org/thoughtcrime/securesms/database/StorySendsDatabaseTest.kt
|
2
|
18311
|
package org.thoughtcrime.securesms.database
import androidx.test.ext.junit.runners.AndroidJUnit4
import junit.framework.TestCase.assertNull
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.containsInAnyOrder
import org.hamcrest.Matchers.hasSize
import org.hamcrest.Matchers.`is`
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.thoughtcrime.securesms.database.model.DistributionListId
import org.thoughtcrime.securesms.database.model.StoryType
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.whispersystems.signalservice.api.push.DistributionId
import org.whispersystems.signalservice.api.push.ServiceId
import java.util.UUID
@RunWith(AndroidJUnit4::class)
class StorySendsDatabaseTest {
private val distributionId1 = DistributionId.from(UUID.randomUUID())
private val distributionId2 = DistributionId.from(UUID.randomUUID())
private val distributionId3 = DistributionId.from(UUID.randomUUID())
private lateinit var distributionList1: DistributionListId
private lateinit var distributionList2: DistributionListId
private lateinit var distributionList3: DistributionListId
private lateinit var distributionListRecipient1: Recipient
private lateinit var distributionListRecipient2: Recipient
private lateinit var distributionListRecipient3: Recipient
private lateinit var recipients1to10: List<RecipientId>
private lateinit var recipients11to20: List<RecipientId>
private lateinit var recipients6to15: List<RecipientId>
private lateinit var recipients6to10: List<RecipientId>
private var messageId1: Long = 0
private var messageId2: Long = 0
private var messageId3: Long = 0
private lateinit var storySends: StorySendsDatabase
@Before
fun setup() {
storySends = SignalDatabase.storySends
recipients1to10 = makeRecipients(10)
recipients11to20 = makeRecipients(10)
distributionList1 = SignalDatabase.distributionLists.createList("1", emptyList(), distributionId = distributionId1)!!
distributionList2 = SignalDatabase.distributionLists.createList("2", emptyList(), distributionId = distributionId2)!!
distributionList3 = SignalDatabase.distributionLists.createList("3", emptyList(), distributionId = distributionId3)!!
distributionListRecipient1 = Recipient.resolved(SignalDatabase.recipients.getOrInsertFromDistributionListId(distributionList1))
distributionListRecipient2 = Recipient.resolved(SignalDatabase.recipients.getOrInsertFromDistributionListId(distributionList2))
distributionListRecipient3 = Recipient.resolved(SignalDatabase.recipients.getOrInsertFromDistributionListId(distributionList3))
messageId1 = MmsHelper.insert(
recipient = distributionListRecipient1,
storyType = StoryType.STORY_WITHOUT_REPLIES,
)
messageId2 = MmsHelper.insert(
recipient = distributionListRecipient2,
storyType = StoryType.STORY_WITH_REPLIES,
)
messageId3 = MmsHelper.insert(
recipient = distributionListRecipient3,
storyType = StoryType.STORY_WITHOUT_REPLIES,
)
recipients6to15 = recipients1to10.takeLast(5) + recipients11to20.take(5)
recipients6to10 = recipients1to10.takeLast(5)
}
@Test
fun getRecipientsToSendTo_noOverlap() {
storySends.insert(messageId1, recipients1to10, 100, false, distributionId1)
storySends.insert(messageId2, recipients11to20, 200, true, distributionId2)
storySends.insert(messageId3, recipients1to10, 300, false, distributionId3)
val recipientIdsForMessage1 = storySends.getRecipientsToSendTo(messageId1, 100, false)
val recipientIdsForMessage2 = storySends.getRecipientsToSendTo(messageId2, 200, true)
assertThat(recipientIdsForMessage1, hasSize(10))
assertThat(recipientIdsForMessage1, containsInAnyOrder(*recipients1to10.toTypedArray()))
assertThat(recipientIdsForMessage2, hasSize(10))
assertThat(recipientIdsForMessage2, containsInAnyOrder(*recipients11to20.toTypedArray()))
}
@Test
fun getRecipientsToSendTo_overlap() {
storySends.insert(messageId1, recipients1to10, 100, false, distributionId1)
storySends.insert(messageId2, recipients6to15, 100, true, distributionId2)
val recipientIdsForMessage1 = storySends.getRecipientsToSendTo(messageId1, 100, false)
val recipientIdsForMessage2 = storySends.getRecipientsToSendTo(messageId2, 100, true)
assertThat(recipientIdsForMessage1, hasSize(5))
assertThat(recipientIdsForMessage1, containsInAnyOrder(*recipients1to10.take(5).toTypedArray()))
assertThat(recipientIdsForMessage2, hasSize(10))
assertThat(recipientIdsForMessage2, containsInAnyOrder(*recipients6to15.toTypedArray()))
}
@Test
fun getRecipientsToSendTo_overlapAll() {
val recipient1 = recipients1to10.first()
val recipient2 = recipients11to20.first()
storySends.insert(messageId1, listOf(recipient1, recipient2), 100, false, distributionId1)
storySends.insert(messageId2, listOf(recipient1), 100, true, distributionId2)
storySends.insert(messageId3, listOf(recipient2), 100, true, distributionId3)
val recipientIdsForMessage1 = storySends.getRecipientsToSendTo(messageId1, 100, false)
val recipientIdsForMessage2 = storySends.getRecipientsToSendTo(messageId2, 100, true)
val recipientIdsForMessage3 = storySends.getRecipientsToSendTo(messageId3, 100, true)
assertThat(recipientIdsForMessage1, hasSize(0))
assertThat(recipientIdsForMessage2, hasSize(1))
assertThat(recipientIdsForMessage2, containsInAnyOrder(recipient1))
assertThat(recipientIdsForMessage3, hasSize(1))
assertThat(recipientIdsForMessage3, containsInAnyOrder(recipient2))
}
@Test
fun getRecipientsToSendTo_overlapWithEarlierMessage() {
storySends.insert(messageId1, recipients6to15, 100, true, distributionId1)
storySends.insert(messageId2, recipients1to10, 100, false, distributionId2)
val recipientIdsForMessage1 = storySends.getRecipientsToSendTo(messageId1, 100, true)
val recipientIdsForMessage2 = storySends.getRecipientsToSendTo(messageId2, 100, false)
assertThat(recipientIdsForMessage1, hasSize(10))
assertThat(recipientIdsForMessage1, containsInAnyOrder(*recipients6to15.toTypedArray()))
assertThat(recipientIdsForMessage2, hasSize(5))
assertThat(recipientIdsForMessage2, containsInAnyOrder(*recipients1to10.take(5).toTypedArray()))
}
@Test
fun getRemoteDeleteRecipients_noOverlap() {
storySends.insert(messageId1, recipients1to10, 100, false, distributionId1)
storySends.insert(messageId2, recipients11to20, 200, true, distributionId2)
storySends.insert(messageId3, recipients1to10, 300, false, distributionId3)
val recipientIdsForMessage1 = storySends.getRemoteDeleteRecipients(messageId1, 100)
val recipientIdsForMessage2 = storySends.getRemoteDeleteRecipients(messageId2, 200)
assertThat(recipientIdsForMessage1, hasSize(10))
assertThat(recipientIdsForMessage1, containsInAnyOrder(*recipients1to10.toTypedArray()))
assertThat(recipientIdsForMessage2, hasSize(10))
assertThat(recipientIdsForMessage2, containsInAnyOrder(*recipients11to20.toTypedArray()))
}
@Test
fun getRemoteDeleteRecipients_overlapNoPreviousDeletes() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients6to15, 200, true, distributionId2)
val recipientIdsForMessage1 = storySends.getRemoteDeleteRecipients(messageId1, 200)
val recipientIdsForMessage2 = storySends.getRemoteDeleteRecipients(messageId2, 200)
assertThat(recipientIdsForMessage1, hasSize(5))
assertThat(recipientIdsForMessage1, containsInAnyOrder(*recipients1to10.take(5).toTypedArray()))
assertThat(recipientIdsForMessage2, hasSize(5))
assertThat(recipientIdsForMessage2, containsInAnyOrder(*recipients6to15.takeLast(5).toTypedArray()))
}
@Test
fun getRemoteDeleteRecipients_overlapWithPreviousDeletes() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
SignalDatabase.mms.markAsRemoteDelete(messageId1)
storySends.insert(messageId2, recipients6to15, 200, true, distributionId2)
val recipientIdsForMessage2 = storySends.getRemoteDeleteRecipients(messageId2, 200)
assertThat(recipientIdsForMessage2, hasSize(10))
assertThat(recipientIdsForMessage2, containsInAnyOrder(*recipients6to15.toTypedArray()))
}
@Test
fun canReply_storyWithReplies() {
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
val canReply = storySends.canReply(recipients1to10[0], 200)
assertThat(canReply, `is`(true))
}
@Test
fun canReply_storyWithoutReplies() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
val canReply = storySends.canReply(recipients1to10[0], 200)
assertThat(canReply, `is`(false))
}
@Test
fun canReply_storyWithAndWithoutRepliesOverlap() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients6to10, 200, true, distributionId2)
val message1OnlyRecipientCanReply = storySends.canReply(recipients1to10[0], 200)
val message2RecipientCanReply = storySends.canReply(recipients6to10[0], 200)
assertThat(message1OnlyRecipientCanReply, `is`(false))
assertThat(message2RecipientCanReply, `is`(true))
}
@Test
fun givenASingleStory_whenIGetFullSentStorySyncManifest_thenIExpectNotNull() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
val manifest = storySends.getFullSentStorySyncManifest(messageId1, 200)
assertNotNull(manifest)
}
@Test
fun givenTwoStories_whenIGetFullSentStorySyncManifestForStory2_thenIExpectNull() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, false, distributionId2)
val manifest = storySends.getFullSentStorySyncManifest(messageId2, 200)
assertNull(manifest)
}
@Test
fun givenTwoStories_whenIGetFullSentStorySyncManifestForStory1_thenIExpectOneManifestPerRecipient() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
val manifest = storySends.getFullSentStorySyncManifest(messageId1, 200)!!
assertEquals(recipients1to10, manifest.entries.map { it.recipientId })
}
@Test
fun givenTwoStories_whenIGetFullSentStorySyncManifestForStory1_thenIExpectTwoListsPerRecipient() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
val manifest = storySends.getFullSentStorySyncManifest(messageId1, 200)!!
manifest.entries.forEach { entry ->
assertEquals(listOf(distributionId1, distributionId2), entry.distributionLists)
}
}
@Test
fun givenTwoStories_whenIGetFullSentStorySyncManifestForStory1_thenIExpectAllRecipientsCanReply() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
val manifest = storySends.getFullSentStorySyncManifest(messageId1, 200)!!
manifest.entries.forEach { entry ->
assertTrue(entry.allowedToReply)
}
}
@Test
fun givenTwoStoriesAndOneIsRemoteDeleted_whenIGetFullSentStorySyncManifestForStory2_thenIExpectNonNullResult() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
SignalDatabase.mms.markAsRemoteDelete(messageId1)
val manifest = storySends.getFullSentStorySyncManifest(messageId2, 200)!!
assertNotNull(manifest)
}
@Test
fun givenTwoStoriesAndOneIsRemoteDeleted_whenIGetRecipientIdsForManifestUpdate_thenIExpectOnlyRecipientsWithStory2() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId1, recipients11to20, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
SignalDatabase.mms.markAsRemoteDelete(messageId1)
val recipientIds = storySends.getRecipientIdsForManifestUpdate(200, messageId1)
assertEquals(recipients1to10.toHashSet(), recipientIds)
}
@Test
fun givenTwoStoriesAndOneIsRemoteDeleted_whenIGetPartialSentStorySyncManifest_thenIExpectOnlyRecipientsThatHadStory1() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
storySends.insert(messageId2, recipients11to20, 200, true, distributionId2)
SignalDatabase.mms.markAsRemoteDelete(messageId1)
val recipientIds = storySends.getRecipientIdsForManifestUpdate(200, messageId1)
val results = storySends.getSentStorySyncManifestForUpdate(200, recipientIds)
val manifestRecipients = results.entries.map { it.recipientId }
assertEquals(recipients1to10, manifestRecipients)
}
@Test
fun givenTwoStoriesAndTheOneThatAllowedRepliesIsRemoteDeleted_whenIGetPartialSentStorySyncManifest_thenIExpectAllowRepliesToBeTrue() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
storySends.insert(messageId2, recipients1to10, 200, true, distributionId2)
SignalDatabase.mms.markAsRemoteDelete(messageId2)
val recipientIds = storySends.getRecipientIdsForManifestUpdate(200, messageId1)
val results = storySends.getSentStorySyncManifestForUpdate(200, recipientIds)
assertTrue(results.entries.all { it.allowedToReply })
}
@Test
fun givenEmptyManifest_whenIApplyRemoteManifest_thenNothingChanges() {
storySends.insert(messageId1, recipients1to10, 200, false, distributionId1)
val expected = storySends.getFullSentStorySyncManifest(messageId1, 200)
val emptyManifest = SentStorySyncManifest(emptyList())
storySends.applySentStoryManifest(emptyManifest, 200)
val result = storySends.getFullSentStorySyncManifest(messageId1, 200)
assertEquals(expected, result)
}
@Test
fun givenAnIdenticalManifest_whenIApplyRemoteManifest_thenNothingChanges() {
val messageId4 = MmsHelper.insert(
recipient = distributionListRecipient1,
storyType = StoryType.STORY_WITHOUT_REPLIES,
sentTimeMillis = 200
)
storySends.insert(messageId4, recipients1to10, 200, false, distributionId1)
val expected = storySends.getFullSentStorySyncManifest(messageId4, 200)
storySends.applySentStoryManifest(expected!!, 200)
val result = storySends.getFullSentStorySyncManifest(messageId4, 200)
assertEquals(expected, result)
}
@Test
fun givenAManifest_whenIApplyRemoteManifestWithoutOneList_thenIExpectMessageToBeMarkedRemoteDeleted() {
val messageId4 = MmsHelper.insert(
recipient = distributionListRecipient1,
storyType = StoryType.STORY_WITHOUT_REPLIES,
sentTimeMillis = 200
)
val messageId5 = MmsHelper.insert(
recipient = distributionListRecipient2,
storyType = StoryType.STORY_WITHOUT_REPLIES,
sentTimeMillis = 200
)
storySends.insert(messageId4, recipients1to10, 200, false, distributionId1)
val remote = storySends.getFullSentStorySyncManifest(messageId4, 200)!!
storySends.insert(messageId5, recipients1to10, 200, false, distributionId2)
storySends.applySentStoryManifest(remote, 200)
assertTrue(SignalDatabase.mms.getMessageRecord(messageId5).isRemoteDelete)
}
@Test
fun givenAManifest_whenIApplyRemoteManifestWithoutOneList_thenIExpectSharedMessageToNotBeMarkedRemoteDeleted() {
val messageId4 = MmsHelper.insert(
recipient = distributionListRecipient1,
storyType = StoryType.STORY_WITHOUT_REPLIES,
sentTimeMillis = 200
)
val messageId5 = MmsHelper.insert(
recipient = distributionListRecipient2,
storyType = StoryType.STORY_WITHOUT_REPLIES,
sentTimeMillis = 200
)
storySends.insert(messageId4, recipients1to10, 200, false, distributionId1)
val remote = storySends.getFullSentStorySyncManifest(messageId4, 200)!!
storySends.insert(messageId5, recipients1to10, 200, false, distributionId2)
storySends.applySentStoryManifest(remote, 200)
assertFalse(SignalDatabase.mms.getMessageRecord(messageId4).isRemoteDelete)
}
@Test
fun givenNoLocalEntries_whenIApplyRemoteManifest_thenIExpectLocalManifestToMatch() {
val messageId4 = MmsHelper.insert(
recipient = distributionListRecipient1,
storyType = StoryType.STORY_WITHOUT_REPLIES,
sentTimeMillis = 2000
)
val remote = SentStorySyncManifest(
recipients1to10.map {
SentStorySyncManifest.Entry(
recipientId = it,
allowedToReply = true,
distributionLists = listOf(distributionId1)
)
}
)
storySends.applySentStoryManifest(remote, 2000)
val local = storySends.getFullSentStorySyncManifest(messageId4, 2000)
assertEquals(remote, local)
}
@Test
fun givenNonStoryMessageAtSentTimestamp_whenIApplyRemoteManifest_thenIExpectLocalManifestToMatchAndNoCrashes() {
val messageId4 = MmsHelper.insert(
recipient = distributionListRecipient1,
storyType = StoryType.STORY_WITHOUT_REPLIES,
sentTimeMillis = 2000
)
MmsHelper.insert(
recipient = Recipient.resolved(recipients1to10.first()),
sentTimeMillis = 2000
)
val remote = SentStorySyncManifest(
recipients1to10.map {
SentStorySyncManifest.Entry(
recipientId = it,
allowedToReply = true,
distributionLists = listOf(distributionId1)
)
}
)
storySends.applySentStoryManifest(remote, 2000)
val local = storySends.getFullSentStorySyncManifest(messageId4, 2000)
assertEquals(remote, local)
}
private fun makeRecipients(count: Int): List<RecipientId> {
return (1..count).map {
SignalDatabase.recipients.getOrInsertFromServiceId(ServiceId.from(UUID.randomUUID()))
}
}
}
|
gpl-3.0
|
dc7bce6dca204b31294c4c3e9301413d
| 38.548596 | 136 | 0.787669 | 4.155924 | false | true | false | false |
iBotPeaches/TestApks
|
Issue1506/app/src/main/java/com/ibotpeaches/issue1506/MainActivity.kt
|
1
|
1516
|
package com.ibotpeaches.issue1506
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
|
unlicense
|
03c15d9d0c135dc921122fe1b23aae54
| 33.454545 | 85 | 0.688654 | 4.621951 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/ide-features-trainer/src/training/learn/lesson/general/MoveLesson.kt
|
5
|
2467
|
// 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 training.learn.lesson.general
import training.dsl.LessonContext
import training.dsl.LessonSample
import training.dsl.LessonUtil
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
class MoveLesson(private val caretText: String, private val sample: LessonSample)
: KLesson("Move", LessonsBundle.message("move.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit
get() = {
prepareSample(sample)
actionTask("MoveLineDown") {
restoreIfModifiedOrMoved(sample)
LessonsBundle.message("move.pull.down", action(it))
}
actionTask("MoveLineUp") {
restoreIfModifiedOrMoved()
LessonsBundle.message("move.pull.up", action(it))
}
caret(caretText)
task("MoveStatementUp") {
restoreIfModifiedOrMoved()
text(LessonsBundle.message("move.whole.method.up", action(it)))
trigger(it, { editor.document.text }, { before, now ->
checkSwapMoreThan2Lines(before, now)
})
test { actions(it) }
}
actionTask("MoveStatementDown") {
restoreIfModifiedOrMoved()
LessonsBundle.message("move.whole.method.down", action(it))
}
}
override val suitableTips = listOf("MoveUpDown")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("help.lines.of.code"),
LessonUtil.getHelpLink("working-with-source-code.html#editor_lines_code_blocks")),
)
}
fun checkSwapMoreThan2Lines(before: String, now: String): Boolean {
val beforeLines = before.split("\n")
val nowLines = now.split("\n")
if (beforeLines.size != nowLines.size) {
return false
}
val change = beforeLines.size - commonPrefix(beforeLines, nowLines) - commonSuffix(beforeLines, nowLines)
return change >= 4
}
private fun <T> commonPrefix(list1: List<T>, list2: List<T>): Int {
val size = Integer.min(list1.size, list2.size)
for (i in 0 until size) {
if (list1[i] != list2[i])
return i
}
return size
}
private fun <T> commonSuffix(list1: List<T>, list2: List<T>): Int {
val size = Integer.min(list1.size, list2.size)
for (i in 0 until size) {
if (list1[list1.size - i - 1] != list2[list2.size - i - 1])
return i
}
return size
}
|
apache-2.0
|
d6f0f912225d989a057576678023f070
| 31.893333 | 140 | 0.680989 | 3.818885 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/gradle/java/src/service/project/VersionCatalogProjectResolver.kt
|
1
|
3866
|
// 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
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.parentsOfType
import com.intellij.util.castSafelyTo
import com.intellij.util.io.exists
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames
import org.jetbrains.plugins.gradle.service.resolve.getRootGradleProjectPath
import org.jetbrains.plugins.gradle.util.GradleConstants.SETTINGS_FILE_NAME
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyConstantExpressionEvaluator
import java.nio.file.Path
fun GroovyFileBase.getVersionCatalogsData(): Map<String, Path> {
if (this.name != SETTINGS_FILE_NAME) {
return emptyMap()
}
return CachedValuesManager.getCachedValue(this) {
val result = computeVersionCatalogsData(this)
CachedValueProvider.Result(result, PsiModificationTracker.MODIFICATION_COUNT)
}
}
private fun computeVersionCatalogsData(settingsFile: GroovyFileBase): Map<String, Path> {
val projectRootLocation = settingsFile.getRootGradleProjectPath()?.let(Path::of) ?: return emptyMap()
val tracker = GradleStructureTracker(projectRootLocation)
runReadAction {
settingsFile.accept(tracker)
}
val mapping = tracker.catalogMapping
val defaultLibsFile = projectRootLocation.resolve("gradle").resolve("libs.versions.toml")
if (defaultLibsFile.exists()) {
val libsValue = mapping["libs"]
if (libsValue == null) {
mapping["libs"] = defaultLibsFile
}
}
return mapping
}
/**
* This is a temporary and hacky implementation aimed to support navigation to version catalogs.
* We need a proper API from Gradle to support this functionality without these unreliable AST-based heuristics.
*/
private class GradleStructureTracker(val projectRoot: Path) : GroovyRecursiveElementVisitor() {
val catalogMapping: MutableMap<String, Path> = mutableMapOf()
override fun visitMethodCallExpression(methodCallExpression: GrMethodCallExpression) {
val method = methodCallExpression.resolveMethod() ?: return super.visitMethodCallExpression(methodCallExpression)
if (method.name == "from" && method.containingClass?.qualifiedName == GradleCommonClassNames.GRADLE_API_VERSION_CATALOG_BUILDER) {
val container = methodCallExpression.parentsOfType<GrMethodCallExpression>().find {
it.resolveMethod()?.returnType?.equalsToText(GradleCommonClassNames.GRADLE_API_VERSION_CATALOG_BUILDER) == true
}
val name = container?.resolveMethod()?.name
if (container == null || name == null) {
return super.visitMethodCallExpression(methodCallExpression)
}
val file = resolveDependencyNotation(methodCallExpression.expressionArguments.singleOrNull(), projectRoot)
if (file != null) {
catalogMapping[name] = file
}
}
super.visitMethodCallExpression(methodCallExpression)
}
}
/**
* @return filename of toml catalog
*/
private fun resolveDependencyNotation(element: PsiElement?, root: Path): Path? {
element ?: return null
if (element is GrMethodCallExpression && element.resolveMethod()?.name == "files") {
val argument = element.argumentList.expressionArguments.firstOrNull()
return GroovyConstantExpressionEvaluator.evaluate(argument)?.castSafelyTo<String>()?.let(root::resolve)?.takeIf(Path::exists)
}
return null
}
|
apache-2.0
|
0fc3bfce8b657cac7230877ce7d469a3
| 43.953488 | 134 | 0.781169 | 4.66345 | false | false | false | false |
intellij-solidity/intellij-solidity
|
src/main/kotlin/me/serce/solidity/lang/psi/impl/linearization.kt
|
1
|
1178
|
package me.serce.solidity.lang.psi.impl
interface Linearizable<T : Linearizable<T>> {
fun getParents(): List<T>
@Suppress("UNCHECKED_CAST")
fun linearize(): List<T> {
return listOf(this as T) + linearizeParents()
}
fun linearizeParents(): List<T> {
val parents = getParents()
return (parents.map { it.linearize() } + listOf(parents)).merge()
}
}
fun <T> List<List<T>>.merge(): List<T> {
val result = mutableListOf<T>()
var lists = this.filter { it.isNotEmpty() }
while (lists.isNotEmpty()) {
val next = lists.nextForMerge()
if (next != null) {
result.add(next)
lists = lists.map { it.filter { i -> i != next } }.filter { it.isNotEmpty() }
} else {
throw LinearizationImpossibleException("result: $result lists: $lists source: $this")
}
}
return result
}
class LinearizationImpossibleException(message: String) : Exception(message)
fun <T> List<List<T>>.nextForMerge(): T? {
for (list in this) {
val head = list.firstOrNull()
val foundInTail = this.any { otherList ->
otherList != list && otherList.lastIndexOf(head) > 0
}
if (!foundInTail)
return head
}
return null
}
|
mit
|
d78f4e6f6da9914c0953e2873866ddbc
| 25.177778 | 91 | 0.635823 | 3.444444 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceManualRangeWithIndicesCallsInspection.kt
|
1
|
7994
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.collections.isMap
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.getArguments
import org.jetbrains.kotlin.idea.intentions.receiverTypeIfSelectorIsSizeOrLength
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ReplaceManualRangeWithIndicesCallsInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
companion object {
private val rangeFunctionNames = setOf("until", "rangeTo", "..")
private val rangeFunctionFqNames = listOf(
"Char",
"Byte", "Short", "Int", "Long",
"UByte", "UShort", "UInt", "ULong"
).map { FqName("kotlin.$it.rangeTo") } + FqName("kotlin.ranges.until")
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitBinaryExpression(binaryExpression: KtBinaryExpression) {
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val operator = binaryExpression.operationReference
visitRange(holder, binaryExpression, left, right, operator)
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
val call = expression.callExpression ?: return
val left = expression.receiverExpression
val right = call.valueArguments.singleOrNull()?.getArgumentExpression() ?: return
val operator = call.calleeExpression ?: return
visitRange(holder, expression, left, right, operator)
}
}
private fun visitRange(holder: ProblemsHolder, range: KtExpression, left: KtExpression, right: KtExpression, operator: KtExpression) {
if (operator.text !in rangeFunctionNames) return
val functionFqName = range.resolveToCall()?.resultingDescriptor?.fqNameOrNull() ?: return
if (functionFqName !in rangeFunctionFqNames) return
val rangeFunction = functionFqName.shortName().asString()
if (left.toIntConstant() != 0) return
val sizeOrLengthCall = right.sizeOrLengthCall(rangeFunction) ?: return
val collection = sizeOrLengthCall.safeAs<KtQualifiedExpression>()?.receiverExpression
if (collection != null && collection !is KtSimpleNameExpression) return
val parent = range.parent.parent
if (parent is KtForExpression) {
val paramElement = parent.loopParameter?.originalElement ?: return
val usageElement = ReferencesSearch.search(paramElement).singleOrNull()?.element
val arrayAccess = usageElement?.parent?.parent as? KtArrayAccessExpression
if (arrayAccess != null &&
arrayAccess.indexExpressions.singleOrNull() == usageElement &&
(arrayAccess.arrayExpression as? KtSimpleNameExpression)?.mainReference?.resolve() == collection?.mainReference?.resolve()
) {
val arrayAccessParent = arrayAccess.parent
if (arrayAccessParent !is KtBinaryExpression ||
arrayAccessParent.left != arrayAccess ||
arrayAccessParent.operationToken !in KtTokens.ALL_ASSIGNMENTS
) {
holder.registerProblem(
range,
KotlinBundle.message("for.loop.over.indices.could.be.replaced.with.loop.over.elements"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceIndexLoopWithCollectionLoopQuickFix(rangeFunction)
)
return
}
}
}
holder.registerProblem(
range,
KotlinBundle.message("range.could.be.replaced.with.indices.call"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceManualRangeWithIndicesCallQuickFix()
)
}
}
class ReplaceManualRangeWithIndicesCallQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.manual.range.with.indices.call.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtExpression
val receiver = when (val secondArg = element.getArguments()?.second) {
is KtBinaryExpression -> (secondArg.left as? KtDotQualifiedExpression)?.receiverExpression
is KtDotQualifiedExpression -> secondArg.receiverExpression
else -> null
}
val psiFactory = KtPsiFactory(project)
val newExpression = if (receiver != null) {
psiFactory.createExpressionByPattern("$0.indices", receiver)
} else {
psiFactory.createExpression("indices")
}
element.replace(newExpression)
}
}
class ReplaceIndexLoopWithCollectionLoopQuickFix(private val rangeFunction: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.index.loop.with.collection.loop.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement.getStrictParentOfType<KtForExpression>() ?: return
val loopParameter = element.loopParameter ?: return
val loopRange = element.loopRange ?: return
val collectionParent = when (loopRange) {
is KtDotQualifiedExpression -> (loopRange.parent as? KtCallExpression)?.valueArguments?.firstOrNull()?.getArgumentExpression()
is KtBinaryExpression -> loopRange.right
else -> null
} ?: return
val sizeOrLengthCall = collectionParent.sizeOrLengthCall(rangeFunction) ?: return
val collection = (sizeOrLengthCall as? KtDotQualifiedExpression)?.receiverExpression
val paramElement = loopParameter.originalElement ?: return
val usageElement = ReferencesSearch.search(paramElement).singleOrNull()?.element ?: return
val arrayAccessElement = usageElement.parent.parent as? KtArrayAccessExpression ?: return
val factory = KtPsiFactory(project)
val newParameter = factory.createLoopParameter("element")
val newReferenceExpression = factory.createExpression("element")
arrayAccessElement.replace(newReferenceExpression)
loopParameter.replace(newParameter)
loopRange.replace(collection ?: factory.createThisExpression())
}
}
private fun KtExpression.toIntConstant(): Int? {
return (this as? KtConstantExpression)?.text?.toIntOrNull()
}
private fun KtExpression.sizeOrLengthCall(rangeFunction: String): KtExpression? {
val expression = when(rangeFunction) {
"until" -> this
"rangeTo" -> (this as? KtBinaryExpression)
?.takeIf { operationToken == KtTokens.MINUS && right?.toIntConstant() == 1}
?.left
else -> null
} ?: return null
val receiverType = expression.receiverTypeIfSelectorIsSizeOrLength() ?: return null
if (receiverType.isMap(DefaultBuiltIns.Instance)) return null
return expression
}
|
apache-2.0
|
434e9ff0ecf099052d790561b19144e5
| 48.9625 | 158 | 0.697148 | 5.40866 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/OptInFixesFactory.kt
|
1
|
14080
|
// 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.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.module.Module
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
object OptInFixesFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val element = diagnostic.psiElement
val containingDeclaration: KtDeclaration = element.getParentOfTypesAndPredicate(
true,
KtDeclarationWithBody::class.java,
KtClassOrObject::class.java,
KtProperty::class.java,
KtTypeAlias::class.java
) {
!KtPsiUtil.isLocal(it)
} ?: return emptyList()
val annotationFqName = when (diagnostic.factory) {
OPT_IN_USAGE -> OPT_IN_USAGE.cast(diagnostic).a
OPT_IN_USAGE_ERROR -> OPT_IN_USAGE_ERROR.cast(diagnostic).a
OPT_IN_OVERRIDE -> OPT_IN_OVERRIDE.cast(diagnostic).a
OPT_IN_OVERRIDE_ERROR -> OPT_IN_OVERRIDE_ERROR.cast(diagnostic).a
else -> null
} ?: return emptyList()
val moduleDescriptor = containingDeclaration.resolveToDescriptorIfAny()?.module ?: return emptyList()
val annotationClassDescriptor = moduleDescriptor.resolveClassByFqName(
annotationFqName, NoLookupLocation.FROM_IDE
) ?: return emptyList()
val applicableTargets = AnnotationChecker.applicableTargetSet(annotationClassDescriptor)
val context = when (element) {
is KtElement -> element.analyze()
else -> containingDeclaration.analyze()
}
fun isApplicableTo(declaration: KtDeclaration): Boolean {
val actualTargetList = AnnotationChecker.getDeclarationSiteActualTargetList(
declaration, declaration.toDescriptor() as? ClassDescriptor, context
)
return actualTargetList.any { it in applicableTargets }
}
val isOverrideError = diagnostic.factory == OPT_IN_OVERRIDE_ERROR || diagnostic.factory == OPT_IN_OVERRIDE
val optInFqName = OptInNames.OPT_IN_FQ_NAME.takeIf { moduleDescriptor.annotationExists(it) }
?: OptInNames.OLD_USE_EXPERIMENTAL_FQ_NAME
val result = mutableListOf<IntentionAction>()
// just to avoid local variable name shadowing
run {
val kind = if (containingDeclaration is KtConstructor<*>)
AddAnnotationFix.Kind.Constructor
else
AddAnnotationFix.Kind.Declaration(containingDeclaration.name)
if (isApplicableTo(containingDeclaration)) {
// When we are fixing a missing annotation on an overridden function, we should
// propose to add a propagating annotation first, and in all other cases
// the non-propagating opt-in annotation should be default.
// The same logic applies to the similar conditional expressions onward.
result.add(
if (isOverrideError)
HighPriorityPropagateOptInAnnotationFix(containingDeclaration, annotationFqName, kind)
else
PropagateOptInAnnotationFix(containingDeclaration, annotationFqName, kind)
)
}
val existingAnnotationEntry = containingDeclaration.findAnnotation(optInFqName)?.createSmartPointer()
result.add(
if (isOverrideError)
UseOptInAnnotationFix(containingDeclaration, optInFqName, kind, annotationFqName, existingAnnotationEntry)
else
HighPriorityUseOptInAnnotationFix(containingDeclaration, optInFqName, kind, annotationFqName, existingAnnotationEntry)
)
}
if (containingDeclaration is KtCallableDeclaration) {
val containingClassOrObject = containingDeclaration.containingClassOrObject
if (containingClassOrObject != null) {
val kind = AddAnnotationFix.Kind.ContainingClass(containingClassOrObject.name)
val isApplicableToContainingClassOrObject = isApplicableTo(containingClassOrObject)
if (isApplicableToContainingClassOrObject) {
result.add(
if (isOverrideError)
HighPriorityPropagateOptInAnnotationFix(containingClassOrObject, annotationFqName, kind)
else
PropagateOptInAnnotationFix(containingClassOrObject, annotationFqName, kind)
)
}
val existingAnnotationEntry = containingClassOrObject.findAnnotation(optInFqName)?.createSmartPointer()
result.add(
if (isOverrideError)
UseOptInAnnotationFix(containingClassOrObject, optInFqName, kind, annotationFqName, existingAnnotationEntry)
else
HighPriorityUseOptInAnnotationFix(
containingClassOrObject, optInFqName, kind, annotationFqName, existingAnnotationEntry
)
)
}
}
val containingFile = containingDeclaration.containingKtFile
val module = containingFile.module
if (module != null) {
result.add(LowPriorityMakeModuleOptInFix(containingFile, module, annotationFqName))
}
// Add the file-level annotation `@file:OptIn(...)`
result.add(
UseOptInFileAnnotationFix(
containingFile, optInFqName, annotationFqName,
findFileAnnotation(containingFile, optInFqName)?.createSmartPointer()
)
)
return result
}
// Find the existing file-level annotation of the specified class if it exists
private fun findFileAnnotation(file: KtFile, annotationFqName: FqName): KtAnnotationEntry? {
val context = file.analyze(BodyResolveMode.PARTIAL)
return file.fileAnnotationList?.annotationEntries?.firstOrNull { entry ->
context.get(BindingContext.ANNOTATION, entry)?.fqName == annotationFqName
}
}
fun ModuleDescriptor.annotationExists(fqName: FqName): Boolean =
resolveClassByFqName(fqName, NoLookupLocation.FROM_IDE) != null
/**
* A specialized subclass of [AddAnnotationFix] that adds @OptIn(...) annotations to declarations,
* containing classes, or constructors.
*
* This class reuses the parent's [invoke] method but overrides the [getText] method to provide
* more descriptive opt-in-specific messages.
*
* @param element a declaration to annotate
* @param optInFqName name of OptIn annotation
* @param kind the annotation kind (desired scope)
* @param argumentClassFqName the fully qualified name of the annotation to opt-in
* @param existingAnnotationEntry the already existing annotation entry (if any)
*
*/
private open class UseOptInAnnotationFix(
element: KtDeclaration,
optInFqName: FqName,
private val kind: Kind,
private val argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : AddAnnotationFix(element, optInFqName, kind, argumentClassFqName, existingAnnotationEntry) {
private val elementName = element.name ?: "?"
override fun getText(): String {
val argumentText = argumentClassFqName.shortName().asString()
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.opt_in.text.use.declaration", argumentText, elementName)
Kind.Constructor -> KotlinBundle.message("fix.opt_in.text.use.constructor", argumentText)
is Kind.Declaration -> KotlinBundle.message("fix.opt_in.text.use.declaration", argumentText, kind.name ?: "?")
is Kind.ContainingClass -> KotlinBundle.message("fix.opt_in.text.use.containing.class", argumentText, kind.name ?: "?")
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
private class HighPriorityUseOptInAnnotationFix(
element: KtDeclaration,
optInFqName: FqName,
kind: Kind,
argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : UseOptInAnnotationFix(element, optInFqName, kind, argumentClassFqName, existingAnnotationEntry),
HighPriorityAction
/**
* A specialized version of [AddFileAnnotationFix] that adds @OptIn(...) annotations to the containing file.
*
* This class reuses the parent's [invoke] method, but overrides the [getText] method to provide
* more descriptive opt-in related messages.
*
* @param file the file there the annotation should be added
* @param optInFqName name of OptIn annotation
* @param argumentClassFqName the fully qualified name of the annotation to opt-in
* @param existingAnnotationEntry the already existing annotation entry (if any)
*/
private open class UseOptInFileAnnotationFix(
file: KtFile,
optInFqName: FqName,
private val argumentClassFqName: FqName,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>?
) : AddFileAnnotationFix(file, optInFqName, argumentClassFqName, existingAnnotationEntry) {
private val fileName = file.name
override fun getText(): String {
val argumentText = argumentClassFqName.shortName().asString()
return KotlinBundle.message("fix.opt_in.text.use.containing.file", argumentText, fileName)
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
/**
* A specialized subclass of [AddAnnotationFix] that adds propagating opted-in annotations
* to declarations, containing classes, or constructors.
*
* This class reuses the parent's [invoke] method but overrides the [getText] method to provide
* more descriptive opt-in-specific messages.
*
* @param element a declaration to annotate
* @param annotationFqName the fully qualified name of the annotation
* @param kind the annotation kind (desired scope)
* @param existingAnnotationEntry the already existing annotation entry (if any)
*
*/
private open class PropagateOptInAnnotationFix(
element: KtDeclaration,
private val annotationFqName: FqName,
private val kind: Kind,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : AddAnnotationFix(element, annotationFqName, Kind.Self, null, existingAnnotationEntry) {
override fun getText(): String {
val argumentText = annotationFqName.shortName().asString()
return when (kind) {
Kind.Self -> KotlinBundle.message("fix.opt_in.text.propagate.declaration", argumentText, "?")
Kind.Constructor -> KotlinBundle.message("fix.opt_in.text.propagate.constructor", argumentText)
is Kind.Declaration -> KotlinBundle.message("fix.opt_in.text.propagate.declaration", argumentText, kind.name ?: "?")
is Kind.ContainingClass -> KotlinBundle.message(
"fix.opt_in.text.propagate.containing.class",
argumentText,
kind.name ?: "?"
)
}
}
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.annotation.family")
}
/**
* A high-priority version of [PropagateOptInAnnotationFix] (for overridden constructor case)
*
* @param element a declaration to annotate
* @param annotationFqName the fully qualified name of the annotation
* @param kind the annotation kind (desired scope)
* @param existingAnnotationEntry the already existing annotation entry (if any)
*/
private class HighPriorityPropagateOptInAnnotationFix(
element: KtDeclaration,
annotationFqName: FqName,
kind: Kind,
existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : PropagateOptInAnnotationFix(element, annotationFqName, kind, existingAnnotationEntry),
HighPriorityAction
private class LowPriorityMakeModuleOptInFix(
file: KtFile,
module: Module,
annotationFqName: FqName
) : MakeModuleOptInFix(file, module, annotationFqName), LowPriorityAction
}
|
apache-2.0
|
7bcadb291762d4ed9d4569041477df0a
| 47.888889 | 138 | 0.685724 | 5.541126 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/api/entity/TootAttachment.kt
|
1
|
11406
|
package jp.juggler.subwaytooter.api.entity
import android.content.SharedPreferences
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.util.*
class TootAttachment : TootAttachmentLike {
companion object {
private fun parseFocusValue(parent: JsonObject?, key: String): Float {
if (parent != null) {
val dv = parent.double(key)
if (dv != null && dv.isFinite()) return clipRange(-1f, 1f, dv.toFloat())
}
return 0f
}
// 下書きからの復元などに使うパラメータ
// 後方互換性的な理由で概ねマストドンに合わせている
private const val KEY_IS_STRING_ID = "isStringId"
private const val KEY_ID = "id"
private const val KEY_TYPE = "type"
private const val KEY_URL = "url"
private const val KEY_REMOTE_URL = "remote_url"
private const val KEY_PREVIEW_URL = "preview_url"
private const val KEY_PREVIEW_REMOTE_URL = "preview_remote_url"
private const val KEY_TEXT_URL = "text_url"
private const val KEY_DESCRIPTION = "description"
private const val KEY_IS_SENSITIVE = "isSensitive"
private const val KEY_META = "meta"
private const val KEY_FOCUS = "focus"
private const val KEY_X = "x"
private const val KEY_Y = "y"
private const val KEY_BLURHASH = "blurhash"
fun decodeJson(src: JsonObject) = TootAttachment(src, decode = true)
private val ext_audio = arrayOf(".mpga", ".mp3", ".aac", ".ogg")
private fun guessMediaTypeByUrl(src: String?): TootAttachmentType? {
val uri = src.mayUri() ?: return null
if (ext_audio.any { uri.path?.endsWith(it) == true }) {
return TootAttachmentType.Audio
}
return null
}
}
constructor(parser: TootParser, src: JsonObject) : this(parser.serviceType, src)
// ID of the attachment
val id: EntityId
//One of: "image", "video", "gifv". or may null ? may "unknown" ?
override val type: TootAttachmentType
//URL of the locally hosted version of the image
val url: String?
//For remote images, the remote URL of the original image
val remote_url: String?
// URL of the preview image
// (Mastodon 2.9.2) audioのpreview_url は .mpga のURL
// (Misskey v11) audioのpreview_url は null
val preview_url: String?
val preview_remote_url: String?
// Shorter URL for the image, for insertion into text (only present on local images)
val text_url: String?
// ALT text (Mastodon 2.0.0 or later)
override val description: String?
override val focusX: Float
override val focusY: Float
// 内部フラグ: 再編集で引き継いだ添付メディアなら真
var redraft: Boolean = false
// MisskeyはメディアごとにNSFWフラグがある
val isSensitive: Boolean
// Mastodon 2.9.0 or later
val blurhash: String?
///////////////////////////////
override fun hasUrl(url: String): Boolean = when (url) {
this.preview_url, this.preview_remote_url, this.remote_url, this.url, this.text_url -> true
else -> false
}
override val urlForDescription: String?
get() = remote_url.notEmpty() ?: url
constructor(serviceType: ServiceType, src: JsonObject) {
when (serviceType) {
ServiceType.MISSKEY -> {
id = EntityId.mayDefault(src.string("id"))
val mimeType = src.string("type") ?: "?"
this.type = when {
mimeType.startsWith("image/") -> TootAttachmentType.Image
mimeType.startsWith("video/") -> TootAttachmentType.Video
mimeType.startsWith("audio/") -> TootAttachmentType.Audio
else -> TootAttachmentType.Unknown
}
url = src.string("url")
preview_url = src.string("thumbnailUrl")
preview_remote_url = null
remote_url = url
text_url = url
description = src.string("comment")?.notBlank()
?: src.string("name")?.notBlank()
focusX = 0f
focusY = 0f
isSensitive = src.optBoolean("isSensitive", false)
blurhash = null
}
ServiceType.NOTESTOCK -> {
id = EntityId.DEFAULT
url = src.string("url")
remote_url = url
preview_url = src.string("img_hash")
?.let { "https://img.osa-p.net/proxy/500x,q100,s$it/$url" }
preview_remote_url = null
text_url = url
description = src.string("name")
isSensitive = false // Misskey用のパラメータなので、マストドンでは適当な値を使ってOK
val mediaType = src.string("mediaType")
type = when {
mediaType?.startsWith("image") == true -> TootAttachmentType.Image
mediaType?.startsWith("video") == true -> TootAttachmentType.Video
mediaType?.startsWith("audio") == true -> TootAttachmentType.Audio
else -> guessMediaTypeByUrl(remote_url ?: url)
?: TootAttachmentType.Unknown
// TODO GIFVかどうかの判定はどうするの?
}
val focus = null // TODO focus指定はどうなるの?
focusX = parseFocusValue(focus, "x")
focusY = parseFocusValue(focus, "y")
blurhash = src.string("blurhash")
}
else -> {
id = EntityId.mayDefault(src.string("id"))
url = src.string("url")
remote_url = src.string("remote_url")
preview_url = src.string("preview_url")
preview_remote_url = src.string("preview_remote_url")
text_url = src.string("text_url")
description = src.string("description")
isSensitive = false // Misskey用のパラメータなので、マストドンでは適当な値を使ってOK
type = when (val tmpType = parseType(src.string("type"))) {
null, TootAttachmentType.Unknown -> {
guessMediaTypeByUrl(remote_url ?: url) ?: TootAttachmentType.Unknown
}
else -> tmpType
}
val focus = src.jsonObject("meta")?.jsonObject("focus")
focusX = parseFocusValue(focus, "x")
focusY = parseFocusValue(focus, "y")
blurhash = src.string("blurhash")
}
}
}
private fun parseType(src: String?) =
TootAttachmentType.values().find { it.id == src }
override fun urlForThumbnail(pref: SharedPreferences) =
if (PrefB.bpPriorLocalURL(pref)) {
preview_url.notEmpty() ?: preview_remote_url.notEmpty()
} else {
preview_remote_url.notEmpty() ?: preview_url.notEmpty()
} ?: when (type) {
TootAttachmentType.Image -> getLargeUrl(pref)
else -> null
}
fun getLargeUrl(pref: SharedPreferences) =
if (PrefB.bpPriorLocalURL(pref)) {
url.notEmpty() ?: remote_url
} else {
remote_url.notEmpty() ?: url
}
fun getLargeUrlList(pref: SharedPreferences) =
ArrayList<String>().apply {
if (PrefB.bpPriorLocalURL(pref)) {
url.notEmpty()?.addTo(this)
remote_url.notEmpty()?.addTo(this)
} else {
remote_url.notEmpty()?.addTo(this)
url.notEmpty()?.addTo(this)
}
}
fun encodeJson() = jsonObject {
put(KEY_IS_STRING_ID, true)
put(KEY_ID, id.toString())
put(KEY_TYPE, type.id)
put(KEY_URL, url)
put(KEY_REMOTE_URL, remote_url)
put(KEY_PREVIEW_URL, preview_url)
put(KEY_PREVIEW_REMOTE_URL, preview_remote_url)
put(KEY_TEXT_URL, text_url)
put(KEY_DESCRIPTION, description)
put(KEY_IS_SENSITIVE, isSensitive)
put(KEY_BLURHASH, blurhash)
if (focusX != 0f || focusY != 0f) {
put(KEY_META, jsonObject {
put(KEY_FOCUS, jsonObject {
put(KEY_X, focusX)
put(KEY_Y, focusY)
})
})
}
}
constructor(
src: JsonObject,
@Suppress("UNUSED_PARAMETER") decode: Boolean, // dummy parameter for choosing this ctor.
) {
id = EntityId.mayDefault(src.string(KEY_ID))
url = src.string(KEY_URL)
remote_url = src.string(KEY_REMOTE_URL)
preview_url = src.string(KEY_PREVIEW_URL)
preview_remote_url = src.string(KEY_PREVIEW_REMOTE_URL)
text_url = src.string(KEY_TEXT_URL)
type = when (val tmpType = parseType(src.string(KEY_TYPE))) {
null, TootAttachmentType.Unknown -> {
guessMediaTypeByUrl(remote_url ?: url) ?: TootAttachmentType.Unknown
}
else -> tmpType
}
description = src.string(KEY_DESCRIPTION)
isSensitive = src.optBoolean(KEY_IS_SENSITIVE)
val focus = src.jsonObject(KEY_META)?.jsonObject(KEY_FOCUS)
focusX = parseFocusValue(focus, KEY_X)
focusY = parseFocusValue(focus, KEY_Y)
blurhash = src.string(KEY_BLURHASH)
}
}
// v1.3 から 添付ファイルの画像のピクセルサイズが取得できるようになった
// https://github.com/tootsuite/mastodon/issues/1985
// "media_attachments" : [
// {
// "id" : 4,
// "type" : "image",
// "remote_url" : "",
// "meta" : {
// "original" : {
// "width" : 600,
// "size" : "600x400",
// "height" : 400,
// "aspect" : 1.5
// },
// "small" : {
// "aspect" : 1.49812734082397,
// "height" : 267,
// "size" : "400x267",
// "width" : 400
// }
// },
// "url" : "http://127.0.0.1:3000/system/media_attachments/files/000/000/004/original/3416fc5188c656da.jpg?1493138517",
// "preview_url" : "http://127.0.0.1:3000/system/media_attachments/files/000/000/004/small/3416fc5188c656da.jpg?1493138517",
// "text_url" : "http://127.0.0.1:3000/media/4hfW3Kt4U9UxDvV_xug"
// },
// {
// "text_url" : "http://127.0.0.1:3000/media/0vTH_B1kjvIvlUBhGBw",
// "preview_url" : "http://127.0.0.1:3000/system/media_attachments/files/000/000/003/small/23519a5e64064e32.png?1493138030",
// "meta" : {
// "fps" : 15,
// "duration" : 5.06,
// "width" : 320,
// "size" : "320x180",
// "height" : 180,
// "length" : "0:00:05.06",
// "aspect" : 1.77777777777778
// },
// "url" : "http://127.0.0.1:3000/system/media_attachments/files/000/000/003/original/23519a5e64064e32.mp4?1493138030",
// "remote_url" : "",
// "type" : "gifv",
// "id" : 3
// }
// ],
|
apache-2.0
|
67a689713f8407cfabbe92506b1d2be8
| 32.892405 | 125 | 0.541538 | 3.713708 | false | false | false | false |
mctoyama/PixelServer
|
src/main/kotlin/org/pixelndice/table/pixelserver/Server.kt
|
1
|
13962
|
package org.pixelndice.table.pixelserver
import com.google.common.base.Throwables
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.hibernate.Session
import org.hibernate.Transaction
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import org.pixelndice.table.pixelprotocol.ChannelCanceledException
import org.pixelndice.table.pixelserver.connection.main.*
import org.pixelndice.table.pixelserver.connection.ping.ContextPing
import org.pixelndice.table.pixelserver.connection.ping.StateStop
import org.pixelndice.table.pixelserverhibernate.Game
import org.pixelndice.table.pixelserverhibernate.Ping
import java.net.UnknownHostException
import java.time.LocalDateTime
private val logger: Logger = LogManager.getLogger(Server::class.java)
class Server @Throws(IOException::class)
constructor(hostname: String, port: Int, block: Int, private val selectTimeout: Long, private val maxClients: Int, private val pingInterval: Long) : Runnable {
@Volatile private var running = true
private val pingSelector: Selector = Selector.open()
private val mainSelector: Selector = Selector.open()
private val ssChannel: ServerSocketChannel
private val ssKey: SelectionKey
@Volatile var numClients: Int = 0
private set
private val inBuffer = ByteBuffer.allocate(block)
private var outBuffer: ByteBuffer = ByteBuffer.allocate(block)
init {
val hostIPAddress = InetAddress.getByName(hostname)
ssChannel = ServerSocketChannel.open()
ssChannel.configureBlocking(false)
ssChannel.socket().bind(InetSocketAddress(hostIPAddress, port))
ssKey = ssChannel.register(mainSelector, SelectionKey.OP_ACCEPT)
logger.info("Server Listening on $hostname:$port")
}
fun terminate() {
running = false
mainSelector.wakeup()
pingSelector.wakeup()
}
override fun run() {
logger.info("Starting server running...")
while (running) {
// mainSelector
// storing number of clients
numClients = mainSelector.keys().size - 1
// removing dead sockets/channels from selector handle
var iterator: MutableIterator<SelectionKey> = mainSelector.keys().iterator()
while (iterator.hasNext()) {
val key = iterator.next()
if (key != ssKey) {
// getting socket
val s = key.channel() as SocketChannel
val ctx = key.attachment() as Context
if (ctx.channel.isCanceled || !s.isConnected) {
try {
s.close()
} catch (e: IOException) {
// nothing to do
// wait until socket is removed
logger.trace("Error socket.close() Ignoring...")
}
logger.trace("Removing dead socket from pool: ${ctx.channel.address}")
}
}
}
var count: Int
try {
count = mainSelector.select(selectTimeout)
} catch (e: IOException) {
count = 0
logger.fatal("Error on mainSelector.select(). Aborting")
System.exit(-100)
}
if (count > 0 && mainSelector.keys().size > maxClients ) {
logger.warn("Maximum number of clients reached. Ignoring new request.")
}
if (count > 0 && mainSelector.keys().size < maxClients + 1) {
iterator = mainSelector.selectedKeys().iterator()
while (iterator.hasNext()) {
val key = iterator.next()
iterator.remove()
// accepting new connection
if (key.isValid && key.isAcceptable) {
var s: SocketChannel
try {
s = ssChannel.accept()
val ctx = Context(s.socket().inetAddress)
s.configureBlocking(false)
s.register(mainSelector, SelectionKey.OP_READ or SelectionKey.OP_WRITE, ctx)
logger.trace("New client connection: ${ctx.channel.address}")
} catch (e: IOException) {
logger.error("Error on accepting connection")
}
} else {
// getting socket
val s = key.channel() as SocketChannel
val ctx = key.attachment() as Context
try {
// reading
if (key.isValid && key.isReadable && !ctx.channel.isCanceled) {
if( s.read(inBuffer) > 0 ) {
inBuffer.flip()
ctx.channel.putByteBuffer(inBuffer)
}
inBuffer.clear()
}
// writing
if (key.isValid && key.isWritable && !ctx.channel.isCanceled) {
ctx.channel.getByteBuffer(outBuffer)
outBuffer.flip()
if( outBuffer.hasRemaining() )
s.write(outBuffer)
outBuffer.clear()
}
} catch (cee: ChannelCanceledException) {
logger.trace("Channel in canceled state. Waiting for disposal. IP: ${ctx.channel.addressAsString}")
} catch (e: IOException) {
logger.trace("Error on reading/writing on socket. Waiting for disposal. IP: ${ctx.channel.addressAsString}")
try {
s.close()
} catch (e1: IOException) {
logger.error("Error on s.close() connection. Ignoring.")
}
key.cancel()
}
}
}
}
// Processing contexts
iterator = mainSelector.keys().iterator()
while (iterator.hasNext()) {
val key = iterator.next()
val ctx = key.attachment() as Context?
ctx?.process()
}
// pingSelector
// remove expired pings
var session: Session? = null
var tx: Transaction? = null
try {
session = sessionFactory.openSession()
val query = session.createNamedQuery("expiredPing", Ping::class.java)
query.setParameter("now", LocalDateTime.now())
val delPingList = query.list()
delPingList.forEach { ping ->
tx = session?.beginTransaction()
Bus.post(Bus.LobbyUnreachable(ping))
session?.delete(ping)
tx?.commit()
}
}catch (e: Exception){
logger.fatal("Hibernate fatal error!")
logger.fatal(Throwables.getStackTraceAsString(e))
tx?.rollback()
}finally {
session?.close()
}
try {
// selects to do pings
session = sessionFactory.openSession()
val query = session.createNamedQuery("refreshPing", Ping::class.java)
query.setParameter("now", LocalDateTime.now())
query.list().forEach { ping ->
val serverIPAddress: InetAddress
val serverAddress: InetSocketAddress
val s: SocketChannel
val ctxPing: ContextPing
try {
serverIPAddress = InetAddress.getByName(ping.hostname)
serverAddress = InetSocketAddress(serverIPAddress, ping.port)
} catch (e: UnknownHostException) {
logger.error("Unknown host exception. Continuing...")
return@forEach
}
try {
s = SocketChannel.open()
s.configureBlocking(false)
s.connect(serverAddress)
} catch (e: IOException) {
logger.error("Opening socket IOException. Continuing...")
return@forEach
}
val operations = SelectionKey.OP_CONNECT or SelectionKey.OP_READ or SelectionKey.OP_WRITE
ctxPing = ContextPing(serverAddress.address)
ctxPing.account = ping.gm!!
s.register(pingSelector, operations, ctxPing)
tx = session?.beginTransaction()
ping.refresh = LocalDateTime.now().plusSeconds(pingInterval)
session?.merge(ping)
tx?.commit()
ctxPing.ping = ping
}
}catch (e: Exception){
logger.fatal("Hibernate fatal error!")
logger.fatal(Throwables.getStackTraceAsString(e))
tx?.rollback()
}finally {
session?.close()
}
// connect, read, write
if (pingSelector.select(selectTimeout) > 0) {
iterator = pingSelector.selectedKeys().iterator()
while (iterator.hasNext()) {
val key = iterator.next()
iterator.remove()
// getting socket
val s = key.channel() as SocketChannel
val c = key.attachment() as ContextPing
try {
// connecting
if (key.isConnectable) {
while (s.isConnectionPending) {
s.finishConnect()
}
logger.trace("Connected. IP: ${c.channel.addressAsString}")
}
// reading
if (key.isReadable && s.isConnected) {
if (s.read(inBuffer) > 0) {
inBuffer.flip()
c.channel.putByteBuffer(inBuffer)
}
inBuffer.clear()
}
// writing
if (key.isWritable && s.isConnected) {
c.channel.getByteBuffer(outBuffer)
outBuffer.flip()
if( outBuffer.hasRemaining() )
s.write(outBuffer)
outBuffer.clear()
}
} catch (e: IOException) {
logger.error("IOException on socket. Socket is closing in the next cycle. IP: $c.channel.getAddressAsString()")
}
}
}
// ping contexts
iterator = pingSelector.keys().iterator()
while (iterator.hasNext()) {
val key = iterator.next()
// getting socket
val s = key.channel() as SocketChannel
val ctx = key.attachment() as ContextPing
// processing context
ctx.process()
if( ctx.state is StateStop){
try {
s.close()
} catch (e: IOException) {
logger.error("IOException s.close() invalid sockets.")
}
}
}
// refresh games
session = null
tx = null
try{
session = sessionFactory.openSession()
val querySelect = session.createNamedQuery("refreshGame",Game::class.java)
querySelect.setParameter("now", LocalDateTime.now())
val list = querySelect.list()
list.forEach { game ->
tx = session.beginTransaction()
val uuid = game.uuid
val gm = game.gm
val campaign = game.campaign
val rpgGameSystem = game.rpgGameSystem
val players = game.players
val hostname = game.hostname
val port = game.port
val ping = Ping()
ping.uuid = uuid
ping.gm = gm!!
ping.campaign = campaign
ping.rpgGameSystem = rpgGameSystem
ping.players = players
ping.hostname = hostname
ping.port = port
session.save(ping)
session.delete(game)
tx?.commit()
}
}catch (e: Exception){
logger.fatal("Hibernate fatal error!")
logger.fatal(Throwables.getStackTraceAsString(e))
tx?.rollback()
}finally {
session?.close()
}
}
}
}
|
bsd-2-clause
|
778ad0b009cc5a000cc71498bb77e20d
| 31.774648 | 159 | 0.474789 | 5.829645 | false | false | false | false |
deso88/TinyGit
|
src/main/kotlin/hamburg/remme/tinygit/domain/service/BranchService.kt
|
1
|
6929
|
package hamburg.remme.tinygit.domain.service
import hamburg.remme.tinygit.I18N
import hamburg.remme.tinygit.Refreshable
import hamburg.remme.tinygit.Service
import hamburg.remme.tinygit.TinyGit
import hamburg.remme.tinygit.domain.Branch
import hamburg.remme.tinygit.domain.Commit
import hamburg.remme.tinygit.domain.Head
import hamburg.remme.tinygit.domain.Repository
import hamburg.remme.tinygit.execute
import hamburg.remme.tinygit.git.BranchAlreadyExistsException
import hamburg.remme.tinygit.git.BranchNameInvalidException
import hamburg.remme.tinygit.git.BranchUnpushedException
import hamburg.remme.tinygit.git.CheckoutException
import hamburg.remme.tinygit.git.gitBranch
import hamburg.remme.tinygit.git.gitBranchDelete
import hamburg.remme.tinygit.git.gitBranchList
import hamburg.remme.tinygit.git.gitBranchMove
import hamburg.remme.tinygit.git.gitCheckout
import hamburg.remme.tinygit.git.gitCheckoutRemote
import hamburg.remme.tinygit.git.gitHead
import hamburg.remme.tinygit.git.gitPushDelete
import hamburg.remme.tinygit.git.gitResetHard
import hamburg.remme.tinygit.git.gitSquash
import hamburg.remme.tinygit.observableList
import javafx.beans.binding.Bindings
import javafx.beans.property.SimpleObjectProperty
import javafx.concurrent.Task
@Service
class BranchService(private val repositoryService: RepositoryService,
private val credentialService: CredentialService) : Refreshable {
val head = SimpleObjectProperty<Head>(Head.EMPTY)
val branches = observableList<Branch>()
val branchesSize = Bindings.size(branches)!!
private lateinit var repository: Repository
private var task: Task<*>? = null
fun isHead(branch: Branch) = head.get().name == branch.name
fun isDetached(branch: Branch) = branch.name == "HEAD"
fun checkoutCommit(commit: Commit, errorHandler: () -> Unit) {
TinyGit.run(I18N["branch.checkoutCommit"], object : Task<Unit>() {
override fun call() = gitCheckout(repository, commit)
override fun succeeded() = TinyGit.fireEvent()
override fun failed() {
when (exception) {
is CheckoutException -> errorHandler()
else -> exception.printStackTrace()
}
}
})
}
fun checkoutLocal(branch: Branch, errorHandler: () -> Unit) {
if (branch != head.get()) {
TinyGit.run(I18N["branch.checkoutLocal"], object : Task<Unit>() {
override fun call() = gitCheckout(repository, branch)
override fun succeeded() = TinyGit.fireEvent()
override fun failed() {
when (exception) {
is CheckoutException -> errorHandler()
else -> exception.printStackTrace()
}
}
})
}
}
fun checkoutRemote(branch: Branch, errorHandler: () -> Unit) {
TinyGit.run(I18N["branch.checkoutRemote"], object : Task<Unit>() {
override fun call() = gitCheckoutRemote(repository, branch)
override fun succeeded() = TinyGit.fireEvent()
override fun failed() {
when (exception) {
is CheckoutException -> checkoutLocal(Branch("", branch.name.substringAfter('/'), false), errorHandler)
else -> exception.printStackTrace()
}
}
})
}
fun rename(branch: Branch, newName: String, branchExistsHandler: () -> Unit) {
try {
gitBranchMove(repository, branch, newName)
TinyGit.fireEvent()
} catch (ex: BranchAlreadyExistsException) {
branchExistsHandler()
}
}
fun deleteLocal(branch: Branch, force: Boolean, branchUnpushedHandler: () -> Unit = {}) {
try {
gitBranchDelete(repository, branch, force)
TinyGit.fireEvent()
} catch (ex: BranchUnpushedException) {
branchUnpushedHandler()
}
}
fun deleteRemote(branch: Branch) {
credentialService.applyCredentials(repositoryService.remote.get())
TinyGit.run(I18N["branch.delete"], object : Task<Unit>() {
override fun call() = gitPushDelete(repository, branch)
override fun succeeded() = TinyGit.fireEvent()
override fun failed() = exception.printStackTrace()
})
}
fun branch(name: String, branchExistsHandler: () -> Unit, nameInvalidHandler: () -> Unit) {
TinyGit.run(I18N["branch.create"], object : Task<Unit>() {
override fun call() = gitBranch(repository, name)
override fun succeeded() = TinyGit.fireEvent()
override fun failed() {
when (exception) {
is BranchAlreadyExistsException -> branchExistsHandler()
is BranchNameInvalidException -> nameInvalidHandler()
else -> exception.printStackTrace()
}
}
})
}
fun reset(commit: Commit) {
TinyGit.run(I18N["branch.reset"], object : Task<Unit>() {
override fun call() = gitResetHard(repository, commit)
override fun succeeded() = TinyGit.fireEvent()
override fun failed() = exception.printStackTrace()
})
}
fun autoReset() {
TinyGit.run(I18N["branch.autoReset"], object : Task<Unit>() {
override fun call() = gitResetHard(repository, head.get())
override fun succeeded() = TinyGit.fireEvent()
override fun failed() = exception.printStackTrace()
})
}
fun autoSquash(baseId: String, message: String) {
TinyGit.run(I18N["branch.autoSquash"], object : Task<Unit>() {
override fun call() = gitSquash(repository, baseId, message)
override fun succeeded() = TinyGit.fireEvent()
override fun failed() = exception.printStackTrace()
})
}
override fun onRefresh(repository: Repository) {
update(repository)
}
override fun onRepositoryChanged(repository: Repository) {
onRepositoryDeselected()
update(repository)
}
override fun onRepositoryDeselected() {
task?.cancel()
head.set(Head.EMPTY)
branches.clear()
}
private fun update(repository: Repository) {
this.repository = repository
task?.cancel()
task = object : Task<Unit>() {
private lateinit var head: Head
private lateinit var branches: List<Branch>
override fun call() {
head = gitHead(repository)
branches = gitBranchList(repository)
}
override fun succeeded() {
[email protected](head)
[email protected](branches)
}
}.execute()
}
}
|
bsd-3-clause
|
7a1fb26fbb646767262f0b155d706e53
| 33.472637 | 123 | 0.622889 | 4.726467 | false | false | false | false |
Iterable/iterable-android-sdk
|
app/src/androidTest/java/com/iterable/iterableapi/util/DataManager.kt
|
1
|
2405
|
package com.iterable.iterableapi.util
import android.content.Context
import android.os.StrictMode
import com.iterable.iterableapi.IterableApi
import com.iterable.iterableapi.IterableInternal
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.Buffer
import okio.source
import java.lang.Exception
class DataManager {
var context: Context? = null
val server = MockWebServer()
val serverUrl: String
val dispatcher = PathBasedStaticDispatcher()
init {
// Required for `server.url("")` to work on main thread without throwing an exception
// DO NOT USE THIS in production. This is for demo purposes only.
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().permitAll().build())
server.dispatcher = dispatcher
serverUrl = server.url("").toString()
}
fun initializeIterableApi(context: Context) {
this.context = context
initHttpMocks()
IterableApi.overrideURLEndpointPath(serverUrl)
IterableApi.initialize(context, "apiKey")
IterableApi.getInstance().setEmail("[email protected]")
loadData("simple-inbox-messages.json")
}
fun initHttpMocks() {
loadFileMock("mocha.png")
loadFileMock("black-coffee.png")
loadFileMock("cappuccino.png")
loadFileMock("latte.png")
}
fun loadFileMock(imageName: String) {
val buffer = Buffer()
try {
context!!.resources.assets.open(imageName).source().use {
buffer.writeAll(it)
}
} catch (e: Exception) {
}
dispatcher.setResponse("/$imageName", MockResponse().setBody(buffer))
}
companion object {
val instance = DataManager()
fun initializeIterableApi(context: Context) {
instance.initializeIterableApi(context)
}
fun loadData(resourceName: String) {
val body = getAssetString(resourceName).replace("https://somewhere.com/", instance.serverUrl)
instance.dispatcher.setResponse("/inApp/getMessages", MockResponse().setBody(body))
IterableInternal.syncInApp()
}
private fun getAssetString(fileName: String): String {
return instance.context!!.resources.assets.open(fileName).bufferedReader().use {
it.readText()
}
}
}
}
|
mit
|
6df89a469753adbbe14f0be4f7f06163
| 30.657895 | 105 | 0.658628 | 4.715686 | false | false | false | false |
indianpoptart/RadioControl
|
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/utilities/AlarmSchedulers.kt
|
1
|
12308
|
package com.nikhilparanjape.radiocontrol.utilities
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.nikhilparanjape.radiocontrol.receivers.*
import java.util.*
/**
* Created by Nikhil on 10/12/2018.
*
* A class with a bunch of AlarmScheduler Utilities for RadioControl
*
* Still contains legacy alarms for older devices that can still utilize timers efficiently
*
* @author Nikhil Paranjape
*
*
*/
class AlarmSchedulers{
//PendingIntent Variables
private val defaultFlag = PendingIntent.FLAG_UPDATE_CURRENT
private val marshmallowFlag = PendingIntent.FLAG_IMMUTABLE or defaultFlag
fun scheduleGeneralAlarm (c: Context, schedule: Boolean, hour: Int, minute: Int, intentApp: String, pIntentApp: String){
val cal = Calendar.getInstance()
// start 30 seconds after boot completed
cal.add(Calendar.HOUR, hour)
// Construct an intent that will execute the AlarmReceiver based on which class you want
val intent = when {
intentApp.contains("Wakeup") -> Intent(c, WakeupReceiver::class.java)
intentApp.contains("TimedAlarm") -> Intent(c, TimedAlarmReceiver::class.java)
intentApp.contains("RootService") -> Intent(c, RootServiceReceiver::class.java)
intentApp.contains("NightMode") -> Intent(c, NightModeReceiver::class.java)
else -> Intent(c,TimedAlarmReceiver::class.java)
}
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
val pIntent = when {
pIntentApp.contains("Wakeup") -> PendingIntent.getBroadcast(c, WakeupReceiver.REQUEST_CODE,
intent, flags)
pIntentApp.contains("TimedAlarm") -> PendingIntent.getBroadcast(c, TimedAlarmReceiver.REQUEST_CODE,
intent, flags)
pIntentApp.contains("RootService") -> PendingIntent.getBroadcast(c, RootServiceReceiver.REQUEST_CODE,
intent, flags)
pIntentApp.contains("NightMode") -> PendingIntent.getBroadcast(c, NightModeReceiver.REQUEST_CODE,
intent, flags)
else -> PendingIntent.getBroadcast(c, TimedAlarmReceiver.REQUEST_CODE,
intent, flags)
}
}
fun cancelAlarm(c: Context, intentApp: String, pIntentApp: String){
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
val intent = when {
intentApp.contains("Wakeup") -> Intent(c, WakeupReceiver::class.java)
intentApp.contains("TimedAlarm") -> Intent(c, TimedAlarmReceiver::class.java)
intentApp.contains("RootService") -> Intent(c, RootServiceReceiver::class.java)
intentApp.contains("NightMode") -> Intent(c, NightModeReceiver::class.java)
else -> Intent(c,TimedAlarmReceiver::class.java)
}
val pIntent = when {
pIntentApp.contains("Wakeup") -> PendingIntent.getBroadcast(c, WakeupReceiver.REQUEST_CODE,
intent, flags)
pIntentApp.contains("TimedAlarm") -> PendingIntent.getBroadcast(c, TimedAlarmReceiver.REQUEST_CODE,
intent, flags)
pIntentApp.contains("RootService") -> PendingIntent.getBroadcast(c, RootServiceReceiver.REQUEST_CODE,
intent, flags)
pIntentApp.contains("NightMode") -> PendingIntent.getBroadcast(c, NightModeReceiver.REQUEST_CODE,
intent, flags)
else -> PendingIntent.getBroadcast(c, TimedAlarmReceiver.REQUEST_CODE,
intent, flags)
}
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarm.cancel(pIntent)
Log.d(TAG, "$intentApp cancelled")
}
fun scheduleWakeupAlarm(c: Context, hour: Int) {
val cal = Calendar.getInstance()
// start 30 seconds after boot completed
cal.add(Calendar.HOUR, hour)
// Construct an intent that will execute the AlarmReceiver
val intent = Intent(c, WakeupReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
// Create a PendingIntent to be triggered when the alarm goes off
val pIntent = PendingIntent.getBroadcast(c, ActionReceiver.REQUEST_CODE,
intent, flags)
// Setup periodic alarm every 5 seconds
val firstMillis = System.currentTimeMillis() // alarm is set right away
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
cal.timeInMillis, pIntent)
}
fun scheduleNightWakeupAlarm(c: Context, hourofDay: Int, minute: Int) {
val cal = Calendar.getInstance()
// start 30 seconds after boot completed
cal.add(Calendar.HOUR_OF_DAY, hourofDay)
cal.add(Calendar.MINUTE, minute)
// Construct an intent that will execute the AlarmReceiver
val intent = Intent(c, TimedAlarmReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
// Create a PendingIntent to be triggered when the alarm goes off
val pIntent = PendingIntent.getBroadcast(c, TimedAlarmReceiver.REQUEST_CODE,
intent, flags)
// Setup periodic alarm every 5 seconds
val firstMillis = System.currentTimeMillis() // alarm is set right away
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
cal.timeInMillis, pIntent)
}
// Setup a recurring alarm every 15,30,60 minutes
@SuppressLint("UnspecifiedImmutableFlag") // Covered this
fun scheduleAlarm(c: Context) {
val preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(c)
val intervalTimeString = preferences.getString("interval_prefs", "10")
val intervalTime = Integer.parseInt(intervalTimeString.toString())
val cal = Calendar.getInstance()
// start 30 seconds after boot completed
cal.add(Calendar.MINUTE, intervalTime)
Log.d(TAG, "Interval: " + intervalTime + cal.time)
// Construct an intent that will execute the AlarmReceiver
val intent = Intent(c, TimedAlarmReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
// Create a PendingIntent to be triggered when the alarm goes off
val pIntent = PendingIntent.getBroadcast(c, TimedAlarmReceiver.REQUEST_CODE,
intent, flags)
// Setup periodic alarm every 5 seconds
val firstMillis = System.currentTimeMillis() // alarm is set right away
val interval = cal.timeInMillis
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
Log.d(TAG, "Time: " + (cal.timeInMillis - firstMillis))
//alarm.setInexactRepeating(RTC, firstMillis,
//cal.getTimeInMillis(), pIntent);
alarm.setInexactRepeating(AlarmManager.RTC, firstMillis + interval, interval, pIntent)
}
fun scheduleRootAlarm(c: Context) {
val cal = Calendar.getInstance()
// start 10 seconds
cal.add(Calendar.SECOND, 5)
// Construct an intent that will execute the AlarmReceiver
val intent = Intent(c, RootServiceReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
// Create a PendingIntent to be triggered when the alarm goes off
val pIntent = PendingIntent.getBroadcast(c, RootServiceReceiver.REQUEST_CODE,
intent, flags)
// Setup periodic alarm every X seconds
val firstMillis = System.currentTimeMillis() // alarm is set right away
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
cal.timeInMillis, pIntent)
Log.d(TAG, "RootClock enabled for " + cal.time)
}
/**
* Cancels the pending root reset clock
* @param c
* @return
*/
fun cancelRootAlarm(c: Context) {
val intent = Intent(c, RootServiceReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
val pIntent = PendingIntent.getBroadcast(c, RootServiceReceiver.REQUEST_CODE,
intent, flags)
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarm.cancel(pIntent)
Log.d(TAG, "RootClock cancelled")
}
fun cancelAlarm(c: Context) {
val intent = Intent(c, TimedAlarmReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
val pIntent = PendingIntent.getBroadcast(c, TimedAlarmReceiver.REQUEST_CODE,
intent, flags)
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarm.cancel(pIntent)
}
fun cancelNightAlarm(c: Context, hourofDay: Int, minute: Int) {
val cal = Calendar.getInstance()
// start 30 seconds after boot completed
cal.add(Calendar.HOUR_OF_DAY, hourofDay)
cal.add(Calendar.MINUTE, minute)
// Construct an intent that will execute the AlarmReceiver
val intent = Intent(c, NightModeReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
// Create a PendingIntent to be triggered when the alarm goes off
val pIntent = PendingIntent.getBroadcast(c, NightModeReceiver.REQUEST_CODE,
intent, flags)
// Setup periodic alarm every 5 seconds
val firstMillis = System.currentTimeMillis() // alarm is set right away
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
cal.timeInMillis, pIntent)
}
fun cancelWakeupAlarm(c: Context) {
val intent = Intent(c, WakeupReceiver::class.java)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
marshmallowFlag
} else{
defaultFlag
}
val pIntent = PendingIntent.getBroadcast(c, WakeupReceiver.REQUEST_CODE,
intent, flags)
val alarm = c.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarm.cancel(pIntent)
}
companion object {
private const val TAG = "RadioControl-Alarms"
}
}
|
gpl-3.0
|
4c11e8c25734093a56647b12af0eb084
| 41.739583 | 124 | 0.653152 | 4.425746 | false | false | false | false |
Virtlink/aesi
|
aesi-intellij/src/main/kotlin/com/virtlink/editorservices/intellij/syntaxcoloring/AesiParserDefinition.kt
|
1
|
2029
|
package com.virtlink.editorservices.intellij.syntaxcoloring
import com.google.inject.Inject
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import com.virtlink.editorservices.intellij.psi.*
open class AesiParserDefinition @Inject constructor(
private val fileType: LanguageFileType,
private val fileElementType: IFileElementType,
private val tokenTypeManager: AesiTokenTypeManager)
: ParserDefinition {
override fun getFileNodeType(): IFileElementType = this.fileElementType
override fun spaceExistanceTypeBetweenTokens(left: ASTNode, right: ASTNode): ParserDefinition.SpaceRequirements
= ParserDefinition.SpaceRequirements.MAY
override fun getStringLiteralElements(): TokenSet = tokenTypeManager.stringLiteralTokens
override fun getWhitespaceTokens(): TokenSet = tokenTypeManager.whitespaceTokens
override fun getCommentTokens(): TokenSet = tokenTypeManager.commentTokens
override fun createLexer(project: Project?): Lexer
= throw UnsupportedOperationException("See AesiFileElementType.doParseContents().")
override fun createParser(project: Project): PsiParser
= throw UnsupportedOperationException("See AesiFileElementType.doParseContents().")
override fun createFile(viewProvider: FileViewProvider): PsiFile = AesiFile2(viewProvider, this.fileType)
override fun createElement(node: ASTNode): PsiElement {
val elementType = node.elementType
if (elementType !is AesiElementType)
throw UnsupportedOperationException("Unexpected element type: $elementType")
return elementType.createElement(node)
}
}
|
apache-2.0
|
23862d0705daa0159b8f5c01c0b418dd
| 40.428571 | 115 | 0.793001 | 5.425134 | false | false | false | false |
google/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/FeatureFlags.kt
|
1
|
1981
|
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.jetbrains.packagesearch.intellij.plugin.util
import com.intellij.openapi.util.registry.RegistryManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.openapi.util.registry.RegistryValueListener
import kotlinx.coroutines.flow.Flow
object FeatureFlags {
val useDebugLogging: Boolean
get() = Registry.`is`("packagesearch.plugin.debug.logging", false)
val showRepositoriesTabFlow
get() = registryChangesFlow("packagesearch.plugin.repositories.tab")
val smartKotlinMultiplatformCheckboxEnabledFlow
get() = registryChangesFlow("packagesearch.plugin.smart.kotlin.multiplatform.checkbox")
}
private fun registryChangesFlow(key: String, defaultValue: Boolean = false): Flow<Boolean> =
ApplicationManager.getApplication().messageBusFlow(RegistryManager.TOPIC, { Registry.`is`(key, defaultValue) }) {
object : RegistryValueListener {
override fun afterValueChanged(value: RegistryValue) {
if (value.key == key) trySend(Registry.`is`(key, defaultValue))
}
}
}
|
apache-2.0
|
f2ec98335831955e7537536740fd360d
| 43.022222 | 117 | 0.692075 | 4.891358 | false | false | false | false |
littleGnAl/Accounting
|
app/src/main/java/com/littlegnal/accounting/ui/main/adapter/MainAccountingDetailHeaderModel.kt
|
1
|
1682
|
/*
* Copyright (C) 2017 littlegnal
*
* 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.littlegnal.accounting.ui.main.adapter
import androidx.appcompat.widget.AppCompatTextView
import android.view.View
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyHolder
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.EpoxyModelWithHolder
import com.littlegnal.accounting.R
@EpoxyModelClass(layout = R.layout.main_accounting_detail_header_layout)
abstract class MainAccountingDetailHeaderModel :
EpoxyModelWithHolder<MainAccountingDetailHeaderModel.HeaderHolder>() {
@EpoxyAttribute var title: String? = null
@EpoxyAttribute var total: String? = null
override fun bind(holder: HeaderHolder) {
super.bind(holder)
holder.header.text = title
holder.total.text = total
}
class HeaderHolder : EpoxyHolder() {
lateinit var header: AppCompatTextView
lateinit var total: AppCompatTextView
override fun bindView(itemView: View) {
header = itemView.findViewById(R.id.main_accounting_detail_header_title)
total = itemView.findViewById(R.id.main_accounting_detail_header_total)
}
}
}
|
apache-2.0
|
3ab7216415b69229c700b427316ca6e6
| 31.980392 | 78 | 0.763971 | 4.173697 | false | false | false | false |
spacecowboy/Feeder
|
app/src/main/java/com/nononsenseapps/feeder/util/HtmlUtils.kt
|
1
|
2051
|
package com.nononsenseapps.feeder.util
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Browser.EXTRA_CREATE_NEW_TAB
import android.widget.Toast
import androidx.annotation.ColorInt
import androidx.browser.customtabs.CustomTabsIntent
import com.nononsenseapps.feeder.R
// Using negative lookahead to skip data: urls, being inline base64
// And capturing original quote to use as ending quote
private val regexImgSrc = """img.*?src=(["'])((?!data).*?)\1""".toRegex(RegexOption.DOT_MATCHES_ALL)
fun naiveFindImageLink(text: String?): String? =
if (text != null) {
val imgLink = regexImgSrc.find(text)?.groupValues?.get(2)
if (imgLink?.contains("twitter_icon", ignoreCase = true) == true) {
null
} else {
imgLink
}
} else {
null
}
/**
* Opens the specified link in a new tab in the browser, or otherwise suitable application. If no suitable application
* could be found, a Toast is displayed and false is returned. Otherwise, true is returned.
*/
fun openLinkInBrowser(context: Context, link: String): Boolean {
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
intent.putExtra(EXTRA_CREATE_NEW_TAB, true)
context.startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, R.string.no_activity_for_link, Toast.LENGTH_SHORT).show()
return false
}
return true
}
fun openLinkInCustomTab(
context: Context,
link: String,
@ColorInt toolbarColor: Int,
): Boolean {
try {
val intent = CustomTabsIntent.Builder().apply {
setToolbarColor(toolbarColor)
addDefaultShareMenuItem()
}.build()
intent.launchUrl(context, Uri.parse(link))
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, R.string.no_activity_for_link, Toast.LENGTH_SHORT).show()
return false
}
return true
}
|
gpl-3.0
|
3010473d49a250ae5e21677ee0fde082
| 32.622951 | 118 | 0.686494 | 4.160243 | false | false | false | false |
allotria/intellij-community
|
python/src/com/jetbrains/python/console/transport/server/TNettyServerTransport.kt
|
3
|
9431
|
package com.jetbrains.python.console.transport.server
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.ConcurrencyUtil
import com.jetbrains.python.console.transport.DirectedMessage
import com.jetbrains.python.console.transport.DirectedMessageCodec
import com.jetbrains.python.console.transport.DirectedMessageHandler
import com.jetbrains.python.console.transport.TCumulativeTransport
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
import io.netty.handler.codec.LengthFieldPrepender
import io.netty.handler.logging.LoggingHandler
import org.apache.thrift.transport.TServerTransport
import org.apache.thrift.transport.TTransport
import org.apache.thrift.transport.TTransportException
import java.util.concurrent.BlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
/**
* @param host the hostname to bind Python Console server at
* @param port the port to bind Python Console server at
*/
class TNettyServerTransport(host: String, port: Int) : TServerTransport() {
private val nettyServer: NettyServer = NettyServer(host, port)
@Throws(TTransportException::class)
override fun listen() {
try {
nettyServer.listen()
}
catch (e: InterruptedException) {
throw TTransportException(e)
}
}
@Throws(InterruptedException::class)
fun waitForBind() {
nettyServer.waitForBind()
}
@Throws(InterruptedException::class)
fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean {
return nettyServer.awaitTermination(timeout, unit)
}
override fun acceptImpl(): TTransport = nettyServer.accept()
override fun interrupt() {
close()
}
override fun close() {
nettyServer.close()
}
@Throws(InterruptedException::class)
fun getReverseTransport(): TTransport = nettyServer.takeReverseTransport()
private class NettyServer(val host: String, val port: Int) {
private val closed: AtomicBoolean = AtomicBoolean(false)
private val acceptQueue: BlockingQueue<TTransport> = LinkedBlockingQueue()
private val reverseTransportQueue: BlockingQueue<TTransport> = LinkedBlockingQueue()
// The first one, often called 'boss', accepts an incoming connection.
private val bossGroup = NioEventLoopGroup(0, ConcurrencyUtil.newNamedThreadFactory("Python Console NIO Event Loop Boss")) // (1)
// The second one, often called 'worker', handles the traffic of the
// accepted connection once the boss accepts the connection and registers
// the accepted connection to the worker.
private val workerGroup = NioEventLoopGroup(0, ConcurrencyUtil.newNamedThreadFactory("Python Console NIO Event Loop Worker"))
private val serverBound = CountDownLatch(1)
fun listen() {
// ServerBootstrap is a helper class that sets up a server. You can set
// up the server using a Channel directly. However, please note that this
// is a tedious process, and you do not need to do that in most cases.
val b = ServerBootstrap() // (2)
b.group(bossGroup, workerGroup)
// Here, we specify to use the NioServerSocketChannel class which is
// used to instantiate a new Channel to accept incoming connections.
.channel(NioServerSocketChannel::class.java) // (3)
// The handler specified here will always be evaluated by a newly
// accepted Channel. The ChannelInitializer is a special handler that
// is purposed to help a user configure a new Channel. It is most
// likely that you want to configure the ChannelPipeline of the new
// Channel by adding some handlers such as DiscardServerHandler to
// implement your network application. As the application gets
// complicated, it is likely that you will add more handlers to the
// pipeline and extract this anonymous class into a top level class
// eventually.
.childHandler(object : ChannelInitializer<SocketChannel>() { // (4)
@Throws(Exception::class)
override fun initChannel(ch: SocketChannel) {
LOG.debug("Connection to Thrift server on $port received")
ch.pipeline().addLast(LoggingHandler("#${TNettyServerTransport::class.java.name}"))
// `FixedLengthFrameDecoder` is excessive but convenient
ch.pipeline().addLast(LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4))
ch.pipeline().addLast(LengthFieldPrepender(4))
// `DirectedMessageCodec` is above Thrift messages
ch.pipeline().addLast(DirectedMessageCodec())
// here comes Thrift
val thriftTransport = TNettyTransport(ch)
val reverseTransport = TNettyClientTransport(ch)
ch.pipeline().addLast(DirectedMessageHandler(reverseTransport.outputStream, thriftTransport.outputStream))
ch.pipeline().addLast(object : ChannelInboundHandlerAdapter() {
override fun channelInactive(ctx: ChannelHandlerContext) {
thriftTransport.close()
reverseTransport.close()
super.channelInactive(ctx)
}
})
// ready!
acceptQueue.put(thriftTransport)
reverseTransportQueue.put(reverseTransport)
}
})
// You can also set the parameters which are specific to the Channel
// implementation. We are writing a TCP/IP server, so we are allowed to
// set the socket options such as tcpNoDelay and keepAlive. Please
// refer to the apidocs of ChannelOption and the specific ChannelConfig
// implementations to get an overview about the supported
// ChannelOptions.
.option(ChannelOption.SO_BACKLOG, 128) // (5)
// Did you notice option() and childOption()? option() is for the
// NioServerSocketChannel that accepts incoming connections.
// childOption() is for the Channels accepted by the parent
// ServerChannel, which is NioServerSocketChannel in this case.
.childOption(ChannelOption.SO_KEEPALIVE, true) // (6)
// Bind and start to accept incoming connections.
// We are ready to go now. What's left is to bind to the port and to
// start the server.
b.bind(host, port).sync() // (7)
LOG.debug("Running Netty server on $port")
serverBound.countDown()
}
/**
* @throws InterruptedException if [CountDownLatch.await] is interrupted
* @throws ServerClosedException if [NettyServer] gets closed
*/
@Throws(InterruptedException::class)
fun waitForBind() {
while (!closed.get()) {
if (serverBound.await(100L, TimeUnit.MILLISECONDS)) {
return
}
}
throw ServerClosedException()
}
fun accept(): TTransport {
try {
while (true) {
val acceptedTransport = acceptQueue.poll(100L, TimeUnit.MILLISECONDS)
if (closed.get()) {
throw TTransportException("Netty server is closed")
}
if (acceptedTransport != null) {
return acceptedTransport
}
}
}
catch (e: InterruptedException) {
throw TTransportException(e)
}
}
/**
* @throws InterruptedException if [BlockingQueue.poll] is interrupted
* @throws ServerClosedException if [NettyServer] gets closed
*/
@Throws(InterruptedException::class)
fun takeReverseTransport(): TTransport {
while (!closed.get()) {
val element = reverseTransportQueue.poll(100L, TimeUnit.MILLISECONDS)
if (element != null) {
return element
}
}
throw ServerClosedException()
}
/**
* Shutdown the server [NioEventLoopGroup].
*
* Does not wait for the server socket to be closed.
*/
fun close() {
if (closed.compareAndSet(false, true)) {
LOG.debug("Closing Netty server")
workerGroup.shutdownGracefully()
bossGroup.shutdownGracefully()
}
}
@Throws(InterruptedException::class)
fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean {
return workerGroup.awaitTermination(timeout, unit) && bossGroup.awaitTermination(timeout, unit)
}
}
private class TNettyTransport(private val channel: SocketChannel) : TCumulativeTransport() {
override fun isOpen(): Boolean = channel.isOpen
override fun writeMessage(content: ByteArray) {
channel.writeAndFlush(DirectedMessage(DirectedMessage.MessageDirection.RESPONSE, content))
}
}
private class TNettyClientTransport(private val channel: SocketChannel) : TCumulativeTransport() {
override fun isOpen(): Boolean = channel.isOpen
override fun writeMessage(content: ByteArray) {
channel.writeAndFlush(DirectedMessage(DirectedMessage.MessageDirection.REQUEST, content))
}
}
companion object {
val LOG = Logger.getInstance(TNettyServerTransport::class.java)
}
}
|
apache-2.0
|
8c0a3cc98ca30b519aff7a46ef48c622
| 37.655738 | 132 | 0.698865 | 4.770359 | false | false | false | false |
allotria/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateStrategy.kt
|
1
|
4490
|
// 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.openapi.updateSettings.impl
import com.intellij.openapi.updateSettings.UpdateStrategyCustomization
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.containers.MultiMap
import com.intellij.util.graph.GraphAlgorithms
import com.intellij.util.graph.InboundSemiGraph
import java.util.*
private val NUMBER = Regex("\\d+")
class UpdateStrategy(private val currentBuild: BuildNumber, private val product: Product?, private val settings: UpdateSettings) {
constructor(currentBuild: BuildNumber, updates: UpdatesInfo, settings: UpdateSettings) :
this(currentBuild, updates[currentBuild.productCode], settings)
private val customization = UpdateStrategyCustomization.getInstance()
enum class State {
LOADED, CONNECTION_ERROR, NOTHING_LOADED
}
fun checkForUpdates(): CheckForUpdateResult {
if (product == null || product.channels.isEmpty()) {
return CheckForUpdateResult(State.NOTHING_LOADED, null)
}
val selectedChannel = settings.selectedChannelStatus
val ignoredBuilds = settings.ignoredBuildNumbers.toSet()
val result = product.channels.asSequence()
.filter { ch -> ch.status >= selectedChannel } // filters out inapplicable channels
.sortedBy { ch -> ch.status } // reorders channels (EAPs first)
.flatMap { ch -> ch.builds.asSequence().map { build -> build to ch } } // maps into a sequence of <build, channel> pairs
.filter { p -> isApplicable(p.first, ignoredBuilds) } // filters out inapplicable builds
.maxWithOrNull(Comparator { p1, p2 -> compareBuilds(p1.first.number, p2.first.number) }) // a build with the max number, preferring the same baseline
val newBuild = result?.first
val updatedChannel = result?.second
val patches = if (newBuild != null) patches(newBuild, product, currentBuild) else null
return CheckForUpdateResult(newBuild, updatedChannel, patches)
}
private fun isApplicable(candidate: BuildInfo, ignoredBuilds: Set<String>): Boolean =
customization.isNewerVersion(candidate.number, currentBuild) &&
candidate.number.asStringWithoutProductCode() !in ignoredBuilds &&
candidate.target?.inRange(currentBuild) ?: true
private fun compareBuilds(n1: BuildNumber, n2: BuildNumber): Int {
val preferSameMajorVersion = customization.haveSameMajorVersion(currentBuild, n1).compareTo(customization.haveSameMajorVersion(currentBuild, n2))
return if (preferSameMajorVersion != 0) preferSameMajorVersion else n1.compareTo(n2)
}
private fun patches(newBuild: BuildInfo, product: Product, from: BuildNumber): UpdateChain? {
val single = newBuild.patches.find { it.isAvailable && it.fromBuild.compareTo(from) == 0 }
if (single != null) {
return UpdateChain(listOf(from, newBuild.number), single.size)
}
val upgrades = MultiMap<BuildNumber, BuildNumber>()
val sizes = mutableMapOf<Pair<BuildNumber, BuildNumber>, Int>()
product.channels.forEach { channel ->
channel.builds.forEach { build ->
val toBuild = build.number.withoutProductCode()
build.patches.forEach { patch ->
if (patch.isAvailable) {
val fromBuild = patch.fromBuild.withoutProductCode()
upgrades.putValue(toBuild, fromBuild)
if (patch.size != null) {
val maxSize = NUMBER.findAll(patch.size).map { it.value.toIntOrNull() }.filterNotNull().maxOrNull()
if (maxSize != null) sizes += (fromBuild to toBuild) to maxSize
}
}
}
}
}
val graph = object : InboundSemiGraph<BuildNumber> {
override fun getNodes() = upgrades.keySet() + upgrades.values()
override fun getIn(n: BuildNumber) = upgrades[n].iterator()
}
val path = GraphAlgorithms.getInstance().findShortestPath(graph, from.withoutProductCode(), newBuild.number.withoutProductCode())
if (path == null || path.size <= 2) return null
var total = 0
for (i in 1 until path.size) {
val size = sizes[path[i - 1] to path[i]]
if (size == null) {
total = -1
break
}
total += size
}
return UpdateChain(path, if (total > 0) total.toString() else null)
}
}
|
apache-2.0
|
991fab164101aa37a4aaf546c476fb63
| 45.28866 | 156 | 0.679955 | 4.716387 | false | false | false | false |
aporter/coursera-android
|
ExamplesKotlin/UISpinner/app/src/main/java/course/examples/ui/spinner/SpinnerActivity.kt
|
1
|
2060
|
package course.examples.ui.spinner
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
class SpinnerActivity : Activity() {
companion object {
private var wasTouched: Boolean = false
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
// Indicates whether spinner was touched by user
wasTouched = false
// Get a reference to the Spinner
val spinner = findViewById<Spinner>(R.id.spinner)
// Create an Adapter that holds a list of colors
val adapter = ArrayAdapter.createFromResource(
this, R.array.colors, R.layout.dropdown_item
)
// Set the Adapter for the spinner
spinner.adapter = adapter
// Set an onTouchListener on the spinner because
// onItemSelected() can be called multiple times by framework
spinner.setOnTouchListener { v: View, _ ->
wasTouched = true
v.performClick()
false
}
// Set an onItemSelectedListener on the spinner
spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>, view: View,
pos: Int, id: Long
) {
if (wasTouched) {
// Display a Toast message indicating the currently selected item
Toast.makeText(
parent.context,
"The color is " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG
).show()
wasTouched = false
}
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
}
}
|
mit
|
bb12984ff10085a84f0f0291147b7c57
| 29.308824 | 85 | 0.601456 | 5.552561 | false | false | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/support/QueueSupport.kt
|
1
|
1549
|
package slatekit.apis.support
import slatekit.apis.ApiRequest
import slatekit.apis.core.Reqs
import slatekit.common.Source
import slatekit.common.utils.Random
import slatekit.results.Notice
interface QueueSupport {
/**
* This can be overridden to support custom call-modes
*/
suspend fun enueue(request: ApiRequest): Notice<String> {
// Convert from web request to Queued request
val req = request.request
val payload = Reqs.toJsonAsQueued(req)
enueue(Random.uuid(), req.path, payload, req.tag)
return slatekit.results.Success("Request processed as queue")
}
/**
* Converts a request for an action that is queued, to an actual queue
*/
suspend fun enqueOrProcess(request: ApiRequest): Notice<String> {
// Coming in as http request and mode is queued ?
val req = request.request
return if (req.source != Source.Queue && request.target?.action?.tags?.contains("queued") == true) {
enueue(request)
} else {
slatekit.results.Failure("Continue processing")
}
}
/**
* Creates a request from the parameters and api info and serializes that as json
* and submits it to a random queue.
* This is designed to work with slatekit.jobs
* @param id = "ABC123",
* @param name = "users.sendWelcomeEmail",
* @param data = "JSON data...",
* @param xid = "abc123"
*/
suspend fun enueue(id: String, name: String, data: String, xid: String)
}
|
apache-2.0
|
dca1b241821be6c0a7b6854240badc2d
| 31.270833 | 108 | 0.639122 | 4.076316 | false | false | false | false |
leafclick/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/util/GithubAccountsMigrationHelper.kt
|
1
|
5539
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.util
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import git4idea.DialogManager
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.authentication.ui.GithubLoginDialog
import java.awt.Component
import java.io.IOException
internal const val GITHUB_SETTINGS_PASSWORD_KEY = "GITHUB_SETTINGS_PASSWORD_KEY"
/**
* Temporary helper
* Will move single-account authorization data to accounts list if it was a token-based auth and clear old settings
*/
@Suppress("DEPRECATION")
class GithubAccountsMigrationHelper {
private val LOG = logger<GithubAccountsMigrationHelper>()
internal fun getOldServer(): GithubServerPath? {
try {
if (hasOldAccount()) {
return GithubServerPath.from(GithubSettings.getInstance().host ?: GithubServerPath.DEFAULT_HOST)
}
}
catch (ignore: Exception) {
// it could be called from AnAction.update()
}
return null
}
private fun hasOldAccount(): Boolean {
// either password-based with specified login or token based
val settings = GithubSettings.getInstance()
return ((settings.authType == GithubAuthData.AuthType.BASIC && settings.login != null) ||
(settings.authType == GithubAuthData.AuthType.TOKEN))
}
/**
* @return false if process was cancelled by user, true otherwise
*/
@CalledInAwt
@JvmOverloads
fun migrate(project: Project, parentComponent: Component? = null): Boolean {
LOG.debug("Migrating old auth")
val settings = GithubSettings.getInstance()
val login = settings.login
val host = settings.host
val password = PasswordSafe.instance.getPassword(CredentialAttributes(GithubSettings::class.java, GITHUB_SETTINGS_PASSWORD_KEY))
val authType = settings.authType
LOG.debug("Old auth data: { login: $login, host: $host, authType: $authType, password null: ${password == null} }")
val hasAnyInfo = login != null || host != null || authType != null || password != null
if (!hasAnyInfo) return true
var dialogCancelled = false
if (service<GithubAccountManager>().accounts.isEmpty()) {
val hostToUse = host ?: GithubServerPath.DEFAULT_HOST
when (authType) {
GithubAuthData.AuthType.TOKEN -> {
LOG.debug("Migrating token auth")
if (password != null) {
val executorFactory = GithubApiRequestExecutor.Factory.getInstance()
try {
val server = GithubServerPath.from(hostToUse)
val progressManager = ProgressManager.getInstance()
val accountName = progressManager.runProcessWithProgressSynchronously(ThrowableComputable<String, IOException> {
executorFactory.create(password).execute(progressManager.progressIndicator,
GithubApiRequests.CurrentUser.get(server)).login
}, "Accessing GitHub", true, project)
val account = GithubAccountManager.createAccount(accountName, server)
registerAccount(account, password)
}
catch (e: Exception) {
LOG.debug("Failed to migrate old token-based auth. Showing dialog.", e)
val dialog = GithubLoginDialog(executorFactory, project, parentComponent)
.withServer(hostToUse, false).withToken(password).withError(e)
dialogCancelled = !registerFromDialog(dialog)
}
}
}
GithubAuthData.AuthType.BASIC -> {
LOG.debug("Migrating basic auth")
val dialog = GithubLoginDialog(GithubApiRequestExecutor.Factory.getInstance(), project, parentComponent,
message = "Password authentication is no longer supported for Github.\n" +
"Personal access token can be acquired instead.")
.withServer(hostToUse, false).withCredentials(login, password)
dialogCancelled = !registerFromDialog(dialog)
}
else -> {
}
}
}
return !dialogCancelled
}
private fun registerFromDialog(dialog: GithubLoginDialog): Boolean {
DialogManager.show(dialog)
return if (dialog.isOK) {
registerAccount(GithubAccountManager.createAccount(dialog.getLogin(), dialog.getServer()), dialog.getToken())
true
}
else false
}
private fun registerAccount(account: GithubAccount, token: String) {
val accountManager = service<GithubAccountManager>()
accountManager.accounts += account
accountManager.updateAccountToken(account, token)
LOG.debug("Registered account $account")
}
companion object {
@JvmStatic
fun getInstance(): GithubAccountsMigrationHelper = service()
}
}
|
apache-2.0
|
734b478cef692999ff8653ef3c1daf6d
| 41.607692 | 140 | 0.698863 | 4.99009 | false | false | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-result/src/main/kotlin/slatekit/results/Utils.kt
|
1
|
657
|
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A Kotlin Tool-Kit for Server + Android
* </slate_header>
*/
package slatekit.results
fun Int.isInSuccessRange(): Boolean = this in Codes.SUCCESS.code..Codes.QUEUED.code
fun Int.isFilteredOut(): Boolean = this == Codes.IGNORED.code
fun Int.isInBadRequestRange(): Boolean = this in Codes.BAD_REQUEST.code..Codes.UNAUTHORIZED.code
fun Int.isInFailureRange(): Boolean = this in Codes.ERRORED.code..Codes.UNEXPECTED.code
|
apache-2.0
|
9afb25841780f9050c5c8b0c74202ad7
| 35.5 | 96 | 0.744292 | 3.551351 | false | false | false | false |
zdary/intellij-community
|
uast/uast-common/src/org/jetbrains/uast/UAnnotationUtils.kt
|
13
|
5059
|
// 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.
@file:JvmName("UAnnotationUtils")
package org.jetbrains.uast
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
/*
* This file contains utility methods to workaround problems with nested annotation in Uast (IDEA-185890).
*/
/**
* @return an annotation name element (identifier) for annotation entry.
* Considers not only direct [UAnnotation]s but also nested annotations, which are not always converted to [UAnnotation]
*/
fun getNameElement(uElement: UElement?): PsiElement? =
when (uElement) {
is UAnnotation -> uElement.namePsiElement
is USimpleNameReferenceExpression -> uElement.sourcePsi
is UCallExpression -> uElement.methodIdentifier?.sourcePsi?.let { PsiTreeUtil.getDeepestFirst(it) }
else -> null
}
/**
* @param identifier an identifier element that occurs in annotation, including annotations nested inside annotations (e.g. as value attribute).
* Passed element should be convertable to [UIdentifier].
* @return an [UDeclaration] to which full annotation belongs to or `null` if given argument is not an identifier in annotation.
*/
fun getIdentifierAnnotationOwner(identifier: PsiElement): UDeclaration? =
getUParentForAnnotationIdentifier(identifier)?.getContainingDeclaration()
/**
* @param identifier an identifier element that occurs in annotation, including annotations nested inside annotations (e.g. as value attribute).
* Passed element should be convertable to [UIdentifier].
* @return an annotation-like owner of passed identifier.
* Result could be:
* - an [UAnnotation] if this is a root annotation
* - an [UCallExpression] if this is a nested annotation
* - another [UElement] if something strange is going on (invalid code for instance)
* - `null` if given argument is not an identifier in annotation.
*/
fun getUParentForAnnotationIdentifier(identifier: PsiElement): UElement? {
val originalParent = getUParentForIdentifier(identifier) ?: return null
when (originalParent) {
is UAnnotation ->
return originalParent
is UCallExpression ->
return if (isResolvedToAnnotation(originalParent.classReference)) originalParent else null
is UReferenceExpression ->
if (isResolvedToAnnotation(originalParent)) {
val parentAnyway = originalParent.parentAnyway ?: return null
val annotationLikeParent = parentAnyway
.withContainingElements
.dropWhile { it is UTypeReferenceExpression || it is UReferenceExpression }
.firstOrNull() ?: return parentAnyway
if (annotationLikeParent !is UAnnotation && annotationLikeParent.uastParent is UAnnotation)
return annotationLikeParent.uastParent
return annotationLikeParent
}
}
return null
}
/**
* @param uElement an element that occurs in annotation
* @return the annotation in which this element occurs and a corresponding parameter name if available
*/
fun getContainingUAnnotationEntry(uElement: UElement?): Pair<UAnnotation, String?>? {
fun tryConvertToEntry(uElement: UElement, parent: UElement, name: String?): Pair<UAnnotation, String?>? {
if (uElement !is UExpression) return null
val uAnnotation = parent.sourcePsi.toUElementOfType<UAnnotation>() ?: return null
val argumentSourcePsi = wrapULiteral(uElement).sourcePsi
return uAnnotation to (name ?: uAnnotation.attributeValues.find { wrapULiteral(it.expression).sourcePsi === argumentSourcePsi }?.name)
}
tailrec fun retrievePsiAnnotationEntry(uElement: UElement?, name: String?): Pair<UAnnotation, String?>? {
if (uElement == null) return null
val parent = uElement.uastParent ?: return null
return when (parent) {
is UAnnotation -> parent to name
is UReferenceExpression -> tryConvertToEntry(uElement, parent, name)
is UCallExpression ->
if (parent.kind == UastCallKind.NESTED_ARRAY_INITIALIZER)
retrievePsiAnnotationEntry(parent, null)
else
tryConvertToEntry(uElement, parent, name)
is UPolyadicExpression -> retrievePsiAnnotationEntry(parent, null)
is UNamedExpression -> retrievePsiAnnotationEntry(parent, parent.name)
else -> null
}
}
return retrievePsiAnnotationEntry(uElement, null)
}
fun getContainingAnnotationEntry(uElement: UElement?): Pair<PsiAnnotation, String?>? {
val (uAnnotation, name) = getContainingUAnnotationEntry(uElement) ?: return null
val psiAnnotation = uAnnotation.javaPsi ?: return null
return psiAnnotation to name
}
private fun isResolvedToAnnotation(reference: UReferenceExpression?) = (reference?.resolve() as? PsiClass)?.isAnnotationType == true
private val UElement.parentAnyway
get() = uastParent ?: generateSequence(sourcePsi?.parent, { it.parent }).mapNotNull { it.toUElement() }.firstOrNull()
|
apache-2.0
|
06ad7e637167fa0a98b3ce3531184ab5
| 44.576577 | 144 | 0.739672 | 4.950098 | false | false | false | false |
zdary/intellij-community
|
platform/lang-impl/src/com/intellij/util/indexing/CorruptionMarker.kt
|
1
|
2872
|
// 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.util.indexing
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.stubs.SerializationManagerEx
import com.intellij.util.indexing.impl.storage.FileBasedIndexLayoutSettings
import com.intellij.util.io.exists
import com.intellij.util.io.readText
import com.intellij.util.io.write
import kotlin.io.path.deleteExisting
internal object CorruptionMarker {
private const val CORRUPTION_MARKER_NAME = "corruption.marker"
private const val MARKED_AS_DIRTY_REASON = "Indexes marked as dirty (IDE is expected to be work)"
private const val EXPLICIT_INVALIDATION_REASON = "Explicit index invalidation"
private val corruptionMarker
get() = PathManager.getIndexRoot().resolve(CORRUPTION_MARKER_NAME)
@JvmStatic
fun markIndexesAsDirty() {
createCorruptionMarker(MARKED_AS_DIRTY_REASON)
}
@JvmStatic
fun markIndexesAsClosed() {
val corruptionMarkerExists = corruptionMarker.exists()
if (corruptionMarkerExists) {
try {
if (corruptionMarker.readText() == MARKED_AS_DIRTY_REASON) {
corruptionMarker.deleteExisting()
}
}
catch (ignored: Exception) { }
}
}
@JvmStatic
fun requestInvalidation() {
FileBasedIndexImpl.LOG.info("Explicit index invalidation has been requested")
createCorruptionMarker(EXPLICIT_INVALIDATION_REASON)
}
@JvmStatic
fun requireInvalidation(): Boolean {
val corruptionMarkerExists = corruptionMarker.exists()
if (corruptionMarkerExists) {
val message = "Indexes are corrupted and will be rebuilt"
try {
val corruptionReason = corruptionMarker.readText()
FileBasedIndexImpl.LOG.info("$message (reason = $corruptionReason)")
}
catch (e: Exception) {
FileBasedIndexImpl.LOG.info(message)
}
}
return IndexInfrastructure.hasIndices() && corruptionMarkerExists
}
@JvmStatic
fun dropIndexes() {
val indexRoot = PathManager.getIndexRoot().toFile()
FileUtil.deleteWithRenaming(indexRoot)
indexRoot.mkdirs()
// serialization manager is initialized before and use removed index root so we need to reinitialize it
SerializationManagerEx.getInstanceEx().reinitializeNameStorage()
ID.reinitializeDiskStorage()
PersistentIndicesConfiguration.saveConfiguration()
FileUtil.delete(corruptionMarker)
FileBasedIndexInfrastructureExtension.EP_NAME.extensions.forEach { it.resetPersistentState() }
FileBasedIndexLayoutSettings.saveCurrentLayout()
}
private fun createCorruptionMarker(reason: String) {
try {
corruptionMarker.write(reason)
}
catch (e: Exception) {
FileBasedIndexImpl.LOG.warn(e)
}
}
}
|
apache-2.0
|
2bd1496735f6241869371f1c107255bb
| 33.614458 | 140 | 0.743036 | 4.42527 | false | false | false | false |
mrbublos/vkm
|
app/src/main/java/vkm/vkm/SettingsFragment.kt
|
1
|
2254
|
package vkm.vkm
import android.view.View
import kotlinx.android.synthetic.main.activity_settings.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import vkm.vkm.utils.VkmFragment
import vkm.vkm.utils.logE
import vkm.vkm.utils.toast
class SettingsFragment : VkmFragment() {
init { layout = R.layout.activity_settings }
override fun init() {
dangerousCommandsVisibility(false)
enableSuggestions.isChecked = State.enableTextSuggestions
enableSuggestions.setOnCheckedChangeListener { _, value -> State.enableTextSuggestions = value }
showDangerousCommands.setOnCheckedChangeListener { _, value -> dangerousCommandsVisibility(value) }
clearDownloaded.setOnClickListener { DownloadManager.clearDownloaded() }
clearQueue.setOnClickListener { DownloadManager.clearQueue() }
useProxy.isChecked = State.useProxy
useProxy.setOnCheckedChangeListener { _, value -> State.useProxy = value }
stopDownload.setOnClickListener { DownloadManager.stopDownload() }
startDownload.setOnClickListener { DownloadManager.downloadComposition(null) }
clearMusicDir.setOnClickListener { DownloadManager.removeAllMusic() }
rehashDownloaded.setOnClickListener { DownloadManager.rehash() }
restoreDownloaded.setOnClickListener {
val me = this
restoreDownloaded.visibility = View.GONE
GlobalScope.launch(Dispatchers.IO) {
try {
DownloadManager.restoreDownloaded()
"List of downloaded files restored".toast(me.context)
} catch (e: Exception) {
"".logE(e)
"Error restoring downloaded files ${e.message}".toast(me.context)
}
GlobalScope.launch(Dispatchers.Main) { restoreDownloaded.visibility = View.VISIBLE }
}
}
}
private fun dangerousCommandsVisibility(visible: Boolean) {
val visibility = if (visible) View.VISIBLE else View.GONE
listOf(clearMusicDir, rehashDownloaded, restoreDownloaded).forEach {
(it.parent as View).visibility = visibility
}
}
}
|
gpl-3.0
|
b8582c9816f33352fae03fa7a49f9ca1
| 35.95082 | 107 | 0.682786 | 5.229698 | false | false | false | false |
deeplearning4j/deeplearning4j
|
nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/FlattenDims.kt
|
1
|
4852
|
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.rule.attribute
import org.nd4j.common.util.ArrayUtil
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.ArgDescriptor
import org.nd4j.samediff.frameworkimport.context.MappingContext
import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
import java.lang.IllegalArgumentException
abstract class FlattenDims<
GRAPH_DEF : GeneratedMessageV3,
OP_DEF_TYPE : GeneratedMessageV3,
NODE_TYPE : GeneratedMessageV3,
ATTR_DEF : GeneratedMessageV3,
ATTR_VALUE_TYPE : GeneratedMessageV3,
TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE : ProtocolMessageEnum>(
mappingNamesToPerform: Map<String, String> = emptyMap(),
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>
) :
BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE>
(
name = "flattendims",
mappingNamesToPerform = mappingNamesToPerform,
transformerArgs = transformerArgs
) {
override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean {
return argDescriptorType == AttributeValueType.LIST_INT ||
argDescriptorType == AttributeValueType.TENSOR
}
override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean {
return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT64) || argDescriptorType.contains(
OpNamespace.ArgDescriptor.ArgType.INT32)
}
override fun convertAttributes(
mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF,
ATTR_VALUE_TYPE, DATA_TYPE>
): List<OpNamespace.ArgDescriptor> {
val ret = ArrayList<OpNamespace.ArgDescriptor>()
for ((k, v) in mappingNamesToPerform()) {
val attr = mappingCtx.irAttributeValueForNode(v)
val transformerArgs = transformerArgs[k]
val baseIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
)
val axis = transformerArgs!![0]!!.int64Value
when(attr.attributeValueType()) {
AttributeValueType.TENSOR -> {
val inputTensor = mappingCtx.tensorInputFor(v)
val asAxisList = inputTensor.toNd4jNDArray().toLongVector().toMutableList()
addToList(ret,k,baseIndex,axis,asAxisList)
}
AttributeValueType.LIST_INT -> {
val axis = transformerArgs!![0]!!.int64Value
val axisList = mappingCtx.irAttributeValueForNode(v).listIntValue()
addToList(ret,k,baseIndex,axis,axisList)
}
else -> {
throw IllegalArgumentException("Illegal type ${attr.attributeValueType()}")
}
}
}
return ret
}
fun addToList(ret: MutableList<OpNamespace.ArgDescriptor>,k: String,baseIndex: Int,axis: Long,axisList: List<Long>) {
val beforeAccessProdValue = if(axis.toInt() == 0) 1L else ArrayUtil.prodLong(axisList.subList(0,axis.toInt()))
val prodValue = ArrayUtil.prodLong(axisList.subList(axis.toInt(),axisList.size - 1))
ret.add(ArgDescriptor {
int64Value = beforeAccessProdValue
argIndex = baseIndex
argType = OpNamespace.ArgDescriptor.ArgType.INT64
name = k
})
ret.add(ArgDescriptor {
int64Value = prodValue
argIndex = baseIndex + 1
argType = OpNamespace.ArgDescriptor.ArgType.INT64
name = k
})
}
}
|
apache-2.0
|
2e0e8cf17a2c177ccdd0603a1b595f5d
| 40.127119 | 121 | 0.641385 | 4.719844 | false | false | false | false |
cout970/Modeler
|
src/main/kotlin/com/cout970/modeler/core/model/AABB.kt
|
1
|
2889
|
package com.cout970.modeler.core.model
import com.cout970.modeler.api.model.mesh.IMesh
import com.cout970.modeler.util.createParentsIfNeeded
import com.cout970.modeler.util.transformVertex
import com.cout970.vector.api.IQuaternion
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.*
import java.io.File
import java.io.FileOutputStream
import java.io.Writer
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
/**
* Created by cout970 on 2017/01/31.
*/
class AABB(a: IVector3, b: IVector3) {
val min: IVector3 = a.min(b)
val max: IVector3 = a.max(b)
val minX get() = min.xd
val minY get() = min.yd
val minZ get() = min.zd
val maxX get() = max.xd
val maxY get() = max.yd
val maxZ get() = max.zd
fun translate(a: IVector3): AABB = AABB(min + a, max + a)
fun rotate(rot: IQuaternion): AABB = AABB(rot.rotate(min).round(), rot.rotate(max).round())
fun scale(a: IVector3): AABB = AABB(min * a, max * a)
fun transform(trs: TRSTransformation) = AABB(trs.matrix.transformVertex(min), trs.matrix.transformVertex(max))
override fun toString(): String {
return "AABB(min=$min, max=$max)"
}
companion object {
fun fromMesh(mesh: IMesh): AABB {
if (mesh.faces.isEmpty()) return AABB(Vector3.ORIGIN, Vector3.ORIGIN)
var min: IVector3 = mesh.pos[0]
var max: IVector3 = mesh.pos[0]
for (pos in mesh.pos) {
min = min.min(pos)
max = max.max(pos)
}
return AABB(min, max)
}
fun export(list: List<AABB>, output: File) {
output.createParentsIfNeeded()
val stream = FileOutputStream(output)
val f = DecimalFormat("0.000", DecimalFormatSymbols.getInstance(Locale.US))
stream.use {
val writer = stream.writer()
val vectorClass = "Vec3d"
writer.print("listOf(\n")
for (i in list.take(list.size - 1)) {
writer.print("$vectorClass(${f.format(i.min.x)}, ${f.format(i.min.y)}, ${f.format(
i.min.z)}) * PIXEL ${"to $vectorClass(" + f.format(i.max.x) + ", " + f.format(
i.max.y) + ", " + f.format(i.max.z) + ") * PIXEL,\n"}")
}
val i = list.last()
writer.print("$vectorClass(${f.format(i.min.x)}, ${f.format(i.min.y)}, ${f.format(i.min.z)}" +
") * PIXEL ${"to $vectorClass(" + f.format(i.max.x) + ", " + f.format(
i.max.y) + ", " + f.format(i.max.z) + ") * PIXEL\n"}")
writer.print(")\n")
writer.flush()
}
}
fun Writer.print(str: String) {
System.out.print(str)
append(str)
}
}
}
|
gpl-3.0
|
4ae46b963600d802e7feee71d605ccec
| 33 | 114 | 0.555556 | 3.518879 | false | false | false | false |
cout970/Modeler
|
src/main/kotlin/com/cout970/modeler/render/tool/Animator.kt
|
1
|
7885
|
package com.cout970.modeler.render.tool
import com.cout970.glutilities.structure.Timer
import com.cout970.modeler.api.animation.*
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.api.model.`object`.IGroupRef
import com.cout970.modeler.api.model.selection.IObjectRef
import com.cout970.modeler.core.model.TRTSTransformation
import com.cout970.modeler.core.model.toTRTS
import com.cout970.modeler.gui.Gui
import com.cout970.modeler.util.lerp
import com.cout970.modeler.util.slerp
import com.cout970.modeler.util.toAxisRotations
import com.cout970.modeler.util.toFrame
import com.cout970.vector.api.IQuaternion
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.vec3Of
import kotlin.math.PI
import kotlin.math.cos
class Animator {
lateinit var gui: Gui
var zoom = 1f
var offset = 0f
var animationTime = 0f
var selectedChannel: IChannelRef? = null
set(value) {
field = value
selectedKeyframe = null
sendUpdate()
}
var selectedKeyframe: Int? = null
set(value) {
field = value
sendUpdate()
}
var animationState = AnimationState.STOP
set(value) {
field = value
sendUpdate()
}
val selectedAnimation: IAnimationRef get() = gui.programState.selectedAnimation
val animation get() = gui.programState.animation
fun sendUpdate() {
gui.listeners.runGuiCommand("updateAnimation")
}
fun updateTime(timer: Timer) {
if (animationState != AnimationState.STOP && gui.state.modelSelection.isNonNull()) {
gui.state.cursor.update(gui)
}
when (animationState) {
AnimationState.FORWARD -> {
animationTime += timer.delta.toFloat()
animationTime %= animation.timeLength
}
AnimationState.BACKWARD -> {
animationTime -= timer.delta.toFloat()
if (animationTime < 0) {
animationTime += animation.timeLength
}
}
else -> Unit
}
}
fun animateGroup(anim: IAnimation, group: IGroupRef, transform: ITransformation): ITransformation {
val validChannels = anim.channels
.filter { it.value.enabled }
.filter { (chanRef) -> (anim.channelMapping[chanRef] as? AnimationTargetGroup)?.ref == group }
.map { it.value }
return animateTransform(validChannels, transform.toTRTS())
}
fun animateObject(anim: IAnimation, obj: IObjectRef, transform: ITransformation): ITransformation {
val validChannels = anim.channels
.filter { it.value.enabled }
.filter { (chanRef) -> (obj in (anim.channelMapping[chanRef] as? AnimationTargetObject)?.refs ?: emptyList()) }
.map { it.value }
if (validChannels.isEmpty()) return transform
return animateTransform(validChannels, transform.toTRTS())
}
fun animateTransform(validChannels: List<IChannel>, current: TRTSTransformation): TRTSTransformation {
val now = animationTime
if (validChannels.isEmpty()) return current
val overrideProperties = mutableListOf<ChannelType>()
val anim = validChannels.fold(TRTSTransformation.IDENTITY) { acc, channel ->
val (prev, next) = getPrevAndNext(now, channel.keyframes)
val combined = interpolateKeyframes(now, prev, next, channel.interpolation)
overrideProperties += channel.type
val focus = when (channel.type) {
ChannelType.TRANSLATION -> TRTSTransformation(translation = combined.translation)
ChannelType.ROTATION -> TRTSTransformation(rotation = combined.rotation, pivot = combined.pivot)
ChannelType.SCALE -> TRTSTransformation(scale = combined.scale)
}
acc.merge(focus)
}
var transform = current
if (ChannelType.ROTATION in overrideProperties) {
transform = transform.merge(TRTSTransformation(
rotation = anim.rotation,
pivot = anim.pivot
))
}
val final = TRTSTransformation(
if (ChannelType.TRANSLATION in overrideProperties) anim.translation else transform.translation,
transform.rotation,
transform.pivot,
if (ChannelType.SCALE in overrideProperties) anim.scale else transform.scale
)
// val final = TRTSTransformation(
// if (ChannelType.TRANSLATION in overrideProperties) anim.translation else transform.translation,
// if (ChannelType.ROTATION in overrideProperties) anim.rotation else transform.rotation,
// if (ChannelType.ROTATION in overrideProperties) anim.pivot else transform.pivot,
// if (ChannelType.SCALE in overrideProperties) anim.scale else transform.scale
// )
return combine(transform, final)
}
companion object {
@Suppress("UNUSED_PARAMETER")
fun combine(original: TRTSTransformation, animation: TRTSTransformation): TRTSTransformation {
// Change if needed a different algorithm
return animation
}
fun interpolateKeyframes(time: Float, prev: IKeyframe, next: IKeyframe, method: InterpolationMethod): TRTSTransformation {
if (next.time == prev.time) return next.value
val size = next.time - prev.time
val step = (time - prev.time) / size
return interpolateTransforms(prev.value, next.value, step, method)
}
fun interpolateTransforms(a: TRTSTransformation, b: TRTSTransformation, delta: Float, method: InterpolationMethod): TRTSTransformation {
val step = delta.toDouble()
return TRTSTransformation(
translation = interpolateVector3(a.translation, b.translation, step, method),
rotation = interpolateQuaternion(a.quatRotation, b.quatRotation, step, method).toAxisRotations(),
pivot = interpolateVector3(a.pivot, b.pivot, step, method),
scale = interpolateVector3(a.scale, b.scale, step, method)
)
}
fun interpolateVector3(a: IVector3, b: IVector3, mu: Double, method: InterpolationMethod): IVector3 {
return when (method) {
InterpolationMethod.LINEAR -> vec3Of(
linear(a.xd, b.xd, mu),
linear(a.yd, b.yd, mu),
linear(a.zd, b.zd, mu)
)
InterpolationMethod.COSINE -> vec3Of(
cosine(a.xd, b.xd, mu),
cosine(a.yd, b.yd, mu),
cosine(a.zd, b.zd, mu)
)
InterpolationMethod.STEP -> a
}
}
fun interpolateQuaternion(a: IQuaternion, b: IQuaternion, mu: Double, method: InterpolationMethod): IQuaternion {
return when (method) {
InterpolationMethod.LINEAR -> a.lerp(b, mu)
InterpolationMethod.COSINE -> a.slerp(b, mu)
InterpolationMethod.STEP -> a
}
}
fun linear(y1: Double, y2: Double, mu: Double): Double {
return y1 * (1 - mu) + y2 * mu
}
fun cosine(y1: Double, y2: Double, mu: Double): Double {
val mu2 = (1 - cos(mu * PI)) / 2
return y1 * (1 - mu2) + y2 * mu2
}
fun getPrevAndNext(time: Float, keyframes: List<IKeyframe>): Pair<IKeyframe, IKeyframe> {
val next = keyframes.firstOrNull { it.time.toFrame() > time.toFrame() } ?: keyframes.first()
val prev = keyframes.lastOrNull { it.time.toFrame() <= time.toFrame() } ?: keyframes.last()
return prev to next
}
}
}
|
gpl-3.0
|
e90212e26ea880d5c320dba04e394a00
| 37.096618 | 144 | 0.616487 | 4.469955 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnectorTest.kt
|
1
|
3421
|
package info.nightscout.androidaps.plugins.general.automation.triggers
import org.json.JSONException
import org.json.JSONObject
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class TriggerConnectorTest : TriggerTestBase() {
@Test fun testTriggerList() {
val t = TriggerConnector(injector)
val t2 = TriggerConnector(injector)
val t3 = TriggerConnector(injector)
Assert.assertTrue(t.size() == 0)
t.list.add(t2)
Assert.assertTrue(t.size() == 1)
Assert.assertEquals(t2, t.list.get(0))
t.list.add(t3)
Assert.assertTrue(t.size() == 2)
Assert.assertEquals(t2, t.list.get(0))
Assert.assertEquals(t3, t.list.get(1))
Assert.assertTrue(t.list.remove(t2))
Assert.assertTrue(t.size() == 1)
Assert.assertEquals(t3, t.list.get(0))
Assert.assertTrue(t.shouldRun())
}
@Test fun testListTriggerOR() {
val t = TriggerConnector(injector, TriggerConnector.Type.OR)
t.list.add(TriggerDummy(injector))
t.list.add(TriggerDummy(injector))
Assert.assertFalse(t.shouldRun())
t.list.add(TriggerDummy(injector, true))
t.list.add(TriggerDummy(injector))
Assert.assertTrue(t.shouldRun())
}
@Test fun testListTriggerXOR() {
val t = TriggerConnector(injector, TriggerConnector.Type.XOR)
t.list.add(TriggerDummy(injector))
t.list.add(TriggerDummy(injector))
Assert.assertFalse(t.shouldRun())
t.list.add(TriggerDummy(injector, true))
t.list.add(TriggerDummy(injector))
Assert.assertTrue(t.shouldRun())
t.list.add(TriggerDummy(injector, true))
t.list.add(TriggerDummy(injector))
Assert.assertFalse(t.shouldRun())
}
@Test fun testListTriggerAND() {
val t = TriggerConnector(injector, TriggerConnector.Type.AND)
t.list.add(TriggerDummy(injector, true))
t.list.add(TriggerDummy(injector, true))
Assert.assertTrue(t.shouldRun())
t.list.add(TriggerDummy(injector, true))
t.list.add(TriggerDummy(injector))
Assert.assertFalse(t.shouldRun())
}
@Test fun toJSONTest() {
val t = TriggerConnector(injector)
Assert.assertEquals(empty, t.toJSON())
t.list.add(TriggerConnector(injector))
Assert.assertEquals(oneItem, t.toJSON())
}
@Test @Throws(JSONException::class) fun fromJSONTest() {
val t = TriggerConnector(injector)
t.list.add(TriggerConnector(injector))
val t2 = TriggerDummy(injector).instantiate(JSONObject(t.toJSON())) as TriggerConnector
Assert.assertEquals(1, t2.size().toLong())
Assert.assertTrue(t2.list[0] is TriggerConnector)
}
companion object {
const val empty = "{\"data\":{\"connectorType\":\"AND\",\"triggerList\":[]},\"type\":\"info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector\"}"
const val oneItem = "{\"data\":{\"connectorType\":\"AND\",\"triggerList\":[\"{\\\"data\\\":{\\\"connectorType\\\":\\\"AND\\\",\\\"triggerList\\\":[]},\\\"type\\\":\\\"info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector\\\"}\"]},\"type\":\"info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector\"}"
}
}
|
agpl-3.0
|
6d908355737a7dbe9efe042fce00b2e9
| 40.228916 | 358 | 0.658872 | 3.891923 | false | true | false | false |
JetBrains/xodus
|
lucene-directory/src/main/kotlin/jetbrains/exodus/lucene/codecs/Lucene87CodecWithNoFieldCompression.kt
|
1
|
2369
|
/**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.lucene.codecs
import org.apache.lucene.codecs.FilterCodec
import org.apache.lucene.codecs.StoredFieldsFormat
import org.apache.lucene.codecs.compressing.CompressingStoredFieldsFormat
import org.apache.lucene.codecs.compressing.CompressionMode
import org.apache.lucene.codecs.compressing.Compressor
import org.apache.lucene.codecs.compressing.Decompressor
import org.apache.lucene.codecs.lucene87.Lucene87Codec
import org.apache.lucene.store.DataInput
import org.apache.lucene.store.DataOutput
import org.apache.lucene.util.BytesRef
/**
* Lucene70Codec with no compression of stored fields.
*/
class Lucene87CodecWithNoFieldCompression : FilterCodec("Lucene70CodecWithNoFieldCompression", Lucene87Codec()) {
private val flatFieldsFormat: StoredFieldsFormat =
CompressingStoredFieldsFormat("Lucene50StoredFieldsFlat", NoCompression, 16, 1, 16)
override fun storedFieldsFormat() = flatFieldsFormat
}
private object NoCompression : CompressionMode() {
override fun newCompressor() = TrivialCompressor()
override fun newDecompressor() = TrivialDecompressor()
}
private class TrivialCompressor : Compressor() {
override fun compress(bytes: ByteArray, off: Int, len: Int, out: DataOutput) =
out.writeBytes(bytes, off, len)
override fun close() {}
}
private class TrivialDecompressor : Decompressor() {
override fun clone() = this
override fun decompress(input: DataInput, originalLength: Int, offset: Int, length: Int, bytes: BytesRef) {
if (bytes.bytes.size < originalLength) {
bytes.bytes = ByteArray(originalLength)
}
input.readBytes(bytes.bytes, 0, originalLength)
bytes.offset = 0
bytes.length = originalLength
}
}
|
apache-2.0
|
5ba917bf6bed43c1dfa8ce2aa4f5fb1b
| 34.373134 | 113 | 0.753482 | 4.15614 | false | false | false | false |
siosio/intellij-community
|
platform/elevation/src/com/intellij/execution/process/elevation/settings/ExplanatoryTextUiUtil.kt
|
1
|
2351
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.process.elevation.settings
import com.intellij.execution.process.elevation.ElevationBundle
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.UIUtil
import java.awt.FontMetrics
internal object ExplanatoryTextUiUtil {
fun message(@NlsContexts.DialogMessage firstSentence: String,
maxLineLength: Int = 70,
fontMetrics: FontMetrics? = null): @NlsSafe String {
return messageHtmlInnards(firstSentence)
.limitWidth(maxLineLength, fontMetrics)
.wrapWith(HtmlChunk.body())
.wrapWith(HtmlChunk.html())
.toString()
}
private fun messageHtmlInnards(@NlsContexts.DialogMessage firstSentence: String): HtmlChunk {
val productName = ApplicationNamesInfo.getInstance().fullProductName
val commentHtml = ElevationBundle.message("text.elevation.explanatory.comment.html", productName)
val warningHtml = ElevationBundle.message("text.elevation.explanatory.warning.html")
return HtmlBuilder()
.append(HtmlChunk.p().addText(firstSentence)).br()
.append(HtmlChunk.p().addRaw(commentHtml)).br()
.append(HtmlChunk.p().addRaw(warningHtml)).br()
.toFragment()
}
private fun HtmlChunk.limitWidth(maxLineLength: Int,
fontMetrics: FontMetrics?): HtmlChunk {
if (maxLineLength <= 0) return this
val maxWidth = stringWidth(toString(), maxLineLength, fontMetrics)
return wrapWith(HtmlChunk.div().attr("width", maxWidth))
}
private fun stringWidth(someText: String,
maxLineLength: Int,
fontMetrics: FontMetrics?): Int {
val text = someText.ifEmpty { "some text to estimate string width with given metric" }
val substring = text.repeat((maxLineLength + 1) / (text.length + 1) + 1).substring(0, maxLineLength)
return fontMetrics?.stringWidth(substring) ?: GraphicsUtil.stringWidth(substring, UIUtil.getLabelFont())
}
}
|
apache-2.0
|
dfd2e3dc00b99f066159de0d9903a729
| 44.211538 | 140 | 0.72735 | 4.521154 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinVersionUtils.kt
|
2
|
7411
|
// 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.
@file:JvmName("KotlinVersionUtils")
package org.jetbrains.kotlin.idea.codeInsight.gradle
import org.jetbrains.kotlin.idea.codeInsight.gradle.GradleKotlinTestUtils.KotlinVersion
import org.jetbrains.kotlin.idea.codeInsight.gradle.MultiplePluginVersionGradleImportingTestCase.KotlinVersionRequirement
import java.util.*
import kotlin.Comparator
val KotlinVersion.isWildcard: Boolean
get() = this.classifier != null &&
this.classifier == WILDCARD_KOTLIN_VERSION_CLASSIFIER
val KotlinVersion.isSnapshot: Boolean
get() = this.classifier != null && this.classifier.lowercase() == "snapshot"
val KotlinVersion.isDev: Boolean
get() = this.classifier != null && this.classifier.lowercase().matches(Regex("""dev-?\d*"""))
val KotlinVersion.isMilestone: Boolean
get() = this.classifier != null &&
this.classifier.lowercase().matches(Regex("""m\d+(-\d*)?"""))
val KotlinVersion.isAlpha: Boolean
get() = this.classifier != null &&
this.classifier.lowercase().matches(Regex("""alpha(\d*)?-?\d*"""))
val KotlinVersion.isBeta: Boolean
get() = this.classifier != null &&
this.classifier.lowercase().matches(Regex("""beta(\d*)?-?\d*"""))
val KotlinVersion.isRC: Boolean
get() = this.classifier != null &&
this.classifier.lowercase().matches(Regex("""(rc)(\d*)?-?\d*"""))
val KotlinVersion.isStable: Boolean
get() = this.classifier == null ||
this.classifier.lowercase().matches(Regex("""(release-)?\d+"""))
val KotlinVersion.isPreRelease: Boolean get() = !isStable
enum class KotlinVersionMaturity {
WILDCARD,
SNAPSHOT,
DEV,
MILESTONE,
ALPHA,
BETA,
RC,
STABLE
}
operator fun KotlinVersion.compareTo(other: KotlinVersion): Int {
if (this == other) return 0
(this.major - other.major).takeIf { it != 0 }?.let { return it }
(this.minor - other.minor).takeIf { it != 0 }?.let { return it }
(this.patch - other.patch).takeIf { it != 0 }?.let { return it }
(this.maturity.ordinal - other.maturity.ordinal).takeIf { it != 0 }?.let { return it }
if (this.classifier == null && other.classifier != null) {
/* eg. 1.6.20 > 1.6.20-200 */
return 1
}
if (this.classifier != null && other.classifier == null) {
/* e.g. 1.6.20-200 < 1.6.20 */
return -1
}
val thisClassifierNumber = this.classifierNumber
val otherClassifierNumber = other.classifierNumber
if (thisClassifierNumber != null && otherClassifierNumber != null) {
(thisClassifierNumber - otherClassifierNumber).takeIf { it != 0 }?.let { return it }
}
if (thisClassifierNumber != null && otherClassifierNumber == null) {
/* e.g. 1.6.20-rc1 > 1.6.20-rc */
return 1
}
if (thisClassifierNumber == null && otherClassifierNumber != null) {
/* e.g. 1.6.20-rc < 1.6.20-rc1 */
return -1
}
val thisBuildNumber = this.buildNumber
val otherBuildNumber = other.buildNumber
if (thisBuildNumber != null && otherBuildNumber != null) {
(thisBuildNumber - otherBuildNumber).takeIf { it != 0 }?.let { return it }
}
if (thisBuildNumber == null && otherBuildNumber != null) {
/* e.g. 1.6.20-M1 > 1.6.20-M1-200 */
return 1
}
if (thisBuildNumber != null && otherBuildNumber == null) {
/* e.g. 1.6.20-M1-200 < 1.6.20-M1 */
return -1
}
return 0
}
val KotlinVersion.buildNumber: Int?
get() {
if (classifier == null) return null
/*
Handle classifiers that only consist of version + build number. This is used for stable releases
like:
1.6.20-1
1.6.20-22
1.6.
*/
val buildNumberOnlyClassifierRegex = Regex("\\d+")
if (buildNumberOnlyClassifierRegex.matches(classifier)) {
return classifier.toIntOrNull()
}
val classifierRegex = Regex("""(.+?)(\d*)?-?(\d*)?""")
val classifierMatch = classifierRegex.matchEntire(classifier) ?: return null
return classifierMatch.groupValues.getOrNull(3)?.toIntOrNull()
}
val KotlinVersion.classifierNumber: Int?
get() {
if (classifier == null) return null
/*
Classifiers with only a buildNumber assigned
*/
val buildNumberOnlyClassifierRegex = Regex("\\d+")
if (buildNumberOnlyClassifierRegex.matches(classifier)) {
return null
}
val classifierRegex = Regex("""(.+?)(\d*)?-?(\d*)?""")
val classifierMatch = classifierRegex.matchEntire(classifier) ?: return null
return classifierMatch.groupValues.getOrNull(2)?.toIntOrNull()
}
fun KotlinVersionRequirement.matches(kotlinVersionString: String): Boolean {
return matches(parseKotlinVersion(kotlinVersionString))
}
fun KotlinVersionRequirement.matches(version: KotlinVersion): Boolean {
return when (this) {
is KotlinVersionRequirement.Exact -> matches(version)
is KotlinVersionRequirement.Range -> matches(version)
}
}
fun KotlinVersionRequirement.Exact.matches(version: KotlinVersion): Boolean {
return this.version == version
}
fun KotlinVersionRequirement.Range.matches(version: KotlinVersion): Boolean {
if (lowestIncludedVersion != null && version < lowestIncludedVersion) return false
if (highestIncludedVersion != null && version > highestIncludedVersion) return false
return true
}
fun parseKotlinVersionRequirement(value: String): KotlinVersionRequirement {
if (value.endsWith("+")) {
return KotlinVersionRequirement.Range(
lowestIncludedVersion = parseKotlinVersion(value.removeSuffix("+")),
highestIncludedVersion = null
)
}
if (value.contains("<=>")) {
val split = value.split(Regex("""\s*<=>\s*"""))
require(split.size == 2) { "Illegal Kotlin version requirement: $value. Example: '1.4.0 <=> 1.5.0'" }
return KotlinVersionRequirement.Range(
lowestIncludedVersion = parseKotlinVersion(split[0]),
highestIncludedVersion = parseKotlinVersion(split[1])
)
}
return KotlinVersionRequirement.Exact(parseKotlinVersion(value))
}
fun parseKotlinVersion(value: String): KotlinVersion {
fun throwInvalid(): Nothing {
throw IllegalArgumentException("Invalid Kotlin version: $value")
}
val baseVersion = value.split("-", limit = 2)[0]
val classifier = value.split("-", limit = 2).getOrNull(1)
val baseVersionSplit = baseVersion.split(".")
if (!(baseVersionSplit.size == 2 || baseVersionSplit.size == 3)) throwInvalid()
return KotlinVersion(
major = baseVersionSplit[0].toIntOrNull() ?: throwInvalid(),
minor = baseVersionSplit[1].toIntOrNull() ?: throwInvalid(),
patch = baseVersionSplit.getOrNull(2)?.let { it.toIntOrNull() ?: throwInvalid() } ?: 0,
classifier = classifier?.lowercase()
)
}
private const val WILDCARD_KOTLIN_VERSION_CLASSIFIER = "*"
fun KotlinVersion.toWildcard(): KotlinVersion {
return KotlinVersion(
major, minor, patch,
classifier = WILDCARD_KOTLIN_VERSION_CLASSIFIER
)
}
val KotlinVersion.isHmppEnabledByDefault get() = this >= parseKotlinVersion("1.6.20-dev-6442")
|
apache-2.0
|
2ed84b775a2a953cc0b04051f711df58
| 33.630841 | 158 | 0.651194 | 4.377437 | false | false | false | false |
JetBrains/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeRootPane.kt
|
1
|
21860
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.openapi.wm.impl
import com.intellij.ide.GeneralSettings
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.jdkEx.JdkEx
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.*
import com.intellij.openapi.components.ComponentManagerEx
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.impl.FrameInfoHelper.Companion.isFloatingMenuBarSupported
import com.intellij.openapi.wm.impl.customFrameDecorations.header.MacToolbarFrameHeader
import com.intellij.openapi.wm.impl.customFrameDecorations.header.MainFrameCustomHeader
import com.intellij.openapi.wm.impl.customFrameDecorations.header.MenuFrameHeader
import com.intellij.openapi.wm.impl.customFrameDecorations.header.titleLabel.CustomDecorationPath
import com.intellij.openapi.wm.impl.customFrameDecorations.header.titleLabel.SelectedEditorFilePath
import com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar.ToolbarFrameHeader
import com.intellij.openapi.wm.impl.headertoolbar.MainToolbar
import com.intellij.openapi.wm.impl.headertoolbar.isToolbarInHeader
import com.intellij.openapi.wm.impl.status.IdeStatusBarImpl
import com.intellij.toolWindow.ToolWindowButtonManager
import com.intellij.toolWindow.ToolWindowPane
import com.intellij.toolWindow.ToolWindowPaneNewButtonManager
import com.intellij.toolWindow.ToolWindowPaneOldButtonManager
import com.intellij.ui.*
import com.intellij.ui.components.JBBox
import com.intellij.ui.components.JBLayeredPane
import com.intellij.ui.components.JBPanel
import com.intellij.ui.mac.MacWinTabsHandler
import com.intellij.util.cancelOnDispose
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.*
import com.jetbrains.JBR
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus
import java.awt.*
import java.awt.event.MouseMotionAdapter
import java.util.function.Consumer
import javax.swing.*
private const val EXTENSION_KEY = "extensionKey"
@Suppress("LeakingThis")
@ApiStatus.Internal
open class IdeRootPane internal constructor(frame: JFrame,
parentDisposable: Disposable,
loadingState: FrameLoadingState?) : JRootPane(), UISettingsListener {
private var toolbar: JComponent? = null
internal var statusBar: IdeStatusBarImpl? = null
private set
private var statusBarDisposed = false
private val northPanel = JBBox.createVerticalBox()
internal var navBarStatusWidgetComponent: JComponent? = null
private set
private var toolWindowPane: ToolWindowPane? = null
private val glassPaneInitialized: Boolean
private var fullScreen = false
private sealed interface Helper {
val toolbarHolder: ToolbarHolder?
fun init(frame: JFrame, pane: JRootPane, parentDisposable: Disposable) {
}
}
private object UndecoratedHelper : Helper {
override val toolbarHolder: ToolbarHolder?
get() = null
override fun init(frame: JFrame, pane: JRootPane, parentDisposable: Disposable) {
ToolbarUtil.setCustomTitleBar(frame, pane) { runnable -> Disposer.register(parentDisposable, runnable::run) }
}
}
private class DecoratedHelper(
val customFrameTitlePane: MainFrameCustomHeader,
val selectedEditorFilePath: SelectedEditorFilePath?,
) : Helper {
override val toolbarHolder: ToolbarHolder? = (customFrameTitlePane as? ToolbarHolder)
?.takeIf { ExperimentalUI.isNewUI() && isToolbarInHeader }
}
private val helper: Helper
init {
if (SystemInfoRt.isWindows && (StartupUiUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF())) {
try {
windowDecorationStyle = FRAME
}
catch (e: Exception) {
logger<IdeRootPane>().error(e)
}
}
val contentPane = contentPane
// listen to mouse motion events for a11y
contentPane.addMouseMotionListener(object : MouseMotionAdapter() {})
val isDecoratedMenu = isDecoratedMenu
if (!isDecoratedMenu && !isFloatingMenuBarSupported) {
jMenuBar = IdeMenuBar.createMenuBar()
helper = UndecoratedHelper
}
else {
if (isDecoratedMenu) {
JBR.getCustomWindowDecoration().setCustomDecorationEnabled(frame, true)
if (SystemInfoRt.isMac) {
ToolbarUtil.removeMacSystemTitleBar(this)
}
val selectedEditorFilePath: SelectedEditorFilePath?
val customFrameTitlePane = if (ExperimentalUI.isNewUI()) {
selectedEditorFilePath = null
if (SystemInfoRt.isMac) {
MacToolbarFrameHeader(frame = frame, root = this)
}
else {
ToolbarFrameHeader(frame = frame, ideMenu = IdeMenuBar.createMenuBar())
}
}
else {
selectedEditorFilePath = CustomDecorationPath(frame)
MenuFrameHeader(frame = frame, headerTitle = selectedEditorFilePath, ideMenu = IdeMenuBar.createMenuBar())
}
helper = DecoratedHelper(
customFrameTitlePane = customFrameTitlePane,
selectedEditorFilePath = selectedEditorFilePath,
)
layeredPane.add(customFrameTitlePane.getComponent(), (JLayeredPane.DEFAULT_LAYER - 2) as Any)
}
else {
helper = UndecoratedHelper
}
if (isFloatingMenuBarSupported) {
menuBar = IdeMenuBar.createMenuBar()
layeredPane.add(menuBar, (JLayeredPane.DEFAULT_LAYER - 1) as Any)
}
}
val glassPane = IdeGlassPaneImpl(rootPane = this, loadingState = loadingState, parentDisposable = parentDisposable)
setGlassPane(glassPane)
glassPaneInitialized = true
if (frame is IdeFrameImpl) {
putClientProperty(UIUtil.NO_BORDER_UNDER_WINDOW_TITLE_KEY, java.lang.Boolean.TRUE)
}
UIUtil.decorateWindowHeader(this)
border = UIManager.getBorder("Window.border")
helper.init(frame, rootPane, parentDisposable)
updateMainMenuVisibility()
if (helper.toolbarHolder == null) {
toolbar = createToolbar(initActions = true)
northPanel.add(toolbar, 0)
val visible = !isToolbarInHeader && !UISettings.shadowInstance.presentationMode
toolbar!!.isVisible = visible
}
if (SystemInfoRt.isMac && JdkEx.isTabbingModeAvailable()) {
contentPane.add(MacWinTabsHandler.wrapRootPaneNorthSide(this, northPanel), BorderLayout.NORTH)
}
else {
contentPane.add(northPanel, BorderLayout.NORTH)
}
@Suppress("LeakingThis")
contentPane.add(createCenterComponent(frame, parentDisposable), BorderLayout.CENTER)
}
companion object {
/**
* Returns true if menu should be placed in toolbar instead of menu bar
*/
internal val isMenuButtonInToolbar: Boolean
get() = SystemInfoRt.isXWindow && ExperimentalUI.isNewUI() && !UISettings.shadowInstance.separateMainMenu
internal fun customizeRawFrame(frame: IdeFrameImpl) {
// some rootPane is required
val rootPane = JRootPane()
if (isDecoratedMenu && !isFloatingMenuBarSupported) {
JBR.getCustomWindowDecoration().setCustomDecorationEnabled(frame, true)
if (SystemInfoRt.isMac) {
ToolbarUtil.removeMacSystemTitleBar(rootPane)
}
}
frame.doSetRootPane(rootPane)
}
@ApiStatus.Internal
fun executeWithPrepareActionManagerAndCustomActionScheme(disposable: Disposable?, task: Consumer<ActionManager>) {
val app = ApplicationManager.getApplication()
@Suppress("DEPRECATION")
val job = app.coroutineScope.launch {
val componentManager = app as ComponentManagerEx
val actionManager = componentManager.getServiceAsync(ActionManager::class.java).await()
componentManager.getServiceAsync(CustomActionsSchema::class.java).join()
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
task.accept(actionManager)
}
}
if (disposable != null) {
job.cancelOnDispose(disposable)
}
}
}
/**
* @return not-null action group or null to use [IdeActions.GROUP_MAIN_MENU] action group
*/
open val mainMenuActionGroup: ActionGroup?
get() = null
protected open fun createCenterComponent(frame: JFrame, parentDisposable: Disposable): Component {
val paneId = WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID
val toolWindowButtonManager: ToolWindowButtonManager
if (ExperimentalUI.isNewUI()) {
toolWindowButtonManager = ToolWindowPaneNewButtonManager(paneId)
toolWindowButtonManager.add(contentPane as JComponent)
}
else {
toolWindowButtonManager = ToolWindowPaneOldButtonManager(paneId)
}
toolWindowPane = ToolWindowPane(frame = frame,
parentDisposable = parentDisposable,
paneId = paneId,
buttonManager = toolWindowButtonManager)
return toolWindowPane!!
}
open fun getToolWindowPane(): ToolWindowPane = toolWindowPane!!
private fun updateScreenState(isInFullScreen: () -> Boolean) {
fullScreen = isInFullScreen()
val bar = jMenuBar
if (helper is DecoratedHelper) {
if (bar != null) {
bar.isVisible = fullScreen
}
helper.customFrameTitlePane.getComponent().isVisible = !fullScreen
}
else if (SystemInfoRt.isXWindow) {
if (bar != null) {
bar.isVisible = fullScreen || !isMenuButtonInToolbar
}
if (toolbar != null) {
val uiSettings = UISettings.shadowInstance
val isNewToolbar = ExperimentalUI.isNewUI()
toolbar!!.isVisible = !fullScreen && ((isNewToolbar && !isToolbarInHeader) || (!isNewToolbar && uiSettings.showMainToolbar))
}
}
}
override fun createRootLayout(): LayoutManager {
return if (isFloatingMenuBarSupported || isDecoratedMenu) MyRootLayout() else super.createRootLayout()
}
final override fun setGlassPane(glass: Component) {
check(!glassPaneInitialized) { "Setting of glass pane for IdeFrame is prohibited" }
super.setGlassPane(glass)
}
/**
* Invoked when enclosed frame is being disposed.
*/
override fun removeNotify() {
if (ScreenUtil.isStandardAddRemoveNotify(this)) {
if (!statusBarDisposed) {
statusBarDisposed = true
Disposer.dispose(statusBar!!)
}
jMenuBar = null
if (helper is DecoratedHelper) {
val customFrameTitlePane = helper.customFrameTitlePane
layeredPane.remove(customFrameTitlePane.getComponent())
Disposer.dispose(customFrameTitlePane)
}
}
super.removeNotify()
}
override fun createLayeredPane(): JLayeredPane {
val result = JBLayeredPane()
result.name = "$name.layeredPane"
return result
}
override fun createContentPane(): Container {
val contentPane = JBPanel<JBPanel<*>>(BorderLayout())
contentPane.background = IdeBackgroundUtil.getIdeBackgroundColor()
return contentPane
}
@RequiresEdt
internal fun preInit(isInFullScreen: () -> Boolean) {
if (isDecoratedMenu || isFloatingMenuBarSupported) {
addPropertyChangeListener(IdeFrameDecorator.FULL_SCREEN) { updateScreenState(isInFullScreen) }
updateScreenState(isInFullScreen)
}
}
fun initToolbar(actionGroups: List<Pair<ActionGroup, String>>) {
val toolbarHolder = helper.toolbarHolder
if (toolbarHolder != null) {
toolbarHolder.initToolbar(actionGroups)
}
else if (ExperimentalUI.isNewUI()) {
(toolbar as MainToolbar).init(actionGroups)
}
}
internal fun updateToolbar() {
val delegate = helper.toolbarHolder
if (delegate != null) {
delegate.updateToolbar()
return
}
toolbar?.let {
disposeIfNeeded(it)
northPanel.remove(it)
}
toolbar = createToolbar()
northPanel.add(toolbar, 0)
val uiSettings = UISettings.shadowInstance
val isNewToolbar = ExperimentalUI.isNewUI()
val visible = ((isNewToolbar && !isToolbarInHeader) || (!isNewToolbar && uiSettings.showMainToolbar)) && !uiSettings.presentationMode
toolbar!!.isVisible = visible
contentPane!!.revalidate()
}
open fun updateNorthComponents() {
val componentCount = northPanel.componentCount
if (componentCount == 0 || (componentCount == 1 && northPanel.getComponent(0) === toolbar)) {
return
}
for (i in 0 until componentCount) {
val component = northPanel.getComponent(i)
if (component !== toolbar) {
component.revalidate()
}
}
contentPane!!.revalidate()
}
fun updateMainMenuActions() {
if (helper is DecoratedHelper) {
val customFrameTitlePane = helper.customFrameTitlePane
// The menu bar is decorated, we update it indirectly.
customFrameTitlePane.updateMenuActions(false)
customFrameTitlePane.getComponent().repaint()
}
else if (menuBar != null) {
// no decorated menu bar, but there is a regular one, update it directly
(menuBar as IdeMenuBar).updateMenuActions(false)
menuBar.repaint()
}
}
fun createAndConfigureStatusBar(frame: IdeFrame, parentDisposable: Disposable) {
val statusBar = createStatusBar(frame)
this.statusBar = statusBar
Disposer.register(parentDisposable, statusBar)
updateStatusBarVisibility()
contentPane!!.add(statusBar, BorderLayout.SOUTH)
}
protected open fun createStatusBar(frame: IdeFrame): IdeStatusBarImpl {
val addToolWindowsWidget = !ExperimentalUI.isNewUI() && !GeneralSettings.getInstance().isSupportScreenReaders
return IdeStatusBarImpl(frame, addToolWindowsWidget)
}
val statusBarHeight: Int
get() {
val statusBar = statusBar
return if (statusBar != null && statusBar.isVisible) statusBar.height else 0
}
private fun updateToolbarVisibility() {
if (toolbar == null) {
toolbar = createToolbar()
northPanel.add(toolbar, 0)
}
val uiSettings = UISettings.shadowInstance
val isNewToolbar = ExperimentalUI.isNewUI()
val visible = ((isNewToolbar && !isToolbarInHeader || !isNewToolbar && uiSettings.showMainToolbar) && !uiSettings.presentationMode)
toolbar!!.isVisible = visible
}
private fun updateStatusBarVisibility() {
val uiSettings = UISettings.shadowInstance
statusBar!!.isVisible = uiSettings.showStatusBar && !uiSettings.presentationMode
}
private fun updateMainMenuVisibility() {
val uiSettings = UISettings.shadowInstance
if (uiSettings.presentationMode || IdeFrameDecorator.isCustomDecorationActive()) {
return
}
val globalMenuVisible = SystemInfoRt.isLinux && GlobalMenuLinux.isPresented()
// don't show swing-menu when global (system) menu presented
val visible = SystemInfo.isMacSystemMenu || !globalMenuVisible && uiSettings.showMainMenu && !isMenuButtonInToolbar
if (menuBar != null && visible != menuBar.isVisible) {
menuBar.isVisible = visible
}
}
fun setProject(project: Project) {
installNorthComponents(project)
statusBar?.let {
project.messageBus.simpleConnect().subscribe(StatusBar.Info.TOPIC, it)
}
(helper as? DecoratedHelper)?.selectedEditorFilePath?.project = project
}
@RequiresEdt
protected open fun installNorthComponents(project: Project) {
val northExtensions = IdeRootPaneNorthExtension.EP_NAME.extensionList
if (northExtensions.isEmpty()) {
return
}
for (extension in northExtensions) {
val component = extension.createComponent(/* project = */ project, /* isDocked = */ false) ?: continue
component.putClientProperty(EXTENSION_KEY, extension.key)
northPanel.add(component)
if (component is StatusBarCentralWidgetProvider) {
navBarStatusWidgetComponent = component.createCentralStatusBarComponent()
}
}
}
internal open fun deinstallNorthComponents(project: Project) {
val count = northPanel.componentCount
for (i in count - 1 downTo 0) {
if (northPanel.getComponent(i) !== toolbar) {
northPanel.remove(i)
}
}
}
fun findNorthUiComponentByKey(key: String): JComponent? {
return northPanel.components.firstOrNull { (it as? JComponent)?.getClientProperty(EXTENSION_KEY) == key } as? JComponent
}
override fun uiSettingsChanged(uiSettings: UISettings) {
UIUtil.decorateWindowHeader(this)
updateToolbarVisibility()
updateStatusBarVisibility()
updateMainMenuVisibility()
val frame = ComponentUtil.getParentOfType(IdeFrameImpl::class.java, this) ?: return
frame.background = JBColor.PanelBackground
(frame.balloonLayout as? BalloonLayoutImpl)?.queueRelayout()
}
private inner class MyRootLayout : RootLayout() {
// do not cache it - MyRootLayout is created before IdeRootPane constructor
private val customFrameTitlePane: MainFrameCustomHeader?
get() = (helper as? DecoratedHelper)?.customFrameTitlePane
override fun preferredLayoutSize(parent: Container): Dimension {
return computeLayoutSize(parent) { it.preferredSize }
}
override fun minimumLayoutSize(parent: Container): Dimension {
return computeLayoutSize(parent) { it.preferredSize }
}
private inline fun computeLayoutSize(parent: Container, getter: (menuBar: Container) -> Dimension): Dimension {
val insets = insets
val rd = contentPane?.let { getter(it) } ?: parent.size
val dimension = getDimension()
val menuBarDimension = getMenuBarDimension(getter)
return Dimension(rd.width.coerceAtLeast(menuBarDimension.width) + insets.left + insets.right + dimension.width,
rd.height + menuBarDimension.height + insets.top + insets.bottom + dimension.height)
}
override fun maximumLayoutSize(target: Container): Dimension {
val insets = insets
val menuBarDimension = getMenuBarDimension { it.maximumSize }
val dimension = getDimension()
val rd = if (contentPane != null) {
contentPane.maximumSize
}
else {
Dimension(Int.MAX_VALUE, Int.MAX_VALUE - insets.top - insets.bottom - menuBarDimension.height - 1)
}
return Dimension(rd.width.coerceAtMost(menuBarDimension.width) + insets.left + insets.right + dimension.width,
rd.height + menuBarDimension.height + insets.top + insets.bottom + dimension.height)
}
private fun getDimension(): Dimension {
val customFrameTitleComponent = customFrameTitlePane?.getComponent()
val dimension = if (customFrameTitleComponent != null && customFrameTitleComponent.isVisible) {
customFrameTitleComponent.preferredSize
}
else {
JBUI.emptySize()
}
return dimension
}
private inline fun getMenuBarDimension(getter: (menuBar: JComponent) -> Dimension): Dimension {
val menuBar = menuBar
if (menuBar != null && menuBar.isVisible && !fullScreen && !isDecoratedMenu) {
return getter(menuBar)
}
else {
return JBUI.emptySize()
}
}
override fun layoutContainer(parent: Container) {
val b = parent.bounds
val i = insets
val w = b.width - i.right - i.left
val h = b.height - i.top - i.bottom
if (layeredPane != null) {
layeredPane.setBounds(i.left, i.top, w, h)
}
glassPane?.setBounds(i.left, i.top, w, h)
var contentY = 0
if (menuBar != null && menuBar.isVisible) {
val mbd = menuBar.preferredSize
menuBar.setBounds(0, 0, w, mbd.height)
if (!fullScreen && !isDecoratedMenu) {
contentY += mbd.height
}
}
val customFrameTitlePane = customFrameTitlePane
if (customFrameTitlePane != null && customFrameTitlePane.getComponent().isVisible) {
val tpd = customFrameTitlePane.getComponent().preferredSize
if (tpd != null) {
val tpHeight = tpd.height
customFrameTitlePane.getComponent().setBounds(0, 0, w, tpHeight)
contentY += tpHeight
}
}
contentPane?.setBounds(0, contentY, w, h - contentY)
}
}
}
private val isToolbarInHeader by lazy { isToolbarInHeader(UISettings.shadowInstance) }
private val isDecoratedMenu: Boolean
get() {
val osSupported = SystemInfoRt.isWindows || (SystemInfoRt.isMac && ExperimentalUI.isNewUI())
return osSupported && (isToolbarInHeader || IdeFrameDecorator.isCustomDecorationActive())
}
private fun createToolbar(initActions: Boolean = true): JComponent {
if (ExperimentalUI.isNewUI()) {
val toolbar = MainToolbar()
if (initActions) {
toolbar.init(MainToolbar.computeActionGroups(CustomActionsSchema.getInstance()))
}
toolbar.border = JBUI.Borders.empty()
return toolbar
}
else {
val group = CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_MAIN_TOOLBAR) as ActionGroup
val toolBar = ActionManagerEx.getInstanceEx().createActionToolbar(ActionPlaces.MAIN_TOOLBAR, group, true)
toolBar.targetComponent = null
toolBar.layoutPolicy = ActionToolbar.WRAP_LAYOUT_POLICY
PopupHandler.installPopupMenu(toolBar.component, "MainToolbarPopupActions", "MainToolbarPopup")
return toolBar.component
}
}
private fun disposeIfNeeded(component: JComponent) {
@Suppress("DEPRECATION")
if (component is Disposable && !Disposer.isDisposed(component)) {
Disposer.dispose(component)
}
}
|
apache-2.0
|
4aadd7eab5eff1dc4baff1c29675e76e
| 35.435 | 137 | 0.70979 | 4.78756 | false | false | false | false |
androidx/androidx
|
security/security-crypto-ktx/src/main/java/androidx/security/crypto/MasterKey.kt
|
3
|
1946
|
/*
* 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.security.crypto
import android.content.Context
/**
* Creates a [MasterKey] with the provided parameters.
*
* @param context The context to work with.
* @param keyAlias The alias to use for the `MasterKey`.
* @param keyScheme The [MasterKey.KeyScheme] to have the `MasterKey` use.
* @param authenticationRequired `true` if the user must authenticate for the `MasterKey` to be
* used.
* @param userAuthenticationValidityDurationSeconds Duration in seconds that the `MasterKey` is
* valid for after the user has authenticated. Must be a value > 0.
* @param requestStrongBoxBacked `true` if the key should be stored in Strong Box, if possible.
*/
public fun MasterKey(
context: Context,
keyAlias: String = MasterKey.DEFAULT_MASTER_KEY_ALIAS,
keyScheme: MasterKey.KeyScheme = MasterKey.KeyScheme.AES256_GCM,
authenticationRequired: Boolean = false,
userAuthenticationValidityDurationSeconds: Int =
MasterKey.getDefaultAuthenticationValidityDurationSeconds(),
requestStrongBoxBacked: Boolean = false
): MasterKey = MasterKey.Builder(context, keyAlias)
.setKeyScheme(keyScheme)
.setUserAuthenticationRequired(
authenticationRequired,
userAuthenticationValidityDurationSeconds
)
.setRequestStrongBoxBacked(requestStrongBoxBacked)
.build()
|
apache-2.0
|
d0e0ca6451c4f12e7b80d20e466fcd98
| 39.541667 | 95 | 0.754882 | 4.373034 | false | false | false | false |
SimpleMobileTools/Simple-Notes
|
app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/OpenNoteDialog.kt
|
1
|
2509
|
package com.simplemobiletools.notes.pro.dialogs
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.notes.pro.R
import com.simplemobiletools.notes.pro.extensions.config
import com.simplemobiletools.notes.pro.helpers.NotesHelper
import com.simplemobiletools.notes.pro.models.Note
import kotlinx.android.synthetic.main.dialog_open_note.view.*
import kotlinx.android.synthetic.main.open_note_item.view.*
class OpenNoteDialog(val activity: Activity, val callback: (checkedId: Long, newNote: Note?) -> Unit) {
private var dialog: AlertDialog? = null
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_open_note, null)
NotesHelper(activity).getNotes {
initDialog(it, view)
}
view.dialog_open_note_new_radio.setOnClickListener {
view.dialog_open_note_new_radio.isChecked = false
NewNoteDialog(activity, setChecklistAsDefault = false) {
callback(0, it)
dialog?.dismiss()
}
}
}
private fun initDialog(notes: ArrayList<Note>, view: View) {
val textColor = activity.getProperTextColor()
notes.forEach {
activity.layoutInflater.inflate(R.layout.open_note_item, null).apply {
val note = it
open_note_item_radio_button.apply {
text = note.title
isChecked = note.id == activity.config.currentNoteId
id = note.id!!.toInt()
setOnClickListener {
callback(note.id!!, null)
dialog?.dismiss()
}
}
open_note_item_icon.apply {
beVisibleIf(note.path.isNotEmpty())
applyColorFilter(textColor)
setOnClickListener {
activity.toast(note.path)
}
}
view.dialog_open_note_linear.addView(this, RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
}
}
activity.getAlertDialogBuilder().apply {
activity.setupDialogStuff(view, this, R.string.open_note) { alertDialog ->
dialog = alertDialog
}
}
}
}
|
gpl-3.0
|
e9b237985f01b192feb9eb86111138ef
| 37.015152 | 157 | 0.607812 | 4.760911 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/compiler-plugins/lombok/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/lombok/gradleJava/LombokGradleProjectResolverExtension.kt
|
4
|
1416
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.lombok.gradleJava
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.util.Key
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradleTooling.model.lombok.LombokModel
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
class LombokGradleProjectResolverExtension : AbstractProjectResolverExtension() {
private val modelClass: Class<LombokModel> = LombokModel::class.java
private val userDataKey: Key<LombokModel> = KEY
override fun getExtraProjectModelClasses() = setOf(modelClass)
override fun getToolingExtensionsClasses() = setOf(
modelClass,
Unit::class.java
)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val model = resolverCtx.getExtraProject(gradleModule, modelClass)
if (model != null) {
ideModule.putCopyableUserData(userDataKey, model)
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
companion object {
val KEY = Key<LombokModel>("LombokModel")
}
}
|
apache-2.0
|
4a2a1625005142a18674562012a289ad
| 37.27027 | 158 | 0.765537 | 4.865979 | false | false | false | false |
fvasco/pinpoi
|
app/src/main/java/io/github/fvasco/pinpoi/importer/AbstractXmlImporter.kt
|
1
|
3320
|
package io.github.fvasco.pinpoi.importer
import io.github.fvasco.pinpoi.model.Placemark
import io.github.fvasco.pinpoi.util.assertDebug
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import java.io.IOException
import java.io.InputStream
import java.util.*
/**
* Base XML importer
*
* @author Francesco Vasco
*/
abstract class AbstractXmlImporter : AbstractImporter() {
protected val parser: XmlPullParser = XML_PULL_PARSER_FACTORY.newPullParser()
protected var placemark: Placemark? = null
protected var text: String = ""
protected var tag: String = DOCUMENT_TAG
private val tagStack = ArrayDeque<String>()
@Throws(IOException::class)
override fun importImpl(inputStream: InputStream) {
try {
parser.setInput(inputStream, null)
var eventType = parser.eventType
tag = DOCUMENT_TAG
handleStartTag()
while (eventType != XmlPullParser.END_DOCUMENT) {
when (eventType) {
XmlPullParser.START_TAG -> {
tagStack.addLast(tag)
tag = parser.name
text = ""
handleStartTag()
}
XmlPullParser.TEXT -> if (text.isEmpty()) text = parser.text else text += parser.text
XmlPullParser.END_TAG -> {
handleEndTag()
tag = tagStack.removeLast()
text = ""
}
}
eventType = parser.next()
}
assertDebug(tag === DOCUMENT_TAG)
assertDebug(placemark == null, placemark)
assertDebug(text == "", text)
} catch (e: XmlPullParserException) {
throw IOException("Error reading XML file", e)
}
}
/**
* Create a new placemark and saves old one
*/
protected fun newPlacemark() {
assertDebug(placemark == null, placemark)
placemark = Placemark()
}
protected fun importPlacemark() {
val p = checkNotNull(placemark) { "No placemark to import" }
if (!p.name.isBlank()) {
importPlacemark(p)
}
placemark = null
}
/**
* Check if current path match given tags, except current tag in [.tag]
*/
protected fun checkCurrentPath(vararg tags: String): Boolean {
if (tags.size != tagStack.size - 1) return false
val iterator = tagStack.descendingIterator()
for (i in tags.indices.reversed()) {
if (tags[i] != iterator.next()) return false
}
return true
}
/**
* Handle a start tag
*/
@Throws(IOException::class)
protected abstract fun handleStartTag()
/**
* Handle a end tag, text is in [.text] attribute
*/
@Throws(IOException::class)
protected abstract fun handleEndTag()
companion object {
private const val DOCUMENT_TAG = "<XML>"
private val XML_PULL_PARSER_FACTORY: XmlPullParserFactory by lazy {
XmlPullParserFactory.newInstance().apply {
isNamespaceAware = true
isValidating = false
}
}
}
}
|
gpl-3.0
|
bcf54c2306732ea9378821428e20ebf9
| 30.320755 | 105 | 0.571988 | 4.903988 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/actions/RunScratchAction.kt
|
1
|
3930
|
// 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.scratch.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbService
import com.intellij.task.ProjectTaskManager
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import org.jetbrains.kotlin.idea.scratch.SequentialScratchExecutor
import org.jetbrains.kotlin.idea.scratch.getScratchFileFromSelectedEditor
import org.jetbrains.kotlin.idea.scratch.printDebugMessage
import org.jetbrains.kotlin.idea.scratch.LOG as log
class RunScratchAction : ScratchAction(
KotlinJvmBundle.message("scratch.run.button"),
AllIcons.Actions.Execute
) {
init {
KeymapManager.getInstance().activeKeymap.getShortcuts("Kotlin.RunScratch").firstOrNull()?.let {
templatePresentation.text += " (${KeymapUtil.getShortcutText(it)})"
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val scratchFile = getScratchFileFromSelectedEditor(project) ?: return
doAction(scratchFile, false)
}
companion object {
fun doAction(scratchFile: ScratchFile, isAutoRun: Boolean) {
val isRepl = scratchFile.options.isRepl
val executor = (if (isRepl) scratchFile.replScratchExecutor else scratchFile.compilingScratchExecutor) ?: return
log.printDebugMessage("Run Action: isRepl = $isRepl")
fun executeScratch() {
try {
if (isAutoRun && executor is SequentialScratchExecutor) {
executor.executeNew()
} else {
executor.execute()
}
} catch (ex: Throwable) {
executor.errorOccurs(KotlinJvmBundle.message("exception.occurs.during.run.scratch.action"), ex, true)
}
}
val isMakeBeforeRun = scratchFile.options.isMakeBeforeRun
log.printDebugMessage("Run Action: isMakeBeforeRun = $isMakeBeforeRun")
val module = scratchFile.module
log.printDebugMessage("Run Action: module = ${module?.name}")
if (!isAutoRun && module != null && isMakeBeforeRun) {
val project = scratchFile.project
ProjectTaskManager.getInstance(project).build(module).onSuccess { executionResult ->
if (executionResult.isAborted || executionResult.hasErrors()) {
executor.errorOccurs(KotlinJvmBundle.message("there.were.compilation.errors.in.module.0", module.name))
}
if (DumbService.isDumb(project)) {
DumbService.getInstance(project).smartInvokeLater {
executeScratch()
}
} else {
executeScratch()
}
}
} else {
executeScratch()
}
}
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabled = !ScratchCompilationSupport.isAnyInProgress()
if (e.presentation.isEnabled) {
e.presentation.text = templatePresentation.text
} else {
e.presentation.text = KotlinJvmBundle.message("other.scratch.file.execution.is.in.progress")
}
val project = e.project ?: return
val scratchFile = getScratchFileFromSelectedEditor(project) ?: return
e.presentation.isVisible = !ScratchCompilationSupport.isInProgress(scratchFile)
}
}
|
apache-2.0
|
6692d8b02170c713c312c394cb4f52d4
| 39.112245 | 158 | 0.637405 | 5.171053 | false | false | false | false |
jwren/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/project/importing/MavenImportContext.kt
|
1
|
5349
|
// 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.idea.maven.project.importing
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.concurrency.Promise
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.model.MavenExplicitProfiles
import org.jetbrains.idea.maven.model.MavenPlugin
import org.jetbrains.idea.maven.model.MavenProjectProblem
import org.jetbrains.idea.maven.project.*
import org.jetbrains.idea.maven.server.NativeMavenProjectHolder
import org.jetbrains.idea.maven.utils.MavenProgressIndicator
data class MavenImportingResult(
val finishPromise: Promise<MavenImportFinishedContext>,
val dummyModulesCreated: Module?
)
sealed abstract class MavenImportContext(val project: Project) {
abstract val indicator: MavenProgressIndicator
}
class MavenStartedImport(project: Project) : MavenImportContext(project) {
override val indicator = MavenProgressIndicator(project, null)
}
class MavenInitialImportContext internal constructor(project: Project,
val paths: ImportPaths,
val profiles: MavenExplicitProfiles,
val generalSettings: MavenGeneralSettings,
val importingSettings: MavenImportingSettings,
val ignorePaths: List<String>,
val ignorePatterns: List<String>,
val dummyModule: Module?
) : MavenImportContext(project) {
override val indicator = MavenProgressIndicator(project, null)
}
data class WrapperData(val distributionUrl: String, val baseDir: VirtualFile)
class MavenReadContext internal constructor(project: Project,
val projectsTree: MavenProjectsTree,
val toResolve: Collection<MavenProject>,
val withSyntaxErrors: Collection<MavenProject>,
val initialContext: MavenInitialImportContext,
val wrapperData: WrapperData?,
override val indicator: MavenProgressIndicator) : MavenImportContext(project) {
fun hasReadingProblems() = !withSyntaxErrors.isEmpty()
fun collectProblems(): Collection<MavenProjectProblem> = withSyntaxErrors.flatMap { it.problems }
}
class MavenResolvedContext internal constructor(project: Project,
val unresolvedArtifacts: Collection<MavenArtifact>,
val projectsToImport: List<MavenProject>,
val nativeProjectHolder: List<Pair<MavenProject, NativeMavenProjectHolder>>,
val readContext: MavenReadContext) : MavenImportContext(project) {
val initialContext = readContext.initialContext
override val indicator = readContext.indicator
}
class MavenPluginResolvedContext internal constructor(project: Project,
val unresolvedPlugins: Set<MavenPlugin>,
val resolvedContext: MavenResolvedContext) : MavenImportContext(project) {
override val indicator = resolvedContext.indicator
}
class MavenSourcesGeneratedContext internal constructor(val resolvedContext: MavenResolvedContext,
val projectsFoldersResolved: List<MavenProject>) : MavenImportContext(
resolvedContext.project) {
override val indicator = resolvedContext.indicator
}
class MavenImportedContext internal constructor(project: Project,
val modulesCreated: List<Module>,
val postImportTasks: List<MavenProjectsProcessorTask>?,
val readContext: MavenReadContext,
val resolvedContext: MavenResolvedContext) : MavenImportContext(project) {
override val indicator = resolvedContext.indicator
}
class MavenImportFinishedContext internal constructor(val context: MavenImportedContext?,
val error: Throwable?,
project: Project) : MavenImportContext(project) {
override val indicator = context?.indicator ?: MavenProgressIndicator(project, null)
constructor(e: Throwable, project: Project) : this(null, e, project)
constructor(context: MavenImportedContext) : this(context, null, context.project)
}
sealed class ImportPaths
class FilesList(val poms: List<VirtualFile>) : ImportPaths() {
constructor(poms: Array<VirtualFile>) : this(poms.asList())
constructor(pom: VirtualFile) : this(listOf(pom))
}
class RootPath(val path: VirtualFile) : ImportPaths()
|
apache-2.0
|
d6c1ed92808fa41e56e941c4efab366a
| 50.442308 | 158 | 0.625351 | 6.003367 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/AddFunctionBodyFix.kt
|
3
|
1427
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
class AddFunctionBodyFix(element: KtFunction) : KotlinPsiOnlyQuickFixAction<KtFunction>(element) {
override fun getFamilyName() = KotlinBundle.message("fix.add.function.body")
override fun getText() = familyName
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
val element = element ?: return false
return !element.hasBody()
}
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
if (!element.hasBody()) {
element.add(KtPsiFactory(project).createEmptyBody())
}
}
companion object : QuickFixesPsiBasedFactory<KtFunction>(KtFunction::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
override fun doCreateQuickFix(psiElement: KtFunction): List<IntentionAction> = listOfNotNull(AddFunctionBodyFix(psiElement))
}
}
|
apache-2.0
|
a5919c0617cbbdf0c86a5c4e6356003d
| 43.59375 | 158 | 0.755431 | 4.678689 | false | false | false | false |
GunoH/intellij-community
|
platform/indexing-api/src/com/intellij/util/indexing/roots/kind/indexableSetOriginsApi.kt
|
2
|
7504
|
// 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.util.indexing.roots.kind
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.SyntheticLibrary
import com.intellij.openapi.util.Condition
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.indexing.IndexableSetContributor
import com.intellij.util.indexing.roots.IndexableFilesIterator
import java.util.*
import java.util.function.Predicate
/**
* Represents an origin of [com.intellij.util.indexing.roots.IndexableFilesIterator].
*/
interface IndexableSetOrigin
/**
* Represents an origin of [com.intellij.util.indexing.roots.IndexableFilesIterator] which has enough info to create iterator on itself.
* Designed for use with [com.intellij.util.indexing.IndexableFilesIndex] in case it's enabled.
* See [com.intellij.util.indexing.IndexableFilesIndex.shouldBeUsed]
*/
abstract class IndexableSetIterableOrigin : IndexableSetOrigin {
abstract val iterationRoots: Collection<VirtualFile>
protected abstract val exclusionData: ExclusionData
fun isExcluded(file: VirtualFile): Boolean = exclusionData.isExcluded(file)
abstract fun createIterator(): IndexableFilesIterator
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as IndexableSetIterableOrigin
if (iterationRoots != other.iterationRoots) return false
if (exclusionData != other.exclusionData) return false
return true
}
override fun hashCode(): Int {
var result = iterationRoots.hashCode()
result = 31 * result + exclusionData.hashCode()
return result
}
interface ExclusionData : Predicate<VirtualFile> {
val rootsToExclude: Iterable<VirtualFile>
fun isExcluded(file: VirtualFile): Boolean
fun addRelevantExcludedRootsFromDirectoryIndexExcludePolicies(allExcludedRoots: Collection<VirtualFile>)
fun setExcludedRootsFromChildContentRoots(childContentRoots: Collection<VirtualFile>)
fun addExcludedFileCondition(condition: Condition<VirtualFile>?)
fun load(data: ExclusionData)
fun isExcludedByCondition(file: VirtualFile): Boolean
override fun test(file: VirtualFile): Boolean = isExcluded(file)
companion object {
fun createExclusionData(includedRoots: Collection<VirtualFile>): ExclusionData = ExclusionDataImpl(includedRoots)
private class ExclusionDataImpl(private val includedRoots: Collection<VirtualFile>) : ExclusionData {
private val excludedRoots: MutableCollection<VirtualFile> = mutableListOf()
private var excludeCondition: Predicate<VirtualFile>? = null
private val excludedChildContentRoots: MutableCollection<VirtualFile> = mutableListOf()
override fun addRelevantExcludedRootsFromDirectoryIndexExcludePolicies(allExcludedRoots: Collection<VirtualFile>) {
for (excludedRoot in allExcludedRoots) {
if (VfsUtilCore.isUnderFiles(excludedRoot, includedRoots)) {
excludedRoots.add(excludedRoot)
}
}
}
override fun setExcludedRootsFromChildContentRoots(childContentRoots: Collection<VirtualFile>) {
excludedChildContentRoots.clear()
for (childContentRoot in childContentRoots) {
if (VfsUtilCore.isUnderFiles(childContentRoot, includedRoots)) {
excludedChildContentRoots.add(childContentRoot)
}
}
}
override fun addExcludedFileCondition(condition: Condition<VirtualFile>?) {
if (condition == null) return
val predicate = Predicate<VirtualFile> { condition.value(it) }
excludeCondition?.also { excludeCondition = it.and(predicate) } ?: run {
excludeCondition = predicate
}
}
override fun isExcluded(file: VirtualFile): Boolean = VfsUtilCore.isUnderFiles(file, excludedRoots) ||
isExcludedByCondition(file) ||
VfsUtilCore.isUnderFiles(file, excludedChildContentRoots)
override val rootsToExclude: Iterable<VirtualFile>
get() = excludedRoots + excludedChildContentRoots
override fun isExcludedByCondition(file: VirtualFile): Boolean = excludeCondition?.test(file) ?: false
override fun load(data: ExclusionData) {
assert(data is ExclusionDataImpl) { "Exclusion data is expected to be the same" }
excludedRoots.clear()
excludedRoots.addAll((data as ExclusionDataImpl).excludedRoots)
excludeCondition = data.excludeCondition
excludedChildContentRoots.clear()
excludedChildContentRoots.addAll(data.excludedChildContentRoots)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ExclusionDataImpl
if (includedRoots != other.includedRoots) return false
if (excludedRoots != other.excludedRoots) return false
//we can't compare conditions, so !== for the sake of reflexivity
if (excludeCondition !== other.excludeCondition) return false
if (excludedChildContentRoots !== other.excludedChildContentRoots) return false
return true
}
override fun hashCode(): Int {
var result = includedRoots.hashCode()
result = 31 * result + excludedRoots.hashCode()
result = 31 * result + (excludeCondition?.hashCode() ?: 0)
result = 31 * result + excludedChildContentRoots.hashCode()
return result
}
}
fun getDummyExclusionData(): ExclusionData = DummyExclusionData
private object DummyExclusionData : ExclusionData {
override val rootsToExclude: Iterable<VirtualFile>
get() = Collections.emptyList()
override fun isExcluded(file: VirtualFile): Boolean = false
override fun isExcludedByCondition(file: VirtualFile): Boolean = false
override fun addRelevantExcludedRootsFromDirectoryIndexExcludePolicies(allExcludedRoots: Collection<VirtualFile>) {
}
override fun setExcludedRootsFromChildContentRoots(childContentRoots: Collection<VirtualFile>) {
}
override fun addExcludedFileCondition(condition: Condition<VirtualFile>?) {
}
override fun load(data: ExclusionData) {
assert(data == DummyExclusionData) { "Can't load non dummy exclusion data into a dummy one" }
}
}
}
}
}
interface ModuleRootOrigin : IndexableSetOrigin {
val module: Module
val roots: List<VirtualFile>
}
interface LibraryOrigin : IndexableSetOrigin {
val classRoots: List<VirtualFile>
val sourceRoots: List<VirtualFile>
}
interface SyntheticLibraryOrigin : IndexableSetOrigin {
val syntheticLibrary: SyntheticLibrary
val rootsToIndex: Collection<VirtualFile>
}
interface SdkOrigin : IndexableSetOrigin {
val sdk: Sdk
val rootsToIndex: Collection<VirtualFile>
}
interface IndexableSetContributorOrigin : IndexableSetOrigin {
val indexableSetContributor: IndexableSetContributor
val rootsToIndex: Set<VirtualFile>
}
interface ProjectFileOrDirOrigin : IndexableSetOrigin {
val fileOrDir: VirtualFile
}
|
apache-2.0
|
144be231c9d65c84956d53a6af3edc14
| 37.482051 | 136 | 0.716018 | 5.175172 | false | false | false | false |
smmribeiro/intellij-community
|
java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaCodeVisionConfigurable.kt
|
9
|
2019
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl
import com.intellij.codeInsight.actions.ReaderModeSettingsListener
import com.intellij.codeInsight.daemon.impl.analysis.JavaCodeVisionSettings
import com.intellij.codeInsight.hints.ChangeListener
import com.intellij.codeInsight.hints.ImmediateConfigurable
import com.intellij.ide.IdeBundle
import com.intellij.java.JavaBundle
import com.intellij.ui.dsl.builder.panel
import org.jetbrains.annotations.Nls
import java.util.function.Supplier
internal class JavaCodeVisionConfigurable(val settings: JavaCodeVisionSettings) : ImmediateConfigurable {
override fun createComponent(listener: ChangeListener): javax.swing.JPanel {
return panel {
row {
text(IdeBundle.message("checkbox.also.in.reader.mode")) {
ReaderModeSettingsListener.goToEditorReaderMode()
}
}
}
}
override val cases: List<ImmediateConfigurable.Case>
get() = listOf(
ImmediateConfigurable.Case(JavaBundle.message("settings.inlay.java.usages"), USAGES_CASE_ID, { settings.isShowUsages }, { settings.isShowUsages = it }),
ImmediateConfigurable.Case(JavaBundle.message("settings.inlay.java.inheritors"), INHERITORS_CASE_ID, { settings.isShowImplementations }, { settings.isShowImplementations = it })
)
override val mainCheckboxText: String
get() = JavaBundle.message("settings.inlay.java.show.hints.for")
companion object {
const val USAGES_CASE_ID = "usages"
const val INHERITORS_CASE_ID = "inheritors"
@JvmStatic
fun getCaseName(caseId: String): Supplier<@Nls String> =
when (caseId) {
USAGES_CASE_ID -> JavaBundle.messagePointer("settings.inlay.java.usages")
INHERITORS_CASE_ID -> JavaBundle.messagePointer("settings.inlay.java.inheritors")
else -> throw IllegalArgumentException("Unknown case id $caseId")
}
}
}
|
apache-2.0
|
193db4000610f91905ad45ae9dc140dd
| 42.891304 | 183 | 0.754829 | 4.38913 | false | true | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/completion/tests/testData/smart/propertyDelegate/ValInClass.kt
|
13
|
1667
|
import kotlin.reflect.KProperty
class X1 {
operator fun getValue(thisRef: C, property: KProperty<*>): String = ""
companion object {
fun create() = X1()
}
}
class X2 {
operator fun getValue(thisRef: String, property: KProperty<*>): String = ""
}
class X3 {
operator fun getValue(thisRef: Any, property: KProperty<*>): String = ""
}
class Y1
class Y2
abstract class Y3
operator fun Y1.getValue(thisRef: C, property: KProperty<*>): String = ""
operator fun Y2.getValue(thisRef: String, property: KProperty<*>): String = ""
operator fun Y3.getValue(thisRef: Any, property: KProperty<*>): String = ""
fun createX1() = X1()
fun createX2() = X2()
fun createX3() = X3()
fun createY1() = Y1()
fun createY2() = Y2()
fun createY3(): Y3 = object : Y3() {}
class C {
val property by <caret>
}
// EXIST: lazy
// EXIST: { itemText: "Delegates.notNull", tailText:"() (kotlin.properties)", typeText: "ReadWriteProperty<Any?, T>", attributes:"" }
// EXIST: { itemText: "Delegates.observable", tailText:"(initialValue: T, crossinline onChange: (KProperty<*>, T, T) -> Unit) (kotlin.properties)", typeText: "ReadWriteProperty<Any?, T>", attributes:"" }
// EXIST: { itemText: "Delegates.vetoable", tailText:"(initialValue: T, crossinline onChange: (KProperty<*>, T, T) -> Boolean) (kotlin.properties)", typeText: "ReadWriteProperty<Any?, T>", attributes:"" }
// EXIST: createX1
// ABSENT: createX2
// EXIST: createX3
// EXIST: createY1
// ABSENT: createY2
// EXIST: createY3
// EXIST: X1
// ABSENT: X2
// EXIST: X3
// EXIST: Y1
// ABSENT: Y2
// ABSENT: Y3
// EXIST: { itemText:"X1.create", tailText:"() (<root>)", typeText:"X1", attributes:"" }
|
apache-2.0
|
2a1b11ef013d097b39110a884912fa38
| 29.309091 | 204 | 0.658668 | 3.395112 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/response/MetaInfoView.kt
|
1
|
1768
|
package ch.rmy.android.http_shortcuts.activities.response
import android.content.Context
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.view.isVisible
import ch.rmy.android.framework.extensions.layoutInflater
import ch.rmy.android.framework.extensions.tryOrIgnore
import ch.rmy.android.http_shortcuts.databinding.ViewMetaInfoBinding
class MetaInfoView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : FrameLayout(context, attrs, defStyleAttr) {
private val binding = ViewMetaInfoBinding.inflate(layoutInflater, this, true)
fun showGeneralInfo(data: List<Pair<String, String>>) {
binding.generalContainer.isVisible = true
binding.generalView.text = toStyledSpan(data)
}
fun showHeaders(headers: List<Pair<String, String>>) {
binding.headersContainer.isVisible = true
binding.headersView.text = toStyledSpan(headers)
}
companion object {
private fun toStyledSpan(data: List<Pair<String, String>>): CharSequence {
val builder = SpannableStringBuilder()
var offset = 0
data.forEach { (name, value) ->
if (offset != 0) {
builder.append("\n")
offset++
}
val line = "$name: $value"
builder.append(line)
tryOrIgnore {
builder.setSpan(StyleSpan(Typeface.BOLD), offset, offset + name.length + 1, 0)
}
offset += line.length
}
return builder
}
}
}
|
mit
|
ced68f91f1fc22a83adc99406276b2d2
| 33 | 98 | 0.648756 | 4.628272 | false | false | false | false |
sksamuel/ktest
|
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/factory/build.kt
|
1
|
426
|
package io.kotest.core.factory
/**
* Builds an immutable [TestFactory] from this [TestFactoryConfiguration].
*/
internal fun TestFactoryConfiguration.build(): TestFactory {
return TestFactory(
factoryId = factoryId,
tests = tests,
tags = _tags,
listeners = _listeners.map { FactoryConstrainedTestListener(factoryId, it) },
extensions = _extensions,
assertionMode = assertions,
)
}
|
mit
|
49ec75d744ec29e3e041d77724582c25
| 27.4 | 83 | 0.692488 | 4.681319 | false | true | false | false |
saksmt/karaf-runner
|
src/main/java/run/smt/karafrunner/modules/impl/util/AggregateModule.kt
|
1
|
924
|
package run.smt.karafrunner.modules.impl.util
import org.kohsuke.args4j.Argument
import run.smt.karafrunner.io.exception.UserErrorException
import run.smt.karafrunner.io.output.hightlight
import run.smt.karafrunner.modules.api.AbstractModule
import run.smt.karafrunner.modules.api.Module
class AggregateModule(private val modulesMapping: Map<String, Module>, defaultModule: String? = null) : AbstractModule() {
@Argument(required = false)
private var moduleName: String? = defaultModule
private lateinit var arguments: List<String>;
override fun run(arguments: List<String>) {
this.arguments = arguments.drop(1)
super.run(arguments.take(1))
}
private val noModule = "Unsupported operation. Use ${"help".hightlight()} for usage"
override fun doRun() {
val module = modulesMapping[moduleName] ?: throw UserErrorException(noModule)
module.run(arguments)
}
}
|
mit
|
4e3951df0ee831dd628c5d5ef228cdf7
| 34.576923 | 122 | 0.74026 | 4.106667 | false | false | false | false |
dinosaurwithakatana/freight
|
freight-processor/src/test/kotlin/io/dwak/freight/processor/FreightProcessorNavigatorTest.kt
|
1
|
40362
|
package io.dwak.freight.processor
import com.google.common.truth.Truth
import com.google.testing.compile.CompilationSubject
import com.google.testing.compile.CompilationSubject.assertThat
import com.google.testing.compile.Compiler
import com.google.testing.compile.Compiler.javac
import com.google.testing.compile.JavaFileObjects
import io.dwak.freight.util.processAndAssertEquals
import org.junit.Test
class FreightProcessorNavigatorTest {
companion object {
private const val NAVIGATOR_PACKAGE = "io.dwak.freight.navigator"
private val FREIGHT_NAVIGATOR = listOf(
"package io.dwak.freight.internal;",
"import com.bluelinelabs.conductor.Router;",
"import io.dwak.freight.Navigator;",
"public abstract class FreightNavigator implements Navigator {",
" @SuppressWarnings(\"WeakerAccess\")",
" protected final Router router;",
" public FreightNavigator(Router router) {",
" this.router = router;",
" }",
" @Override",
" public boolean popToRoot() {",
" return router.popToRoot();",
" }",
" @Override",
" public boolean goBack() {",
" return router.popCurrentController();",
" }",
"}")
private val freightNavigatorJavaSource
= JavaFileObjects.forSourceLines("io.dwak.freight.internal.FreightNavigator",
FREIGHT_NAVIGATOR)
}
@Test
fun singleControllerNoExtrasNoScope() {
val inputFile
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test\")",
"public class TestController extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val mainNavigatorName = "$NAVIGATOR_PACKAGE.main.MainNavigator"
val expectedInterfaceOutput
= JavaFileObjects.forSourceLines(mainNavigatorName,
"package $NAVIGATOR_PACKAGE.main;",
"",
"import io.dwak.freight.Navigator;",
"",
"public interface MainNavigator extends Navigator {",
" void goToTest();",
"}")
val freightMainNavigatorName = "$NAVIGATOR_PACKAGE.main.Freight_MainNavigator"
val expectedFreightImplOutput
= JavaFileObjects.forSourceLines(freightMainNavigatorName,
"package $NAVIGATOR_PACKAGE.main;",
"import com.bluelinelabs.conductor.Router;",
"import com.bluelinelabs.conductor.RouterTransaction;",
"import io.dwak.freight.internal.FreightNavigator;",
"import java.lang.Override;",
"import test.TestControllerBuilder;",
"public class Freight_MainNavigator extends FreightNavigator implements MainNavigator {",
" public Freight_MainNavigator(Router router) {",
" super(router);",
" }",
" @Override",
" public void goToTest() {",
" final TestControllerBuilder builder = new TestControllerBuilder();",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test\");",
" router.pushController(rt);",
" }",
"}")
processAndAssertEquals(listOf(freightNavigatorJavaSource, inputFile),
mainNavigatorName to expectedInterfaceOutput,
freightMainNavigatorName to expectedFreightImplOutput)
}
@Test
fun singleControllerSingleExtraNoScope() {
val inputFile
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import io.dwak.freight.annotation.Extra;",
"import android.os.Bundle;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"import java.lang.String;",
"@ControllerBuilder(value = \"Test\")",
"public class TestController extends Controller {",
" @Extra String stringExtra;",
"",
" public TestController(Bundle bundle){",
" super(bundle);",
" }",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val mainNavigatorName = "$NAVIGATOR_PACKAGE.main.MainNavigator"
val expectedInterfaceOutput
= JavaFileObjects.forSourceLines(mainNavigatorName,
"package $NAVIGATOR_PACKAGE.main;",
"",
"import io.dwak.freight.Navigator;",
"import java.lang.String;",
"",
"public interface MainNavigator extends Navigator {",
" void goToTest(final String stringExtra);",
"}")
val freightMainNavigatorName = "$NAVIGATOR_PACKAGE.main.Freight_MainNavigator"
val expectedFreightImplOutput
= JavaFileObjects.forSourceLines(freightMainNavigatorName,
"package $NAVIGATOR_PACKAGE.main;",
"import com.bluelinelabs.conductor.Router;",
"import com.bluelinelabs.conductor.RouterTransaction;",
"import io.dwak.freight.internal.FreightNavigator;",
"import java.lang.Override;",
"import java.lang.String;",
"import test.TestControllerBuilder;",
"public class Freight_MainNavigator extends FreightNavigator implements MainNavigator {",
" public Freight_MainNavigator(Router router) {",
" super(router);",
" }",
" @Override",
" public void goToTest(final String stringExtra) {",
" final TestControllerBuilder builder = new TestControllerBuilder();",
" builder.stringExtra(stringExtra);",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test\");",
" router.pushController(rt);",
" }",
"}")
processAndAssertEquals(listOf(freightNavigatorJavaSource, inputFile),
mainNavigatorName to expectedInterfaceOutput,
freightMainNavigatorName to expectedFreightImplOutput)
}
@Test
fun singleControllerNoExtrasCustomScope() {
val inputFile
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test\", scope = \"Test\")",
"public class TestController extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val testNavigator = "$NAVIGATOR_PACKAGE.test.TestNavigator"
val expectedInterfaceOutput
= JavaFileObjects.forSourceLines(testNavigator,
"package $NAVIGATOR_PACKAGE.test;",
"",
"import io.dwak.freight.Navigator;",
"",
"public interface TestNavigator extends Navigator {",
" void goToTest();",
"}")
val freightMainNavigator = "$NAVIGATOR_PACKAGE.test.Freight_TestNavigator"
val expectedFreightImplOutput
= JavaFileObjects.forSourceLines(freightMainNavigator,
"package $NAVIGATOR_PACKAGE.test;",
"import com.bluelinelabs.conductor.Router;",
"import com.bluelinelabs.conductor.RouterTransaction;",
"import io.dwak.freight.internal.FreightNavigator;",
"import java.lang.Override;",
"import test.TestControllerBuilder;",
"public class Freight_TestNavigator extends FreightNavigator implements TestNavigator {",
" public Freight_TestNavigator(Router router) {",
" super(router);",
" }",
" @Override",
" public void goToTest() {",
" final TestControllerBuilder builder = new TestControllerBuilder();",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test\");",
" router.pushController(rt);",
" }",
"}")
processAndAssertEquals(listOf(freightNavigatorJavaSource, inputFile),
testNavigator to expectedInterfaceOutput,
freightMainNavigator to expectedFreightImplOutput)
}
@Test
fun singleControllerNoNameNoExtrasCustomScope() {
val inputFile
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(scope = \"Test\")",
"public class TestController extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val testNavigator = "$NAVIGATOR_PACKAGE.test.TestNavigator"
val expectedInterfaceOutput
= JavaFileObjects.forSourceLines(testNavigator,
"package $NAVIGATOR_PACKAGE.test;",
"",
"import io.dwak.freight.Navigator;",
"",
"public interface TestNavigator extends Navigator {",
" void goToTest();",
"}")
val freightMainNavigator = "$NAVIGATOR_PACKAGE.test.Freight_TestNavigator"
val expectedFreightImplOutput
= JavaFileObjects.forSourceLines(freightMainNavigator,
"package $NAVIGATOR_PACKAGE.test;",
"import com.bluelinelabs.conductor.Router;",
"import com.bluelinelabs.conductor.RouterTransaction;",
"import io.dwak.freight.internal.FreightNavigator;",
"import java.lang.Override;",
"import test.TestControllerBuilder;",
"public class Freight_TestNavigator extends FreightNavigator implements TestNavigator {",
" public Freight_TestNavigator(Router router) {",
" super(router);",
" }",
" @Override",
" public void goToTest() {",
" final TestControllerBuilder builder = new TestControllerBuilder();",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test\");",
" router.pushController(rt);",
" }",
"}")
val compilation = javac()
.withProcessors(FreightProcessor())
.withOptions("-Xlint:-processing")
.compile(inputFile)
assertThat(compilation).succeeded()
assertThat(compilation).hadWarningContaining("needs a screen name value")
}
@Test
fun singleControllerNoExtrasNoScopeFailedPopChangeHandler() {
val inputFile
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test\", popChangeHandler = String.class)",
"public class TestController extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val compilation = javac()
.withProcessors(FreightProcessor())
.withOptions("-Xlint:-processing")
.compile(inputFile)
assertThat(compilation).failed()
assertThat(compilation).hadErrorContaining("must be of type ControllerChangeHandler")
}
@Test
fun singleControllerNoExtrasNoScopeFailedPushChangeHandler() {
val inputFile
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test\", pushChangeHandler = String.class)",
"public class TestController extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val compilation = javac()
.withProcessors(FreightProcessor())
.withOptions("-Xlint:-processing")
.compile(inputFile)
assertThat(compilation).failed()
assertThat(compilation).hadErrorContaining("must be of type ControllerChangeHandler")
}
@Test
fun twoControllersNoExtrasNoScope() {
val testController
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test\")",
"public class TestController extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val testController2
= JavaFileObjects.forSourceLines("test.TestController2",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test2\")",
"public class TestController2 extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val mainNavigatorName = "$NAVIGATOR_PACKAGE.main.MainNavigator"
val expectedInterfaceOutput
= JavaFileObjects.forSourceLines(mainNavigatorName,
"package $NAVIGATOR_PACKAGE.main;",
"",
"import io.dwak.freight.Navigator;",
"",
"public interface MainNavigator extends Navigator {",
" void goToTest();",
" void goToTest2();",
"}")
val freightMainNavigator = "$NAVIGATOR_PACKAGE.main.Freight_MainNavigator"
val expectedFreightImplOutput
= JavaFileObjects.forSourceLines(freightMainNavigator,
"package $NAVIGATOR_PACKAGE.main;",
"import com.bluelinelabs.conductor.Router;",
"import com.bluelinelabs.conductor.RouterTransaction;",
"import io.dwak.freight.internal.FreightNavigator;",
"import java.lang.Override;",
"import test.TestController2Builder;",
"import test.TestControllerBuilder;",
"public class Freight_MainNavigator extends FreightNavigator implements MainNavigator {",
" public Freight_MainNavigator(Router router) {",
" super(router);",
" }",
" @Override",
" public void goToTest() {",
" final TestControllerBuilder builder = new TestControllerBuilder();",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test\");",
" router.pushController(rt);",
" }",
" @Override",
" public void goToTest2() {",
" final TestController2Builder builder = new TestController2Builder();",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test2\");",
" router.pushController(rt);",
" }",
"}")
processAndAssertEquals(listOf(freightNavigatorJavaSource, testController, testController2),
mainNavigatorName to expectedInterfaceOutput,
freightMainNavigator to expectedFreightImplOutput)
}
@Test
fun twoControllersNoExtrasCustomScope() {
val testController
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test\", scope = \"Test\")",
"public class TestController extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val testController2
= JavaFileObjects.forSourceLines("test.TestController2",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test2\", scope = \"Test\")",
"public class TestController2 extends Controller {",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val testNavigatorName = "$NAVIGATOR_PACKAGE.test.TestNavigator"
val expectedInterfaceOutput
= JavaFileObjects.forSourceLines(testNavigatorName,
"package $NAVIGATOR_PACKAGE.test;",
"",
"import io.dwak.freight.Navigator;",
"",
"public interface TestNavigator extends Navigator {",
" void goToTest();",
" void goToTest2();",
"}")
val freightImplName = "$NAVIGATOR_PACKAGE.test.Freight_TestNavigator"
val expectedFreightImplOutput
= JavaFileObjects.forSourceLines(freightImplName,
"package $NAVIGATOR_PACKAGE.test;",
"import com.bluelinelabs.conductor.Router;",
"import com.bluelinelabs.conductor.RouterTransaction;",
"import io.dwak.freight.internal.FreightNavigator;",
"import java.lang.Override;",
"import test.TestController2Builder;",
"import test.TestControllerBuilder;",
"public class Freight_TestNavigator extends FreightNavigator implements TestNavigator {",
" public Freight_TestNavigator(Router router) {",
" super(router);",
" }",
" @Override",
" public void goToTest() {",
" final TestControllerBuilder builder = new TestControllerBuilder();",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test\");",
" router.pushController(rt);",
" }",
" @Override",
" public void goToTest2() {",
" final TestController2Builder builder = new TestController2Builder();",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test2\");",
" router.pushController(rt);",
" }",
"}")
processAndAssertEquals(listOf(freightNavigatorJavaSource, testController, testController2),
testNavigatorName to expectedInterfaceOutput,
freightImplName to expectedFreightImplOutput)
}
@Test
fun twoControllersWithExtrasCustomScope() {
val testController
= JavaFileObjects.forSourceLines("test.TestController",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import io.dwak.freight.annotation.Extra;",
"import android.os.Bundle;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"import java.lang.String;",
"@ControllerBuilder(value = \"Test\", scope = \"Test\")",
"public class TestController extends Controller {",
" @Extra String myExtra;",
"",
" public TestController(Bundle bundle) {",
" super(bundle);",
" }",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val testController2
= JavaFileObjects.forSourceLines("test.TestController2",
"package test;",
"import com.bluelinelabs.conductor.Controller;",
"import io.dwak.freight.annotation.ControllerBuilder;",
"import io.dwak.freight.annotation.Extra;",
"import android.os.Bundle;",
"import android.support.annotation.NonNull;",
"import android.support.annotation.Nullable;",
"import android.view.LayoutInflater;",
"import android.view.View;",
"import android.view.ViewGroup;",
"@ControllerBuilder(value = \"Test2\", scope = \"Test\")",
"public class TestController2 extends Controller {",
" @Extra int myExtra2;",
"",
" public TestController2(Bundle bundle) {",
" super(bundle);",
" }",
"",
" @NonNull",
" @Override",
" protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {",
" return null;",
" }",
"}")
val testNavigatorName = "$NAVIGATOR_PACKAGE.test.TestNavigator"
val expectedInterfaceOutput
= JavaFileObjects.forSourceLines(testNavigatorName,
"package $NAVIGATOR_PACKAGE.test;",
"",
"import io.dwak.freight.Navigator;",
"import java.lang.String;",
"",
"public interface TestNavigator extends Navigator {",
" void goToTest(final String myExtra);",
"",
" void goToTest2(final int myExtra2);",
"}")
val freightImplName = "$NAVIGATOR_PACKAGE.test.Freight_TestNavigator"
val expectedFreightImplOutput
= JavaFileObjects.forSourceLines(freightImplName,
"package $NAVIGATOR_PACKAGE.test;",
"import com.bluelinelabs.conductor.Router;",
"import com.bluelinelabs.conductor.RouterTransaction;",
"import io.dwak.freight.internal.FreightNavigator;",
"import java.lang.Override;",
"import java.lang.String;",
"import test.TestController2Builder;",
"import test.TestControllerBuilder;",
"public class Freight_TestNavigator extends FreightNavigator implements TestNavigator {",
" public Freight_TestNavigator(Router router) {",
" super(router);",
" }",
" @Override",
" public void goToTest(final String myExtra) {",
" final TestControllerBuilder builder = new TestControllerBuilder();",
" builder.myExtra(myExtra);",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test\");",
" router.pushController(rt);",
" }",
" @Override",
" public void goToTest2(final int myExtra2) {",
" final TestController2Builder builder = new TestController2Builder();",
" builder.myExtra2(myExtra2);",
" RouterTransaction rt = builder.asTransaction()",
" .tag(\"Test2\");",
" router.pushController(rt);",
" }",
"}")
processAndAssertEquals(listOf(freightNavigatorJavaSource, testController, testController2),
testNavigatorName to expectedInterfaceOutput,
freightImplName to expectedFreightImplOutput)
}
}
|
apache-2.0
|
b7c1f29a0feaca403d2b0955f5ad8e3c
| 62.364207 | 139 | 0.398964 | 7.660277 | false | true | false | false |
seventhroot/elysium
|
bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/profession/RPKProfessionImpl.kt
|
1
|
3471
|
/*
* Copyright 2020 Ren Binden
*
* 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.rpkit.professions.bukkit.profession
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQuality
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQualityProvider
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import org.bukkit.Material
import org.nfunk.jep.JEP
import kotlin.math.roundToInt
class RPKProfessionImpl(
override var id: Int = 0,
override val name: String,
override val maxLevel: Int,
val plugin: RPKProfessionsBukkit
): RPKProfession {
override fun getAmountFor(action: RPKCraftingAction, material: Material, level: Int): Double {
val actionConfigSectionName = when (action) {
RPKCraftingAction.CRAFT -> "crafting"
RPKCraftingAction.SMELT -> "smelting"
RPKCraftingAction.MINE -> "mining"
}
return plugin.config.getDouble("professions.$name.$actionConfigSectionName.$level.$material.amount",
if (level > 1)
getAmountFor(action, material, level - 1)
else
plugin.config.getDouble("default.$actionConfigSectionName.$material.amount", 1.0)
)
}
override fun getQualityFor(action: RPKCraftingAction, material: Material, level: Int): RPKItemQuality? {
val actionConfigSectionName = when (action) {
RPKCraftingAction.CRAFT -> "crafting"
RPKCraftingAction.SMELT -> "smelting"
RPKCraftingAction.MINE -> "mining"
}
val itemQualityProvider = plugin.core.serviceManager.getServiceProvider(RPKItemQualityProvider::class)
val itemQualityName = plugin.config.getString("professions.$name.$actionConfigSectionName.$level.$material.quality")
?: when {
level > 1 -> return getQualityFor(action, material, level - 1)
else -> plugin.config.getString("default.$actionConfigSectionName.$material.quality")
}
?: return null
return itemQualityProvider.getItemQuality(itemQualityName)
}
override fun getExperienceNeededForLevel(level: Int): Int {
val expression = plugin.config.getString("professions.$name.experience.formula")
val parser = JEP()
parser.addStandardConstants()
parser.addStandardFunctions()
parser.addVariable("level", level.toDouble())
parser.parseExpression(expression)
return parser.value.roundToInt()
}
override fun getExperienceFor(action: RPKCraftingAction, material: Material): Int {
val actionConfigSectionName = when (action) {
RPKCraftingAction.CRAFT -> "crafting"
RPKCraftingAction.SMELT -> "smelting"
RPKCraftingAction.MINE -> "mining"
}
return plugin.config.getInt("professions.$name.experience.items.$actionConfigSectionName.$material")
}
}
|
apache-2.0
|
7f710ba5f2bae8be0a33b0b983b3f6bc
| 41.864198 | 124 | 0.681648 | 4.972779 | false | true | false | false |
avito-tech/Konveyor
|
konveyor/src/main/java/com/avito/konveyor/adapter/SimpleAdapterPresenter.kt
|
1
|
1174
|
package com.avito.konveyor.adapter
import com.avito.konveyor.blueprint.Item
import com.avito.konveyor.blueprint.ItemPresenter
import com.avito.konveyor.blueprint.ItemView
import com.avito.konveyor.blueprint.ViewTypeProvider
import com.avito.konveyor.data_source.DataSource
import com.avito.konveyor.data_source.ListDataSource
class SimpleAdapterPresenter(private val viewTypeProvider: ViewTypeProvider,
private val itemBinder: ItemPresenter<ItemView, Item>) : AdapterPresenter {
private var dataSource: DataSource<out Item> = ListDataSource(emptyList())
override fun onDataSourceChanged(dataSource: DataSource<out Item>) {
this.dataSource = dataSource
}
override fun getCount(): Int = dataSource.count
override fun bindView(view: ItemView, position: Int) = itemBinder.bindView(view, getItem(position), position)
override fun getViewType(position: Int): Int {
val item = dataSource.getItem(position)
return viewTypeProvider.getItemViewType(item)
}
override fun getItemId(position: Int) = getItem(position).id
private fun getItem(position: Int) = dataSource.getItem(position)
}
|
mit
|
c73524a0d8f31b20bc95b0ebd4192c0c
| 35.71875 | 113 | 0.756388 | 4.238267 | false | false | false | false |
ibinti/intellij-community
|
platform/projectModel-api/src/com/intellij/util/jdom.kt
|
5
|
4866
|
/*
* 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.util
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.reference.SoftReference
import com.intellij.util.io.inputStream
import com.intellij.util.io.outputStream
import com.intellij.util.text.CharSequenceReader
import org.jdom.Document
import org.jdom.Element
import org.jdom.JDOMException
import org.jdom.Parent
import org.jdom.filter.ElementFilter
import org.jdom.input.SAXBuilder
import org.jdom.input.SAXHandler
import org.xml.sax.EntityResolver
import org.xml.sax.InputSource
import org.xml.sax.XMLReader
import java.io.*
import java.nio.file.Path
import javax.xml.XMLConstants
private val cachedSaxBuilder = ThreadLocal<SoftReference<SAXBuilder>>()
private fun getSaxBuilder(): SAXBuilder {
val reference = cachedSaxBuilder.get()
var saxBuilder = SoftReference.dereference<SAXBuilder>(reference)
if (saxBuilder == null) {
saxBuilder = object : SAXBuilder() {
override fun configureParser(parser: XMLReader, contentHandler: SAXHandler?) {
super.configureParser(parser, contentHandler)
try {
parser.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)
}
catch (ignore: Exception) {
}
}
}
saxBuilder.ignoringBoundaryWhitespace = true
saxBuilder.ignoringElementContentWhitespace = true
saxBuilder.entityResolver = EntityResolver { publicId, systemId -> InputSource(CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY)) }
cachedSaxBuilder.set(SoftReference<SAXBuilder>(saxBuilder))
}
return saxBuilder
}
@JvmOverloads
@Throws(IOException::class)
fun Parent.write(file: Path, lineSeparator: String = "\n", filter: JDOMUtil.ElementOutputFilter? = null) {
write(file.outputStream(), lineSeparator, filter)
}
@JvmOverloads
fun Parent.write(output: OutputStream, lineSeparator: String = "\n", filter: JDOMUtil.ElementOutputFilter? = null) {
output.bufferedWriter().use { writer ->
if (this is Document) {
JDOMUtil.writeDocument(this, writer, lineSeparator)
}
else {
JDOMUtil.writeElement(this as Element, writer, JDOMUtil.createOutputter(lineSeparator, filter))
}
}
}
@Throws(IOException::class, JDOMException::class)
fun loadElement(chars: CharSequence) = loadElement(CharSequenceReader(chars))
@Throws(IOException::class, JDOMException::class)
fun loadElement(reader: Reader): Element = loadDocument(reader).detachRootElement()
@Throws(IOException::class, JDOMException::class)
fun loadElement(stream: InputStream): Element = loadDocument(stream.reader()).detachRootElement()
@Throws(IOException::class, JDOMException::class)
fun loadElement(path: Path): Element = loadDocument(path.inputStream().bufferedReader()).detachRootElement()
fun loadDocument(reader: Reader): Document = reader.use { getSaxBuilder().build(it) }
fun Element?.isEmpty() = this == null || JDOMUtil.isEmpty(this)
fun Element.getOrCreate(name: String): Element {
var element = getChild(name)
if (element == null) {
element = Element(name)
addContent(element)
}
return element
}
fun Element.get(name: String): Element? = getChild(name)
fun Element.element(name: String): Element {
val element = Element(name)
addContent(element)
return element
}
fun Element.attribute(name: String, value: String?): Element = setAttribute(name, value)
fun <T> Element.remove(name: String, transform: (child: Element) -> T): List<T> {
val result = SmartList<T>()
val groupIterator = getContent(ElementFilter(name)).iterator()
while (groupIterator.hasNext()) {
val child = groupIterator.next()
result.add(transform(child))
groupIterator.remove()
}
return result
}
fun Element.toByteArray(): ByteArray {
val out = BufferExposingByteArrayOutputStream(512)
JDOMUtil.write(this, out, "\n")
return out.toByteArray()
}
fun Element.addOptionTag(name: String, value: String) {
val element = Element("option")
element.setAttribute("name", name)
element.setAttribute("value", value)
addContent(element)
}
fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream {
val out = BufferExposingByteArrayOutputStream(512)
JDOMUtil.write(this, out, lineSeparator)
return out
}
|
apache-2.0
|
179f4ded830c42bba66b7837940b91a7
| 33.034965 | 129 | 0.752363 | 4.216638 | false | false | false | false |
firebase/quickstart-android
|
storage/app/src/main/java/com/google/firebase/quickstart/firebasestorage/kotlin/MyDownloadService.kt
|
1
|
5065
|
package com.google.firebase.quickstart.firebasestorage.kotlin
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.firebasestorage.R
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.ktx.component1
import com.google.firebase.storage.ktx.component2
import com.google.firebase.storage.ktx.storage
class MyDownloadService : MyBaseTaskService() {
private lateinit var storageRef: StorageReference
override fun onCreate() {
super.onCreate()
// Initialize Storage
storageRef = Firebase.storage.reference
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.d(TAG, "onStartCommand:$intent:$startId")
if (ACTION_DOWNLOAD == intent.action) {
// Get the path to download from the intent
val downloadPath = intent.getStringExtra(EXTRA_DOWNLOAD_PATH)!!
downloadFromPath(downloadPath)
}
return Service.START_REDELIVER_INTENT
}
private fun downloadFromPath(downloadPath: String) {
Log.d(TAG, "downloadFromPath:$downloadPath")
// Mark task started
taskStarted()
showProgressNotification(getString(R.string.progress_downloading), 0, 0)
// Download and get total bytes
storageRef.child(downloadPath).getStream { (_, totalBytes), inputStream ->
var bytesDownloaded: Long = 0
val buffer = ByteArray(1024)
var size: Int = inputStream.read(buffer)
while (size != -1) {
bytesDownloaded += size.toLong()
showProgressNotification(getString(R.string.progress_downloading),
bytesDownloaded, totalBytes)
size = inputStream.read(buffer)
}
// Close the stream at the end of the Task
inputStream.close()
}.addOnSuccessListener { (_, totalBytes) ->
Log.d(TAG, "download:SUCCESS")
// Send success broadcast with number of bytes downloaded
broadcastDownloadFinished(downloadPath, totalBytes)
showDownloadFinishedNotification(downloadPath, totalBytes.toInt())
// Mark task completed
taskCompleted()
}.addOnFailureListener { exception ->
Log.w(TAG, "download:FAILURE", exception)
// Send failure broadcast
broadcastDownloadFinished(downloadPath, -1)
showDownloadFinishedNotification(downloadPath, -1)
// Mark task completed
taskCompleted()
}
}
/**
* Broadcast finished download (success or failure).
* @return true if a running receiver received the broadcast.
*/
private fun broadcastDownloadFinished(downloadPath: String, bytesDownloaded: Long): Boolean {
val success = bytesDownloaded != -1L
val action = if (success) DOWNLOAD_COMPLETED else DOWNLOAD_ERROR
val broadcast = Intent(action)
.putExtra(EXTRA_DOWNLOAD_PATH, downloadPath)
.putExtra(EXTRA_BYTES_DOWNLOADED, bytesDownloaded)
return LocalBroadcastManager.getInstance(applicationContext)
.sendBroadcast(broadcast)
}
/**
* Show a notification for a finished download.
*/
private fun showDownloadFinishedNotification(downloadPath: String, bytesDownloaded: Int) {
// Hide the progress notification
dismissProgressNotification()
// Make Intent to MainActivity
val intent = Intent(this, MainActivity::class.java)
.putExtra(EXTRA_DOWNLOAD_PATH, downloadPath)
.putExtra(EXTRA_BYTES_DOWNLOADED, bytesDownloaded)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val success = bytesDownloaded != -1
val caption = if (success) {
getString(R.string.download_success)
} else {
getString(R.string.download_failure)
}
showFinishedNotification(caption, intent, true)
}
companion object {
private const val TAG = "Storage#DownloadService"
/** Actions */
const val ACTION_DOWNLOAD = "action_download"
const val DOWNLOAD_COMPLETED = "download_completed"
const val DOWNLOAD_ERROR = "download_error"
/** Extras */
const val EXTRA_DOWNLOAD_PATH = "extra_download_path"
const val EXTRA_BYTES_DOWNLOADED = "extra_bytes_downloaded"
val intentFilter: IntentFilter
get() {
val filter = IntentFilter()
filter.addAction(DOWNLOAD_COMPLETED)
filter.addAction(DOWNLOAD_ERROR)
return filter
}
}
}
|
apache-2.0
|
e73b02e243cb32b129b8d1d6fa8dd840
| 33.222973 | 97 | 0.644817 | 5.142132 | false | false | false | false |
kmruiz/sonata
|
backend/src/main/kotlin/io/sonatalang/snc/backend/intrinsics/internal/FunctionDefinitionIntrinsic.kt
|
1
|
1802
|
package io.sonatalang.snc.backend.intrinsics.internal
import io.sonatalang.snc.backend.Backend
import io.sonatalang.snc.backend.intrinsics.Intrinsic
import io.sonatalang.snc.middleEnd.domain.function.GlobalFunction
import io.sonatalang.snc.middleEnd.domain.node.LetFunctionNode
import io.sonatalang.snc.middleEnd.domain.node.Node
import io.sonatalang.snc.middleEnd.domain.type.RuntimeType
object FunctionDefinitionIntrinsic: Intrinsic {
override fun canResolve(expression: Node) = expression is LetFunctionNode
override fun resolve(expression: Node, backend: Backend): String {
val fn = expression as LetFunctionNode
val overloadedFn: GlobalFunction?
try {
overloadedFn = backend.functionConsumer.consumeFunction(fn.name.name) as GlobalFunction
} catch (ex: Throwable) {
return ""
}
if (overloadedFn.overloads.size == 1) {
return (
"""function ${backend.compileToString(fn.name)}(${fn.parameters.map { backend.compileToString(it) }.joinToString()}) {
return ${backend.compileToString(fn.body)}
}""")
}
var result = "function ${backend.compileToString(fn.name)}(${fn.parameters.map { backend.compileToString(it) }.joinToString()}) {\n"
result += " " + overloadedFn.overloads.map { overload ->
val matchedParams = fn.parameters.map { it.name }.zip(overload.forParameters.filter { it is RuntimeType }.map { it as RuntimeType }.map { it.paramType.qualifiedName() }).map {
"${it.second}(${it.first})"
}.joinToString(" && ")
"""if ($matchedParams) {
${backend.compileToString(overload.body)}
} """
}.joinToString("else ") + """else {
throw new Error("Overloaded default")
}
}"""
return result
}
}
|
gpl-2.0
|
37043a9e4fe7c669d51d74de9d88e20e
| 40.930233 | 187 | 0.673141 | 4.260047 | false | false | false | false |
mcruncher/worshipsongs-android
|
app/src/main/java/org/worshipsongs/domain/SongDragDrop.kt
|
1
|
1150
|
package org.worshipsongs.domain
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.apache.commons.lang3.StringUtils
import java.util.*
/**
* Author : Madasamy
* Version : 3.x.x
*/
class SongDragDrop : DragDrop
{
var tamilTitle: String? = null
constructor()
{
}
constructor(id: Long, title: String, checked: Boolean) : super(id, title, checked)
{
}
override fun toString(): String
{
return super.toString() + "SongDragDrop{" + "tamilTitle='" + tamilTitle + '\''.toString() + '}'.toString()
}
companion object
{
fun toJson(items: List<SongDragDrop>): String
{
val gson = Gson()
return gson.toJson(items)
}
fun toList(jsonString: String): List<SongDragDrop>
{
if (StringUtils.isNotBlank(jsonString))
{
val gson = Gson()
val type = object : TypeToken<ArrayList<SongDragDrop>>()
{
}.type
return gson.fromJson(jsonString, type)
}
return ArrayList()
}
}
}
|
gpl-3.0
|
7e1952dc8c5599f1320dd96a67e1f61f
| 21.115385 | 114 | 0.553043 | 4.423077 | false | false | false | false |
gradle/gradle
|
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/codegen/ApiExtensionsGenerator.kt
|
3
|
15650
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("ApiExtensionsGenerator")
package org.gradle.kotlin.dsl.codegen
import org.gradle.api.file.RelativePath
import org.gradle.api.internal.file.pattern.PatternMatcher
import org.gradle.kotlin.dsl.support.appendReproducibleNewLine
import org.gradle.kotlin.dsl.support.useToRun
import java.io.File
/**
* Generate source file with Kotlin extensions enhancing the given api for the Gradle Kotlin DSL.
*
* @param outputDirectory the directory where the generated sources will be written
* @param packageName the name of the package where the generated members will be added
* @param sourceFilesBaseName the base name for generated source files
* @param classPath the api classpath elements
* @param classPathDependencies the api classpath dependencies
* @param apiSpec the api include/exclude spec
* @param parameterNamesSupplier the api function parameter names
*
* @return the list of generated source files
*/
internal
fun generateKotlinDslApiExtensionsSourceTo(
outputDirectory: File,
packageName: String,
sourceFilesBaseName: String,
classPath: List<File>,
classPathDependencies: List<File>,
apiSpec: PatternMatcher,
parameterNamesSupplier: ParameterNamesSupplier
): List<File> =
apiTypeProviderFor(classPath, classPathDependencies, parameterNamesSupplier).use { api ->
val extensionsPerTarget =
kotlinDslApiExtensionsDeclarationsFor(api, apiSpec).groupedByTarget()
val sourceFiles =
ArrayList<File>(extensionsPerTarget.size)
val packageDir =
outputDirectory.resolve(packageName.replace('.', File.separatorChar))
fun sourceFile(name: String) =
packageDir.resolve(name).also { sourceFiles.add(it) }
packageDir.mkdirs()
for ((index, extensionsSubset) in extensionsPerTarget.values.withIndex()) {
writeExtensionsTo(
sourceFile("$sourceFilesBaseName$index.kt"),
packageName,
extensionsSubset
)
}
sourceFiles
}
private
fun Sequence<KotlinExtensionFunction>.groupedByTarget(): Map<ApiType, List<KotlinExtensionFunction>> =
groupBy { it.targetType }
private
fun writeExtensionsTo(outputFile: File, packageName: String, extensions: List<KotlinExtensionFunction>): Unit =
outputFile.bufferedWriter().useToRun {
write(fileHeaderFor(packageName))
write("\n")
extensions.forEach {
write("\n${it.toKotlinString()}")
}
}
private
fun kotlinDslApiExtensionsDeclarationsFor(
api: ApiTypeProvider,
apiSpec: PatternMatcher
): Sequence<KotlinExtensionFunction> =
api.allTypes()
.filter { type ->
val relativeSourcePath = relativeSourcePathOf(type)
type.isPublic && apiSpec.test(relativeSourcePath.segments, relativeSourcePath.isFile)
}
.flatMap { type -> kotlinExtensionFunctionsFor(type) }
.distinctBy(::signatureKey)
private
fun relativeSourcePathOf(type: ApiType) =
RelativePath.parse(true, type.sourceName.replace(".", File.separator))
private
fun signatureKey(extension: KotlinExtensionFunction): List<Any> = extension.run {
listOf(targetType.sourceName, name) +
parameters.flatMap { apiTypeKey(it.type) }
}
private
fun apiTypeKey(usage: ApiTypeUsage): List<Any> = usage.run {
listOf(sourceName, isNullable, isRaw, variance) +
typeArguments.flatMap(::apiTypeKey) +
bounds.flatMap(::apiTypeKey)
}
// TODO Policy for extensions with reified generics
//
// Goals
// - make the dsl predictable
// - prevent ambiguous overload situations
//
// Rules
// 1. an extension should either require no type parameters, a single reifeid type parameter, at call site
// 2. all type parameters must all be reifeid or values (TypeOf, KClass or Class)
// 3. when overloading, prefer TypeOf over Class
// 4. in case the policy forbids your overloads, discuss
private
fun kotlinExtensionFunctionsFor(type: ApiType): Sequence<KotlinExtensionFunction> =
candidatesForExtensionFrom(type)
.sortedWithTypeOfTakingFunctionsFirst()
.flatMap { function ->
val candidateFor = object {
val groovyNamedArgumentsToVarargs =
function.parameters.firstOrNull()?.type?.isGroovyNamedArgumentMap == true
val javaClassToKotlinClass =
function.parameters.any { it.type.hasJavaClass() }
val extension
get() = groovyNamedArgumentsToVarargs || javaClassToKotlinClass
}
if (!candidateFor.extension) {
return@flatMap emptySequence<KotlinExtensionFunction>()
}
val extensionTypeParameters = function.typeParameters + type.typeParameters
sequenceOf(
KotlinExtensionFunction(
description = "Kotlin extension function ${if (candidateFor.javaClassToKotlinClass) "taking [kotlin.reflect.KClass] " else ""}for [${type.sourceName}.${function.name}]",
isIncubating = function.isIncubating,
isDeprecated = function.isDeprecated,
typeParameters = extensionTypeParameters,
targetType = type,
name = function.name,
parameters = function.newMappedParameters().groovyNamedArgumentsToVarargs().javaClassToKotlinClass(),
returnType = function.returnType
)
)
}
private
fun ApiTypeUsage.hasJavaClass(): Boolean =
isJavaClass ||
isKotlinArray && typeArguments.single().isJavaClass ||
isKotlinCollection && typeArguments.single().isJavaClass
private
fun candidatesForExtensionFrom(type: ApiType) =
type.functions.filter(::isCandidateForExtension).asSequence()
private
fun Sequence<ApiFunction>.sortedWithTypeOfTakingFunctionsFirst() =
sortedBy { f ->
if (f.parameters.any { it.type.isGradleTypeOf }) 0
else 1
}
private
fun ApiFunction.newMappedParameters() =
parameters.map { MappedApiFunctionParameter(it) }
private
data class MappedApiFunctionParameter(
val original: ApiFunctionParameter,
val index: Int = original.index,
val type: ApiTypeUsage = original.type,
val isVarargs: Boolean = original.isVarargs,
val asArgument: String = "${if (original.isVarargs) "*" else ""}`${original.name ?: "p$index"}`"
) {
val name: String
get() = original.name ?: "p$index"
}
private
fun List<MappedApiFunctionParameter>.groovyNamedArgumentsToVarargs() =
firstOrNull()?.takeIf { it.type.isGroovyNamedArgumentMap }?.let { first ->
val mappedMapParameter = first.copy(
type = ApiTypeUsage(
sourceName = SourceNames.kotlinArray,
typeArguments = listOf(
ApiTypeUsage(
"Pair",
typeArguments = listOf(
ApiTypeUsage("String"),
ApiTypeUsage("Any", isNullable = true)
)
)
)
),
isVarargs = true,
asArgument = "mapOf(*${first.asArgument})"
)
if (last().type.isSAM) last().let { action -> drop(1).dropLast(1) + mappedMapParameter + action }
else drop(1) + mappedMapParameter
} ?: this
private
fun List<MappedApiFunctionParameter>.javaClassToKotlinClass() =
map { p ->
p.type.run {
when {
isJavaClass -> p.copy(
type = toKotlinClass(),
asArgument = "${p.asArgument}.java"
)
isKotlinArray && typeArguments.single().isJavaClass -> p.copy(
type = toArrayOfKotlinClasses(),
asArgument = "${p.asArgument}.map { it.java }.toTypedArray()"
)
isKotlinCollection && typeArguments.single().isJavaClass -> p.copy(
type = toCollectionOfKotlinClasses(),
asArgument = "${p.asArgument}.map { it.java }"
)
else -> p
}
}
}
private
data class KotlinExtensionFunction(
val description: String,
val isIncubating: Boolean,
val isDeprecated: Boolean,
val typeParameters: List<ApiTypeUsage>,
val targetType: ApiType,
val name: String,
val parameters: List<MappedApiFunctionParameter>,
val returnType: ApiTypeUsage
) {
fun toKotlinString(): String = StringBuilder().apply {
appendReproducibleNewLine(
"""
/**
* $description.
*
* @see ${targetType.sourceName}.$name
*/
""".trimIndent()
)
if (isDeprecated) appendReproducibleNewLine("""@Deprecated("Deprecated Gradle API")""")
if (isIncubating) appendReproducibleNewLine("@org.gradle.api.Incubating")
append("inline fun ")
if (typeParameters.isNotEmpty()) append("${typeParameters.joinInAngleBrackets { it.toTypeParameterString() }} ")
append(targetType.sourceName)
if (targetType.typeParameters.isNotEmpty()) append(targetType.typeParameters.toTypeArgumentsString(targetType))
append(".")
append("`$name`")
append("(")
append(parameters.toDeclarationString())
append("): ")
append(returnType.toTypeArgumentString())
appendReproducibleNewLine(" =")
appendReproducibleNewLine("`$name`(${parameters.toArgumentsString()})".prependIndent())
appendReproducibleNewLine()
}.toString()
private
fun List<MappedApiFunctionParameter>.toDeclarationString(): String =
takeIf { it.isNotEmpty() }?.let { list ->
list.mapIndexed { index, p ->
when {
index == list.lastIndex && p.isVarargs && p.type.isKotlinArray -> "vararg `${p.name}`: ${singleTypeArgumentStringOf(p)}"
index == list.size - 2 && list.last().type.isSAM && p.isVarargs && p.type.isKotlinArray -> "vararg `${p.name}`: ${singleTypeArgumentStringOf(p)}"
else -> "`${p.name}`: ${p.type.toTypeArgumentString()}"
}
}.joinToString(separator = ", ")
} ?: ""
private
fun singleTypeArgumentStringOf(p: MappedApiFunctionParameter) =
p.type.typeArguments.single().toTypeArgumentString()
private
fun List<MappedApiFunctionParameter>.toArgumentsString(): String =
takeIf { it.isNotEmpty() }
?.sortedBy { it.original.index }
?.joinToString(separator = ", ") { it.asArgument }
?: ""
}
private
fun ApiTypeUsage.toKotlinClass() =
ApiTypeUsage(
SourceNames.kotlinClass,
isNullable,
typeArguments = singleTypeArgumentRawToStarProjection()
)
private
fun ApiTypeUsage.toArrayOfKotlinClasses() =
ApiTypeUsage(
SourceNames.kotlinArray,
isNullable,
typeArguments = listOf(ApiTypeUsage(SourceNames.kotlinClass, typeArguments = typeArguments.single().singleTypeArgumentRawToStarProjection()))
)
private
fun ApiTypeUsage.toCollectionOfKotlinClasses() =
ApiTypeUsage(
SourceNames.kotlinCollection,
isNullable,
typeArguments = listOf(ApiTypeUsage(SourceNames.kotlinClass, typeArguments = typeArguments.single().singleTypeArgumentRawToStarProjection()))
)
private
fun ApiTypeUsage.singleTypeArgumentRawToStarProjection() =
if (isRaw) singletonListOfStarProjectionTypeUsage
else typeArguments.also { it.single() }
private
fun Boolean.toKotlinNullabilityString(): String =
if (this) "?" else ""
private
fun ApiTypeUsage.toTypeParameterString(): String =
"$sourceName${
bounds.takeIf { it.isNotEmpty() }?.let { " : ${it.single().toTypeParameterString()}" } ?: ""
}${typeArguments.toTypeParametersString(type)}${isNullable.toKotlinNullabilityString()}"
private
fun List<ApiTypeUsage>.toTypeParametersString(type: ApiType? = null): String =
rawTypesToStarProjections(type).joinInAngleBrackets { it.toTypeParameterString() }
private
fun ApiTypeUsage.toTypeArgumentString(): String =
"${variance.toKotlinString()}$sourceName${typeArguments.toTypeArgumentsString(type)}${isNullable.toKotlinNullabilityString()}"
private
fun Variance.toKotlinString() =
when (this) {
Variance.INVARIANT -> ""
Variance.COVARIANT -> "out "
Variance.CONTRAVARIANT -> "in "
}
private
fun List<ApiTypeUsage>.toTypeArgumentsString(type: ApiType? = null): String =
rawTypesToStarProjections(type).joinInAngleBrackets { it.toTypeArgumentString() }
private
fun List<ApiTypeUsage>.rawTypesToStarProjections(type: ApiType? = null): List<ApiTypeUsage> =
when {
isNotEmpty() -> this
type?.typeParameters?.isNotEmpty() == true -> List(type.typeParameters.size) { starProjectionTypeUsage }
else -> emptyList()
}
private
fun <T> List<T>?.joinInAngleBrackets(transform: (T) -> CharSequence = { it.toString() }) =
this?.takeIf { it.isNotEmpty() }
?.joinToString(separator = ", ", prefix = "<", postfix = ">", transform = transform)
?: ""
private
val ApiTypeUsage.isGroovyNamedArgumentMap
get() = isMap && (
typeArguments.all { it.isAny }
|| typeArguments.all { it.isStarProjectionTypeUsage }
|| (typeArguments[0].isString && (typeArguments[1].isStarProjectionTypeUsage || typeArguments[1].isAny))
)
private
object SourceNames {
const val javaClass = "java.lang.Class"
const val groovyClosure = "groovy.lang.Closure"
const val gradleAction = "org.gradle.api.Action"
const val gradleTypeOf = "org.gradle.api.reflect.TypeOf"
const val kotlinClass = "kotlin.reflect.KClass"
const val kotlinArray = "kotlin.Array"
const val kotlinCollection = "kotlin.collections.Collection"
}
private
val ApiTypeUsage.isSAM
get() = type?.isSAM == true
private
val ApiTypeUsage.isAny
get() = sourceName == "Any"
private
val ApiTypeUsage.isString
get() = sourceName == "String"
private
val ApiTypeUsage.isMap
get() = sourceName == "kotlin.collections.Map"
private
val ApiTypeUsage.isJavaClass
get() = sourceName == SourceNames.javaClass
private
val ApiTypeUsage.isGroovyClosure
get() = sourceName == SourceNames.groovyClosure
private
val ApiTypeUsage.isGradleTypeOf
get() = sourceName == SourceNames.gradleTypeOf
private
val ApiTypeUsage.isKotlinArray
get() = sourceName == SourceNames.kotlinArray
private
val ApiTypeUsage.isKotlinCollection
get() = sourceName == SourceNames.kotlinCollection
private
fun isCandidateForExtension(function: ApiFunction): Boolean = function.run {
name !in functionNameBlackList &&
isPublic &&
!isStatic &&
parameters.none { it.type.isGroovyClosure }
}
private
val functionNameBlackList = listOf("<init>")
|
apache-2.0
|
fa45bb8587bbd2eec87a485cdecf5545
| 30.808943 | 189 | 0.659744 | 4.673037 | false | false | false | false |
khanhpq29/My-Task
|
app/src/main/java/ht/pq/khanh/task/sleepawake/AwakeFragment.kt
|
1
|
3374
|
package ht.pq.khanh.task.sleepawake
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.SwitchCompat
import android.text.format.DateFormat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import android.widget.TextView
import android.widget.TimePicker
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import ht.pq.khanh.extension.inflateLayout
import ht.pq.khanh.extension.showToast
import ht.pq.khanh.multitask.R
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by khanh on 15/10/2017.
*/
class AwakeFragment : Fragment(), TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
@BindView(R.id.tv_awake_day)
lateinit var tvAwakeDay: TextView
@BindView(R.id.tv_awake_hour)
lateinit var tvAwakeHour: TextView
@BindView(R.id.switch_awake)
lateinit var switchAwake: SwitchCompat
private val DATE_FORMAT = "MMM, dd yyyy"
private val TIME_FORMAT = "hh:mm a"
private val simpleDateFormat by lazy { SimpleDateFormat(DATE_FORMAT) }
private val simpleTimeFormat by lazy { SimpleDateFormat(TIME_FORMAT) }
private val timeReminder: Calendar by lazy { Calendar.getInstance() }
private val dateReminder: Calendar by lazy { Calendar.getInstance() }
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = container!!.inflateLayout(R.layout.fragment_awake)
ButterKnife.bind(this, view)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
switchAwake.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked){
activity.showToast("on")
}else {
activity.showToast("off")
}
}
}
@OnClick(R.id.tv_awake_hour)
fun changeAwakeHour() {
val calendar = Calendar.getInstance()
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val timePicker = TimePickerDialog(activity, this, hour, minute, DateFormat.is24HourFormat(activity))
timePicker.show()
}
@OnClick(R.id.btnAwakeDay)
fun addAwakeDay() {
val calendar = Calendar.getInstance()
val day = calendar.get(Calendar.DAY_OF_MONTH)
val month = calendar.get(Calendar.MONTH)
val year = calendar.get(Calendar.YEAR)
val datePicker = DatePickerDialog(context, this, year, month, day)
datePicker.show()
}
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
timeReminder.set(Calendar.HOUR_OF_DAY, hourOfDay)
timeReminder.set(Calendar.MINUTE, minute)
tvAwakeHour.text = simpleTimeFormat.format(timeReminder.timeInMillis)
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
dateReminder.set(Calendar.YEAR, year)
dateReminder.set(Calendar.MONTH, month)
dateReminder.set(Calendar.DAY_OF_MONTH, dayOfMonth)
tvAwakeDay.text = simpleDateFormat.format(dateReminder.timeInMillis)
}
}
|
apache-2.0
|
7c087f0c0392613c2ed600124b50620d
| 38.244186 | 117 | 0.71636 | 4.281726 | false | false | false | false |
coil-kt/coil
|
coil-base/src/main/java/coil/fetch/AssetUriFetcher.kt
|
1
|
1179
|
package coil.fetch
import android.net.Uri
import android.webkit.MimeTypeMap
import coil.ImageLoader
import coil.decode.AssetMetadata
import coil.decode.DataSource
import coil.decode.ImageSource
import coil.request.Options
import coil.util.getMimeTypeFromUrl
import coil.util.isAssetUri
import okio.buffer
import okio.source
internal class AssetUriFetcher(
private val data: Uri,
private val options: Options
) : Fetcher {
override suspend fun fetch(): FetchResult {
val path = data.pathSegments.drop(1).joinToString("/")
return SourceResult(
source = ImageSource(
source = options.context.assets.open(path).source().buffer(),
context = options.context,
metadata = AssetMetadata(path)
),
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromUrl(path),
dataSource = DataSource.DISK
)
}
class Factory : Fetcher.Factory<Uri> {
override fun create(data: Uri, options: Options, imageLoader: ImageLoader): Fetcher? {
if (!isAssetUri(data)) return null
return AssetUriFetcher(data, options)
}
}
}
|
apache-2.0
|
c68d0122938f2da6857c3006f0f6f6d8
| 27.756098 | 94 | 0.668363 | 4.716 | false | false | false | false |
XiaoQiWen/KRefreshLayout
|
app_kotlin/src/main/kotlin/gorden/krefreshlayout/demo/widget/recyclerview/KRecyclerView.kt
|
1
|
8709
|
package gorden.krefreshlayout.demo.widget.recyclerview
import android.content.Context
import android.support.v4.util.SparseArrayCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
@Suppress("unused")
/**
* 支持添加Header Footer
* 支持加载更多
*/
class KRecyclerView(context: Context, attrs: AttributeSet?, defStyle: Int) : RecyclerView(context, attrs, defStyle) {
private val ITEM_TYPE_HEADER_INIT = 100000
private val ITEM_TYPE_FOOTER_INIT = 200000
private val ITEM_TYPE_LOADMORE = 300000
var hasMore: Boolean = false
set(value) {
field = value
if (value) showMore = true
}
var showMore:Boolean = false
private var mLoading: Boolean = false
var loadMoreEnable: Boolean = true
private var mWrapAdapter: WrapAdapter = WrapAdapter()
private var mInnerAdapter: Adapter<ViewHolder>? = null
private var mLoadMoreView: KLoadMoreView? = null
private val mHeaderViews = SparseArrayCompat<View>()
private val mFooterViews = SparseArrayCompat<View>()
private var mLoadMoreListener: ((RecyclerView) -> Unit)? = null
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
override fun setAdapter(adapter: Adapter<ViewHolder>?) {
if (mInnerAdapter!=null){
mInnerAdapter?.unregisterAdapterDataObserver(mDataObserver)
}
mInnerAdapter = adapter
mInnerAdapter?.registerAdapterDataObserver(mDataObserver)
super.setAdapter(mWrapAdapter)
}
/**
* 添加HeaderView
*/
fun addHeaderView(view: View) {
mHeaderViews.put(mHeaderViews.size() + ITEM_TYPE_HEADER_INIT, view)
mWrapAdapter.notifyDataSetChanged()
}
/**
* 添加FooterView
*/
fun addFooterView(view: View) {
mFooterViews.put(mFooterViews.size() + ITEM_TYPE_FOOTER_INIT, view)
mWrapAdapter.notifyDataSetChanged()
}
/**
* 设置LoadMoreView
* 必须是一个视图View
*/
fun setLoadMoreView(loadMoreView: KLoadMoreView) {
if (loadMoreView !is View) {
throw IllegalStateException("KLoadMoreView must is a View?")
}
this.mLoadMoreView = loadMoreView
mWrapAdapter.notifyDataSetChanged()
removeOnScrollListener(defaultScrollListener)
if (!(mLoadMoreView?.shouldLoadMore(this) ?: true)) {
addOnScrollListener(defaultScrollListener)
}
}
/**
* 开始加载更多
*/
fun startLoadMore() {
if (!mLoading && loadMoreEnable && hasMore) {
mLoading = true
mLoadMoreView?.onLoadMore(this)
mLoadMoreListener?.invoke(this)
}
}
/**
* 加载完成
*/
fun loadMoreComplete(hasMore: Boolean) {
mLoading = false
mLoadMoreView?.onComplete(this, hasMore)
this.hasMore = hasMore
}
fun loadMoreError(errorCode: Int) {
mLoading = false
mLoadMoreView?.onError(this, errorCode)
}
/**
* 设置加载更多监听
*/
fun setLoadMoreListener(loadMoreListener: (recyclerView: RecyclerView) -> Unit): Unit {
mLoadMoreListener = loadMoreListener
}
/**
* 默认的加载触发时机
*/
private val defaultScrollListener = object : OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (!recyclerView.canScrollVertically(1)) {
startLoadMore()
}
}
}
private inner class WrapAdapter : Adapter<ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (!isContent(position)) {
return
}
mInnerAdapter?.onBindViewHolder(holder, position - mHeaderViews.size())
}
override fun getItemCount(): Int {
val adapterCount = mInnerAdapter?.itemCount ?: 0
if (adapterCount > 0) {
return adapterCount + mHeaderViews.size() + mFooterViews.size() + if (mLoadMoreView == null||!showMore) 0 else 1
} else {//防止没有内容的时候加载更多显示出来
return mHeaderViews.size() + mFooterViews.size()
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder? {
if (mHeaderViews[viewType] != null) {
return object : ViewHolder(mHeaderViews[viewType]) {
init {
itemView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
}
}
}
if (viewType == ITEM_TYPE_LOADMORE)
return object : ViewHolder(mLoadMoreView as View) {
init {
itemView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
}
}
if (mFooterViews[viewType] != null) {
return object : ViewHolder(mFooterViews[viewType]) {
init {
itemView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
}
}
}
return mInnerAdapter?.onCreateViewHolder(parent, viewType)
}
override fun getItemViewType(position: Int): Int {
if (position < mHeaderViews.size()) {
return mHeaderViews.keyAt(position)
}
if (mLoadMoreView != null && position == itemCount - 1&&showMore) {
return ITEM_TYPE_LOADMORE
}
if (position >= mHeaderViews.size() + (mInnerAdapter?.itemCount ?: 0)) {
return mFooterViews.keyAt(position - mHeaderViews.size() - (mInnerAdapter?.itemCount ?: 0))
}
return mInnerAdapter?.getItemViewType(position - mHeaderViews.size()) ?: -1
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView?) {
mInnerAdapter?.onAttachedToRecyclerView(recyclerView)
val layoutManager = layoutManager
if (layoutManager is GridLayoutManager) {
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
if (!isContent(position)) {
return layoutManager.spanCount
}
return 1
}
}
}
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
mInnerAdapter?.onViewAttachedToWindow(holder)
val position = holder.layoutPosition
val layoutParams = holder.itemView.layoutParams
if (!isContent(position) && layoutParams != null && layoutParams is StaggeredGridLayoutManager.LayoutParams) {
layoutParams.isFullSpan = true
}
}
fun isContent(position: Int): Boolean {
if (position < mHeaderViews.size())
return false
if (mLoadMoreView != null && position == itemCount - 1)
return false
if (position >= mHeaderViews.size() + (mInnerAdapter?.itemCount ?: 0))
return false
return true
}
}
private val mDataObserver = object : AdapterDataObserver() {
override fun onChanged() {
mWrapAdapter.notifyDataSetChanged()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
mWrapAdapter.notifyItemRangeChanged(positionStart, itemCount)
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
mWrapAdapter.notifyItemRangeChanged(positionStart, itemCount, payload)
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
mWrapAdapter.notifyItemRangeInserted(positionStart, itemCount)
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
mWrapAdapter.notifyItemMoved(fromPosition, toPosition)
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
mWrapAdapter.notifyItemRangeRemoved(positionStart, itemCount)
}
}
}
|
apache-2.0
|
e3bc8e7839fde07bbf776e57f8781437
| 33.304 | 128 | 0.605831 | 5.070964 | false | false | false | false |
MaibornWolff/codecharta
|
analysis/filter/MergeFilter/src/main/kotlin/de/maibornwolff/codecharta/filter/mergefilter/ProjectMerger.kt
|
1
|
3826
|
package de.maibornwolff.codecharta.filter.mergefilter
import de.maibornwolff.codecharta.model.AttributeDescriptor
import de.maibornwolff.codecharta.model.AttributeType
import de.maibornwolff.codecharta.model.BlacklistItem
import de.maibornwolff.codecharta.model.Edge
import de.maibornwolff.codecharta.model.MutableNode
import de.maibornwolff.codecharta.model.Project
import de.maibornwolff.codecharta.model.ProjectBuilder
import mu.KotlinLogging
class ProjectMerger(private val projects: List<Project>, private val nodeMerger: NodeMergerStrategy) {
private val logger = KotlinLogging.logger { }
fun merge(): Project {
return when {
areAllAPIVersionsCompatible() -> ProjectBuilder(
mergeProjectNodes(),
mergeEdges(),
mergeAttributeTypes(),
mergeAttributeDescriptors(),
mergeBlacklist()
).build()
else -> throw MergeException("API versions not supported.")
}
}
private fun areAllAPIVersionsCompatible(): Boolean {
val unsupportedAPIVersions = projects
.map { it.apiVersion }
.filter { !Project.isAPIVersionCompatible(it) }
return unsupportedAPIVersions.isEmpty()
}
private fun mergeProjectNodes(): List<MutableNode> {
val mergedNodes = nodeMerger.mergeNodeLists(projects.map { listOf(it.rootNode.toMutableNode()) })
nodeMerger.logMergeStats()
return mergedNodes
}
private fun mergeEdges(): MutableList<Edge> {
return if (nodeMerger.javaClass.simpleName == "RecursiveNodeMergerStrategy") {
getMergedEdges()
} else {
getEdgesOfMainAndWarnIfDiscards()
}
}
private fun getEdgesOfMainAndWarnIfDiscards(): MutableList<Edge> {
projects.forEachIndexed { i, project ->
if (project.edges.isNotEmpty() && i > 0) logger.warn("Edges were not merged. Use recursive strategy to merge edges.")
}
return projects.first().edges.toMutableList()
}
private fun getMergedEdges(): MutableList<Edge> {
val mergedEdges = mutableListOf<Edge>()
projects.forEach { it.edges.forEach { mergedEdges.add(it) } }
return mergedEdges.distinctBy { listOf(it.fromNodeName, it.toNodeName) }.toMutableList()
}
private fun mergeAttributeTypes(): MutableMap<String, MutableMap<String, AttributeType>> {
val mergedAttributeTypes: MutableMap<String, MutableMap<String, AttributeType>> = mutableMapOf()
projects.forEach {
it.attributeTypes.forEach { attributeTypes ->
val key: String = attributeTypes.key
if (mergedAttributeTypes.containsKey(key)) {
attributeTypes.value.forEach { attribute ->
if (!mergedAttributeTypes[key]!!.containsKey(attribute.key)) {
mergedAttributeTypes[key]!![attribute.key] = attribute.value
}
}
} else {
mergedAttributeTypes[key] = attributeTypes.value
}
}
}
return mergedAttributeTypes
}
private fun mergeAttributeDescriptors(): MutableMap<String, AttributeDescriptor> {
val mergedAttributeDescriptors: MutableMap<String, AttributeDescriptor> = mutableMapOf()
projects.forEach { mergedAttributeDescriptors.putAll(it.attributeDescriptors) }
return mergedAttributeDescriptors
}
private fun mergeBlacklist(): MutableList<BlacklistItem> {
val mergedBlacklist = mutableListOf<BlacklistItem>()
projects.forEach { project -> project.blacklist.forEach { mergedBlacklist.add(it) } }
return mergedBlacklist.distinctBy { it.toString() }.toMutableList()
}
}
|
bsd-3-clause
|
f387d591664f24d67e6cc0b787823566
| 39.273684 | 129 | 0.658129 | 5.149394 | false | false | false | false |
tronalddump-io/tronald-app
|
src/main/kotlin/io/tronalddump/app/slack/AccessToken.kt
|
1
|
584
|
package io.tronalddump.app.slack
import com.fasterxml.jackson.annotation.JsonProperty
import java.io.Serializable
class AccessToken(
@JsonProperty("access_token")
val accessToken: String? = null,
@JsonProperty("scope")
val scope: String? = null,
@JsonProperty("team_id")
val teamId: String? = null,
@JsonProperty("team_name")
val teamName: String? = null,
@JsonProperty("user_id")
val userId: String? = null,
@JsonProperty("user_name")
val userName: String? = null
) : Serializable
|
gpl-3.0
|
7013bd02a69fb41202b6fd5e82898ff3
| 23.375 | 52 | 0.625 | 4.325926 | false | false | false | false |
jlutteringer/Alloy
|
alloy/utilities/src/main/java/alloy/utilities/entity/Entities.kt
|
1
|
6547
|
package alloy.utilities.entity
import alloy.utilities.core._Functions
import alloy.utilities.core._Reflection
import alloy.utilities.core.toOptional
import alloy.utilities.core.toSet
import java.math.BigDecimal
import java.time.Instant
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.KType
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.jvmErasure
/**
* Created by jlutteringer on 1/17/18.
*/
data class Entity(
val id: String,
val name: String,
val fields : Set<EntityField>,
val metadata: Map<String, Any> = mapOf()): ConcreteType {
fun getField(name : String) : EntityField {
return requireNotNull(fields.find { it.name == name }, { "Couldn't find field by name: $name" })
}
}
data class EntityField(
val name: String,
val type: EntityType,
val metadata: Map<String, Any> = mapOf()) {
}
interface EntityType
interface ConcreteType: EntityType
data class SimpleType(val name: String): ConcreteType
data class ParameterizedType(val root: ConcreteType, val typeParameters: List<EntityType>): EntityType
typealias TypeResolver = (KType) -> Optional<EntityType>
typealias TypeAlias = (EntityType) -> EntityType
data class EntityReaderConfiguration(val typeAlias: TypeAlias = _Functions::identity)
class EntityReader(val configuration: EntityReaderConfiguration = Entities.DEFAULT_ENTITY_READER_CONFIGURATION) {
val typeResolvers: MutableList<TypeResolver> = mutableListOf()
init {
typeResolvers.add(this.buildPrimitiveTypeResolver())
typeResolvers.add(this.buildObjectTypeResolver())
}
fun describe(type: Class<*>) = describe(type.kotlin)
fun describe(type: KClass<*>): Entity {
val id = type.qualifiedName!!
val name = type.simpleName!!
val fields = type.memberProperties.stream().map { this.mapProperty(it) }.toSet()
return Entity(id, name, fields)
}
fun mapProperty(property: KProperty1<*, *>): EntityField {
val name = property.name
val type = this.mapType(property.returnType)
return EntityField(name, type)
}
fun mapType(type: KType): EntityType {
val result = typeResolvers.stream()
.map { it.invoke(type) }
.filter { it.isPresent }
.map { it.get() }
.findFirst()
if(!result.isPresent) {
throw RuntimeException()
}
return configuration.typeAlias.invoke(result.get())
}
internal fun buildPrimitiveTypeResolver(): TypeResolver {
val typeResolverMap: Map<KClass<*>, (KType) -> EntityType> = mapOf(
Any::class to { _ -> EntityTypes.Any },
String::class to { _ -> EntityTypes.String },
Long::class to { _ -> EntityTypes.Long },
BigDecimal::class to { _ -> EntityTypes.Decimal },
Instant::class to { _ -> EntityTypes.Instant },
Double::class to { _ -> EntityTypes.Double },
Map::class to { type ->
if (type.arguments.isEmpty()) {
EntityTypes.Map
}
else {
EntityTypes.Map(keyType = this.mapType(type.arguments[0].type!!), valueType = this.mapType(type.arguments[1].type!!))
}
},
List::class to { type ->
if (type.arguments.isEmpty()) {
EntityTypes.List
}
else {
EntityTypes.List(type = this.mapType(type.arguments[0].type!!))
}
},
Set::class to { type ->
if (type.arguments.isEmpty()) {
EntityTypes.Set
}
else {
EntityTypes.Set(type = this.mapType(type.arguments[0].type!!))
}
}
)
val topLevelTypes = typeResolverMap.keys
return typeResolver@{ type ->
if(type.jvmErasure == Any::class) {
return@typeResolver typeResolverMap[Any::class]!!.invoke(type).toOptional()
}
val matchingType = _Reflection.findMatchingTopLevelType(type.jvmErasure, topLevelTypes)
if(matchingType != Any::class) {
return@typeResolver typeResolverMap[matchingType]!!.invoke(type).toOptional()
}
Optional.empty()
}
}
internal fun buildObjectTypeResolver(): TypeResolver = { type -> Optional.of(this.describe(type.jvmErasure)) }
}
object Entities {
val DEFAULT_ENTITY_READER_CONFIGURATION = EntityReaderConfiguration()
val SIMPLE_TYPE_ALIAS = aliasTypes(mapOf(
EntityTypes.Long to EntityTypes.Number,
EntityTypes.Decimal to EntityTypes.Number,
EntityTypes.Double to EntityTypes.Number,
EntityTypes.Instant to EntityTypes.Date,
EntityTypes.Set to EntityTypes.List
))
val DEFAULT_ENTITY_READER = EntityReader()
val SIMPLE_ENTITY_READER = EntityReader(configuration = EntityReaderConfiguration(SIMPLE_TYPE_ALIAS))
fun aliasTypes(map: Map<ConcreteType, ConcreteType>): TypeAlias {
val typeAlias: TypeAlias = { type ->
if(type is ConcreteType && map.containsKey(type)) {
map[type]!!
}
else if(type is ParameterizedType && map.containsKey(type.root)) {
val conversionType = map[type.root]!!
type.copy(root = conversionType)
}
else {
type
}
}
return typeAlias
}
}
object EntityTypes {
val Any = SimpleType("Any")
val String = SimpleType("String")
val Number = SimpleType("Number")
val Long = SimpleType("Long")
val Decimal = SimpleType("Decimal")
val Date = SimpleType("Date")
val Instant = SimpleType("Instant")
val Double = SimpleType("Double")
val Map = SimpleType("Map")
val List = SimpleType("List")
val Set = SimpleType("Set")
fun Map(keyType: EntityType, valueType: EntityType): EntityType = ParameterizedType(EntityTypes.Map, listOf(keyType, valueType))
fun List(type: EntityType): EntityType = ParameterizedType(EntityTypes.List, listOf(type))
fun Set(type: EntityType): EntityType = ParameterizedType(EntityTypes.Set, listOf(type))
}
|
mit
|
fcc1d7c7be3e6e47dc2e2408334320d7
| 33.282723 | 141 | 0.60165 | 4.72026 | false | false | false | false |
christophpickl/kpotpourri
|
common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/file/file.kt
|
1
|
5833
|
package com.github.christophpickl.kpotpourri.common.file
import com.github.christophpickl.kpotpourri.common.KPotpourriException
import mu.KotlinLogging.logger
import java.io.File
import java.nio.file.Files
private val log = logger {}
/**
* Data structure containing the filename and the suffix (without leading dot).
*/
data class FileName(
val name: String,
val suffix: String?
) {
companion object {
/**
* Factory method.
*/
fun by(fullName: String): FileName {
if (!fullName.contains(".")) {
return withoutSuffix(fullName)
}
if (fullName.startsWith(".")) {
val secondLastDot = fullName.removePrefix(".").lastIndexOf(".")
if (secondLastDot == -1) {
return withoutSuffix(fullName)
}
return extract(fullName, secondLastDot + 1)
}
if (fullName.endsWith(".")) {
val secondLastDot = fullName.removeSuffix(".").lastIndexOf(".")
if (secondLastDot == -1) {
return withoutSuffix(fullName)
}
return FileName(fullName.substring(0, secondLastDot + 1), fullName.substring(secondLastDot + 1))
}
return extract(fullName, fullName.lastIndexOf("."))
}
private fun extract(fullName: String, lastDot: Int) =
if (lastDot == fullName.length - 1) {
withoutSuffix(fullName)
} else {
FileName(fullName.substring(0, lastDot), fullName.substring(lastDot + 1))
}
private fun withoutSuffix(fullName: String) = FileName(fullName, null)
}
}
/**
* Create a temporary file which deletes itself when the JVM exits.
*/
fun tempFile(name: String): File {
val fileName = FileName.by(name)
val temp = File.createTempFile(fileName.name, fileName.suffix?.let { ".$it" })
temp.deleteOnExit()
return temp
}
/**
* Checks if the File exists or throws a [KPotpourriException].
*
* Formerly known as `ensureExists()`.
*/
fun File.verifyExists() = this.apply {
if (!exists()) {
throw KPotpourriException("Expected a file existing at: $absolutePath")
}
}
/**
* Checks if it's actually a file and not a directory or throws a [KPotpourriException].
*/
fun File.verifyIsFile() = this.apply {
if (!isFile) {
throw KPotpourriException("Expected to be a file: $canonicalPath")
}
}
/**
* Checks if it's an existing file and not a directory or throws a [KPotpourriException].
*/
fun File.verifyExistsAndIsFile() = this.apply {
verifyExists()
verifyIsFile()
}
/**
* Cuts off the starting part, e.g.: "/top/sub/file.txt".nameStartingFrom("/top") => "/sub/file.txt"
*/
fun File.nameStartingFrom(other: File) =
this.canonicalPath.substring(other.canonicalPath.length)
/**
* Move a file by using JDK7's [Files] class.
*/
fun File.move(target: File) {
log.debug { "move() ... from ${this.absolutePath} to ${target.absolutePath}" }
Files.move(this.toPath(), target.toPath())
}
/**
* Create file if not existing and all of its directory structure.
*/
fun File.touch() {
parentFile.mkdirs()
createNewFile()
}
/**
* Delete the directory recursively and recreate the directory structure.
*/
fun File.resetDirectory(): File {
log.debug { "Delete and recreate directory: $canonicalPath" }
if (exists() && !isDirectory) {
throw KPotpourriException("Expected to be a directory: $canonicalPath")
}
if (exists() && !deleteRecursively()) {
throw KPotpourriException("Could not delete directory: $canonicalPath")
}
mkdirsIfNecessary()
return this
}
/**
* Creates all directories if not yet existing.
*/
fun File.mkdirsIfNecessary(): File {
if (!exists()) {
if (mkdirs()) {
log.debug { "Created directory: $canonicalPath" }
} else {
throw KPotpourriException("Failed to created directory at: $canonicalPath")
}
} else if (!isDirectory) {
throw KPotpourriException("Directory must be a directory at: $canonicalPath")
} else {
log.debug { "Directory already exists at: $canonicalPath" }
}
return this
}
/**
* List all contained files and returns only if suffix matches, ignoring folders by name optionally.
*/
fun File.scanForFilesRecursively(
suffix: String,
ignoreFolders: List<String> = emptyList()
): List<File> {
if (!exists() || !isDirectory) {
throw KPotpourriException("Invalid folder: $canonicalPath")
}
val foundFiles = mutableListOf<File>()
listFiles { _ -> true }.forEach { file ->
if (file.isDirectory && !ignoreFolders.contains(file.name)) {
foundFiles.addAll(file.scanForFilesRecursively(suffix, ignoreFolders))
} else if (file.isFile && file.name.endsWith(".$suffix", ignoreCase = true)) {
log.trace { "Found proper file while scanning: ${file.canonicalPath}" }
foundFiles += file
}
}
return foundFiles
}
/**
* Format given byte count into a proper readable format like "256 KB" or "12 MB".
*/
fun toHumanReadable(bytes: Long): String {
val kilo = bytes / 1024
if (kilo < 1024) {
return "$kilo KB"
}
val mega = kilo / 1024
if (mega < 1024) {
return "$mega MB"
}
val giga = mega / 1024
return "$giga GB"
}
/**
* See toHumanReadable(bytes: Long)
*/
fun toHumanReadable(bytes: Int) = toHumanReadable(bytes.toLong())
/**
* See toHumanReadable(bytes: Long)
*/
val File.humanReadableSize: String get() = toHumanReadable(length())
/**
* See toHumanReadable(bytes: Long)
*/
val ByteArray.humanReadableSize: String get() = toHumanReadable(size)
|
apache-2.0
|
dc66b02fceb518212d8487bec0f13054
| 28.165 | 112 | 0.620093 | 4.199424 | false | false | false | false |
oukingtim/king-admin
|
king-admin-kotlin/src/main/kotlin/com/oukingtim/util/StringTools.kt
|
1
|
2678
|
package com.oukingtim.util
/**
* Created by oukingtim
*/
object StringTools {
/**
* 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。
* 例如:HelloWorld->HELLO_WORLD
* @param name 转换前的驼峰式命名的字符串
* *
* @return 转换后下划线大写方式命名的字符串
*/
fun underscoreName(name: String?): String {
val result = StringBuilder()
if (name != null && name.length > 0) {
// 将第一个字符处理成大写
result.append(name.substring(0, 1).toUpperCase())
// 循环处理其余字符
for (i in 1..name.length - 1) {
val s = name.substring(i, i + 1)
// 在大写字母前添加下划线
if (s == s.toUpperCase() && !Character.isDigit(s[0])) {
result.append("_")
}
// 其他字符直接转成大写
result.append(s.toUpperCase())
}
}
return result.toString()
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。
* 例如:HELLO_WORLD->HelloWorld
* @param name 转换前的下划线大写方式命名的字符串
* *
* @return 转换后的驼峰式命名的字符串
*/
fun camelName(name: String?): String {
val result = StringBuilder()
// 快速检查
if (name == null || name.isEmpty()) {
// 没必要转换
return ""
} else if (!name.contains("_")) {
// 不含下划线,仅将首字母小写
return name.substring(0, 1).toLowerCase() + name.substring(1)
}
// 用下划线将原始字符串分割
val camels = name.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (camel in camels) {
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty()) {
continue
}
// 处理真正的驼峰片段
if (result.length == 0) {
// 第一个驼峰片段,全部字母都小写
result.append(camel.toLowerCase())
} else {
// 其他的驼峰片段,首字母大写
result.append(camel.substring(0, 1).toUpperCase())
result.append(camel.substring(1).toLowerCase())
}
}
return result.toString()
}
}
|
mit
|
57560d59fa1eb2ee6aa31830bd9ac326
| 28.785714 | 92 | 0.497121 | 3.216049 | false | false | false | false |
jghoman/workshop-jb
|
src/i_introduction/_4_String_Templates/StringTemplates.kt
|
6
|
1278
|
package i_introduction._4_String_Templates
import java.util.regex.Pattern
import util.TODO
fun example1(a: Any, b: Any) =
"There is a text in which some variables ($a, $b) appear."
fun example2(a: Any, b: Any) =
"You can write it in a Java way as well. Like this: " + a + ", " + b + "!"
fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}"
fun example4() =
"""
You can use triple-quoted strings to write multiline text.
There is no escaping here, so it can be useful for writing patterns as well.
String template entries (${42}) are allowed here.
"""
fun getPatternInAUsualString() = "(\\w)* (\\w)* \\((\\d{2})\\.(\\d{2})\\.(\\d{4})\\)"
fun getPatternInTQString() = """(\w*) (\w*) \((\d{2})\.(\d{2})\.(\d{4})\)"""
fun example() = Pattern.compile(getPatternInTQString()).matcher("Douglas Adams (11.03.1952)").find()
val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"
fun todoTask4() = TODO(
"""
Task 4.
Copy the body of 'getPatternInTQString()' to 'task4()' function
and rewrite it in such a way that it matches 'Douglas Adams (11 MAR 1952)'.
Use the 'month' variable.
""",
references = { getPatternInTQString(); month })
fun task4(): String = todoTask4()
|
mit
|
537dbf69b55355e1227f921b446d2f23
| 32.631579 | 100 | 0.621283 | 3.086957 | false | false | false | false |
yongce/DevTools
|
app/src/main/java/me/ycdev/android/devtools/device/BluetoothViewerActivity.kt
|
1
|
5827
|
package me.ycdev.android.devtools.device
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import me.ycdev.android.arch.activity.AppCompatBaseActivity
import me.ycdev.android.devtools.databinding.ActBluetoothViewerBinding
import me.ycdev.android.lib.common.wrapper.BroadcastHelper.registerForExternal
import me.ycdev.android.lib.common.wrapper.IntentHelper.getIntExtra
import me.ycdev.android.lib.common.wrapper.IntentHelper.getStringExtra
import timber.log.Timber
class BluetoothViewerActivity : AppCompatBaseActivity(), OnClickListener {
private lateinit var binding: ActBluetoothViewerBinding
private var logContents = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActBluetoothViewerBinding.inflate(layoutInflater)
setContentView(binding.root)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
initViews()
registerBluetoothReceiver()
}
private fun initViews() {
appendNewLog("Cur state: " + getStateString(bluetoothState))
binding.enable.setOnClickListener(this)
binding.disable.setOnClickListener(this)
}
override fun onDestroy() {
super.onDestroy()
unregisterBluetoothReceiver()
}
private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (BluetoothAdapter.ACTION_STATE_CHANGED == action) {
val preState = getIntExtra(
intent,
BluetoothAdapter.EXTRA_PREVIOUS_STATE,
STATE_UNKNOWN
)
val newState = getIntExtra(
intent,
BluetoothAdapter.EXTRA_STATE, STATE_UNKNOWN
)
addStateChangeLog(preState, newState)
} else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED == action) {
val preState = getIntExtra(
intent,
BluetoothAdapter.EXTRA_PREVIOUS_CONNECTION_STATE,
STATE_UNKNOWN
)
val newState = getIntExtra(
intent,
BluetoothAdapter.EXTRA_CONNECTION_STATE,
STATE_UNKNOWN
)
val remoteDevice = getStringExtra(
intent,
BluetoothDevice.EXTRA_DEVICE
)
addConnectionChangeLog(preState, newState, remoteDevice)
}
}
}
private fun registerBluetoothReceiver() {
val intentFilter = IntentFilter()
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
registerForExternal(this, receiver, intentFilter)
}
private fun unregisterBluetoothReceiver() {
unregisterReceiver(receiver)
}
private fun addStateChangeLog(preState: Int, newState: Int) {
val log =
"State changed: " + getStateString(preState) + " -> " + getStateString(newState)
appendNewLog(log)
}
private fun addConnectionChangeLog(
preState: Int,
newState: Int,
remoteDevice: String?
) {
val log =
("Connection changed: " + getStateString(preState) + " -> " + getStateString(newState) +
", remoteDevice: " + remoteDevice)
appendNewLog(log)
}
private fun appendNewLog(log: String) {
Timber.tag(TAG).i(log)
logContents = log + "\n" + logContents
binding.logViewer.text = logContents
}
private fun getStateString(state: Int): String {
if (state == BluetoothAdapter.STATE_ON) {
return "on"
} else if (state == BluetoothAdapter.STATE_OFF) {
return "off"
} else if (state == BluetoothAdapter.STATE_CONNECTED) {
return "connected"
} else if (state == BluetoothAdapter.STATE_CONNECTING) {
return "connecting"
} else if (state == BluetoothAdapter.STATE_DISCONNECTED) {
return "disconnected"
} else if (state == BluetoothAdapter.STATE_DISCONNECTING) {
return "disconnecting"
} else if (state == BluetoothAdapter.STATE_TURNING_OFF) {
return "turning_off"
} else if (state == BluetoothAdapter.STATE_TURNING_ON) {
return "turning_on"
}
return "unknown-($state)"
}
private val bluetoothAdapter: BluetoothAdapter?
get() {
val mgr = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
return mgr.adapter
}
private val bluetoothState: Int
get() {
val adapter = bluetoothAdapter
return adapter?.state ?: STATE_UNKNOWN
}
private fun enableBluetooth() {
val adapter = bluetoothAdapter
adapter?.enable()
}
private fun disableBluetooth() {
val adapter = bluetoothAdapter
adapter?.disable()
}
override fun onClick(v: View) {
if (v === binding.enable) {
enableBluetooth()
} else if (v === binding.disable) {
disableBluetooth()
}
}
companion object {
private const val TAG = "BluetoothViewerActivity"
private const val STATE_UNKNOWN = -1
}
}
|
apache-2.0
|
37821e28e3488dbc022fb3b20fa99492
| 32.877907 | 100 | 0.623477 | 5.129401 | false | false | false | false |
spark/photon-tinker-android
|
app/src/main/java/io/particle/android/sdk/ui/devicelist/DeviceFilterFragment.kt
|
1
|
7036
|
package io.particle.android.sdk.ui.devicelist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import androidx.annotation.DrawableRes
import androidx.collection.arrayMapOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import com.snakydesign.livedataextensions.distinctUntilChanged
import io.particle.android.sdk.cloud.ParticleDevice
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.ALL_SELECTED
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.NONE_SELECTED
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.OFFLINE_ONLY
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.ONLINE_ONLY
import io.particle.sdk.app.R
import kotlinx.android.synthetic.main.fragment_filter_fragment.*
import mu.KotlinLogging
class DeviceFilterFragment : Fragment() {
companion object {
fun newInstance() = DeviceFilterFragment()
}
private val filterViewModel: DeviceFilterViewModel by activityViewModels()
private val draftDeviceFilter: DraftDeviceFilter by lazy { filterViewModel.draftDeviceFilter }
private val onlineStatusFilterButtons: Map<CheckedTextView, OnlineStatusFilter> by lazy {
arrayMapOf(
action_filter_online_status_online to OnlineStatusFilter.ONLINE_ONLY,
action_filter_online_status_offline to OnlineStatusFilter.OFFLINE_ONLY
)
}
private val deviceTypeFilterbuttons: Map<DeviceTypeFilter, DeviceTypeFilterButton> by lazy {
arrayMapOf(
DeviceTypeFilter.BORON to action_filter_device_type_boron,
DeviceTypeFilter.ELECTRON to action_filter_device_type_electron,
DeviceTypeFilter.ARGON to action_filter_device_type_argon,
DeviceTypeFilter.PHOTON to action_filter_device_type_photon,
DeviceTypeFilter.XENON to action_filter_device_type_xenon,
DeviceTypeFilter.OTHER to action_filter_device_type_other
)
}
private var setUpRadioGroupListener = false
private val log = KotlinLogging.logger {}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
draftDeviceFilter.updateFromLiveConfig()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_filter_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
action_reset.setOnClickListener { filterViewModel.draftDeviceFilter.resetConfig() }
p_action_back.setOnClickListener {
draftDeviceFilter.updateFromLiveConfig()
closeFilterView()
}
for ((v, onlineStatus) in onlineStatusFilterButtons.entries) {
v.setOnClickListener { draftDeviceFilter.updateOnlineStatus(onlineStatus) }
}
for ((deviceType, v) in deviceTypeFilterbuttons.entries) {
setUpDeviceTypeFilter(v, deviceType)
}
action_filter_device_list.setOnClickListener {
draftDeviceFilter.commitDraftConfig()
closeFilterView()
}
draftDeviceFilter.filteredDeviceListLD.observe(this, Observer { updateCommitButton(it!!) })
draftDeviceFilter.deviceListViewConfigLD
.distinctUntilChanged()
.observe(
viewLifecycleOwner,
Observer { setUiFromConfig(it) }
)
}
private fun setUpDeviceTypeFilter(view: DeviceTypeFilterButton, filter: DeviceTypeFilter) {
view.filter = filter
view.setOnClickListener {
val isChecked = !view.isChecked // set from the last time the UI updated from the model
if (isChecked) {
draftDeviceFilter.includeDeviceInDeviceTypeFilter(filter)
} else {
draftDeviceFilter.removeDeviceFromDeviceTypeFilter(filter)
}
}
}
private fun closeFilterView() {
requireActivity().supportFragmentManager.popBackStack()
}
@Suppress("BooleanLiteralArgument") // ignore the Pair booleans below; it's fine in this case
private fun setUiFromConfig(config: DeviceListViewConfig) {
log.info { "setUiFromConfig(): config=$config" }
fun updateCheckedButton(checkedTextView: CheckedTextView, checked: Boolean) {
@DrawableRes val bg = if (checked) {
R.drawable.device_filter_button_background_selected
} else {
R.drawable.device_filter_button_background_unselected
}
checkedTextView.setBackgroundResource(bg)
checkedTextView.isChecked = checked
}
// SORTING
val sortButtonId = when (config.sortCriteria) {
SortCriteria.ONLINE_STATUS -> R.id.action_sort_by_online_status
SortCriteria.DEVICE_TYPE -> R.id.action_sort_by_device_type
SortCriteria.NAME -> R.id.action_sort_by_name
SortCriteria.LAST_HEARD -> R.id.action_sort_by_last_heard
}
sort_by_radiogroup.check(sortButtonId)
// ONLINE/OFFLINE STATUS FILTER
val (onlineChecked, offlineChecked) = when (config.onlineStatusFilter) {
ALL_SELECTED -> Pair(true, true)
NONE_SELECTED -> Pair(false, false)
ONLINE_ONLY -> Pair(true, false)
OFFLINE_ONLY -> Pair(false, true)
}
updateCheckedButton(action_filter_online_status_online, onlineChecked)
updateCheckedButton(action_filter_online_status_offline, offlineChecked)
// DEVICE TYPE FILTER
for (deviceTypeFilter in DeviceTypeFilter.values()) {
val shouldBeChecked = config.deviceTypeFilters.contains(deviceTypeFilter)
val button = deviceTypeFilterbuttons[deviceTypeFilter]
button?.isChecked = shouldBeChecked
}
// set this last to avoid some observer loops
if (!setUpRadioGroupListener) {
sort_by_radiogroup.setOnCheckedChangeListener { _, checkedId ->
val newSortCriteria = when (checkedId) {
R.id.action_sort_by_device_type -> SortCriteria.DEVICE_TYPE
R.id.action_sort_by_name -> SortCriteria.NAME
R.id.action_sort_by_last_heard -> SortCriteria.LAST_HEARD
else -> SortCriteria.ONLINE_STATUS
}
draftDeviceFilter.updateSort(newSortCriteria)
}
setUpRadioGroupListener = true
}
}
private fun updateCommitButton(newFilteredDeviceList: List<ParticleDevice>) {
val actionLabel = "Show ${newFilteredDeviceList.size} devices"
action_filter_device_list.text = actionLabel
}
}
|
apache-2.0
|
1068e7d2acecd528c6257c26be77fe2d
| 38.088889 | 99 | 0.682774 | 4.930624 | false | true | false | false |
robinverduijn/gradle
|
buildSrc/subprojects/versioning/src/main/kotlin/org/gradle/gradlebuild/versioning/DetermineCommitId.kt
|
1
|
3927
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.versioning
import org.gradle.api.DefaultTask
import org.gradle.api.file.ProjectLayout
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.internal.os.OperatingSystem
import org.gradle.process.internal.ExecActionFactory
import java.io.ByteArrayOutputStream
import javax.inject.Inject
@Suppress("unused")
open class DetermineCommitId @Inject constructor(
objects: ObjectFactory,
layout: ProjectLayout,
private val execActionFactory: ExecActionFactory
) : DefaultTask() {
@get:OutputFile
val commitIdFile = objects.fileProperty()
.convention(layout.buildDirectory.file("determined-commit-id.txt"))
@get:Internal
val determinedCommitId: Provider<String>
get() = commitIdFile.map { it.asFile.readText() }
init {
outputs.upToDateWhen { false }
}
private
val promotionCommitId: String? =
project.findProperty("promotionCommitId")?.toString()
private
val rootDir =
project.rootDir
@TaskAction
fun determineCommitId() {
val commitId = buildStrategies().mapNotNull { it() }.first()
commitIdFile.get().asFile.writeText(commitId)
}
private
fun buildStrategies(): Sequence<() -> String?> = sequenceOf(
// For promotion builds use the commitId passed in as a project property
{ promotionCommitId },
// Builds of Gradle happening on the CI server
{ System.getenv("BUILD_VCS_NUMBER") },
// For the discovery builds, this points to the Gradle revision
{ firstSystemEnvStartsWithOrNull("BUILD_VCS_NUMBER_Gradle_Master") },
// For the discovery release builds, this points to the Gradle revision
{ firstSystemEnvStartsWithOrNull("BUILD_VCS_NUMBER_Gradle_release_branch") },
// If it's a checkout, ask Git for it
{ gitCommitId() },
// It's a source distribution, we don't know.
{ "<unknown>" }
)
private
fun firstSystemEnvStartsWithOrNull(prefix: String) =
System.getenv().asSequence().firstOrNull { it.key.startsWith(prefix) }?.value
private
fun gitCommitId(): String? {
val gitDir = rootDir.resolve(".git")
if (!gitDir.isDirectory) {
return null
}
val execOutput = ByteArrayOutputStream()
val execResult = execActionFactory.newExecAction().apply {
workingDir = rootDir
isIgnoreExitValue = true
commandLine = listOf("git", "log", "-1", "--format=%H")
if (OperatingSystem.current().isWindows) {
commandLine = listOf("cmd", "/c") + commandLine
}
standardOutput = execOutput
}.execute()
return when {
execResult.exitValue == 0 -> String(execOutput.toByteArray()).trim()
gitDir.resolve("HEAD").exists() -> {
// Read commit id directly from filesystem
val headRef = gitDir.resolve("HEAD").readText()
.replace("ref: ", "").trim()
gitDir.resolve(headRef).readText().trim()
}
else -> null
}
}
}
|
apache-2.0
|
77789e929a5c7f4b08b125a12c51a855
| 34.0625 | 85 | 0.65699 | 4.587617 | false | false | false | false |
halawata13/ArtichForAndroid
|
app/src/main/java/net/halawata/artich/model/MenuListAdapter.kt
|
2
|
993
|
package net.halawata.artich.model
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import net.halawata.artich.R
import net.halawata.artich.entity.SideMenuItem
import kotlin.collections.ArrayList
class MenuListAdapter(val context: Context, var data: ArrayList<SideMenuItem>, val resource: Int): BaseAdapter() {
override fun getCount(): Int = data.size
override fun getItem(position: Int): Any = data[position]
override fun getItemId(position: Int): Long = data[position].id
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val activity = context as Activity
val item = getItem(position) as SideMenuItem
val view = convertView ?: activity.layoutInflater.inflate(resource, null)
(view.findViewById(R.id.list_title) as TextView).text = item.title
return view
}
}
|
mit
|
f6f715cc19b9ef357f59573f34707cdc
| 31.032258 | 114 | 0.746224 | 4.317391 | false | false | false | false |
anton-okolelov/intellij-rust
|
src/test/kotlin/org/rust/ide/highlight/RsHighlightExitPointsHandlerFactoryTest.kt
|
1
|
5698
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.highlight
import com.intellij.codeInsight.highlighting.HighlightUsagesHandler
import org.intellij.lang.annotations.Language
import org.rust.lang.RsTestBase
class RsHighlightExitPointsHandlerFactoryTest : RsTestBase() {
fun doTest(@Language("Rust") check: String, vararg usages: String) {
InlineFile(check)
HighlightUsagesHandler.invoke(myFixture.project, myFixture.editor, myFixture.file)
val highlighters = myFixture.editor.markupModel.allHighlighters
val actual = highlighters.map { myFixture.file.text.substring(it.startOffset, it.endOffset) }.toList()
assertSameElements(actual, usages.toList())
}
fun `test highlight all returns`() = doTest("""
fn main() {
if true {
/*caret*/return 1;
}
return 0;
}
""", "return 1", "return 0")
fun `test highlight try macro as return`() = doTest("""
fn main() {
if true {
try!(Err(()))
}
/*caret*/return 0;
}
""", "try!(Err(()))", "return 0")
fun `test highlight diverging macros as return`() = doTest("""
fn main() {
if true {
panic!("test")
} else {
unimplemented!()
}
/*caret*/return 0;
}
""", "panic!(\"test\")", "unimplemented!()", "return 0")
fun `test highlight ? operator as return`() = doTest("""
fn main() {
if true {
Err(())/*caret*/?
}
return 0;
}
""", "?", "return 0")
fun `test highlight complex return as return`() = doTest("""
struct S;
impl S {
fn foo(self) -> Result<S, i32> {Ok(self)}
fn bar(self) -> S {self}
}
fn main() {
let s = S;
s.foo()/*caret*/?.bar().foo()?;
return 0;
}
""", "?", "?", "return 0")
fun `test highlight last stmt lit as return`() = doTest("""
fn test() {}
fn main() {
if true {
/*caret*/return 1;
}
test();
0
}
""", "return 1", "0")
fun `test highlight last stmt call as return`() = doTest("""
fn test() -> i32 {}
fn main() {
if true {
/*caret*/return 1;
}
test()
}
""", "return 1", "test()")
fun `test highlight should not highlight inner function`() = doTest("""
fn main() {
fn bar() {
return 2;
}
/*caret*/return 1;
}
""", "return 1")
fun `test highlight should not highlight inner lambda`() = doTest("""
fn main() {
let one = || { return 1; };
/*caret*/return 2;
}
""", "return 2")
fun `test highlight should not highlight outer function`() = doTest("""
fn main() {
let one = || { /*caret*/return 1; };
return 2;
}
""", "return 1")
fun `test highlight last stmt if as return`() = doTest("""
fn test() -> i32 {}
fn main() {
if true {
/*caret*/return 1;
}
if false { 2 } else { 3 }
}
""", "return 1", "2", "3")
fun `test highlight last stmt if in if and match as return`() = doTest("""
fn test() -> i32 {}
fn main() {
if true {
/*caret*/return 1;
}
if false {
match None {
Some(_) => 2,
None => 3,
}
} else {
if true {
4
} else {
5
}
}
}
""", "return 1", "2", "3", "4", "5")
fun `test highlight last stmt match as return`() = doTest("""
fn test() -> i32 {}
fn main() {
if true {
/*caret*/return 1;
}
match Some("test") {
Some(s) => { 2 }
_ => 3,
}
}
""", "return 1", "2", "3")
fun `test highlight last stmt match with inner as return`() = doTest("""
fn test() -> Result<i32,i32> {}
fn main() {
if true {
/*caret*/return 1;
}
match test()? {
Some(s) => 2,
_ => 3,
}
}
""", "return 1", "?", "2", "3")
fun `test highlight last stmt match with pat as return`() = doTest("""
fn test() -> Result<i32,i32> {}
fn main() {
if true {
/*caret*/return 1;
}
match "test" {
"test" => 2,
_ => 3,
}
}
""", "return 1", "2", "3")
fun `test highlight last stmt match in match and if as return`() = doTest("""
fn test() -> Result<i32,i32> {}
fn main() {
if true {
/*caret*/return 1;
}
match None {
Some(_) => match "test" {
"test" => 2,
_ => 3,
},
_ => if true {
4
} else {
5
},
}
}
""", "return 1", "2", "3", "4", "5")
fun `test return in macro`() = doTest("""
macro_rules! foo {
() => { /*caret*/return }
}
""")
}
|
mit
|
e1d0f2741c731284cc70d88846672488
| 25.751174 | 110 | 0.402773 | 4.483084 | false | true | false | false |
jdinkla/groovy-java-ray-tracer
|
src/main/kotlin/net/dinkla/raytracer/brdf/GlossySpecular.kt
|
1
|
1611
|
package net.dinkla.raytracer.brdf
import net.dinkla.raytracer.colors.Color
import net.dinkla.raytracer.hits.Shade
import net.dinkla.raytracer.math.Vector3D
class GlossySpecular(// specular intensity
var ks: Double = 0.25,// specular color
var cs: Color? = Color.WHITE,// specular exponent
var exp: Double = 5.0) : BRDF() {
override fun f(sr: Shade, wo: Vector3D, wi: Vector3D): Color {
assert(null != cs)
val nDotWi = wi dot sr.normal
val r = (wi * (-1.0)) + (Vector3D(sr.normal) * (2 * nDotWi))
val rDotWo = r dot wo
return if (rDotWo > 0) {
cs!! * (ks * Math.pow(rDotWo, exp))
} else {
Color.BLACK
}
}
override fun sampleF(sr: Shade, wo: Vector3D): BRDF.Sample {
assert(null != cs)
val sample = newSample()
val nDotWo = sr.normal dot wo
val r = -wo + (sr.normal * (2 * nDotWo))
val u = Vector3D(0.00424, 1.0, 0.00764).cross(r).normalize()
val v = u.cross(r)
val sp = sampler!!.sampleHemisphere()
sample.wi = u.times(sp.x).plus(v.times(sp.y)).plus(r.times(sp.z))
val nDotWi = sr.normal.dot(sample.wi!!)
if (nDotWi < 0) {
sample.wi = u.times(-sp.x).plus(v.times(-sp.y)).plus(r.times(-sp.z))
}
val phongLobe = Math.pow(sample.wi!!.dot(r), exp)
sample.pdf = phongLobe * nDotWi
sample.color = cs!!.times(ks * phongLobe)
return sample
}
override fun rho(sr: Shade, wo: Vector3D): Color {
throw RuntimeException("GlossySpecular.rho")
}
}
|
apache-2.0
|
9829d10c7eb5afe7f6d31f525bc3d8ca
| 30 | 80 | 0.569212 | 3.128155 | false | false | false | false |
huoguangjin/MultiHighlight
|
src/main/java/com/github/huoguangjin/multihighlight/highlight/MultiHighlightTextHandler.kt
|
1
|
3530
|
package com.github.huoguangjin.multihighlight.highlight
import com.github.huoguangjin.multihighlight.config.TextAttributesFactory
import com.intellij.find.FindManager
import com.intellij.find.FindModel
import com.intellij.injected.editor.EditorWindow
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiFile
import java.text.MessageFormat
class MultiHighlightTextHandler(
private val project: Project,
private val editor: Editor,
private val psiFile: PsiFile?,
) {
fun highlight() {
val selectionModel = editor.selectionModel
if (!selectionModel.hasSelection()) {
selectionModel.selectWordAtCaret(false)
}
val selectedText = selectionModel.selectedText ?: return
highlightText(selectedText)
}
fun highlightText(text: String) {
if (text.isEmpty()) {
return
}
val multiHighlightManager = MultiHighlightManager.getInstance()
val textRanges = findText(text)
val textAttr = TextAttributesFactory.getNextTextAttr()
if (editor is EditorWindow) {
// The text ranges are found in the injected editor which is an EditorWindow. Different EditorWindows created from
// the same injected document (DocumentWindow) are not referenced in the EditorFactory, but their host editors can
// be referenced by the same host document. Highlight the text ranges in the host editors so that we can also
// add/remove highlighters across editors.
// see: [com.intellij.openapi.editor.impl.EditorFactoryImpl.createEditor]
val hostEditor = editor.delegate
val injectedDocument = editor.document
val hostTextRanges = textRanges.map(injectedDocument::injectedToHost)
multiHighlightManager.addHighlighters(hostEditor, textAttr, hostTextRanges)
} else {
multiHighlightManager.addHighlighters(editor, textAttr, textRanges)
}
val highlightCount = textRanges.size
WindowManager.getInstance().getStatusBar(project).info = if (highlightCount > 0) {
MessageFormat.format("{0} {0, choice, 1#text|2#texts} highlighted", highlightCount)
} else {
"No texts highlighted"
}
}
private fun findText(text: String): MutableList<TextRange> {
val findManager = FindManager.getInstance(project)
val charSequence = editor.document.immutableCharSequence
val maxOffset = charSequence.length
val findModel = FindModel().apply {
copyFrom(findManager.findInFileModel)
stringToFind = text
}
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
var offset = 0
val textRanges = mutableListOf<TextRange>()
while (true) {
val result = findManager.findString(charSequence, offset, findModel, virtualFile)
if (!result.isStringFound) {
break
}
val newOffset = result.endOffset
if (newOffset > maxOffset) {
break
}
if (offset == newOffset) {
if (offset < maxOffset - 1) {
offset += 1
} else {
// reach document end
textRanges.add(result)
break
}
} else {
offset = newOffset
if (offset == result.startOffset) {
// result.startOffset == result.endOffset, skip zero width range
offset += 1
}
}
textRanges.add(result)
}
return textRanges
}
}
|
gpl-3.0
|
c0f982980bef8ebdee268af05dca60c2
| 31.990654 | 120 | 0.705949 | 4.614379 | false | false | false | false |
xfournet/intellij-community
|
platform/platform-impl/src/com/intellij/codeInsight/hints/filtering/StringMatcherBuilder.kt
|
13
|
1929
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints.filtering
interface StringMatcher {
fun isMatching(text: String): Boolean
}
class StringMatcherImpl(private val matcher: (String) -> Boolean) : StringMatcher {
override fun isMatching(text: String) = matcher(text)
}
object StringMatcherBuilder {
fun create(matcher: String): StringMatcher? {
if (matcher.isEmpty()) return StringMatcherImpl { true }
return createAsterisksMatcher(matcher)
}
private fun createAsterisksMatcher(matcher: String): StringMatcher? {
val asterisksCount = matcher.count { it == '*' }
if (asterisksCount > 2) return null
if (asterisksCount == 0) {
return StringMatcherImpl { it == matcher }
}
if (matcher == "*") {
return StringMatcherImpl { true }
}
if (matcher.startsWith('*') && asterisksCount == 1) {
val target = matcher.substring(1)
return StringMatcherImpl { it.endsWith(target) }
}
if (matcher.endsWith('*') && asterisksCount == 1) {
val target = matcher.substring(0, matcher.length - 1)
return StringMatcherImpl { it.startsWith(target) }
}
if (matcher.startsWith('*') && matcher.endsWith('*')) {
val target = matcher.substring(1, matcher.length - 1)
return StringMatcherImpl { it.contains(target) }
}
return null
}
}
|
apache-2.0
|
13678099dcc2b2ebc4b9cc4363585540
| 29.634921 | 83 | 0.685329 | 3.993789 | false | false | false | false |
google/ksp
|
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/AsMemberOfProcessor.kt
|
1
|
10126
|
package com.google.devtools.ksp.processor
import com.google.devtools.ksp.getClassDeclarationByName
import com.google.devtools.ksp.getDeclaredFunctions
import com.google.devtools.ksp.isConstructor
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
@Suppress("unused") // used by generated tests
class AsMemberOfProcessor : AbstractTestProcessor() {
val results = mutableListOf<String>()
// keep a list of all signatures we generate and ensure equals work as expected
private val functionsBySignature = mutableMapOf<String, MutableSet<KSFunction>>()
override fun toResult(): List<String> {
return results
}
override fun process(resolver: Resolver): List<KSAnnotated> {
val base = resolver.getClassDeclarationByName("Base")!!
val child1 = resolver.getClassDeclarationByName("Child1")!!
addToResults(resolver, base, child1.asStarProjectedType())
val child2 = resolver.getClassDeclarationByName("Child2")!!
addToResults(resolver, base, child2.asStarProjectedType())
val child2WithString = resolver.getDeclaration<KSPropertyDeclaration>("child2WithString")
addToResults(resolver, base, child2WithString.type.resolve())
// check cases where given type is not a subtype
val notAChild = resolver.getClassDeclarationByName("NotAChild")!!
addToResults(resolver, base, notAChild.asStarProjectedType())
val listOfStrings = resolver.getDeclaration<KSPropertyDeclaration>("listOfStrings").type.resolve()
val setOfStrings = resolver.getDeclaration<KSPropertyDeclaration>("setOfStrings").type.resolve()
val listClass = resolver.getClassDeclarationByName("kotlin.collections.List")!!
val setClass = resolver.getClassDeclarationByName("kotlin.collections.Set")!!
val listGet = listClass.getAllFunctions().first {
it.simpleName.asString() == "get"
}
results.add("List#get")
results.add("listOfStrings: " + resolver.asMemberOfSignature(listGet, listOfStrings))
results.add("setOfStrings: " + resolver.asMemberOfSignature(listGet, setOfStrings))
val setContains = setClass.getAllFunctions().first {
it.simpleName.asString() == "contains"
}
results.add("Set#contains")
results.add("listOfStrings: " + resolver.asMemberOfSignature(setContains, listOfStrings))
results.add("setOfStrings: " + resolver.asMemberOfSignature(setContains, setOfStrings))
val javaBase = resolver.getClassDeclarationByName("JavaBase")!!
val javaChild1 = resolver.getClassDeclarationByName("JavaChild1")!!
addToResults(resolver, javaBase, javaChild1.asStarProjectedType())
val fileLevelFunction = resolver.getDeclaration<KSFunctionDeclaration>("fileLevelFunction")
results.add("fileLevelFunction: " + resolver.asMemberOfSignature(fileLevelFunction, listOfStrings))
// TODO we should eventually support this, probably as different asReceiverOf kind of API
val fileLevelExtensionFunction = resolver.getDeclaration<KSFunctionDeclaration>("fileLevelExtensionFunction")
results.add(
"fileLevelExtensionFunction: " +
resolver.asMemberOfSignature(fileLevelExtensionFunction, listOfStrings)
)
val fileLevelProperty = resolver.getDeclaration<KSPropertyDeclaration>("fileLevelProperty")
results.add("fileLevelProperty: " + resolver.asMemberOfSignature(fileLevelProperty, listOfStrings))
val errorType = resolver.getDeclaration<KSPropertyDeclaration>("errorType").type.resolve()
results.add("errorType: " + resolver.asMemberOfSignature(listGet, errorType))
// make sure values are cached
val first = listGet.asMemberOf(listOfStrings)
val second = listGet.asMemberOf(listOfStrings)
if (first !== second) {
results.add("cache error, repeated computation")
}
// validate equals implementation
// all functions with the same signature should be equal to each-other unless there is an error / incomplete
// type in them
val notEqualToItself = functionsBySignature.filter { (_, functions) ->
functions.size != 1
}.keys
results.add("expected comparison failures")
results.addAll(notEqualToItself)
// make sure we don't have any false positive equals
functionsBySignature.forEach { (signature, functions) ->
functionsBySignature.forEach { (otherSignature, otherFunctions) ->
if (signature != otherSignature && functions.any { otherFunctions.contains(it) }) {
results.add("Unexpected equals between $otherSignature and $signature")
}
}
}
val javaImpl = resolver.getClassDeclarationByName("JavaImpl")!!
val getX = javaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "getX" }
val getY = javaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "getY" }
val setY = javaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "setY" }
results.add(getX.asMemberOf(javaImpl.asStarProjectedType()).toSignature())
results.add(getY.asMemberOf(javaImpl.asStarProjectedType()).toSignature())
results.add(setY.asMemberOf(javaImpl.asStarProjectedType()).toSignature())
return emptyList()
}
private inline fun <reified T : KSDeclaration> Resolver.getDeclaration(name: String): T {
return getNewFiles().first {
it.fileName == "Input.kt"
}.declarations.filterIsInstance<T>().first {
it.simpleName.asString() == name
}
}
private fun addToResults(resolver: Resolver, baseClass: KSClassDeclaration, child: KSType) {
results.add(child.toSignature())
val baseProperties = baseClass.getAllProperties()
val baseFunction = baseClass.getDeclaredFunctions().filterNot { it.isConstructor() }
results.addAll(
baseProperties.map { property ->
val typeSignature = resolver.asMemberOfSignature(
property = property,
containing = child
)
"${property.simpleName.asString()}: $typeSignature"
}
)
results.addAll(
baseFunction.map { function ->
val functionSignature = resolver.asMemberOfSignature(
function = function,
containing = child
)
"${function.simpleName.asString()}: $functionSignature"
}
)
}
private fun Resolver.asMemberOfSignature(
function: KSFunctionDeclaration,
containing: KSType
): String {
val result = kotlin.runCatching {
function.asMemberOf(containing).also {
if (it !== function.asMemberOf(containing)) {
results.add("cache error, repeated computation")
}
}
}
return if (result.isSuccess) {
val ksFunction = result.getOrThrow()
val signature = ksFunction.toSignature()
// record it to validate equality against other signatures
functionsBySignature.getOrPut(signature) {
mutableSetOf()
}.add(ksFunction)
signature
} else {
result.exceptionOrNull()!!.toSignature()
}
}
private fun Resolver.asMemberOfSignature(
property: KSPropertyDeclaration,
containing: KSType
): String {
val result = kotlin.runCatching {
property.asMemberOf(containing).also {
if (it !== property.asMemberOf(containing)) {
results.add("cache error, repeated computation")
}
}
}
return if (result.isSuccess) {
result.getOrThrow().toSignature()
} else {
result.exceptionOrNull()!!.toSignature()
}
}
private fun Throwable.toSignature() = "${this::class.qualifiedName}: $message"
private fun KSType.toSignature(): String {
val name = this.declaration.qualifiedName?.asString()
?: this.declaration.simpleName.asString()
val qName = name + nullability.toSignature()
if (arguments.toList().isEmpty()) {
return qName
}
val args = arguments.joinToString(", ") {
it.type?.resolve()?.toSignature() ?: "no-type"
}
return "$qName<$args>"
}
private fun KSTypeParameter.toSignature(): String {
val boundsSignature = if (bounds.toList().isEmpty()) {
""
} else {
bounds.joinToString(
separator = ", ",
prefix = ": "
) {
it.resolve().toSignature()
}
}
val varianceSignature = if (variance.label.isBlank()) {
""
} else {
"${variance.label} "
}
val name = this.name.asString()
return "$varianceSignature$name$boundsSignature"
}
private fun KSFunction.toSignature(): String {
val returnType = this.returnType?.toSignature() ?: "no-return-type"
val params = parameterTypes.joinToString(", ") {
it?.toSignature() ?: "no-type-param"
}
val paramTypeArgs = this.typeParameters.joinToString(", ") {
it.toSignature()
}
val paramTypesSignature = if (paramTypeArgs.isBlank()) {
""
} else {
"<$paramTypeArgs>"
}
val receiverSignature = if (extensionReceiverType != null) {
extensionReceiverType!!.toSignature() + "."
} else {
""
}
return "$receiverSignature$paramTypesSignature($params) -> $returnType"
}
private fun Nullability.toSignature() = when (this) {
Nullability.NULLABLE -> "?"
Nullability.NOT_NULL -> "!!"
Nullability.PLATFORM -> ""
}
}
|
apache-2.0
|
098afd8cc5eb89bb9dde709c7cdc38b8
| 42.089362 | 117 | 0.629962 | 5.219588 | false | false | false | false |
jmesserli/discord-bernbot
|
discord-bot/src/main/kotlin/nu/peg/discord/service/internal/DefaultAudioService.kt
|
1
|
3590
|
package nu.peg.discord.service.internal
import nu.peg.discord.service.AudioService
import nu.peg.discord.util.DiscordClientListener
import nu.peg.discord.util.getLogger
import org.springframework.stereotype.Service
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.handle.obj.IGuild
import sx.blah.discord.handle.obj.IVoiceChannel
import sx.blah.discord.util.audio.AudioPlayer
import java.net.URL
@Service
class DefaultAudioService : AudioService, DiscordClientListener {
companion object {
private val LOGGER = getLogger(DefaultAudioService::class)
}
private lateinit var discordClient: IDiscordClient
private val guildJoined: MutableMap<IGuild, Boolean> = mutableMapOf()
private val guildLeaveThreads: MutableMap<IGuild, Thread> = mutableMapOf()
override fun discordClientAvailable(client: IDiscordClient) {
discordClient = client
}
override fun joinVoice(channel: IVoiceChannel) {
if (guildJoined[channel.guild] == true) {
LOGGER.info("Not joining voice channel ${channel.name} on ${channel.guild.name} because the bot has already joined a channel on this guild")
return
}
channel.join()
guildJoined[channel.guild] = true
LOGGER.debug("Joined channel ${channel.name} on ${channel.guild.name}")
}
override fun queueAudio(guild: IGuild, audio: URL) {
if (guildJoined[guild] != true) {
LOGGER.info("Join a channel before queueing audio")
return
}
val player = AudioPlayer.getAudioPlayerForGuild(guild)
player.queue(audio)
LOGGER.debug("Queued audio $audio for playing on ${guild.name}")
}
override fun queueLeaveOnFinished(guild: IGuild) {
if (guildJoined[guild] != true) {
LOGGER.info("Guild ${guild.name} is not joined")
return
}
if (guildLeaveThreads[guild] != null) {
LOGGER.info("Guild ${guild.name} is already queued for leaving")
return
}
val player = AudioPlayer.getAudioPlayerForGuild(guild)
if (player.currentTrack == null) {
LOGGER.info("Leaving guild ${guild.name} because no song is playing")
guild.connectedVoiceChannel?.leave()
return
}
val thread = object : Thread() {
override fun run() {
do {
val track = player.currentTrack
if (track == null) {
LOGGER.debug("Player for guild ${guild.name} has stopped playing, leaving channel")
guild.connectedVoiceChannel?.leave()
guildJoined[guild] = false
guildLeaveThreads.remove(guild)
return
}
Thread.sleep(500)
} while (!interrupted())
}
}
guildLeaveThreads[guild] = thread
thread.start()
LOGGER.debug("Started watching audio player for guild ${guild.name} for leaving")
}
override fun forceLeave(guild: IGuild) {
if (guildJoined[guild] != true) {
LOGGER.debug("Bot has not joined guild ${guild.name}, not leaving")
return
}
guildJoined[guild] = false
guildLeaveThreads[guild]?.interrupt()
guildLeaveThreads.remove(guild)
guild.connectedVoiceChannel?.leave()
}
override fun forceLeaveAll() {
guildJoined.filter { it.value }.map { it.key }.forEach(this::forceLeave)
}
}
|
mit
|
d5031b5efd1fc2706a3334dcbc7f5272
| 32.877358 | 152 | 0.616713 | 4.656291 | false | false | false | false |
yyued/CodeX-UIKit-Android
|
library/src/main/java/com/yy/codex/uikit/NSRange.kt
|
1
|
307
|
package com.yy.codex.uikit
/**
* Created by cuiminghui on 2017/1/9.
*/
class NSRange(val location: Int, val length: Int) {
override fun equals(other: Any?): Boolean {
var other = other as? NSRange ?: return false
return location == other.location && length == other.length
}
}
|
gpl-3.0
|
f508e1f5773c7e3482b4f40e6522fc3d
| 20.928571 | 67 | 0.638436 | 3.743902 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/psi/element/MdWikiLinkStubElementType.kt
|
1
|
1086
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.tree.IElementType
import com.vladsch.md.nav.psi.util.MdTypes
class MdWikiLinkStubElementType(debugName: String) : MdLinkElementStubElementType<MdWikiLink, MdWikiLinkStub>(debugName) {
override fun createPsi(stub: MdWikiLinkStub) = MdWikiLinkImpl(stub, this)
override fun getExternalId(): String = "markdown.link-element.wiki"
override fun createStub(parentStub: StubElement<PsiElement>, linkRefWithAnchorText: String): MdWikiLinkStub = MdWikiLinkStubImpl(parentStub, linkRefWithAnchorText)
override fun getLinkRefTextType(): IElementType = MdTypes.WIKI_LINK_REF
override fun getLinkRefAnchorMarkerType(): IElementType? = MdTypes.WIKI_LINK_REF_ANCHOR_MARKER
override fun getLinkRefAnchorType(): IElementType? = MdTypes.WIKI_LINK_REF_ANCHOR
}
|
apache-2.0
|
1847c8ed5594c1eff524af392b6f607f
| 62.882353 | 177 | 0.804788 | 4.258824 | false | true | false | false |
dya-tel/TSU-Schedule
|
src/test/kotlin/ru/dyatel/tsuschedule/parsing/GroupScheduleParserTest.kt
|
1
|
1434
|
package ru.dyatel.tsuschedule.parsing
import org.junit.Test
import ru.dyatel.tsuschedule.EmptyResultException
import ru.dyatel.tsuschedule.model.LessonType
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class GroupScheduleParserTest {
private val requester = DataRequester()
private fun check(group: String) {
val lessons = GroupScheduleParser.parse(requester.groupSchedule(group))
assertFalse(lessons.isEmpty(), "No lessons were received")
val weekdayCount = lessons
.map { it.weekday }
.distinct()
.count()
assertFalse(lessons.all { it.type == LessonType.UNKNOWN }, "Failed to recognize all lesson types")
assertTrue(weekdayCount > 1, "Got too few weekdays")
}
@Test fun testBadGroup() {
assertFailsWith<EmptyResultException> { check("221") }
}
@Test fun test221251() = check("221251")
@Test fun test221261() = check("221261")
@Test fun test221271() = check("221271")
@Test fun test230751() = check("230751")
@Test fun test720551() = check("720551-ПБ")
@Test fun test721075() = check("721075")
@Test fun test132361() = check("132361")
@Test fun test420851() = check("420851")
@Test fun test520761() = check("520761")
@Test fun test622651() = check("622651")
@Test fun test930169() = check("930169")
}
|
mit
|
f31d89047a9d990f4f760be89995501e
| 25.518519 | 106 | 0.661313 | 3.923288 | false | true | false | false |
team401/2017-Robot-Code
|
src/main/java/org/team401/robot/camera/Camera.kt
|
1
|
1166
|
package org.team401.robot.camera
import edu.wpi.cscore.UsbCamera
import edu.wpi.first.wpilibj.CameraServer
import org.team401.robot.Constants
class Camera(width: Int, height: Int, fps: Int) {
val cameraServer = CameraServer.getInstance()!!
val frontCam: UsbCamera
val backCam: UsbCamera
var frontEnabled: Boolean = true
init {
frontCam = cameraServer.startAutomaticCapture("Front", Constants.CAMERA_FRONT)
frontCam.setResolution(width, height)
frontCam.setFPS(fps)
backCam = cameraServer.startAutomaticCapture("Back", Constants.CAMERA_BACK)
backCam.setResolution(width, height)
backCam.setFPS(fps)
}
fun getCurrentCamera(): UsbCamera {
if (frontEnabled)
return frontCam
return backCam
}
fun switchCamera() {
if (frontEnabled)
switchToBackCamera()
else
switchToFrontCamera()
}
fun switchToBackCamera() {
frontEnabled = false
cameraServer.server.source = backCam
}
fun switchToFrontCamera() {
frontEnabled = true
cameraServer.server.source = frontCam
}
}
|
gpl-3.0
|
5b216e55270c881895a13e75caf09856
| 23.829787 | 86 | 0.656089 | 4.224638 | false | false | false | false |
herbeth1u/VNDB-Android
|
app/src/main/java/com/booboot/vndbandroid/api/SocketPool.kt
|
1
|
857
|
package com.booboot.vndbandroid.api
import com.booboot.vndbandroid.model.vndb.Options
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import javax.net.ssl.SSLSocket
object SocketPool {
const val MAX_SOCKETS = 10
private val SOCKETS = arrayOfNulls<SSLSocket>(MAX_SOCKETS)
private val LOCKS: ConcurrentMap<Int, Int> = ConcurrentHashMap()
var throttleHandlingSocket = -1
fun getSocket(server: VNDBServer, options: Options): SSLSocket? {
server.login(options)
return SOCKETS[options.socketIndex]
}
fun getSocket(socketIndex: Int): SSLSocket? = SOCKETS[socketIndex]
fun setSocket(socketIndex: Int, socket: SSLSocket?) {
SOCKETS[socketIndex] = socket
}
fun getLock(id: Int): Int {
LOCKS.putIfAbsent(id, id)
return LOCKS[id] ?: 0
}
}
|
gpl-3.0
|
fb15f3dc1ff63433661a7d928c185ef1
| 27.6 | 70 | 0.710618 | 3.808889 | false | false | false | false |
ZsemberiDaniel/EgerBusz
|
app/src/main/java/com/zsemberidaniel/egerbuszuj/realm/objects/StopTime.kt
|
1
|
504
|
package com.zsemberidaniel.egerbuszuj.realm.objects
import io.realm.RealmObject
/**
* Created by zsemberi.daniel on 2017. 05. 12..
*/
open class StopTime : RealmObject() {
var trip: Trip? = null
var stop: Stop? = null
var hour: Byte = 0
var minute: Byte = 0
var stopSequence: Int = 0
companion object {
val CN_TRIP = "trip"
val CN_STOP = "stop"
val CN_HOUR = "hour"
val CN_MINUTE = "minute"
val CN_SEQUENCE = "stopSequence"
}
}
|
apache-2.0
|
25b4a88d93607b1809641746212d8174
| 19.16 | 51 | 0.599206 | 3.524476 | false | false | false | false |
openhab/openhab.android
|
mobile/src/main/java/org/openhab/habdroid/util/MjpegInputStream.kt
|
1
|
3110
|
/*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.util
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.DataInputStream
import java.io.IOException
import java.io.InputStream
import java.util.Properties
class MjpegInputStream(stream: InputStream) : DataInputStream(BufferedInputStream(stream, FRAME_MAX_LENGTH)) {
@Throws(IOException::class)
private fun getEndOfSequence(stream: DataInputStream, sequence: ByteArray): Int {
var seqIndex = 0
for (i in 0 until FRAME_MAX_LENGTH) {
val c = stream.readUnsignedByte().toByte()
if (c == sequence[seqIndex]) {
seqIndex++
if (seqIndex == sequence.size) {
return i + 1
}
} else {
seqIndex = 0
}
}
return -1
}
@Throws(IOException::class)
private fun getStartOfSequence(stream: DataInputStream, sequence: ByteArray): Int {
val end = getEndOfSequence(stream, sequence)
return if (end < 0) -1 else end - sequence.size
}
@Throws(IOException::class, NumberFormatException::class)
private fun parseContentLength(headerBytes: ByteArray): Int {
val headerIn = ByteArrayInputStream(headerBytes)
val props = Properties()
try {
props.load(headerIn)
} catch (e: IllegalArgumentException) {
throw IOException("Error loading props", e)
}
return Integer.parseInt(props.getProperty(CONTENT_LENGTH))
}
@Throws(IOException::class)
fun readMjpegFrame(): Bitmap? {
mark(FRAME_MAX_LENGTH)
val headerLen = getStartOfSequence(this, SOI_MARKER)
reset()
if (headerLen < 0) {
return null
}
val header = ByteArray(headerLen)
readFully(header)
val contentLength = try {
parseContentLength(header)
} catch (nfe: NumberFormatException) {
getEndOfSequence(this, EOF_MARKER)
}
reset()
skipBytes(headerLen)
if (contentLength < 0) {
return null
}
val frameData = ByteArray(contentLength)
readFully(frameData)
return BitmapFactory.decodeStream(ByteArrayInputStream(frameData))
}
companion object {
private val SOI_MARKER = byteArrayOf(0xFF.toByte(), 0xD8.toByte())
private val EOF_MARKER = byteArrayOf(0xFF.toByte(), 0xD9.toByte())
private const val HEADER_MAX_LENGTH = 100
private const val FRAME_MAX_LENGTH = 400000 + HEADER_MAX_LENGTH
private const val CONTENT_LENGTH = "Content-Length"
}
}
|
epl-1.0
|
e57c63575e19200c6a8c345e0d0678f3
| 29.792079 | 110 | 0.637942 | 4.481268 | false | false | false | false |
MFlisar/Lumberjack
|
library/src/main/java/com/michaelflisar/lumberjack/T.kt
|
1
|
4817
|
package com.michaelflisar.lumberjack
import com.michaelflisar.lumberjack.data.TimerData
import java.util.*
/**
* Created by Michael on 17.01.2019.
*/
object T {
private val mTimers = HashMap<Any, TimerData>()
private val mEmptyData = TimerData()
// ------------------
// Simple stop watch like time logging
// ------------------
/**
* start a time log accessable (and bound to) the provided key
* and will reset any already existing data bound to that key
*
* @param key the key that this timer should be bound to
* @return true, if another timer has been replaced, false if not
*/
fun start(key: Any): Boolean {
val timerData = clear(key)
mTimers[key] = TimerData().start()
return timerData != null
}
/**
* adds a lap to the timer bound to the provider key
*
* @param key the key that the desired timer is bound to
* @return the last laps duration or null, if key does not exist or timer was stopped already
*/
fun lap(key: Any): Long? {
val data = getTimer(key)
return data.lap()
}
/**
* stops a timer, afterwards you can't add laps any more and the end time is saved as well
*
* @param key the key that the desired timer is bound to
* @return the total duration or null, if key does not exist or timer was stopped already
*/
fun stop(key: Any): Long? {
val data = getTimer(key)
return data.stop()
}
/**
* Clears all data that exists for a given key
*
* @param key the key that the desired timer is bound to
* @return the removed data or null, if key did not exist
*/
fun clear(key: Any): TimerData? {
return mTimers.remove(key)
}
/**
* Checks if a timer is existing
*
* @param key the key that the desired timer is bound to
*/
fun exists(key: Any): Boolean {
return mTimers.containsKey(key)
}
// ------------------
// Convenient action functions with pretty result print as result
// ------------------
/**
* start a time log accessable (and bound to) the provided key
* and will reset any already existing data bound to that key
*
* @param key the key that this timer should be bound to
* @return a logable message that the timer has been started
*/
fun printAndStart(key: Any): String {
val replaced = start(key)
val data = getTimer(key)
return "New timer started at ${data.getStartTime()}${if (replaced) " [old timer has been replaced!]" else ""}"
}
/**
* adds a lap to the timer bound to the provider key
*
* @param key the key that the desired timer is bound to
* @return the last laps duration as a readable string or null, if key does not exist or timer was stopped already
*/
fun printAndLap(key: Any): String {
val lap = lap(key) ?: return "NULL"
return "Lap = " + lap + "ms"
}
/**
* stops a timer
*
* @param key the key that the desired timer is bound to
* @return the total duration as a readable string or null, if key does not exist or timer was stopped already
*/
fun printAndStop(key: Any): String {
val stop = stop(key) ?: return "NULL"
return "Total = " + stop + "ms"
}
/**
* adds a lap to the timer bound to the provider key
*
* @param key the key that the desired timer is bound to
* @return the last laps duration and the total duration as a readable string or null, if key does not exist or timer was stopped already
*/
fun printAndLapTotal(key: Any): String {
val lap = lap(key) ?: return "NULL"
val data = getTimer(key)
val total = data.getTotal() ?: "NULL"
return "Total = " + total + "ms | Lap = " + lap + "ms"
}
fun print(key: Any): String {
if (!exists(key)) {
return "Timer[$key] does not exist!"
}
val data = getTimer(key)
var info = "Started: ${data.wasStarted()}"
data.getLaps()?.size?.let {
info += " | Laps: ${it}"
}
info += " | Total = ${data.getTotal()}ms | Running: ${data.isRunning()}"
return info
}
// ------------------
// getters
// ------------------
fun getStart(key: Any): Long? {
val data = mTimers[key]
return data?.getStart()
}
fun getLaps(key: Any): List<Long>? {
val data = mTimers[key]
return data?.getLaps()
}
fun getEnd(key: Any): Long? {
val data = mTimers[key]
return data?.getEnd()
}
// ------------------
// internal functions - null save
// ------------------
private fun getTimer(key: Any): TimerData = mTimers[key] ?: mEmptyData
}
|
apache-2.0
|
b17706fb3b2ab12dd41c33c13c42723d
| 28.740741 | 141 | 0.572971 | 4.061551 | false | false | false | false |
SchoolPower/SchoolPower-Android
|
app/src/main/java/com/carbonylgroup/schoolpower/activities/TextViewingActivity.kt
|
1
|
3125
|
/**
* Copyright (C) 2019 SchoolPower Studio
*/
package com.carbonylgroup.schoolpower.activities
import android.app.AlertDialog
import android.content.Intent
import android.widget.TextView
import com.carbonylgroup.schoolpower.R
import kotlinx.android.synthetic.main.activity_text_viewing.*
import android.content.Intent.ACTION_SEND
import android.os.StrictMode
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.carbonylgroup.schoolpower.utils.Utils
import java.io.File
import androidx.core.content.FileProvider
class TextViewingActivity : BaseActivity() {
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun initActivity() {
super.initActivity()
setContentView(R.layout.activity_text_viewing)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
this.title = intent.getStringExtra("title")
findViewById<TextView>(R.id.text_viewing_text).text = intent.getStringExtra("text")
if (!intent.getBooleanExtra("shareEnabled", false)) fab.hide()
fab.setOnClickListener { _ ->
val alertDialog =
AlertDialog.Builder(this)
.setAdapter(ArrayAdapter<String>(this, R.layout.simple_list_item,
arrayOf(getString(R.string.share_as_file),
getString(R.string.share_as_text))), null)
.create()
alertDialog.listView.setOnItemClickListener { _: AdapterView<*>, _: View, position: Int, _: Long ->
if (position == 0) shareFile(filesDir.toString() + "/" + Utils.StudentDataFileName)
else sharePlainText(intent.getStringExtra("text"))
alertDialog.dismiss()
}
alertDialog.show()
}
}
private fun shareFile(path: String) {
val intentShareFile = Intent(Intent.ACTION_SEND)
val fileWithinMyDir = File(path)
if (fileWithinMyDir.exists()) {
val uri = FileProvider.getUriForFile(this,
"com.carbonylgroup.schoolpower", fileWithinMyDir)
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
intentShareFile.type = "application/json"
intentShareFile.putExtra(Intent.EXTRA_STREAM, uri)
intentShareFile.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(intentShareFile, getString(R.string.share_as_file)))
}
}
private fun sharePlainText(text: String?) {
val sharingIntent = Intent(ACTION_SEND)
sharingIntent.type = "text/plain"
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, text)
startActivity(Intent.createChooser(sharingIntent, getString(R.string.share_as_text)))
}
}
|
gpl-3.0
|
95ac620ff817fb40a32d71d5729e0d86
| 36.650602 | 111 | 0.65824 | 4.742033 | false | false | false | false |
WijayaPrinting/wp-javafx
|
openpss-client-javafx/src/com/hendraanggrian/openpss/control/Action.kt
|
1
|
1042
|
package com.hendraanggrian.openpss.control
import com.hendraanggrian.openpss.R
import com.jfoenix.controls.JFXButton
import javafx.beans.DefaultProperty
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
import javafx.scene.Node
import javafx.scene.control.Tooltip
import javafx.scene.image.ImageView
import ktfx.getValue
import ktfx.setValue
import ktfx.toBinding
@DefaultProperty("graphic")
class Action @JvmOverloads constructor(text: String? = null, graphic: Node? = null) : JFXButton(null, graphic) {
constructor(text: String? = null, graphicUrl: String? = null) :
this(text, graphicUrl?.let { ImageView(it) })
private val tooltipTextProperty = SimpleStringProperty(text)
fun tooltipTextProperty(): StringProperty = tooltipTextProperty
var tooltipText: String? by tooltipTextProperty
init {
buttonType = ButtonType.FLAT
styleClass += R.style.flat
tooltipProperty().bind(tooltipTextProperty.toBinding { it?.let { Tooltip(it) } })
}
}
|
apache-2.0
|
9f8f3d84f69b516e9e062da5d706905e
| 33.733333 | 112 | 0.763916 | 4.359833 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/widget/ForegroundLinearLayout.kt
|
1
|
6875
|
/*
* ******************************************************************************
* Copyright (c)
* https://gist.github.com/chrisbanes/9091754
* https://github.com/gabrielemariotti/cardslib/blob/master/library-core/src/main/java/it/gmariotti/cardslib/library/view/ForegroundLinearLayout.java
*
* 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.boardgamegeek.ui.widget
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import androidx.core.content.withStyledAttributes
import com.boardgamegeek.R
open class ForegroundLinearLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private var foregroundDrawable: Drawable? = null
private val selfBounds = Rect()
private val overlayBounds = Rect()
private var foregroundGravity = Gravity.FILL
private var isForegroundInPadding = true
private var foregroundBoundsChanged = false
init {
context.withStyledAttributes(attrs, R.styleable.ForegroundLinearLayout, defStyleAttr, defStyleRes) {
foregroundGravity = getInt(R.styleable.BggForegroundLinearLayout_android_foregroundGravity, foregroundGravity)
getDrawable(R.styleable.BggForegroundLinearLayout_android_foreground)?.let { foreground = it }
isForegroundInPadding = getBoolean(R.styleable.BggForegroundLinearLayout_foregroundInsidePadding, true)
}
}
/**
* Describes how the foreground is positioned.
*
* @return foreground gravity.
* @see .setForegroundGravity
*/
override fun getForegroundGravity(): Int {
return foregroundGravity
}
/**
* Describes how the foreground is positioned. Defaults to START and TOP.
*
* @param foregroundGravity See [android.view.Gravity]
* @see .getForegroundGravity
*/
override fun setForegroundGravity(foregroundGravity: Int) {
var gravity = foregroundGravity
if (this.foregroundGravity != gravity) {
if (gravity and Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK == 0) {
gravity = foregroundGravity or Gravity.START
}
if (gravity and Gravity.VERTICAL_GRAVITY_MASK == 0) {
gravity = foregroundGravity or Gravity.TOP
}
this.foregroundGravity = gravity
if (this.foregroundGravity == Gravity.FILL) {
foregroundDrawable?.getPadding(Rect())
}
requestLayout()
}
}
override fun verifyDrawable(who: Drawable): Boolean {
return super.verifyDrawable(who) || who === foregroundDrawable
}
override fun jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState()
foregroundDrawable?.jumpToCurrentState()
}
override fun drawableStateChanged() {
super.drawableStateChanged()
if (foregroundDrawable?.isStateful == true) {
foregroundDrawable?.state = drawableState
}
}
/**
* Supply a Drawable that is to be rendered on top of all of the child
* views in the frame layout. Any padding in the Drawable will be taken
* into account by ensuring that the children are inset to be placed
* inside of the padding area.
*
* @param drawable The Drawable to be drawn on top of the children.
*/
override fun setForeground(drawable: Drawable?) {
if (foregroundDrawable !== drawable) {
foregroundDrawable?.callback = null
unscheduleDrawable(foregroundDrawable)
foregroundDrawable = drawable
if (drawable != null) {
setWillNotDraw(false)
drawable.callback = this
if (drawable.isStateful) drawable.state = drawableState
if (foregroundGravity == Gravity.FILL) {
drawable.getPadding(Rect())
}
} else {
setWillNotDraw(true)
}
requestLayout()
invalidate()
}
}
/**
* Returns the drawable used as the foreground of this FrameLayout. The
* foreground drawable, if non-null, is always drawn on top of the children.
*
* @return A Drawable or null if no foreground was set.
*/
override fun getForeground(): Drawable? {
return foregroundDrawable
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
foregroundBoundsChanged = changed
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
foregroundBoundsChanged = true
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
if (foregroundDrawable != null) {
val foreground = foregroundDrawable
if (foregroundBoundsChanged) {
foregroundBoundsChanged = false
val selfBounds = this.selfBounds
val overlayBounds = this.overlayBounds
val w = right - left
val h = bottom - top
if (isForegroundInPadding) {
selfBounds.set(0, 0, w, h)
} else {
selfBounds.set(paddingLeft, paddingTop, w - paddingRight, h - paddingBottom)
}
Gravity.apply(foregroundGravity, foreground!!.intrinsicWidth, foreground.intrinsicHeight, selfBounds, overlayBounds)
foreground.bounds = overlayBounds
}
foreground!!.draw(canvas)
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun drawableHotspotChanged(x: Float, y: Float) {
super.drawableHotspotChanged(x, y)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
foregroundDrawable?.setHotspot(x, y)
}
}
}
|
gpl-3.0
|
40c48f8fd76a802beb0e9d46d88b2644
| 34.25641 | 151 | 0.629964 | 4.963899 | false | false | false | false |
fossasia/open-event-android
|
app/src/main/java/org/fossasia/openevent/general/auth/AuthViewModel.kt
|
1
|
1800
|
package org.fossasia.openevent.general.auth
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Network
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
class AuthViewModel(
private val authService: AuthService,
private val network: Network,
private val resource: Resource
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableProgress = MutableLiveData<Boolean>()
val progress: LiveData<Boolean> = mutableProgress
val mutableStatus = SingleLiveEvent<Boolean>()
val isUserExists: LiveData<Boolean> = mutableStatus
private val mutableError = SingleLiveEvent<String>()
val error: SingleLiveEvent<String> = mutableError
fun checkUser(email: String) {
if (!network.isNetworkConnected()) {
mutableError.value = resource.getString(R.string.no_internet_message)
return
}
compositeDisposable += authService.checkEmail(email)
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({
mutableStatus.value = !it.result
Timber.d("Success!")
}, {
mutableError.value = resource.getString(R.string.error)
Timber.d(it, "Failed")
})
}
}
|
apache-2.0
|
4c86d685dce88393729bd5129be96a90
| 36.5 | 81 | 0.699444 | 5.084746 | false | false | false | false |
jonninja/node.kt
|
src/main/kotlin/node/express/middleware/CookieParser.kt
|
1
|
714
|
package node.express.middleware
import node.express.Request
import node.express.Response
import node.express.Handler
import node.express.Cookie
import node.express.RouteHandler
/**
* Defines a cookie parser
*/
public fun cookieParser(): RouteHandler.()->Unit {
return {
var cookiesString = req.header("cookie")
var cookieMap = hashMapOf<String, Cookie>()
if (cookiesString != null) {
var pairs = cookiesString!!.split("[;,]".toRegex()).toTypedArray()
pairs.forEach {
val cookie = Cookie.parse(it)
if (!cookieMap.containsKey(cookie.key)) {
cookieMap.put(cookie.key, cookie)
}
}
}
req.attributes.set("cookies", cookieMap)
next()
}
}
|
mit
|
183ff2b1347439be93c8b8047ba06ba1
| 24.535714 | 72 | 0.661064 | 4.011236 | false | false | false | false |
shadowfox-ninja/ShadowUtils
|
shadow-android/src/main/java/tech/shadowfox/shadow/android/common/RxExtentions.kt
|
1
|
1759
|
@file:Suppress("UNUSED")
package tech.shadowfox.shadow.android.common
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import tech.shadowfox.shadow.android.utils.e
/**
* Copyright 2017 Camaron Crowe
*
* 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.
**/
fun <T> Observable<T>.watchOnMain(subScheduler: Scheduler? = null, watcher: (T) -> Unit): Disposable =
observeMain(subScheduler).doOnNext(watcher)
.onErrorResumeNext({ t: Throwable -> e("Error In Observable", t = t); Observable.empty<T>() }).subscribe()
fun <T> Observable<T>.observeMain(subScheduler: Scheduler? = null): Observable<T> = observeOn(AndroidSchedulers.mainThread()).apply {
if(subScheduler != null) subscribeOn(subScheduler)
}
fun <T> Single<T>.observeMain(subScheduler: Scheduler? = null): Single<T> = observeOn(AndroidSchedulers.mainThread()).apply {
if(subScheduler != null) subscribeOn(subScheduler)
}
fun <T> Maybe<T>.observeMain(subScheduler: Scheduler? = null): Maybe<T> = observeOn(AndroidSchedulers.mainThread()).apply {
if(subScheduler != null) subscribeOn(subScheduler)
}
|
apache-2.0
|
c262b29c958b6e2972be2436b8afc09d
| 44.128205 | 133 | 0.750426 | 4.109813 | false | false | false | false |
RoverPlatform/rover-android
|
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/concerns/text/ViewText.kt
|
1
|
3004
|
package io.rover.sdk.experiences.ui.blocks.concerns.text
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Build
import android.text.Layout
import android.view.Gravity
import android.widget.TextView
import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView
import io.rover.sdk.experiences.ui.concerns.ViewModelBinding
/**
* Mixin that binds a text block view model to the relevant parts of a [TextView].
*/
internal class ViewText(
private val textView: TextView,
private val textToSpannedTransformer: RichTextToSpannedTransformer
) : ViewTextInterface {
init {
textView.setLineSpacing(0f, 1.0f)
// we can disable the built-in font padding because we already take font height padding into
// account in our height measurement. If this were left on, an inappropriate gap would be
// left at the top of the text and ironically push the descenders off the bottom (don't
// worry, the ascenders do not appear to be clipped either).
textView.includeFontPadding = false
// This is set to prevent the wrong line spacing being used on android 10+ when StyleSpans are applied
if (Build.VERSION.SDK_INT >= 29) {
textView.isFallbackLineSpacing = false
}
// Experiences app does not wrap text on text blocks. This seems particularly
// important for short, tight blocks.
// Unfortunately, we cannot disable it on Android older than 23.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.hyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE
}
}
override var viewModelBinding: MeasuredBindableView.Binding<TextViewModelInterface>? by ViewModelBinding { binding, _ ->
if (binding != null) {
// TODO: this may be a fair bit of compute at bind-time. But not sure where to put
// memoized android-specific stuff (the Spanned below) because the ViewModel is
// off-limits for Android stuff
val spanned = textToSpannedTransformer.transform(
binding.viewModel.text,
binding.viewModel.boldRelativeToBlockWeight()
)
textView.text = spanned
textView.gravity = when (binding.viewModel.fontAppearance.align) {
Paint.Align.RIGHT -> Gravity.END
Paint.Align.LEFT -> Gravity.START
Paint.Align.CENTER -> Gravity.CENTER_HORIZONTAL
} or if (binding.viewModel.centerVertically) Gravity.CENTER_VERTICAL else 0
textView.textSize = binding.viewModel.fontAppearance.fontSize.toFloat()
textView.setTextColor(binding.viewModel.fontAppearance.color)
textView.typeface = Typeface.create(
binding.viewModel.fontAppearance.font.fontFamily, binding.viewModel.fontAppearance.font.fontStyle
)
textView.setSingleLine(binding.viewModel.singleLine)
}
}
}
|
apache-2.0
|
09d247e8286b85f02b3cd7591103cd26
| 41.914286 | 124 | 0.684754 | 4.72327 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies
|
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/powdermaker/PowderMakerRecipe.kt
|
1
|
2347
|
package net.ndrei.teslapoweredthingies.machines.powdermaker
import net.minecraft.item.ItemStack
import net.minecraft.util.ResourceLocation
import net.ndrei.teslacorelib.utils.equalsIgnoreSize
import net.ndrei.teslacorelib.utils.equalsIgnoreSizeAndNBT
import net.ndrei.teslapoweredthingies.common.BaseTeslaRegistryEntry
import net.ndrei.teslapoweredthingies.common.IChancedRecipeOutput
import net.ndrei.teslapoweredthingies.common.IRecipeOutput
class PowderMakerRecipe(name: ResourceLocation, private var input: List<ItemStack>, private var output: List<IRecipeOutput>)
: BaseTeslaRegistryEntry<PowderMakerRecipe>(PowderMakerRecipe::class.java, name) {
fun canProcess(stack: ItemStack)=
this.input.any { it.equalsIgnoreSizeAndNBT(stack) && (stack.count >= it.count) }
fun getInputCount(stack: ItemStack) =
this.input.first { it.equalsIgnoreSizeAndNBT(stack) && (stack.count >= it.count) }.count
fun process(stack: ItemStack): PowderMakerRecipeResult {
val primary = mutableListOf<ItemStack>()
val secondary = mutableListOf<ItemStack>()
val remaining = stack.copy()
val matchingInput = this.input.firstOrNull { it.equalsIgnoreSize(remaining) && (remaining.count >= it.count) }
if (/*this.canProcess(remaining)*/ matchingInput != null) {
remaining.shrink(matchingInput.count)
this.output
.filter { it !is IChancedRecipeOutput }
.map { it.getOutput() }
.filterTo(primary) { !it.isEmpty }
this.output
.filter { it is IChancedRecipeOutput }
.map { it.getOutput() }
.filterTo(secondary) { !it.isEmpty }
}
return PowderMakerRecipeResult(remaining, primary.toTypedArray(), secondary.toTypedArray())
}
fun getPossibleInputs() = this.input
fun getPossibleOutputs() =
this.output
.map { it.getPossibleOutput() }
.filter { !it.isEmpty }
.map { listOf(it) }
.filter { !it.isEmpty() }
.toList()
fun getOutputs()
= this.output.toList()
fun ensureValidOutputs(): List<List<ItemStack>> {
this.output = this.output.filter {
!it.getPossibleOutput().isEmpty
}
return this.getPossibleOutputs()
}
}
|
mit
|
1d3516538bf6c34ff0ef2af5e3400d83
| 35.671875 | 124 | 0.662548 | 4.566148 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.