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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rcgroot/open-gpstracker-ng | studio/base/src/mock/java/nl/sogeti/android/gpstracker/ng/mock/MockGpsStatusController.kt | 1 | 2806 | /*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: René de Groot
** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.mock
import android.os.Handler
import android.os.Looper
import nl.sogeti.android.gpstracker.ng.base.common.controllers.gpsstatus.GpsStatusController
typealias Action = (GpsStatusController.Listener) -> Unit
class MockGpsStatusController(val listener: GpsStatusController.Listener) : GpsStatusController {
private val commands = listOf<Action>(
{ it.onStartListening() },
{ it.onChange(0, 0) },
{ it.onChange(0, 8) },
{ it.onChange(1, 10) },
{ it.onChange(3, 12) },
{ it.onChange(5, 11) },
{ it.onChange(7, 14) },
{ it.onChange(9, 21) },
{ it.onFirstFix() },
{ it.onStopListening() }
)
private var handler: Handler? = null
override fun startUpdates() {
handler = Handler(Looper.getMainLooper())
nextCommand(0)
}
override fun stopUpdates() {
handler = null
}
private fun scheduleNextCommand(i: Int) {
handler?.postDelayed({ nextCommand(i) }, 1500)
}
private fun nextCommand(i: Int) {
handler?.let {
commands[i](listener)
val next = if (i < (commands.count() - 1)) i + 1 else 0
scheduleNextCommand(next)
}
}
}
| gpl-3.0 | 8170a88b246ecbc76b1c668a9232a3e5 | 37.424658 | 97 | 0.578253 | 4.509646 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/attach/BatchProcessingActivity.kt | 2 | 11802 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.attach
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import edu.berkeley.boinc.BOINCActivity
import edu.berkeley.boinc.R
import edu.berkeley.boinc.attach.HintFragment.Companion.HINT_TYPE_CONTRIBUTION
import edu.berkeley.boinc.attach.HintFragment.Companion.HINT_TYPE_PLATFORMS
import edu.berkeley.boinc.attach.HintFragment.Companion.HINT_TYPE_PROJECTWEBSITE
import edu.berkeley.boinc.attach.HintFragment.Companion.newInstance
import edu.berkeley.boinc.attach.ProjectAttachService.Companion.RESULT_READY
import edu.berkeley.boinc.attach.ProjectAttachService.Companion.RESULT_SUCCESS
import edu.berkeley.boinc.attach.ProjectAttachService.LocalBinder
import edu.berkeley.boinc.databinding.AttachProjectBatchProcessingLayoutBinding
import edu.berkeley.boinc.utils.Logging
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class BatchProcessingActivity : AppCompatActivity() {
private lateinit var binding: AttachProjectBatchProcessingLayoutBinding
private var attachService: ProjectAttachService? = null
private var asIsBound = false
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Logging.logVerbose(Logging.Category.GUI_ACTIVITY, "BatchProcessingActivity onCreate")
// setup layout
binding = AttachProjectBatchProcessingLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
// Instantiate a PagerAdapter.
// provides content to pager
val mPagerAdapter = HintPagerAdapter(supportFragmentManager, lifecycle)
binding.hintContainer.adapter = mPagerAdapter
binding.hintContainer.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(arg0: Int) {
adaptHintHeader()
}
})
adaptHintHeader()
doBindService()
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (binding.hintContainer.currentItem == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
finish()
} else {
// Otherwise, select the previous step.
binding.hintContainer.currentItem--
}
}
})
}
override fun onDestroy() {
Logging.logVerbose(Logging.Category.GUI_ACTIVITY, "BatchProcessingActivity onDestroy")
super.onDestroy()
doUnbindService()
}
// triggered by continue button
fun continueClicked(@Suppress("UNUSED_PARAMETER") v: View) {
val conflicts = attachService!!.anyUnresolvedConflicts()
Logging.logDebug(Logging.Category.USER_ACTION, "BatchProcessingActivity.continueClicked: conflicts? $conflicts")
if (conflicts) {
// conflicts occurred, bring up resolution screen
Logging.logDebug(Logging.Category.GUI_ACTIVITY, "attachProject(): conflicts exists, open resolution activity...")
startActivity(Intent(this@BatchProcessingActivity,
BatchConflictListActivity::class.java).apply {
putExtra("conflicts", true)
})
} else {
// everything successful, go back to projects screen and clear history
startActivity(Intent(this, BOINCActivity::class.java).apply {
// add flags to return to main activity and clearing all others and clear the back stack
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
putExtra("targetFragment", R.string.tab_projects) // make activity display projects fragment
})
}
}
// triggered by share button
fun shareClicked(@Suppress("UNUSED_PARAMETER") v: View) {
Logging.logVerbose(Logging.Category.USER_ACTION, "BatchProcessingActivity.shareClicked.")
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
val flag = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
@Suppress("DEPRECATION")
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
} else {
Intent.FLAG_ACTIVITY_NEW_DOCUMENT
}
addFlags(flag)
// Add data to the intent, the receiving app will decide what to do with it.
putExtra(Intent.EXTRA_SUBJECT, getString(R.string.social_invite_content_title))
}
if (Build.MANUFACTURER.equals("Amazon", ignoreCase = true)) {
intent.putExtra(Intent.EXTRA_TEXT, String.format(getString(R.string.social_invite_content_body),
Build.MANUFACTURER, getString(R.string.social_invite_content_url_amazon)))
} else {
intent.putExtra(Intent.EXTRA_TEXT, String.format(getString(R.string.social_invite_content_body),
Build.MANUFACTURER, getString(R.string.social_invite_content_url_google)))
}
startActivity(Intent.createChooser(intent, getString(R.string.social_invite_intent_title)))
}
// adapts header text and icons when hint selection changes
private fun adaptHintHeader() {
val position = binding.hintContainer.currentItem
Logging.logVerbose(Logging.Category.GUI_VIEW, "BatchProcessingActivity.adaptHintHeader position: $position")
val hintText = getString(R.string.attachproject_hints_header) + " ${position + 1}/$NUM_HINTS"
binding.hintHeaderText.text = hintText
var leftVisibility = View.VISIBLE
var rightVisibility = View.VISIBLE
if (position == 0) {
// first element reached
leftVisibility = View.GONE
} else if (position == NUM_HINTS - 1) {
// last element reached
rightVisibility = View.GONE
}
binding.hintHeaderImageLeft.visibility = leftVisibility
binding.hintHeaderImageRight.visibility = rightVisibility
}
// previous image in hint header clicked
fun previousHintClicked(@Suppress("UNUSED_PARAMETER") view: View) {
Logging.logVerbose(Logging.Category.USER_ACTION, "BatchProcessingActivity.previousHintClicked.")
binding.hintContainer.currentItem--
}
// previous image in hint header clicked
fun nextHintClicked(@Suppress("UNUSED_PARAMETER") view: View) {
Logging.logVerbose(Logging.Category.USER_ACTION, "BatchProcessingActivity.nextHintClicked.")
binding.hintContainer.currentItem++
}
private val mASConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
// This is called when the connection with the service has been established, getService returns
// the Monitor object that is needed to call functions.
attachService = (service as LocalBinder).service
asIsBound = true
// start attaching projects
lifecycleScope.launch {
attachProject()
}
}
override fun onServiceDisconnected(className: ComponentName) {
// This should not happen
attachService = null
asIsBound = false
}
}
private fun doBindService() {
// bind to attach service
bindService(Intent(this, ProjectAttachService::class.java), mASConnection,
Service.BIND_AUTO_CREATE)
}
private fun doUnbindService() {
if (asIsBound) {
// Detach existing connection.
unbindService(mASConnection)
asIsBound = false
}
}
private suspend fun attachProject() {
Logging.logDebug(Logging.Category.PROJECTS, "attachProject(): ${attachService!!.numberOfSelectedProjects}" +
" projects to attach....")
// shown while project configs are loaded
binding.attachStatusText.text = getString(R.string.attachproject_login_loading)
withContext(Dispatchers.Default) {
// wait until service is ready
while (!attachService!!.projectConfigRetrievalFinished) {
Logging.logDebug(Logging.Category.PROJECTS, "attachProject(): project config retrieval has" +
" not finished yet, wait...")
delay(1000)
}
Logging.logDebug(Logging.Category.PROJECTS, "attachProject(): project config retrieval finished," +
" continue with attach.")
// attach projects, one at a time
attachService!!.selectedProjects
// skip already tried projects in batch processing
.filter { it.result == RESULT_READY }
.onEach {
Logging.logDebug(Logging.Category.PROJECTS, "attachProject(): trying: ${it.info?.name}")
binding.attachStatusText.text = getString(R.string.attachproject_working_attaching,
it.info?.name)
}
.map { it.lookupAndAttach(false) }
.filter { it != RESULT_SUCCESS }
.forEach { Logging.logError(Logging.Category.PROJECTS, "attachProject() attach returned conflict: $it") }
Logging.logDebug(Logging.Category.PROJECTS, "attachProject(): finished.")
}
binding.attachStatusOngoingWrapper.visibility = View.GONE
binding.continueButton.visibility = View.VISIBLE
binding.shareButton.visibility = View.VISIBLE
}
private inner class HintPagerAdapter constructor(fm: FragmentManager, lc: Lifecycle)
: FragmentStateAdapter(fm, lc) {
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> newInstance(HINT_TYPE_CONTRIBUTION)
1 -> newInstance(HINT_TYPE_PROJECTWEBSITE)
else -> newInstance(HINT_TYPE_PLATFORMS)
}
}
override fun getItemCount(): Int = NUM_HINTS
}
companion object {
private const val NUM_HINTS = 3 // number of available hint screens
}
}
| lgpl-3.0 | a19660d17db82ebd690fa7e8c55ec4cf | 41.301075 | 125 | 0.667514 | 4.992386 | false | false | false | false |
usbpc102/usbBot | src/main/kotlin/usbbot/config/DBMiscFunctions.kt | 1 | 1961 | package usbbot.config
import org.apache.commons.dbutils.ResultSetHandler
fun getHelptext(name: String) : String? =
DatabaseConnection.queryRunner
.query("SELECT helptext FROM command_helptext WHERE name = ?",
MiscResultSetHandlers.helptextHandler,
name)
fun getWatchedCategoriesForGuild(guildID: Long) : Collection<Long> =
DatabaseConnection.queryRunner
.query("SELECT channelid FROM watched_categories WHERE guildid = ?",
MiscResultSetHandlers.longCollection,
guildID)
fun delWatchedForGuild(guildID: Long, category: Long) =
DatabaseConnection.queryRunner
.update("DELETE FROM watched_categories WHERE guildid = ? AND channelid = ?",
guildID, category)
fun addWatchedForGuild(guildID: Long, category: Long) =
DatabaseConnection.queryRunner
.update("INSERT INTO watched_categories (guildid, channelid) VALUES (?, ?)",
guildID, category)
fun isWached(guildID: Long, category: Long) : Int =
DatabaseConnection.queryRunner
.query("SELECT COUNT(*) FROM watched_categories WHERE guildid = ? AND channelid = ?",
MiscResultSetHandlers.singleInt,
guildID, category)
/**
* The Object that contains the The ResultSetHandlers for every Table/Request that dosen't have its own data class
*/
object MiscResultSetHandlers {
val singleInt = ResultSetHandler<Int> {
it.next()
it.getInt(1)
}
val longCollection = ResultSetHandler {
val output = mutableListOf<Long>()
while (it.next()) {
output.add(it.getLong(1))
}
output
}
val helptextHandler = ResultSetHandler<String?> {
if (it.next()) {
it.getString(1)
} else {
null
}
}
} | mit | e93444929e0459a37e4a433bdff95ad1 | 35.333333 | 114 | 0.601224 | 4.830049 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/widget/WidgetSelectionFactory.kt | 1 | 3089 | package treehou.se.habit.ui.widget
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage
import se.treehou.ng.ohcommunicator.connector.models.OHMapping
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.services.IServerHandler
import treehou.se.habit.R
import treehou.se.habit.ui.adapter.WidgetAdapter
import treehou.se.habit.util.logging.Logger
import javax.inject.Inject
class WidgetSelectionFactory @Inject constructor() : WidgetFactory {
@Inject lateinit var logger: Logger
@Inject lateinit var server: OHServer
@Inject lateinit var page: OHLinkedPage
@Inject lateinit var serverHandler: IServerHandler
override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.widget_selection, parent, false)
return SelectionWidgetViewHolder(view)
}
inner class SelectionWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) {
private var lastPosition = -1
private val selectorSpinner: Spinner = view.findViewById(R.id.selectorSpinner)
override fun bind(itemWidget: WidgetAdapter.WidgetItem) {
super.bind(itemWidget)
updateSpinner()
}
private fun updateSpinner() {
selectorSpinner.onItemSelectedListener = null
val mappings = widget.mapping
val mappingAdapter = ArrayAdapter<OHMapping>(context, R.layout.item_text, mappings)
val itemName = widget.item?.name
val itemState = widget.item?.state
selectorSpinner.adapter = mappingAdapter
if(itemState != null) {
for (i in mappings.indices) {
if (mappings[i].command == itemState) {
selectorSpinner.setSelection(i)
lastPosition = i
break
}
}
}
//TODO request value
// Prevents rouge initial fire
selectorSpinner.post({
selectorSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
if (itemName != null && position != lastPosition) {
val mapping = mappings[position]
serverHandler.sendCommand(itemName, mapping.command)
lastPosition = position
}
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
mappingAdapter.notifyDataSetChanged()
})
}
}
companion object {
const val TAG = "WidgetSwitchFactory"
}
} | epl-1.0 | 232a8f7982b85d11697376f4105ed53c | 37.625 | 110 | 0.635157 | 5.30756 | false | false | false | false |
drakeet/MultiType | sample/src/main/kotlin/com/drakeet/multitype/sample/weibo/WeiboActivity.kt | 1 | 3251 | /*
* Copyright (c) 2016-present. Drakeet Xu
*
* 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.drakeet.multitype.sample.weibo
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.MultiTypeAdapter
import com.drakeet.multitype.sample.MenuBaseActivity
import com.drakeet.multitype.sample.R
import com.drakeet.multitype.sample.weibo.content.SimpleImage
import com.drakeet.multitype.sample.weibo.content.SimpleImageViewBinder
import com.drakeet.multitype.sample.weibo.content.SimpleText
import com.drakeet.multitype.sample.weibo.content.SimpleTextViewBinder
import java.util.*
/**
* @author Drakeet Xu
*/
class WeiboActivity : MenuBaseActivity() {
private lateinit var adapter: MultiTypeAdapter
private lateinit var items: MutableList<Any>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
val recyclerView = findViewById<RecyclerView>(R.id.list)
adapter = MultiTypeAdapter()
adapter.register(Weibo::class).to(
SimpleTextViewBinder(),
SimpleImageViewBinder()
).withLinker { _, weibo ->
when (weibo.content) {
is SimpleText -> 0
is SimpleImage -> 1
else -> 0
}
}
recyclerView.adapter = adapter
items = ArrayList()
val user = User("drakeet", R.drawable.avatar_drakeet)
val simpleText = SimpleText("A simple text Weibo: Hello World.")
val simpleImage = SimpleImage(R.drawable.img_10)
for (i in 0..19) {
items.add(Weibo(user, simpleText))
items.add(Weibo(user, simpleImage))
}
adapter.items = items
adapter.notifyDataSetChanged()
loadRemoteData()
}
private fun loadRemoteData() {
val weiboList = WeiboJsonParser.fromJson(
JSON_FROM_SERVICE
.replace("\$avatar", "" + R.drawable.avatar_drakeet)
.replace("\$content", "" + R.drawable.img_00)
)
items = ArrayList(items)
items.addAll(0, weiboList)
adapter.items = items
adapter.notifyDataSetChanged()
}
companion object {
private const val JSON_FROM_SERVICE = """[
{
"content":{
"text":"A simple text Weibo: JSON_FROM_SERVICE.",
"content_type":"simple_text"
},
"createTime":"Just now",
"user":{
"avatar":${"$"}avatar,
"name":"drakeet"
}
},
{
"content":{
"resId":${"$"}content,
"content_type":"simple_image"
},
"createTime":"Just now(JSON_FROM_SERVICE)",
"user":{
"avatar":${"$"}avatar,
"name":"drakeet"
}
}
]"""
}
}
| apache-2.0 | 2956d7a9820090c481fe2c4512e54cda | 28.288288 | 75 | 0.649954 | 4.233073 | false | false | false | false |
ojacquemart/spring-kotlin-euro-bets | src/main/kotlin/org/ojacquemart/eurobets/firebase/management/group/GroupsUpdateScheduler.kt | 2 | 2466 | package org.ojacquemart.eurobets.firebase.management.group
import com.firebase.client.DataSnapshot
import com.firebase.client.FirebaseError
import com.firebase.client.ValueEventListener
import org.ojacquemart.eurobets.firebase.Collections
import org.ojacquemart.eurobets.firebase.config.FirebaseRef
import org.ojacquemart.eurobets.lang.loggerFor
import org.springframework.scheduling.TaskScheduler
import org.springframework.stereotype.Component
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.*
@Component
class GroupsUpdateScheduler(val taskScheduler: TaskScheduler, val groupsUpdater: GroupsUpdater, val ref: FirebaseRef) {
private val log = loggerFor<GroupsUpdateScheduler>()
var updateScheduled = false
fun scheduleUpdate() {
log.debug("Check if groups updated is needed")
if (!updateScheduled) {
updateScheduled = true
ref.firebase.child(Collections.settings).child("dayId")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: FirebaseError?) {
updateScheduled = false
}
override fun onDataChange(p0: DataSnapshot?) {
doUpdateIfDayInGroupPhase(p0?.getValue(Int::class.java))
updateScheduled = false
}
})
}
}
private fun doUpdateIfDayInGroupPhase(dayId: Int?) {
if (dayId != null && isDayInGroupPhase(dayId)) {
log.debug("Current game day id: $dayId")
doScheduleUpdate()
} else {
log.info("No groups update needed")
}
}
private fun isDayInGroupPhase(dayId: Int) = dayId <= MAX_DAY_ID_GROUP_PHASE
private fun doScheduleUpdate() {
val updateDate = getUpdateDate()
log.info("Schedule groups update in $UPDATE_DELAY_IN_MINUTES minutes et $updateDate")
taskScheduler.schedule({
groupsUpdater.update()
}, updateDate)
}
private fun getUpdateDate(): Date {
log.debug("Build update date")
val ldtInDelay = LocalDateTime.now().plusMinutes(UPDATE_DELAY_IN_MINUTES)
return Date.from(ldtInDelay.atZone(ZoneId.systemDefault()).toInstant())
}
companion object {
val UPDATE_DELAY_IN_MINUTES = 15L
val MAX_DAY_ID_GROUP_PHASE = 3
}
} | unlicense | b28d2aec33cc07598844ab277ba05a51 | 31.038961 | 119 | 0.64558 | 4.769826 | false | false | false | false |
Jire/Abendigo | src/main/kotlin/org/abendigo/plugin/Every.kt | 2 | 962 | @file:JvmName("Every")
package org.abendigo.plugin
import org.abendigo.DEBUG
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.MILLISECONDS
import kotlin.concurrent.thread
@JvmOverloads
fun sleep(duration: Long, timeUnit: TimeUnit = MILLISECONDS) {
var ns = timeUnit.toNanos(duration)
val ms = ns / 1000000
ns -= (ms * 1000000)
Thread.sleep(ms, ns.toInt())
}
@JvmOverloads
fun sleep(duration: Int, timeUnit: TimeUnit = MILLISECONDS) = sleep(duration.toLong(), timeUnit)
@JvmOverloads
inline fun <T> every(duration: Long, timeUnit: TimeUnit = MILLISECONDS, crossinline action: () -> T) {
thread {
do {
try {
action()
} catch (t: Throwable) {
if (DEBUG) t.printStackTrace()
}
sleep(duration, timeUnit)
} while (!Thread.interrupted())
}
}
@JvmOverloads
inline fun <T> every(duration: Int, timeUnit: TimeUnit = MILLISECONDS, crossinline action: () -> T): Unit
= every(duration.toLong(), timeUnit, action) | gpl-3.0 | 531d10f32db50d1089323e9b872985d2 | 25.027027 | 105 | 0.716216 | 3.536765 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-CSS-JS/src/main/kotlin/o/katydid/css/styles/builders/KatydidBorderStyleBuilder.kt | 1 | 13401 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package o.katydid.css.styles.builders
import o.katydid.css.colors.Color
import o.katydid.css.measurements.Length
import o.katydid.css.styles.KatydidStyle
import o.katydid.css.types.ELineStyle
import o.katydid.css.types.ELineWidth
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder class for setting border-bottom properties of a given [style] from a nested block.
*/
@KatydidStyleBuilderDsl
class KatydidBorderBottomStyleBuilder(
private val style: KatydidStyle
) {
fun color(value: Color) =
style.borderBottomColor(value)
fun style(value: ELineStyle) =
style.borderBottomStyle(value)
fun width(value: ELineWidth) =
style.borderBottomWidth(value)
fun width(value: Length) =
style.borderBottomWidth(value)
}
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder class for setting border-left properties of a given [style] from a nested block.
*/
@KatydidStyleBuilderDsl
class KatydidBorderLeftStyleBuilder(
private val style: KatydidStyle
) {
fun color(value: Color) =
style.borderLeftColor(value)
fun style(value: ELineStyle) =
style.borderLeftStyle(value)
fun width(value: ELineWidth) =
style.borderLeftWidth(value)
fun width(value: Length) =
style.borderLeftWidth(value)
}
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder class for setting border-right properties of a given [style] from a nested block.
*/
@KatydidStyleBuilderDsl
class KatydidBorderRightStyleBuilder(
private val style: KatydidStyle
) {
fun color(value: Color) =
style.borderRightColor(value)
fun style(value: ELineStyle) =
style.borderRightStyle(value)
fun width(value: ELineWidth) =
style.borderRightWidth(value)
fun width(value: Length) =
style.borderRightWidth(value)
}
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder class for setting border-top properties of a given [style] from a nested block.
*/
@KatydidStyleBuilderDsl
class KatydidBorderTopStyleBuilder(
private val style: KatydidStyle
) {
fun color(value: Color) =
style.borderTopColor(value)
fun style(value: ELineStyle) =
style.borderTopStyle(value)
fun width(value: ELineWidth) =
style.borderTopWidth(value)
fun width(value: Length) =
style.borderTopWidth(value)
}
//---------------------------------------------------------------------------------------------------------------------
/**
* Builder class for setting border properties of a given [style] from a nested block.
*/
@KatydidStyleBuilderDsl
class KatydidBorderStyleBuilder(
private val style: KatydidStyle
) {
fun bottom(build: KatydidBorderBottomStyleBuilder.() -> Unit) =
KatydidBorderBottomStyleBuilder(style).build()
fun bottom(lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderBottom(lineStyle, color)
fun bottom(width: ELineWidth, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderBottom(width, lineStyle, color)
fun bottom(width: Length, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderBottom(width, lineStyle, color)
fun color(top: Color, right: Color = top, bottom: Color = top, left: Color = right) =
style.borderColor(top, right, bottom, left)
fun left(build: KatydidBorderLeftStyleBuilder.() -> Unit) =
KatydidBorderLeftStyleBuilder(style).build()
fun left(lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderLeft(lineStyle, color)
fun left(width: ELineWidth, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderLeft(width, lineStyle, color)
fun left(width: Length, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderLeft(width, lineStyle, color)
fun right(build: KatydidBorderRightStyleBuilder.() -> Unit) =
KatydidBorderRightStyleBuilder(style).build()
fun right(lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderRight(lineStyle, color)
fun right(width: ELineWidth, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderRight(width, lineStyle, color)
fun right(width: Length, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderRight(width, lineStyle, color)
fun style(top: ELineStyle, right: ELineStyle = top, bottom: ELineStyle = top, left: ELineStyle = right) =
style.borderStyle(top, right, bottom, left)
fun top(build: KatydidBorderTopStyleBuilder.() -> Unit) =
KatydidBorderTopStyleBuilder(style).build()
fun top(lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderTop(lineStyle, color)
fun top(width: ELineWidth, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderTop(width, lineStyle, color)
fun top(width: Length, lineStyle: ELineStyle? = null, color: Color? = null) =
style.borderTop(width, lineStyle, color)
fun width(top: ELineWidth, right: ELineWidth = top, bottom: ELineWidth = top, left: ELineWidth = right) =
style.borderWidth(top, right, bottom, left)
fun width(top: Length, right: Length = top, bottom: Length = top, left: Length = right) =
style.borderWidth(top, right, bottom, left)
}
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.border(build: KatydidBorderStyleBuilder.() -> Unit) =
KatydidBorderStyleBuilder(this).build()
fun KatydidStyle.border(style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border", "", style, color)
fun KatydidStyle.border(width: ELineWidth, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border", width, style, color)
fun KatydidStyle.border(width: Length, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border", width, style, color)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderBottom(style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-bottom", "", style, color)
fun KatydidStyle.borderBottom(width: ELineWidth, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-bottom", width, style, color)
fun KatydidStyle.borderBottom(width: Length, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-bottom", width, style, color)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderBottomColor(value: Color) =
setProperty("border-bottom-color", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderBottomStyle(value: ELineStyle) =
setProperty("border-bottom-style", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderBottomWidth(value: ELineWidth) =
setProperty("border-bottom-width", "$value")
fun KatydidStyle.borderBottomWidth(value: Length) =
setProperty("border-bottom-width", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderColor(top: Color, right: Color = top, bottom: Color = top, left: Color = right) =
setBoxProperty("border-color", top, right, bottom, left)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderLeft(style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-left", "", style, color)
fun KatydidStyle.borderLeft(width: ELineWidth, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-left", width, style, color)
fun KatydidStyle.borderLeft(width: Length, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-left", width, style, color)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderLeftColor(value: Color) =
setProperty("border-left-color", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderLeftStyle(value: ELineStyle) =
setProperty("border-left-style", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderLeftWidth(value: ELineWidth) =
setProperty("border-left-width", "$value")
fun KatydidStyle.borderLeftWidth(value: Length) =
setProperty("border-left-width", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderRight(style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-right", "", style, color)
fun KatydidStyle.borderRight(width: ELineWidth, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-right", width, style, color)
fun KatydidStyle.borderRight(width: Length, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-right", width, style, color)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderRightColor(value: Color) =
setProperty("border-right-color", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderRightStyle(value: ELineStyle) =
setProperty("border-right-style", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderRightWidth(value: ELineWidth) =
setProperty("border-right-width", "$value")
fun KatydidStyle.borderRightWidth(value: Length) =
setProperty("border-right-width", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderStyle(top: ELineStyle, right: ELineStyle = top, bottom: ELineStyle = top, left: ELineStyle = right) =
setBoxProperty("border-style", top, right, bottom, left)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderTop(style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-top", "", style, color)
fun KatydidStyle.borderTop(width: ELineWidth, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-top", width, style, color)
fun KatydidStyle.borderTop(width: Length, style: ELineStyle? = null, color: Color? = null) =
setBorderProperty("border-top", width, style, color)
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderTopColor(value: Color) =
setProperty("border-top-color", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderTopStyle(value: ELineStyle) =
setProperty("border-top-style", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderTopWidth(value: ELineWidth) =
setProperty("border-top-width", "$value")
fun KatydidStyle.borderTopWidth(value: Length) =
setProperty("border-top-width", "$value")
//---------------------------------------------------------------------------------------------------------------------
fun KatydidStyle.borderWidth(top: ELineWidth, right: ELineWidth = top, bottom: ELineWidth = top, left: ELineWidth = right) =
setBoxProperty("border-width", top, right, bottom, left)
fun KatydidStyle.borderWidth(top: Length, right: Length = top, bottom: Length = top, left: Length = right) =
setBoxProperty("border-width", top, right, bottom, left)
//---------------------------------------------------------------------------------------------------------------------
private fun <T> KatydidStyle.setBorderProperty(key: String, width: T?, style: ELineStyle?, color: Color?) {
var css = "$width"
if (style != null) {
css += " $style"
}
if (color != null) {
css += " $color"
}
require(css.isNotEmpty()) { "Specify at least one non-null parameter for $key." }
setProperty(key, css.trim())
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 2a758cae3c07b537793f008796a4a017 | 37.179487 | 124 | 0.532498 | 4.844902 | false | false | false | false |
YUKAI/KonashiInspectorForAndroid | app/src/main/java/com/uxxu/konashi/inspector/android/SpiFragment.kt | 1 | 7623 | package com.uxxu.konashi.inspector.android
import android.support.v4.app.Fragment
import android.bluetooth.BluetoothGattCharacteristic
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Button
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.Spinner
import android.widget.Switch
import android.widget.Toast
import com.uxxu.konashi.lib.Konashi
import com.uxxu.konashi.lib.KonashiListener
import com.uxxu.konashi.lib.KonashiManager
import org.jdeferred.DoneCallback
import org.jdeferred.DonePipe
import org.jdeferred.FailCallback
import org.jdeferred.Promise
import java.util.Arrays
import info.izumin.android.bletia.BletiaException
import kotlin.experimental.and
/**
* Created by e10dokup on 12/16/15
*/
class SpiFragment : Fragment() {
private var mKonashiManager: KonashiManager? = null
private var mSpiSwitch: Switch? = null
private var mSpiSpeedSpinner: Spinner? = null
private var mSpiDataEditText: EditText? = null
private var mSpiDataSendButton: Button? = null
private var mSpiResultEditText: EditText? = null
private var mSpiResultClearButton: Button? = null
private var mValue: ByteArray? = null
private val mKonashiListener = object : KonashiListener {
override fun onConnect(manager: KonashiManager) {}
override fun onDisconnect(manager: KonashiManager) {}
override fun onError(manager: KonashiManager, e: BletiaException) {}
override fun onUpdatePioOutput(manager: KonashiManager, value: Int) {}
override fun onUpdateUartRx(manager: KonashiManager, value: ByteArray) {}
override fun onUpdateSpiMiso(manager: KonashiManager, value: ByteArray) {
mValue = value
mSpiResultEditText!!.append(String(mValue!!))
}
override fun onUpdateBatteryLevel(manager: KonashiManager, level: Int) {}
override fun onFindNoDevice(manager: KonashiManager) {}
override fun onConnectOtherDevice(manager: KonashiManager) {}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity!!.title = getString(R.string.title_spi)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_spi, container, false)
initSpiViews(view)
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mKonashiManager = Konashi.getManager()
mKonashiManager!!.addListener(mKonashiListener)
}
override fun onDestroy() {
mKonashiManager!!.removeListener(mKonashiListener)
super.onDestroy()
}
private fun initSpiViews(parent: View) {
mSpiSpeedSpinner = parent.findViewById<View>(R.id.spiSpeedSpinner) as Spinner
mSpiSpeedSpinner!!.setSelection(1)
mSpiSpeedSpinner!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
resetSpi()
}
override fun onNothingSelected(adapterView: AdapterView<*>) {}
}
mSpiSwitch = parent.findViewById<View>(R.id.spiSwitch) as Switch
mSpiSwitch!!.setOnCheckedChangeListener { compoundButton, b -> resetSpi() }
mSpiDataEditText = parent.findViewById<View>(R.id.spiDataEditText) as EditText
mSpiDataSendButton = parent.findViewById<View>(R.id.spiDataSendButton) as Button
mSpiDataSendButton!!.setOnClickListener {
try {
mKonashiManager!!.digitalWrite(Konashi.PIO2, Konashi.LOW)
.then(DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void> { mKonashiManager!!.spiWrite(mSpiDataEditText!!.text.toString().toByteArray()) })
.then(DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void> { mKonashiManager!!.digitalWrite(Konashi.PIO2, Konashi.HIGH) })
.then(DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void> { mKonashiManager!!.spiRead() })
.then { result ->
val data = ByteArray(result.value.size)
for (i in 0 until result.value.size) {
val temp = result.value[i] and 0xff.toByte()
data[i] = temp
}
mSpiResultEditText!!.setText(Arrays.toString(data))
}
.fail { result -> Toast.makeText(activity, result.message, Toast.LENGTH_SHORT).show() }
} catch (e: NullPointerException) {
// TODO: hotfix for https://github.com/YUKAI/konashi-android-sdk/issues/170
noticeForNoSpiDevices()
}
}
mSpiResultEditText = parent.findViewById<View>(R.id.spiResultEditText) as EditText
mSpiResultClearButton = parent.findViewById<View>(R.id.spiResultClearButton) as Button
mSpiResultClearButton!!.setOnClickListener { mSpiResultEditText!!.setText("") }
setEnableSpiViews(false)
}
private fun noticeForNoSpiDevices() {
activity!!.runOnUiThread { Toast.makeText(activity, getString(R.string.message_spi_notSupported), Toast.LENGTH_SHORT).show() }
}
private fun resetSpi() {
if (!mKonashiManager!!.isReady) {
return
}
if (mSpiSwitch!!.isChecked) {
val i = mSpiSpeedSpinner!!.selectedItemPosition
val labels = resources.getStringArray(R.array.spiSpeedLabels)
val label = labels[i]
val speed = Utils.spiLabelToValue(activity!!, label)
try {
mKonashiManager!!.spiConfig(Konashi.SPI_MODE_ENABLE_CPOL0_CPHA0,
Konashi.SPI_BIT_ORDER_LITTLE_ENDIAN, speed)
.then(DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void> { mKonashiManager!!.pinMode(Konashi.PIO2, Konashi.OUTPUT) })
.then(DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void> {
setEnableSpiViews(true)
mKonashiManager!!.digitalWrite(Konashi.PIO2, Konashi.HIGH)
})
.fail { result -> Toast.makeText(activity, result.message, Toast.LENGTH_SHORT).show() }
} catch (e: NullPointerException) {
// TODO: hotfix for https://github.com/YUKAI/konashi-android-sdk/issues/170
noticeForNoSpiDevices()
}
} else {
try {
mKonashiManager!!.spiConfig(Konashi.SPI_MODE_DISABLE, Konashi.SPI_BIT_ORDER_LITTLE_ENDIAN, Konashi.SPI_SPEED_1M)
.then { setEnableSpiViews(false) }
} catch (e: NullPointerException) {
// TODO: hotfix for https://github.com/YUKAI/konashi-android-sdk/issues/170
noticeForNoSpiDevices()
}
}
}
private fun setEnableSpiViews(enable: Boolean) {
mSpiSpeedSpinner!!.isEnabled = enable
mSpiDataEditText!!.isEnabled = enable
mSpiDataSendButton!!.isEnabled = enable
}
}
| apache-2.0 | 71d637484e8c783ff829cc7c26807678 | 40.429348 | 201 | 0.657615 | 4.434555 | false | false | false | false |
oldergod/red | app/src/main/java/com/benoitquenaudon/tvfoot/red/app/domain/libraries/LibrariesAdapter.kt | 1 | 1862 | package com.benoitquenaudon.tvfoot.red.app.domain.libraries
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.benoitquenaudon.tvfoot.red.R
import com.benoitquenaudon.tvfoot.red.databinding.LibraryRowBinding
import io.reactivex.subjects.PublishSubject
import javax.inject.Inject
class LibrariesAdapter @Inject constructor(
val libraries: List<Library>
) : androidx.recyclerview.widget.RecyclerView.Adapter<ViewHolder>() {
val libraryClickObservable: PublishSubject<Library> = PublishSubject.create()
override fun getItemCount(): Int = libraries.size + 1
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (holder is LibraryViewHolder) {
holder.bind(libraries[position - 1]) // adjust for header
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
if (viewType == VIEW_TYPE_HEADER) {
return LibraryHeaderViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.library_header_row, parent, false))
} else if (viewType == VIEW_TYPE_LIBRARY) {
val layoutInflater = LayoutInflater.from(parent.context)
val binding: LibraryRowBinding =
DataBindingUtil.inflate(
layoutInflater,
R.layout.library_row,
parent, false)
return LibraryViewHolder(binding, this)
}
throw IllegalStateException("unknown viewType $viewType")
}
override fun getItemViewType(position: Int): Int {
return if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_LIBRARY
}
fun onClick(library: Library) {
libraryClickObservable.onNext(library)
}
companion object Constant {
const val VIEW_TYPE_HEADER: Int = 0
const val VIEW_TYPE_LIBRARY: Int = 1
}
} | apache-2.0 | 29fac78f41fbc6b273639fc98dc34bc4 | 34.150943 | 98 | 0.736842 | 4.574939 | false | false | false | false |
BilledTrain380/sporttag-psa | app/setup/src/main/kotlin/ch/schulealtendorf/psa/setup/entity/AuthorityEntity.kt | 1 | 2013 | /*
* Copyright (c) 2018 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sporttag PSA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.setup.entity
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.ManyToMany
import javax.persistence.Table
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
@Entity
@Table(name = "AUTHORITY")
data class AuthorityEntity(
@Id
@NotNull
@Size(min = 1, max = 20)
var role: String = "ROLE_USER",
@ManyToMany(mappedBy = "authorities")
var users: Set<UserEntity> = setOf()
)
| gpl-3.0 | db8c5190f5a267ffff3b5c245f6a4192 | 34.140351 | 77 | 0.750874 | 4.252654 | false | false | false | false |
sargunster/PokeKotlin | pokekotlin/src/test/kotlin/me/sargunvohra/lib/pokekotlin/test/model/EncounterTest.kt | 1 | 1544 | package me.sargunvohra.lib.pokekotlin.test.model
import me.sargunvohra.lib.pokekotlin.model.Name
import me.sargunvohra.lib.pokekotlin.model.NamedApiResource
import me.sargunvohra.lib.pokekotlin.test.util.mockClient
import org.junit.Test
import kotlin.test.assertEquals
class EncounterTest {
@Test
fun getEncounterMethod() {
mockClient.getEncounterMethod(5).apply {
assertEquals(5, id)
assertEquals("surf", name)
assertEquals(14, order)
assert(Name(
name = "Surfing",
language = NamedApiResource("en", "language", 9)
) in names)
}
}
@Test
fun getEncounterCondition() {
mockClient.getEncounterCondition(5).apply {
assertEquals(5, id)
assertEquals("radio", name)
assert(NamedApiResource("radio-hoenn", "encounter-condition-value", 15) in values)
assert(Name(
name = "Radio",
language = NamedApiResource("en", "language", 9)
) in names)
}
}
@Test
fun getEncounterConditionValue() {
mockClient.getEncounterConditionValue(5).apply {
assertEquals(5, id)
assertEquals("time-night", name)
assertEquals(NamedApiResource("time", "encounter-condition", 2), condition)
assert(Name(
name = "At night",
language = NamedApiResource("en", "language", 9)
) in names)
}
}
}
| apache-2.0 | a3db2726cca33c95dc816c12bad685f1 | 30.510204 | 94 | 0.577073 | 4.650602 | false | true | false | false |
slartus/4pdaClient-plus | qms/qms-impl/src/main/java/org/softeg/slartus/forpdaplus/qms/impl/screens/threads/QmsContactThreadsFragment.kt | 1 | 8869 | package org.softeg.slartus.forpdaplus.qms.impl.screens.threads
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.RecyclerView
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.launch
import org.softeg.slartus.forpdaplus.core.AppActions
import org.softeg.slartus.forpdaplus.core.interfaces.IOnBackPressed
import org.softeg.slartus.forpdaplus.core_lib.ui.fragments.BaseFragment
import org.softeg.slartus.forpdaplus.qms.impl.R
import org.softeg.slartus.forpdaplus.qms.impl.databinding.FragmentQmsContactThreadsBinding
import org.softeg.slartus.forpdaplus.qms.impl.screens.threads.fingerprints.QmsThreadFingerprint
import org.softeg.slartus.forpdaplus.qms.impl.screens.threads.fingerprints.QmsThreadSelectableFingerprint
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Provider
@AndroidEntryPoint
class QmsContactThreadsFragment :
BaseFragment<FragmentQmsContactThreadsBinding>(FragmentQmsContactThreadsBinding::inflate),
IOnBackPressed {
@Inject
lateinit var appActions: Provider<AppActions>
private val viewModel: QmsContactThreadsViewModel by lazy {
val viewModel: QmsContactThreadsViewModel by viewModels()
viewModel.setArguments(arguments)
viewModel
}
private var threadsAdapter: QmsContactThreadsAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
threadsAdapter = createContactsAdapter().apply {
this.stateRestorationPolicy =
RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
registerForContextMenu(binding.threadsRecyclerView)
binding.swipeToRefresh.setOnRefreshListener {
viewModel.onReloadClick()
}
binding.newThreadFab.setOnClickListener {
viewModel.onNewThreadClick()
}
binding.deleteThreadFab.setOnClickListener {
viewModel.onDeleteSelectionClick()
}
subscribeToViewModel()
binding.threadsRecyclerView.adapter = threadsAdapter
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_qms_threads, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.profile_interlocutor_item -> {
viewModel.onContactProfileClick()
}
}
return super.onOptionsItemSelected(item)
}
private fun subscribeToViewModel() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
viewModel.uiState.collect { state ->
onUiState(state)
}
}
launch {
viewModel.loading.collect {
setLoading(it)
}
}
launch {
viewModel.events.collect {
onEvent(it)
}
}
launch {
viewModel.contact
.filterNotNull()
.collect {
setFragmentResult(
ARG_CONTACT_NICK,
bundleOf(ARG_CONTACT_NICK to it.nick)
)
}
}
launch {
viewModel.selectionMode
.filterNotNull()
.collect {
binding.deleteThreadFab.isVisible = it
binding.newThreadFab.isVisible = !it
}
}
}
}
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
viewModel.onHiddenChanged(hidden)
}
private fun onEvent(event: QmsContactThreadsViewModel.Event) {
viewModel.onEventReceived()
when (event) {
QmsContactThreadsViewModel.Event.Empty -> {
// ignore
}
is QmsContactThreadsViewModel.Event.Error -> Timber.e(event.exception)
is QmsContactThreadsViewModel.Event.ShowQmsThread ->
appActions.get().showQmsThread(
event.contactId,
event.contactNick,
event.threadId,
event.threadTitle
)
is QmsContactThreadsViewModel.Event.ShowContactProfile -> appActions.get()
.showUserProfile(event.contactId, event.contactNick)
is QmsContactThreadsViewModel.Event.ShowNewThread -> appActions.get()
.showNewQmsContactThread(event.contactId, event.contactNick)
is QmsContactThreadsViewModel.Event.ShowConfirmDeleteDialog -> {
AlertDialog.Builder(requireContext())
.setTitle(R.string.confirm_action)
.setMessage(
getString(
R.string.ask_deleting_dialogs,
event.selectedIds.size,
event.userNick
)
).setPositiveButton(
R.string.ok
) { dialog, _ ->
dialog.dismiss()
viewModel.onConfirmDeleteSelectionClick(event.selectedIds)
}
.setNegativeButton(R.string.cancel, null)
.create()
.show()
}
is QmsContactThreadsViewModel.Event.Progress -> {
binding.deleteThreadFab.isEnabled = !event.visible
binding.newThreadFab.isEnabled = !event.visible
binding.progressBcgView.isVisible = event.visible
binding.progressBar.isVisible = event.visible
}
}
}
private fun onUiState(state: QmsContactThreadsViewModel.UiState) {
when (state) {
QmsContactThreadsViewModel.UiState.Initialize -> {
// nothing
}
is QmsContactThreadsViewModel.UiState.Items -> {
threadsAdapter?.submitList(state.items)
binding.emptyTextView.isVisible = state.items.isEmpty()
}
}
}
private fun setLoading(loading: Boolean) {
try {
if (activity == null) return
binding.swipeToRefresh.isRefreshing = loading
} catch (ignore: Throwable) {
Timber.w("TAG", ignore.toString())
}
}
private fun createContactsAdapter() = QmsContactThreadsAdapter(
listOf(
QmsThreadFingerprint(
accentBackground = getAccentBackgroundRes(),
onClickListener = { _, item -> viewModel.onThreadClick(item) },
onLongClickListener = { _, _ ->
viewModel.onLongClickListener()
true
}),
QmsThreadSelectableFingerprint(
accentBackground = getAccentBackgroundRes(),
onClickListener = { _, item ->
viewModel.onThreadSelectableClick(item)
}),
)
)
@DrawableRes
private fun getAccentBackgroundRes(): Int {
return when (viewModel.accentColor) {
QmsContactThreadsViewModel.AccentColor.Blue -> R.drawable.qmsnewblue
QmsContactThreadsViewModel.AccentColor.Gray -> R.drawable.qmsnewgray
else -> R.drawable.qmsnew
}
}
override fun onDestroyView() {
binding.threadsRecyclerView.adapter = null
super.onDestroyView()
}
companion object {
const val ARG_CONTACT_ID = "QmsContactThreadsFragment.CONTACT_ID"
const val ARG_CONTACT_NICK = "QmsContactThreadsFragment.CONTACT_NICK"
}
override fun onBackPressed(): Boolean {
return viewModel.onBack()
}
} | apache-2.0 | a63bfcc892160d85a2ac47fb974000b5 | 35.652893 | 105 | 0.5977 | 5.553538 | false | false | false | false |
syrop/Victor-Events | events/src/main/kotlin/pl/org/seva/events/main/data/firestore/FsBase.kt | 1 | 4001 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.main.data.firestore
import com.google.firebase.firestore.*
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
abstract class FsBase {
private val db = FirebaseFirestore.getInstance()
protected val communities get() = db collection COMMUNITIES
protected val String.admins get() = db collection PRIVATE document this collection COMM_ADMINS
protected val String.events get() = db collection COMMUNITIES document this collection COMM_EVENTS
protected val String.comm get() = db collection COMMUNITIES document this
protected val String.privateComm get() = db collection PRIVATE document this
protected val String.name get() = db collection COMMUNITIES document this collection COMM_NAME
private infix fun CollectionReference.document(ch: String) = this.document(ch)
private infix fun DocumentReference.collection(ch: String) = this.collection(ch)
private infix fun FirebaseFirestore.collection(ref: String) = this.collection(ref)
protected suspend fun DocumentReference.read() = withContext(Dispatchers.IO) {
suspendCancellableCoroutine { continuation: CancellableContinuation<DocumentSnapshot> ->
get().addOnCompleteListener { result ->
if (result.isSuccessful) {
continuation.resume(checkNotNull(result.result))
} else {
continuation.resumeWithException(checkNotNull(result.exception))
}
}
}
}
protected suspend fun Query.read() = withContext(Dispatchers.IO) {
suspendCancellableCoroutine { continuation: CancellableContinuation<List<DocumentSnapshot>> ->
get().addOnCompleteListener { result ->
if (result.isSuccessful) {
continuation.resume(checkNotNull(result.result).documents)
} else {
continuation.resumeWithException(checkNotNull(result.exception))
}
}
}
}
companion object {
/** Root of community-related data that can be read by anyone. */
const val COMMUNITIES = "communities"
/** Root of user-related data that can be read only by logged in users. */
const val PRIVATE = "private"
/** Per community. */
const val COMM_EVENTS = "events"
/** Comm name. */
const val COMM_NAME = "name"
/** Comm description. */
const val COMM_DESC = "desc"
/** May not be null. */
const val EVENT_COMM = "comm"
/** May not be null. */
const val EVENT_NAME = "name"
/** GeoPoint. */
const val EVENT_LOCATION = "location"
/** String representation of ZonedDateTime */
const val EVENT_TIME = "time"
/** Nullable. */
const val EVENT_DESC = "description"
/** Admin e-mails per community. */
const val COMM_ADMINS = "admins"
const val ADMIN_GRANTED = "admin_granted"
}
}
| gpl-3.0 | dc21c8885145ae78659fc73d45fcd576 | 38.22549 | 102 | 0.674831 | 4.837969 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/cachestorage/Domain.kt | 1 | 8760 | package pl.wendigo.chrome.api.cachestorage
import kotlinx.serialization.json.Json
/**
* CacheStorageDomain represents CacheStorage protocol domain request/response operations and events that can be captured.
*
* This API is marked as experimental in protocol definition and can change in the future.
* @link Protocol [CacheStorage](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage) domain documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
class CacheStorageDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain("CacheStorage", """""", connection) {
/**
* Deletes a cache.
*
* @link Protocol [CacheStorage#deleteCache](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteCache) method documentation.
*/
fun deleteCache(input: DeleteCacheRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CacheStorage.deleteCache", Json.encodeToJsonElement(DeleteCacheRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Deletes a cache entry.
*
* @link Protocol [CacheStorage#deleteEntry](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteEntry) method documentation.
*/
fun deleteEntry(input: DeleteEntryRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("CacheStorage.deleteEntry", Json.encodeToJsonElement(DeleteEntryRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Requests cache names.
*
* @link Protocol [CacheStorage#requestCacheNames](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames) method documentation.
*/
fun requestCacheNames(input: RequestCacheNamesRequest): io.reactivex.rxjava3.core.Single<RequestCacheNamesResponse> = connection.request("CacheStorage.requestCacheNames", Json.encodeToJsonElement(RequestCacheNamesRequest.serializer(), input), RequestCacheNamesResponse.serializer())
/**
* Fetches cache entry.
*
* @link Protocol [CacheStorage#requestCachedResponse](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse) method documentation.
*/
fun requestCachedResponse(input: RequestCachedResponseRequest): io.reactivex.rxjava3.core.Single<RequestCachedResponseResponse> = connection.request("CacheStorage.requestCachedResponse", Json.encodeToJsonElement(RequestCachedResponseRequest.serializer(), input), RequestCachedResponseResponse.serializer())
/**
* Requests data from cache.
*
* @link Protocol [CacheStorage#requestEntries](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries) method documentation.
*/
fun requestEntries(input: RequestEntriesRequest): io.reactivex.rxjava3.core.Single<RequestEntriesResponse> = connection.request("CacheStorage.requestEntries", Json.encodeToJsonElement(RequestEntriesRequest.serializer(), input), RequestEntriesResponse.serializer())
}
/**
* Represents request frame that can be used with [CacheStorage#deleteCache](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteCache) operation call.
*
* Deletes a cache.
* @link [CacheStorage#deleteCache](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteCache) method documentation.
* @see [CacheStorageDomain.deleteCache]
*/
@kotlinx.serialization.Serializable
data class DeleteCacheRequest(
/**
* Id of cache for deletion.
*/
val cacheId: CacheId
)
/**
* Represents request frame that can be used with [CacheStorage#deleteEntry](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteEntry) operation call.
*
* Deletes a cache entry.
* @link [CacheStorage#deleteEntry](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteEntry) method documentation.
* @see [CacheStorageDomain.deleteEntry]
*/
@kotlinx.serialization.Serializable
data class DeleteEntryRequest(
/**
* Id of cache where the entry will be deleted.
*/
val cacheId: CacheId,
/**
* URL spec of the request.
*/
val request: String
)
/**
* Represents request frame that can be used with [CacheStorage#requestCacheNames](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames) operation call.
*
* Requests cache names.
* @link [CacheStorage#requestCacheNames](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames) method documentation.
* @see [CacheStorageDomain.requestCacheNames]
*/
@kotlinx.serialization.Serializable
data class RequestCacheNamesRequest(
/**
* Security origin.
*/
val securityOrigin: String
)
/**
* Represents response frame that is returned from [CacheStorage#requestCacheNames](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames) operation call.
* Requests cache names.
*
* @link [CacheStorage#requestCacheNames](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames) method documentation.
* @see [CacheStorageDomain.requestCacheNames]
*/
@kotlinx.serialization.Serializable
data class RequestCacheNamesResponse(
/**
* Caches for the security origin.
*/
val caches: List<Cache>
)
/**
* Represents request frame that can be used with [CacheStorage#requestCachedResponse](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse) operation call.
*
* Fetches cache entry.
* @link [CacheStorage#requestCachedResponse](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse) method documentation.
* @see [CacheStorageDomain.requestCachedResponse]
*/
@kotlinx.serialization.Serializable
data class RequestCachedResponseRequest(
/**
* Id of cache that contains the entry.
*/
val cacheId: CacheId,
/**
* URL spec of the request.
*/
val requestURL: String,
/**
* headers of the request.
*/
val requestHeaders: List<Header>
)
/**
* Represents response frame that is returned from [CacheStorage#requestCachedResponse](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse) operation call.
* Fetches cache entry.
*
* @link [CacheStorage#requestCachedResponse](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse) method documentation.
* @see [CacheStorageDomain.requestCachedResponse]
*/
@kotlinx.serialization.Serializable
data class RequestCachedResponseResponse(
/**
* Response read from the cache.
*/
val response: CachedResponse
)
/**
* Represents request frame that can be used with [CacheStorage#requestEntries](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries) operation call.
*
* Requests data from cache.
* @link [CacheStorage#requestEntries](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries) method documentation.
* @see [CacheStorageDomain.requestEntries]
*/
@kotlinx.serialization.Serializable
data class RequestEntriesRequest(
/**
* ID of cache to get entries from.
*/
val cacheId: CacheId,
/**
* Number of records to skip.
*/
val skipCount: Int? = null,
/**
* Number of records to fetch.
*/
val pageSize: Int? = null,
/**
* If present, only return the entries containing this substring in the path
*/
val pathFilter: String? = null
)
/**
* Represents response frame that is returned from [CacheStorage#requestEntries](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries) operation call.
* Requests data from cache.
*
* @link [CacheStorage#requestEntries](https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries) method documentation.
* @see [CacheStorageDomain.requestEntries]
*/
@kotlinx.serialization.Serializable
data class RequestEntriesResponse(
/**
* Array of object store data entries.
*/
val cacheDataEntries: List<DataEntry>,
/**
* Count of returned entries from this storage. If pathFilter is empty, it
is the count of all entries from this storage.
*/
val returnCount: Double
)
| apache-2.0 | 5a3447ce7e78908108d52e7b65fb7f88 | 38.818182 | 326 | 0.756963 | 4.308903 | false | false | false | false |
stripe/stripe-android | stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/api/dto/CardScanRequests.kt | 1 | 2973 | package com.stripe.android.stripecardscan.framework.api.dto
import com.stripe.android.core.networking.HEADER_AUTHORIZATION
import com.stripe.android.core.networking.HEADER_CONTENT_TYPE
import com.stripe.android.core.networking.StripeRequest
import com.stripe.android.stripecardscan.framework.api.CARD_SCAN_RETRY_STATUS_CODES
import java.io.OutputStream
import java.io.OutputStreamWriter
/**
* A class representing a StripeCardScan's API request.
*/
internal data class CardScanRequest internal constructor(
override val method: Method,
override val retryResponseCodes: Iterable<Int>,
internal val baseUrl: String,
internal val path: String,
internal val stripePublishableKey: String,
internal val encodedPostData: String? = null
) : StripeRequest() {
override val mimeType: MimeType = MimeType.Form
override val url: String
get() {
val fullPath = if (path.startsWith("/")) path else "/$path"
return "$baseUrl$fullPath"
}
override val headers = mapOf(
HEADER_AUTHORIZATION to "Bearer $stripePublishableKey"
)
override var postHeaders: Map<String, String>? = mapOf(
HEADER_CONTENT_TYPE to MimeType.Form.toString()
)
override fun writePostBody(outputStream: OutputStream) {
OutputStreamWriter(outputStream).use {
it.write(encodedPostData)
it.flush()
}
}
override fun toString(): String {
return "${method.code} $url"
}
internal companion object {
fun createGet(
stripePublishableKey: String,
baseUrl: String,
path: String,
retryResponseCodes: Iterable<Int>
): CardScanRequest {
return CardScanRequest(
method = Method.GET,
retryResponseCodes = retryResponseCodes,
baseUrl = baseUrl,
path = path,
stripePublishableKey = stripePublishableKey
)
}
fun createPost(
stripePublishableKey: String,
baseUrl: String,
path: String,
encodedPostData: String,
retryResponseCodes: Iterable<Int>
): CardScanRequest {
return CardScanRequest(
method = Method.POST,
retryResponseCodes = retryResponseCodes,
baseUrl = baseUrl,
path = path,
stripePublishableKey = stripePublishableKey,
encodedPostData = encodedPostData
)
}
}
}
/**
* A class representing a StripeCardScan's request to download a file.
*/
internal data class CardScanFileDownloadRequest(
override val url: String
) : StripeRequest() {
override val method: Method = Method.GET
override val mimeType: MimeType = MimeType.Form
override val retryResponseCodes = CARD_SCAN_RETRY_STATUS_CODES
override val headers: Map<String, String> = mapOf()
}
| mit | 065e2afca24b6df0b348e5fcb0b3b329 | 30.967742 | 83 | 0.639085 | 4.87377 | false | false | false | false |
kittinunf/Fuel | fuel/src/test/kotlin/com/github/kittinunf/fuel/core/requests/CancellableRequestTest.kt | 1 | 6563 | package com.github.kittinunf.fuel.core.requests
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.Handler
import com.github.kittinunf.fuel.core.Headers
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.core.extensions.authentication
import com.github.kittinunf.fuel.test.MockHttpTestCase
import com.google.common.net.MediaType
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.fail
import org.junit.Test
import org.mockserver.model.BinaryBody
import java.io.ByteArrayInputStream
import java.io.File
import java.util.Random
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
class CancellableRequestTest : MockHttpTestCase() {
private fun expectNoResponseCallbackHandler() = object : Handler<ByteArray> {
override fun success(value: ByteArray) { fail("Expected to not hit success path, actual $value") }
override fun failure(error: FuelError) { fail("Expected to not hit failure path, actual $error") }
}
@Test
fun testCancellationDuringSendingRequest() {
val semaphore = Semaphore(0)
mock.chain(
request = mock.request().withMethod(Method.POST.value).withPath("/cancel-during-request"),
response = mock.reflect().withDelay(TimeUnit.MILLISECONDS, 200)
)
val request = Fuel.post(mock.path("cancel-during-request"))
val running = request
.requestProgress { _, _ -> request.tryCancel() }
.body("my-body")
.interrupt { semaphore.release() }
.response(expectNoResponseCallbackHandler())
// Run the request
if (!semaphore.tryAcquire(5, TimeUnit.SECONDS)) {
fail("Expected request to be cancelled via interruption")
}
assertThat(running.isDone, equalTo(true))
assertThat(running.isCancelled, equalTo(true))
}
@Test
fun testCancellationDuringReceivingResponse() {
val manager = FuelManager()
val interruptedSemaphore = Semaphore(0)
val responseWrittenSemaphore = Semaphore(0)
val bytes = ByteArray(10 * manager.progressBufferSize).apply { Random().nextBytes(this) }
val file = File.createTempFile("random-bytes", ".bin")
mock.chain(
request = mock.request().withMethod(Method.GET.value).withPath("/cancel-response"),
response = mock.response().withBody(bytes).withDelay(TimeUnit.MILLISECONDS, 200)
)
val running = manager.download(mock.path("cancel-response"))
.fileDestination { _, _ -> file }
.responseProgress { readBytes, _ ->
responseWrittenSemaphore.release()
Thread.sleep(200)
if (readBytes > 9 * manager.progressBufferSize)
fail("Expected request to be cancelled by now")
}
.interrupt { interruptedSemaphore.release() }
.response(expectNoResponseCallbackHandler())
if (!responseWrittenSemaphore.tryAcquire(3, 5, TimeUnit.SECONDS)) {
fail("Expected body to be at least ${3 * manager.progressBufferSize} bytes")
}
// Cancel while writing body
running.cancel()
// Run the request
if (!interruptedSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
fail("Expected request to be cancelled via interruption")
}
assertThat(running.isDone, equalTo(true))
assertThat(running.isCancelled, equalTo(true))
assertThat("Expected file to be incomplete", file.length() < bytes.size, equalTo(true))
}
// Random Test Failure when interruptSemaphore didn't acquired on 5 secs
@Test
fun testCancellationInline() {
val interruptSemaphore = Semaphore(0)
val bodyReadSemaphore = Semaphore(0)
mock.chain(
request = mock.request().withMethod(Method.POST.value).withPath("/cancel-inline"),
response = mock.reflect().withDelay(TimeUnit.MILLISECONDS, 200)
)
val running = FuelManager()
.request(Method.POST, mock.path("cancel-inline"), listOf("foo" to "bar"))
.authentication().basic("username", "password")
.body(
{ ByteArrayInputStream("my-body".toByteArray()).also { bodyReadSemaphore.release() } },
{ "my-body".length.toLong() }
)
.interrupt { interruptSemaphore.release() }
.response(expectNoResponseCallbackHandler())
if (!bodyReadSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
fail("Expected body to be serialized")
}
running.cancel()
if (!interruptSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
fail("Expected request to be cancelled via interruption")
}
assertThat(running.isDone, equalTo(true))
assertThat(running.isCancelled, equalTo(true))
}
@Test
fun interruptCallback() {
val manager = FuelManager()
val interruptSemaphore = Semaphore(0)
val responseWrittenCallback = Semaphore(0)
val bytes = ByteArray(10 * manager.progressBufferSize).apply { Random().nextBytes(this) }
mock.chain(
request = mock.request().withMethod(Method.GET.value).withPath("/bytes"),
response = mock.response()
.withBody(BinaryBody(bytes, MediaType.OCTET_STREAM))
.withDelay(TimeUnit.MILLISECONDS, 200)
)
val file = File.createTempFile(bytes.toString(), null)
val running = FuelManager()
.download(mock.path("bytes"))
.fileDestination { _, _ -> file }
.header(Headers.CONTENT_TYPE, "application/octet-stream")
.responseProgress { _, _ ->
responseWrittenCallback.release()
Thread.sleep(200)
}
.interrupt { interruptSemaphore.release() }
.response(expectNoResponseCallbackHandler())
if (!responseWrittenCallback.tryAcquire(5, TimeUnit.SECONDS)) {
fail("Expected response to be partially written")
}
running.cancel()
if (!interruptSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
fail("Expected request to be cancelled via interruption")
}
assertThat(running.isDone, equalTo(true))
assertThat(running.isCancelled, equalTo(true))
}
}
| mit | d01e6d4f1d81e715f9773f84f25406b4 | 37.380117 | 106 | 0.64376 | 4.731795 | false | true | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/commands/lang/CommandHighlightingAnnotator.kt | 1 | 2986 | package com.github.jk1.ytplugin.commands.lang
import com.github.jk1.ytplugin.commands.CommandService
import com.github.jk1.ytplugin.commands.CommandService.Companion.SERVICE_KEY
import com.github.jk1.ytplugin.commands.ICommandService
import com.github.jk1.ytplugin.commands.model.CommandAssistResponse
import com.github.jk1.ytplugin.commands.model.CommandHighlightRange
import com.github.jk1.ytplugin.commands.model.YouTrackCommand
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.editor.HighlighterColors.TEXT
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.psi.PsiFile
/**
* Highlights YouTrack command based on the server-residing command parser's response.
* It's main duty is to map highlight range classes and to compute necessary text
* attributes to display the command.
*/
class CommandHighlightingAnnotator : ExternalAnnotator<CommandAssistResponse, List<CommandHighlightRange>>() {
companion object {
private val TEXT_ATTRIBUTES = mapOf<String, TextAttributes>(
"field" to DefaultLanguageHighlighterColors.CONSTANT.defaultAttributes,
"keyword" to DefaultLanguageHighlighterColors.KEYWORD.defaultAttributes,
"string" to DefaultLanguageHighlighterColors.STRING.defaultAttributes,
"error" to HighlighterColors.BAD_CHARACTER.defaultAttributes
)
}
override fun collectInformation(file: PsiFile, editor: Editor, hasErrors: Boolean): CommandAssistResponse {
val component: ICommandService = file.getUserData(SERVICE_KEY)
?: throw IllegalStateException("Command component user data is missing from the PSI file")
val session = file.getUserData(CommandService.ISSUE_KEY)
?: throw IllegalStateException("Command component user data is missing from the PSI file")
return component.suggest(YouTrackCommand(session, file.text, editor.caretModel.offset))
}
override fun doAnnotate(collectedInfo: CommandAssistResponse): List<CommandHighlightRange> {
return collectedInfo.highlightRanges
}
override fun apply(file: PsiFile, ranges: List<CommandHighlightRange>, holder: AnnotationHolder) {
ranges.forEach {
if ("error" == it.styleClass) {
holder.newSilentAnnotation(HighlightSeverity.ERROR).range(it.getTextRange()).create()
} else {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
.range(it.getTextRange())
.enforcedTextAttributes(TEXT_ATTRIBUTES[it.styleClass] ?: TEXT.defaultAttributes)
.create()
}
}
}
} | apache-2.0 | b62be2d199bae7dee28935b8eabba8b1 | 49.627119 | 111 | 0.743135 | 5.018487 | false | false | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/tv/TvPutioFileCardPresenter.kt | 1 | 2547 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.stevenschoen.putionew.tv
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.leanback.widget.ImageCardView
import androidx.leanback.widget.Presenter
import com.squareup.picasso.Picasso
import com.stevenschoen.putionew.R
import com.stevenschoen.putionew.model.files.PutioFile
class TvPutioFileCardPresenter : Presenter() {
companion object {
private const val CARD_WIDTH = 500
private const val CARD_HEIGHT = 176
}
override fun onCreateViewHolder(parent: ViewGroup): Presenter.ViewHolder {
val cardView = ImageCardView(parent.context)
cardView.isFocusable = true
cardView.isFocusableInTouchMode = true
return Presenter.ViewHolder(cardView)
}
override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, item: Any) {
val file = item as PutioFile
val cardView = viewHolder.view as ImageCardView
cardView.titleText = file.name
//cardView.setContentText(PutioUtils.humanReadableByteCount(file.size, false));
cardView.setMainImageDimensions(CARD_WIDTH, CARD_HEIGHT)
val mainImageView = cardView.mainImageView
if (file.isFolder) {
cardView.setMainImageScaleType(ImageView.ScaleType.CENTER_INSIDE)
Picasso.get().cancelRequest(mainImageView)
mainImageView.setImageResource(R.drawable.ic_putio_folder_accent)
} else {
cardView.setMainImageScaleType(ImageView.ScaleType.CENTER_CROP)
Picasso.get().load(file.screenshot).into(mainImageView)
}
if (file.isAccessed) {
cardView.badgeImage = ContextCompat.getDrawable(cardView.context, R.drawable.ic_fileinfo_accessed)
}
}
override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) {
val cardView = viewHolder.view as ImageCardView
// Remove references to images so that the garbage collector can free up memory
cardView.badgeImage = null
cardView.mainImage = null
}
}
| mit | 3127e9378a5fb9cdf96b7de6fba040b9 | 36.455882 | 104 | 0.764036 | 4.468421 | false | false | false | false |
djkovrik/YapTalker | data/src/main/java/com/sedsoftware/yaptalker/data/database/YapTalkerDatabase.kt | 1 | 1059 | package com.sedsoftware.yaptalker.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.sedsoftware.yaptalker.data.database.converter.DateConverter
import com.sedsoftware.yaptalker.data.database.dao.BlacklistedTagDao
import com.sedsoftware.yaptalker.data.database.dao.BlacklistedTopicDao
import com.sedsoftware.yaptalker.data.database.model.BlacklistedTagDbModel
import com.sedsoftware.yaptalker.data.database.model.BlacklistedTopicDbModel
@Database(
entities = [
(BlacklistedTagDbModel::class), (BlacklistedTopicDbModel::class)
],
version = 1,
exportSchema = false
)
@TypeConverters(DateConverter::class)
abstract class YapTalkerDatabase : RoomDatabase() {
companion object {
const val DATABASE_NAME = "yaptalker_db"
const val TAGS_BLACKLIST_TABLE = "blacklist_tags"
const val TOPICS_BLACKLIST_TABLE = "blacklist_topics"
}
abstract fun getTagsDao(): BlacklistedTagDao
abstract fun getTopicsDao(): BlacklistedTopicDao
}
| apache-2.0 | a7662638622ae4a09257dc4d729ccb6c | 34.3 | 76 | 0.783758 | 4.394191 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/chatroom/MessageAdapter.kt | 1 | 2134 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.screens.chatroom
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.recyclerview.widget.RecyclerView
import com.app.playhvz.R
import com.app.playhvz.firebase.classmodels.Message
import com.app.playhvz.firebase.classmodels.Player
class MessageAdapter(
private var items: List<Message>,
val context: Context,
val lifecycleOwner: LifecycleOwner
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var players: Map<String, LiveData<Player>> = mapOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return MessageViewHolder(
LayoutInflater.from(context).inflate(
R.layout.list_item_chat_room_message,
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val message = items[position]
val previousMessage = if (position == 0) {
null
} else {
items[position - 1]
}
(holder as MessageViewHolder).onBind(items[position], players[message.senderId], previousMessage, lifecycleOwner)
}
override fun getItemCount(): Int {
return items.size
}
fun setData(data: List<Message>, players: Map<String, LiveData<Player>>) {
items = data
this.players = players
}
} | apache-2.0 | 9b35fa3bfa4b7810542c190c0d527ef8 | 31.348485 | 121 | 0.697282 | 4.550107 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/alarms/AlarmReceiver.kt | 1 | 5672 | package nerd.tuxmobil.fahrplan.congress.alarms
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_ONE_SHOT
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.annotation.VisibleForTesting
import androidx.core.net.toUri
import info.metadude.android.eventfahrplan.commons.logging.Logging
import nerd.tuxmobil.fahrplan.congress.alarms.AlarmReceiver.AlarmIntentFactory.Companion.ALARM_SESSION
import nerd.tuxmobil.fahrplan.congress.autoupdate.UpdateService
import nerd.tuxmobil.fahrplan.congress.contract.BundleKeys
import nerd.tuxmobil.fahrplan.congress.extensions.withExtras
import nerd.tuxmobil.fahrplan.congress.notifications.NotificationHelper
import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository
import nerd.tuxmobil.fahrplan.congress.schedule.MainActivity.Companion.createLaunchIntent
import nerd.tuxmobil.fahrplan.congress.utils.PendingIntentCompat.FLAG_IMMUTABLE
class AlarmReceiver : BroadcastReceiver() {
companion object {
const val ALARM_UPDATE = "nerd.tuxmobil.fahrplan.congress.ALARM_UPDATE"
private const val ALARM_DISMISSED = "nerd.tuxmobil.fahrplan.congress.ALARM_DISMISSED"
private const val LOG_TAG = "AlarmReceiver"
private const val BUNDLE_KEY_NOTIFICATION_ID = "BUNDLE_KEY_NOTIFICATION_ID"
private const val INVALID_NOTIFICATION_ID = -1
private const val DEFAULT_REQUEST_CODE = 0
/**
* Returns a unique [Intent] to delete the data associated with the
* given session alarm [notificationId].
* The [Intent] is composed with a fake data URI to comply with the uniqueness rules
* defined by [Intent.filterEquals].
*/
private fun createDeleteNotificationIntent(context: Context, notificationId: Int) =
Intent(context, AlarmReceiver::class.java).apply {
action = ALARM_DISMISSED
putExtra(BUNDLE_KEY_NOTIFICATION_ID, notificationId)
data = "fake://$notificationId".toUri()
}
}
private val logging = Logging.get()
override fun onReceive(context: Context, intent: Intent) {
logging.d(LOG_TAG, "Received alarm = ${intent.action}.")
when (intent.action) {
ALARM_DISMISSED -> onSessionAlarmNotificationDismissed(intent)
ALARM_UPDATE -> UpdateService.start(context)
ALARM_SESSION -> {
val sessionId = intent.getStringExtra(BundleKeys.ALARM_SESSION_ID)!!
val day = intent.getIntExtra(BundleKeys.ALARM_DAY, 1)
val start = intent.getLongExtra(BundleKeys.ALARM_START_TIME, System.currentTimeMillis())
val title = intent.getStringExtra(BundleKeys.ALARM_TITLE)!!
logging.report(LOG_TAG, "sessionId = $sessionId, intent = $intent")
//Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
val uniqueNotificationId = AppRepository.createSessionAlarmNotificationId(sessionId)
val launchIntent = createLaunchIntent(context, sessionId, day, uniqueNotificationId)
val contentIntent = PendingIntent.getActivity(
context,
DEFAULT_REQUEST_CODE,
launchIntent,
FLAG_ONE_SHOT or FLAG_IMMUTABLE
)
val notificationHelper = NotificationHelper(context)
val soundUri = AppRepository.readAlarmToneUri()
val deleteNotificationIntent = createDeleteNotificationIntent(context, uniqueNotificationId)
val deleteBroadcastIntent = PendingIntent.getBroadcast(
context,
DEFAULT_REQUEST_CODE,
deleteNotificationIntent,
FLAG_IMMUTABLE
)
val builder = notificationHelper.getSessionAlarmNotificationBuilder(
contentIntent, title, start, soundUri, deleteBroadcastIntent
)
val isInsistentAlarmsEnabled = AppRepository.readInsistentAlarmsEnabled()
notificationHelper.notify(uniqueNotificationId, builder, isInsistentAlarmsEnabled)
AppRepository.deleteAlarmForSessionId(sessionId)
}
}
}
private fun onSessionAlarmNotificationDismissed(intent: Intent) {
val notificationId = intent.getIntExtra(BUNDLE_KEY_NOTIFICATION_ID, INVALID_NOTIFICATION_ID)
check(notificationId != INVALID_NOTIFICATION_ID) {
"Bundle does not contain NOTIFICATION_ID."
}
AppRepository.deleteSessionAlarmNotificationId(notificationId)
}
internal class AlarmIntentFactory(
val context: Context,
val sessionId: String,
val title: String,
val day: Int,
val startTime: Long,
) {
fun getIntent(isAddAlarmIntent: Boolean) = Intent(context, AlarmReceiver::class.java)
.withExtras(
BundleKeys.ALARM_SESSION_ID to sessionId,
BundleKeys.ALARM_DAY to day,
BundleKeys.ALARM_TITLE to title,
BundleKeys.ALARM_START_TIME to startTime
).apply {
action = if (isAddAlarmIntent) ALARM_SESSION else ALARM_DELETE
data = "alarm://$sessionId".toUri()
}
companion object {
@VisibleForTesting
const val ALARM_SESSION = "nerd.tuxmobil.fahrplan.congress.ALARM_SESSION"
@VisibleForTesting
const val ALARM_DELETE = "de.machtnix.fahrplan.ALARM"
}
}
}
| apache-2.0 | 760061c59a19fc2e8b43011405e8e057 | 42.29771 | 108 | 0.663787 | 5.114518 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/stubs/index/StubKeys.kt | 2 | 1400 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.stubs.index
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.stubs.StubIndexKey
import com.tang.intellij.lua.comment.psi.LuaDocTagAlias
import com.tang.intellij.lua.comment.psi.LuaDocTagClass
import com.tang.intellij.lua.psi.LuaClassMember
object StubKeys {
val CLASS_MEMBER = StubIndexKey.createIndexKey<Int, LuaClassMember>("lua.index.class.member")
val SHORT_NAME = StubIndexKey.createIndexKey<String, NavigatablePsiElement>("lua.index.short_name")
val CLASS = StubIndexKey.createIndexKey<String, LuaDocTagClass>("lua.index.class")
val SUPER_CLASS = StubIndexKey.createIndexKey<String, LuaDocTagClass>("lua.index.super_class")
val ALIAS = StubIndexKey.createIndexKey<String, LuaDocTagAlias>("lua.index.alias")
}
| apache-2.0 | 2d260cfff37dbce3b1c4b030cd3b9730 | 44.16129 | 103 | 0.774286 | 4.022989 | false | false | false | false |
inorichi/tachiyomi-extensions | src/all/batoto/src/eu/kanade/tachiyomi/extension/all/batoto/BatoToUrlActivity.kt | 1 | 1435 | package eu.kanade.tachiyomi.extension.all.batoto
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
class BatoToUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val host = intent?.data?.host
val pathSegments = intent?.data?.pathSegments
if (host != null && pathSegments != null) {
val query = fromGuya(pathSegments)
if (query == null) {
Log.e("BatoToUrlActivity", "Unable to parse URI from intent $intent")
finish()
exitProcess(1)
}
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", query)
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("BatoToUrlActivity", e.toString())
}
}
finish()
exitProcess(0)
}
private fun fromGuya(pathSegments: MutableList<String>): String? {
return if (pathSegments.size >= 2) {
val id = pathSegments[1]
"ID:$id"
} else {
null
}
}
}
| apache-2.0 | 9d02e8a60fceb8ab2e048b2df307ed22 | 27.137255 | 85 | 0.567247 | 4.83165 | false | false | false | false |
hpedrorodrigues/GZMD | app/src/main/kotlin/com/hpedrorodrigues/gzmd/manager/NestedScrollViewManager.kt | 1 | 3734 | /*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd.manager
import android.os.Handler
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.support.v4.widget.NestedScrollView
import com.hpedrorodrigues.gzmd.listener.AppBarStateChangeListener
class NestedScrollViewManager(val nestedScrollView: NestedScrollView,
val appBar: AppBarLayout,
val coordinator: CoordinatorLayout,
val scrollSpeed: Long) {
private var wasFullScrolled = false
var cancelAutoScroll = false
set(value) {
field = value
if (!running && !value) {
enableAutoScroll()
}
}
var running = false
private set
var isAppBarExpanded = false
val appBarStateChangedListener = object : AppBarStateChangeListener() {
override fun onStateChanged(appBarLayout: AppBarLayout, state: State) {
isAppBarExpanded = !state.equals(State.COLLAPSED)
}
}
private fun formatScrollSpeed() = 200 - scrollSpeed
private fun registerAppBarScrollListener() = appBar
.addOnOffsetChangedListener(appBarStateChangedListener)
fun enableAutoScroll() {
registerAppBarScrollListener()
running = true
nestedScrollView.isSmoothScrollingEnabled = true
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
if (isAppBarExpanded) {
scrollWithCoordinatorLayout()
} else {
scrollOnlyNestedView()
}
if (isFullScrolled()) {
wasFullScrolled = true
}
if (!cancelAutoScroll) {
handler.postDelayed(this, formatScrollSpeed())
} else {
running = false
}
}
}, formatScrollSpeed())
}
fun scrollWithCoordinatorLayout() {
(appBar.layoutParams as CoordinatorLayout.LayoutParams)
.behavior
?.onNestedPreScroll(coordinator, appBar, nestedScrollView, 0, 1, intArrayOf(0, 0))
}
fun scrollOnlyNestedView() {
val targetScroll = nestedScrollView.scrollY + 1
nestedScrollView.scrollTo(0, targetScroll)
nestedScrollView.isSmoothScrollingEnabled = true
ViewCompat.postOnAnimationDelayed(nestedScrollView, object : Runnable {
override fun run() {
ViewCompat.postOnAnimation(nestedScrollView, this)
}
}, formatScrollSpeed())
}
fun isFullScrolled(): Boolean {
var height = 0
if (nestedScrollView.childCount > 0) {
val childView = nestedScrollView.getChildAt(nestedScrollView.childCount - 1)
height = childView.bottom + nestedScrollView.paddingBottom
}
height -= nestedScrollView.height
return height.equals(nestedScrollView.scrollY)
}
} | apache-2.0 | 0d26eff52945420c28437d6736ea4754 | 30.125 | 98 | 0.630423 | 5.334286 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/search/options/reference/CustomConstraintModuleUriReferenceContributor.kt | 1 | 2797 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.search.options.reference
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.ElementPatternCondition
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReferenceContributor
import com.intellij.psi.PsiReferenceRegistrar
import com.intellij.util.ProcessingContext
import uk.co.reecedunn.intellij.plugin.marklogic.search.options.SearchOptions
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmAttributeNode
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementNode
import uk.co.reecedunn.intellij.plugin.xpm.optree.item.localName
import uk.co.reecedunn.intellij.plugin.xpm.optree.item.namespaceUri
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDirAttributeValue
import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryElementType
import uk.co.reecedunn.intellij.plugin.xquery.psi.reference.ModuleUriReference
class CustomConstraintModuleUriReferenceContributor : PsiReferenceContributor(), ElementPattern<PsiElement> {
// region PsiReferenceContributor
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
registrar.registerReferenceProvider(this, ModuleUriReference)
}
// endregion
// region ElementPattern
override fun accepts(o: Any?): Boolean {
val value = o as? XQueryDirAttributeValue ?: return false
val node = value.parent as? XdmAttributeNode ?: return false
val parent = node.parentNode as? XdmElementNode ?: return false
if (parent.namespaceUri != SearchOptions.NAMESPACE) return false
return when (parent.localName) {
"parse" -> node.localName == "at"
"start-facet" -> node.localName == "at"
"finish-facet" -> node.localName == "at"
else -> false
}
}
override fun accepts(o: Any?, context: ProcessingContext?): Boolean = accepts(o)
override fun getCondition(): ElementPatternCondition<PsiElement> = PATTERN.condition
companion object {
private val PATTERN = PlatformPatterns.psiElement(XQueryElementType.DIR_ATTRIBUTE_VALUE)
}
// endregion
}
| apache-2.0 | af786acac4497c902b67307dc2f57629 | 40.746269 | 109 | 0.758312 | 4.439683 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | my_library_framework/src/main/java/com/vmenon/mpo/my_library/framework/MpoRetrofitApiShowUpdateDataSource.kt | 1 | 1422 | package com.vmenon.mpo.my_library.framework
import com.vmenon.mpo.common.framework.retrofit.MediaPlayerOmegaRetrofitService
import com.vmenon.mpo.my_library.data.ShowUpdateDataSource
import com.vmenon.mpo.my_library.domain.EpisodeModel
import com.vmenon.mpo.my_library.domain.ShowModel
import com.vmenon.mpo.my_library.domain.ShowUpdateModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class MpoRetrofitApiShowUpdateDataSource(
private val mediaPlayerOmegaRetrofitService: MediaPlayerOmegaRetrofitService
) : ShowUpdateDataSource {
override suspend fun getShowUpdate(show: ShowModel): ShowUpdateModel? =
withContext(Dispatchers.IO) {
mediaPlayerOmegaRetrofitService.getPodcastUpdate(
show.feedUrl,
show.lastEpisodePublished
).map { episode ->
ShowUpdateModel(
newEpisode = EpisodeModel(
name = episode.name,
description = episode.description,
artworkUrl = episode.artworkUrl,
downloadUrl = episode.downloadUrl,
lengthInSeconds = episode.length,
published = episode.published,
type = episode.type,
show = show
)
)
}.blockingGet()
}
} | apache-2.0 | 7441ed3f090964b637d55d2935d9a053 | 40.852941 | 80 | 0.627989 | 5.366038 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/crash/CrashScreen.kt | 1 | 4991 | package eu.kanade.presentation.crash
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.BugReport
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.kanade.presentation.util.horizontalPadding
import eu.kanade.presentation.util.verticalPadding
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.CrashLogUtil
import kotlinx.coroutines.launch
@Composable
fun CrashScreen(
exception: Throwable?,
onRestartClick: () -> Unit,
) {
val scope = rememberCoroutineScope()
val context = LocalContext.current
Scaffold(
contentWindowInsets = WindowInsets.systemBars,
bottomBar = {
val strokeWidth = Dp.Hairline
val borderColor = MaterialTheme.colorScheme.outline
Column(
modifier = Modifier
.background(MaterialTheme.colorScheme.surface)
.drawBehind {
drawLine(
borderColor,
Offset(0f, 0f),
Offset(size.width, 0f),
strokeWidth.value,
)
}
.padding(WindowInsets.navigationBars.asPaddingValues())
.padding(horizontal = horizontalPadding, vertical = verticalPadding),
verticalArrangement = Arrangement.spacedBy(verticalPadding),
) {
Button(
onClick = {
scope.launch {
CrashLogUtil(context).dumpLogs()
}
},
modifier = Modifier.fillMaxWidth(),
) {
Text(text = stringResource(id = R.string.pref_dump_crash_logs))
}
OutlinedButton(
onClick = onRestartClick,
modifier = Modifier.fillMaxWidth(),
) {
Text(text = stringResource(R.string.crash_screen_restart_application))
}
}
},
) { paddingValues ->
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.padding(paddingValues)
.padding(top = 56.dp)
.padding(horizontal = horizontalPadding),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(
imageVector = Icons.Outlined.BugReport,
contentDescription = null,
modifier = Modifier
.size(64.dp),
)
Text(
text = stringResource(R.string.crash_screen_title),
style = MaterialTheme.typography.titleLarge,
)
Text(
text = stringResource(R.string.crash_screen_description, stringResource(id = R.string.app_name)),
modifier = Modifier
.padding(vertical = verticalPadding),
)
Box(
modifier = Modifier
.padding(vertical = verticalPadding)
.clip(MaterialTheme.shapes.small)
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceVariant),
) {
Text(
text = exception.toString(),
modifier = Modifier
.padding(all = verticalPadding),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
| apache-2.0 | 14a84c9f27e2b9f75e058079cb9ff1f2 | 38.611111 | 113 | 0.609497 | 5.564103 | false | false | false | false |
da1z/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt | 3 | 19659 | /*
* 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.ide.ui
import com.intellij.ide.WelcomeWizardUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ComponentTreeEventDispatcher
import com.intellij.util.PlatformUtils
import com.intellij.util.SystemProperties
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.UIUtil.isValidFont
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SerializationFilter
import com.intellij.util.xmlb.XmlSerializerUtil
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.Transient
import java.awt.Font
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
import javax.swing.SwingConstants
@State(name = "UISettings", storages = arrayOf(Storage("ui.lnf.xml")))
class UISettings : BaseState(), PersistentStateComponent<UISettings> {
// These font properties should not be set in the default ctor,
// so that to make the serialization logic judge if a property
// should be stored or shouldn't by the provided filter only.
@get:Property(filter = FontFilter::class)
@get:OptionTag("FONT_FACE")
var fontFace by string()
@get:Property(filter = FontFilter::class)
@get:OptionTag("FONT_SIZE")
var fontSize by storedProperty(defFontSize)
@get:Property(filter = FontFilter::class)
@get:OptionTag("FONT_SCALE")
var fontScale by storedProperty(0f)
@get:OptionTag("RECENT_FILES_LIMIT") var recentFilesLimit by storedProperty(50)
@get:OptionTag("CONSOLE_COMMAND_HISTORY_LIMIT") var consoleCommandHistoryLimit by storedProperty(300)
@get:OptionTag("OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE") var overrideConsoleCycleBufferSize by storedProperty(false)
@get:OptionTag("CONSOLE_CYCLE_BUFFER_SIZE_KB") var consoleCycleBufferSizeKb by storedProperty(1024)
@get:OptionTag("EDITOR_TAB_LIMIT") var editorTabLimit by storedProperty(10)
@get:OptionTag("REUSE_NOT_MODIFIED_TABS") var reuseNotModifiedTabs by storedProperty(false)
@get:OptionTag("ANIMATE_WINDOWS") var animateWindows by storedProperty(true)
@get:OptionTag("SHOW_TOOL_WINDOW_NUMBERS") var showToolWindowsNumbers by storedProperty(true)
@get:OptionTag("HIDE_TOOL_STRIPES") var hideToolStripes by storedProperty(true)
@get:OptionTag("WIDESCREEN_SUPPORT") var wideScreenSupport by storedProperty(false)
@get:OptionTag("LEFT_HORIZONTAL_SPLIT") var leftHorizontalSplit by storedProperty(false)
@get:OptionTag("RIGHT_HORIZONTAL_SPLIT") var rightHorizontalSplit by storedProperty(false)
@get:OptionTag("SHOW_EDITOR_TOOLTIP") var showEditorToolTip by storedProperty(true)
@get:OptionTag("SHOW_MEMORY_INDICATOR") var showMemoryIndicator by storedProperty(false)
@get:OptionTag("ALLOW_MERGE_BUTTONS") var allowMergeButtons by storedProperty(true)
@get:OptionTag("SHOW_MAIN_TOOLBAR") var showMainToolbar by storedProperty(false)
@get:OptionTag("SHOW_STATUS_BAR") var showStatusBar by storedProperty(true)
@get:OptionTag("SHOW_NAVIGATION_BAR") var showNavigationBar by storedProperty(true)
@get:OptionTag("ALWAYS_SHOW_WINDOW_BUTTONS") var alwaysShowWindowsButton by storedProperty(false)
@get:OptionTag("CYCLE_SCROLLING") var cycleScrolling by storedProperty(true)
@get:OptionTag("SCROLL_TAB_LAYOUT_IN_EDITOR") var scrollTabLayoutInEditor by storedProperty(true)
@get:OptionTag("HIDE_TABS_IF_NEED") var hideTabsIfNeed by storedProperty(true)
@get:OptionTag("SHOW_CLOSE_BUTTON") var showCloseButton by storedProperty(true)
@get:OptionTag("EDITOR_TAB_PLACEMENT") var editorTabPlacement by storedProperty(1)
@get:OptionTag("HIDE_KNOWN_EXTENSION_IN_TABS") var hideKnownExtensionInTabs by storedProperty(false)
@get:OptionTag("SHOW_ICONS_IN_QUICK_NAVIGATION") var showIconInQuickNavigation by storedProperty(true)
@get:OptionTag("CLOSE_NON_MODIFIED_FILES_FIRST") var closeNonModifiedFilesFirst by storedProperty(false)
@get:OptionTag("ACTIVATE_MRU_EDITOR_ON_CLOSE") var activeMruEditorOnClose by storedProperty(false)
// TODO[anton] consider making all IDEs use the same settings
@get:OptionTag("ACTIVATE_RIGHT_EDITOR_ON_CLOSE") var activeRightEditorOnClose by storedProperty(PlatformUtils.isAppCode())
@get:OptionTag("IDE_AA_TYPE") var ideAAType by storedProperty(AntialiasingType.SUBPIXEL)
@get:OptionTag("EDITOR_AA_TYPE") var editorAAType by storedProperty(AntialiasingType.SUBPIXEL)
@get:OptionTag("COLOR_BLINDNESS") var colorBlindness by storedProperty<ColorBlindness?>()
@get:OptionTag("MOVE_MOUSE_ON_DEFAULT_BUTTON") var moveMouseOnDefaultButton by storedProperty(false)
@get:OptionTag("ENABLE_ALPHA_MODE") var enableAlphaMode by storedProperty(false)
@get:OptionTag("ALPHA_MODE_DELAY") var alphaModeDelay by storedProperty(1500)
@get:OptionTag("ALPHA_MODE_RATIO") var alphaModeRatio by storedProperty(0.5f)
@get:OptionTag("MAX_CLIPBOARD_CONTENTS") var maxClipboardContents by storedProperty(5)
@get:OptionTag("OVERRIDE_NONIDEA_LAF_FONTS") var overrideLafFonts by storedProperty(false)
@get:OptionTag("SHOW_ICONS_IN_MENUS") var showIconsInMenus by storedProperty(!PlatformUtils.isAppCode())
// IDEADEV-33409, should be disabled by default on MacOS
@get:OptionTag("DISABLE_MNEMONICS") var disableMnemonics by storedProperty(SystemInfo.isMac)
@get:OptionTag("DISABLE_MNEMONICS_IN_CONTROLS") var disableMnemonicsInControls by storedProperty(false)
@get:OptionTag("USE_SMALL_LABELS_ON_TABS") var useSmallLabelsOnTabs by storedProperty(SystemInfo.isMac)
@get:OptionTag("MAX_LOOKUP_WIDTH2") var maxLookupWidth by storedProperty(500)
@get:OptionTag("MAX_LOOKUP_LIST_HEIGHT") var maxLookupListHeight by storedProperty(11)
@get:OptionTag("HIDE_NAVIGATION_ON_FOCUS_LOSS") var hideNavigationOnFocusLoss by storedProperty(true)
@get:OptionTag("DND_WITH_PRESSED_ALT_ONLY") var dndWithPressedAltOnly by storedProperty(false)
@get:OptionTag("DEFAULT_AUTOSCROLL_TO_SOURCE") var defaultAutoScrollToSource by storedProperty(false)
@Transient var presentationMode = false
@get:OptionTag("PRESENTATION_MODE_FONT_SIZE") var presentationModeFontSize by storedProperty(24)
@get:OptionTag("MARK_MODIFIED_TABS_WITH_ASTERISK") var markModifiedTabsWithAsterisk by storedProperty(false)
@get:OptionTag("SHOW_TABS_TOOLTIPS") var showTabsTooltips by storedProperty(true)
@get:OptionTag("SHOW_DIRECTORY_FOR_NON_UNIQUE_FILENAMES") var showDirectoryForNonUniqueFilenames by storedProperty(true)
var smoothScrolling by storedProperty(SystemInfo.isMac && (SystemInfo.isJetBrainsJvm || SystemInfo.isJavaVersionAtLeast("9")))
@get:OptionTag("NAVIGATE_TO_PREVIEW") var navigateToPreview by storedProperty(false)
@get:OptionTag("SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY") var sortLookupElementsLexicographically by storedProperty(false)
@get:OptionTag("MERGE_EQUAL_STACKTRACES") var mergeEqualStackTraces by storedProperty(true)
@get:OptionTag("SORT_BOOKMARKS") var sortBookmarks by storedProperty(false)
@get:OptionTag("PIN_FIND_IN_PATH_POPUP") var pinFindInPath by storedProperty(false)
private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java)
init {
WelcomeWizardUtil.getAutoScrollToSource()?.let {
defaultAutoScrollToSource = it
}
}
private fun withDefFont(): UISettings {
initDefFont()
return this
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Please use {@link UISettingsListener#TOPIC}")
fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener)
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
fun fireUISettingsChanged() {
updateDeprecatedProperties()
// todo remove when all old properties will be converted
incrementModificationCount()
IconLoader.setFilter(ColorBlindnessSupport.get(colorBlindness)?.filter)
// if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components
if (this === _instance) {
myTreeDispatcher.multicaster.uiSettingsChanged(this)
ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this)
}
}
@Suppress("DEPRECATION")
private fun updateDeprecatedProperties() {
HIDE_TOOL_STRIPES = hideToolStripes
SHOW_MAIN_TOOLBAR = showMainToolbar
CYCLE_SCROLLING = cycleScrolling
SHOW_CLOSE_BUTTON = showCloseButton
EDITOR_AA_TYPE = editorAAType
PRESENTATION_MODE = presentationMode
OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts
PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize
CONSOLE_COMMAND_HISTORY_LIMIT = consoleCommandHistoryLimit
FONT_SIZE = fontSize
FONT_FACE = fontFace
EDITOR_TAB_LIMIT = editorTabLimit
OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = overrideConsoleCycleBufferSize
CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb
}
private fun initDefFont() {
val fontData = systemFontFaceAndSize
if (fontFace == null) fontFace = fontData.first
if (fontSize <= 0) fontSize = fontData.second
if (fontScale <= 0) fontScale = defFontScale
}
class FontFilter : SerializationFilter {
override fun accepts(accessor: Accessor, bean: Any): Boolean {
val settings = bean as UISettings
val fontData = systemFontFaceAndSize
if ("fontFace" == accessor.name) {
return fontData.first != settings.fontFace
}
// fontSize/fontScale should either be stored in pair or not stored at all
// otherwise the fontSize restore logic gets broken (see loadState)
return !(fontData.second == settings.fontSize && 1f == settings.fontScale)
}
}
override fun getState() = this
override fun loadState(state: UISettings) {
XmlSerializerUtil.copyBean(state, this)
resetModificationCount()
updateDeprecatedProperties()
// Check tab placement in editor
if (editorTabPlacement != TABS_NONE &&
editorTabPlacement != SwingConstants.TOP &&
editorTabPlacement != SwingConstants.LEFT &&
editorTabPlacement != SwingConstants.BOTTOM &&
editorTabPlacement != SwingConstants.RIGHT) {
editorTabPlacement = SwingConstants.TOP
}
// Check that alpha delay and ratio are valid
if (alphaModeDelay < 0) {
alphaModeDelay = 1500
}
if (alphaModeRatio < 0.0f || alphaModeRatio > 1.0f) {
alphaModeRatio = 0.5f
}
fontSize = restoreFontSize(fontSize, fontScale)
fontScale = defFontScale
initDefFont()
// 1. Sometimes system font cannot display standard ASCII symbols. If so we have
// find any other suitable font withing "preferred" fonts first.
var fontIsValid = isValidFont(Font(fontFace, Font.PLAIN, fontSize))
if (!fontIsValid) {
for (preferredFont in arrayOf("dialog", "Arial", "Tahoma")) {
if (isValidFont(Font(preferredFont, Font.PLAIN, fontSize))) {
fontFace = preferredFont
fontIsValid = true
break
}
}
// 2. If all preferred fonts are not valid in current environment
// we have to find first valid font (if any)
if (!fontIsValid) {
val fontNames = UIUtil.getValidFontNames(false)
if (fontNames.isNotEmpty()) {
fontFace = fontNames[0]
}
}
}
if (maxClipboardContents <= 0) {
maxClipboardContents = 5
}
fireUISettingsChanged()
}
companion object {
private val LOG = Logger.getInstance(UISettings::class.java)
const val ANIMATION_DURATION = 300 // Milliseconds
/** Not tabbed pane. */
const val TABS_NONE = 0
private @Volatile var _instance: UISettings? = null
@JvmStatic
val instance: UISettings
get() = instanceOrNull!!
@JvmStatic
val instanceOrNull: UISettings?
get() {
var result = _instance
if (result == null) {
if (ApplicationManager.getApplication() == null) {
return null
}
result = ServiceManager.getService(UISettings::class.java)
_instance = result
}
return result
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@JvmStatic
val shadowInstance: UISettings
get() {
val app = ApplicationManager.getApplication()
return (if (app == null) null else instanceOrNull) ?: UISettings().withDefFont()
}
private val systemFontFaceAndSize: Pair<String, Int>
get() {
val fontData = UIUtil.getSystemFontData()
if (fontData != null) {
return fontData
}
return Pair.create("Dialog", 12)
}
@JvmField
val FORCE_USE_FRACTIONAL_METRICS = SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false)
@JvmStatic
fun setupFractionalMetrics(g2d: Graphics2D) {
if (FORCE_USE_FRACTIONAL_METRICS) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON)
}
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from
* `updateUI()` or `setUI()` method of component.
*/
@JvmStatic
fun setupAntialiasing(g: Graphics) {
val g2d = g as Graphics2D
g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue())
val application = ApplicationManager.getApplication()
if (application == null) {
// We cannot use services while Application has not been loaded yet
// So let's apply the default hints.
UIUtil.applyRenderingHints(g)
return
}
val uiSettings = ServiceManager.getService(UISettings::class.java)
if (uiSettings != null) {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
}
else {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)
}
setupFractionalMetrics(g2d)
}
/**
* @see #setupAntialiasing(Graphics)
*/
@JvmStatic
fun setupComponentAntialiasing(component: JComponent) {
com.intellij.util.ui.GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent())
}
@JvmStatic
fun setupEditorAntialiasing(component: JComponent) {
instance.editorAAType?.let { GraphicsUtil.setAntialiasingType(component, it.textInfo) }
}
/**
* Returns the default font scale, which depends on the HiDPI mode (see JBUI#ScaleType).
* <p>
* The font is represented:
* - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f
* - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale
*
* @return the system font scale
*/
@JvmStatic
val defFontScale: Float
get() = if (UIUtil.isJreHiDPIEnabled()) 1f else JBUI.sysScale()
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Int
get() = Math.round(UIUtil.DEF_SYSTEM_FONT_SIZE * defFontScale)
@JvmStatic
fun restoreFontSize(readSize: Int, readScale: Float?): Int {
var size = readSize
if (readScale == null || readScale <= 0) {
// Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX.
if (UIUtil.isJreHiDPIEnabled() && !SystemInfo.isMac) size = defFontSize
}
else {
if (readScale != defFontScale) size = Math.round((readSize / readScale) * defFontScale)
}
LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale")
return size
}
}
//<editor-fold desc="Deprecated stuff.">
@Suppress("unused")
@Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace"))
@JvmField
@Transient
var FONT_FACE: String? = null
@Suppress("unused")
@Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize"))
@JvmField
@Transient
var FONT_SIZE: Int? = 0
@Suppress("unused")
@Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes"))
@JvmField
@Transient
var HIDE_TOOL_STRIPES = true
@Suppress("unused")
@Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit"))
@JvmField
@Transient
var CONSOLE_COMMAND_HISTORY_LIMIT = 300
@Suppress("unused")
@Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling"))
@JvmField
@Transient
var CYCLE_SCROLLING = true
@Suppress("unused")
@Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar"))
@JvmField
@Transient
var SHOW_MAIN_TOOLBAR = false
@Suppress("unused")
@Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton"))
@JvmField
@Transient
var SHOW_CLOSE_BUTTON = true
@Suppress("unused")
@Deprecated("Use editorAAType", replaceWith = ReplaceWith("editorAAType"))
@JvmField
@Transient
var EDITOR_AA_TYPE: AntialiasingType? = AntialiasingType.SUBPIXEL
@Suppress("unused")
@Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode"))
@JvmField
@Transient
var PRESENTATION_MODE = false
@Suppress("unused")
@Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts"))
@JvmField
@Transient
var OVERRIDE_NONIDEA_LAF_FONTS = false
@Suppress("unused")
@Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize"))
@JvmField
@Transient
var PRESENTATION_MODE_FONT_SIZE = 24
@Suppress("unused")
@Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit"))
@JvmField
@Transient
var EDITOR_TAB_LIMIT = editorTabLimit
@Suppress("unused")
@Deprecated("Use overrideConsoleCycleBufferSize", replaceWith = ReplaceWith("overrideConsoleCycleBufferSize"))
@JvmField
@Transient
var OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false
@Suppress("unused")
@Deprecated("Use consoleCycleBufferSizeKb", replaceWith = ReplaceWith("consoleCycleBufferSizeKb"))
@JvmField
@Transient
var CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb
//</editor-fold>
} | apache-2.0 | 3608c78b86b08811a71d8dd7c03bb941 | 39.619835 | 140 | 0.737728 | 4.490407 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/base/analysis/LibraryDependenciesCache.kt | 1 | 8169 | // 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.base.analysis
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.util.Condition
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.caches.project.CachedValue
import org.jetbrains.kotlin.caches.project.getValue
import org.jetbrains.kotlin.idea.base.analysis.libraries.LibraryDependencyCandidate
import org.jetbrains.kotlin.idea.base.facet.isHMPPEnabled
import org.jetbrains.kotlin.idea.base.projectStructure.*
import org.jetbrains.kotlin.idea.base.projectStructure.LibraryDependenciesCache.LibraryDependencies
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class LibraryDependenciesCacheImpl(private val project: Project) : LibraryDependenciesCache {
companion object {
fun getInstance(project: Project): LibraryDependenciesCache = project.service()
}
private val cache by CachedValue(project) {
CachedValueProvider.Result(
ContainerUtil.createConcurrentWeakMap<LibraryInfo, LibraryDependencies>(),
ProjectRootManager.getInstance(project)
)
}
private val moduleDependenciesCache by CachedValue(project) {
CachedValueProvider.Result(
ContainerUtil.createConcurrentWeakMap<Module, Pair<Set<LibraryDependencyCandidate>, Set<SdkInfo>>>(),
ProjectRootManager.getInstance(project)
)
}
override fun getLibraryDependencies(library: LibraryInfo): LibraryDependencies {
return cache.getOrPut(library) { computeLibrariesAndSdksUsedWith(library) }
}
private fun computeLibrariesAndSdksUsedWith(libraryInfo: LibraryInfo): LibraryDependencies {
val (dependencyCandidates, sdks) = computeLibrariesAndSdksUsedWithNoFilter(libraryInfo)
val libraryDependenciesFilter = DefaultLibraryDependenciesFilter union SharedNativeLibraryToNativeInteropFallbackDependenciesFilter
val libraries = libraryDependenciesFilter(libraryInfo.platform, dependencyCandidates).flatMap { it.libraries }
return LibraryDependencies(libraries, sdks.toList())
}
//NOTE: used LibraryRuntimeClasspathScope as reference
private fun computeLibrariesAndSdksUsedWithNoFilter(libraryInfo: LibraryInfo): Pair<Set<LibraryDependencyCandidate>, Set<SdkInfo>> {
val libraries = LinkedHashSet<LibraryDependencyCandidate>()
val sdks = LinkedHashSet<SdkInfo>()
for (module in getLibraryUsageIndex().getModulesLibraryIsUsedIn(libraryInfo)) {
ProgressManager.checkCanceled()
val (moduleLibraries, moduleSdks) = moduleDependenciesCache.getOrPut(module) {
computeLibrariesAndSdksUsedIn(module)
}
libraries.addAll(moduleLibraries)
sdks.addAll(moduleSdks)
}
val filteredLibraries = filterForBuiltins(libraryInfo, libraries)
return filteredLibraries to sdks
}
private fun computeLibrariesAndSdksUsedIn(module: Module): Pair<Set<LibraryDependencyCandidate>, Set<SdkInfo>> {
val libraries = LinkedHashSet<LibraryDependencyCandidate>()
val sdks = LinkedHashSet<SdkInfo>()
val processedModules = HashSet<Module>()
val condition = Condition<OrderEntry> { orderEntry ->
orderEntry.safeAs<ModuleOrderEntry>()?.let {
it.module?.run { this !in processedModules } ?: false
} ?: true
}
ModuleRootManager.getInstance(module).orderEntries().recursively().satisfying(condition).process(object : RootPolicy<Unit>() {
override fun visitModuleSourceOrderEntry(moduleSourceOrderEntry: ModuleSourceOrderEntry, value: Unit) {
processedModules.add(moduleSourceOrderEntry.ownerModule)
}
override fun visitLibraryOrderEntry(libraryOrderEntry: LibraryOrderEntry, value: Unit) {
libraryOrderEntry.library.safeAs<LibraryEx>()?.takeIf { !it.isDisposed }?.let {
libraries += LibraryInfoCache.getInstance(project).get(it).mapNotNull { libraryInfo ->
LibraryDependencyCandidate.fromLibraryOrNull(
project,
libraryInfo.library
)
}
}
}
override fun visitJdkOrderEntry(jdkOrderEntry: JdkOrderEntry, value: Unit) {
jdkOrderEntry.jdk?.let { jdk ->
sdks += SdkInfo(project, jdk)
}
}
}, Unit)
return libraries to sdks
}
/*
* When built-ins are created from module dependencies (as opposed to loading them from classloader)
* we must resolve Kotlin standard library containing some of the built-ins declarations in the same
* resolver for project as JDK. This comes from the following requirements:
* - JvmBuiltins need JDK and standard library descriptors -> resolver for project should be able to
* resolve them
* - Builtins are created in BuiltinsCache -> module descriptors should be resolved under lock of the
* SDK resolver to prevent deadlocks
* This means we have to maintain dependencies of the standard library manually or effectively drop
* resolver for SDK otherwise. Libraries depend on superset of their actual dependencies because of
* the inability to get real dependencies from IDEA model. So moving stdlib with all dependencies
* down is a questionable option.
*/
private fun filterForBuiltins(libraryInfo: LibraryInfo, dependencyLibraries: Set<LibraryDependencyCandidate>): Set<LibraryDependencyCandidate> {
return if (!IdeBuiltInsLoadingState.isFromClassLoader && libraryInfo.isCoreKotlinLibrary(project)) {
dependencyLibraries.filterTo(mutableSetOf()) { dep ->
dep.libraries.any { it.isCoreKotlinLibrary(project) }
}
} else {
dependencyLibraries
}
}
private fun getLibraryUsageIndex(): LibraryUsageIndex {
return CachedValuesManager.getManager(project).getCachedValue(project) {
CachedValueProvider.Result(LibraryUsageIndex(), ProjectRootModificationTracker.getInstance(project))
}!!
}
private inner class LibraryUsageIndex {
private val modulesLibraryIsUsedIn: MultiMap<LibraryWrapper, Module> = MultiMap.createSet()
init {
for (module in ModuleManager.getInstance(project).modules) {
for (entry in ModuleRootManager.getInstance(module).orderEntries) {
if (entry is LibraryOrderEntry) {
val library = entry.library
if (library != null) {
modulesLibraryIsUsedIn.putValue(library.wrap(), module)
}
}
}
}
}
fun getModulesLibraryIsUsedIn(libraryInfo: LibraryInfo) = sequence<Module> {
val ideaModelInfosCache = getIdeaModelInfosCache(project)
for (module in modulesLibraryIsUsedIn[libraryInfo.library.wrap()]) {
val mappedModuleInfos = ideaModelInfosCache.getModuleInfosForModule(module)
if (mappedModuleInfos.any { it.platform.canDependOn(libraryInfo, module.isHMPPEnabled) }) {
yield(module)
}
}
}
}
}
| apache-2.0 | d6c123e4aee245de66ced0e82de2cf10 | 47.052941 | 158 | 0.699474 | 5.579918 | false | false | false | false |
PolymerLabs/arcs | java/arcs/sdk/Handle.kt | 1 | 2197 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.sdk
import arcs.core.entity.Handle
import arcs.core.entity.QueryCollectionHandle
import arcs.core.entity.ReadCollectionHandle
import arcs.core.entity.ReadQueryCollectionHandle
import arcs.core.entity.ReadSingletonHandle
import arcs.core.entity.ReadWriteCollectionHandle
import arcs.core.entity.ReadWriteQueryCollectionHandle
import arcs.core.entity.ReadWriteSingletonHandle
import arcs.core.entity.WriteCollectionHandle
import arcs.core.entity.WriteQueryCollectionHandle
import arcs.core.entity.WriteSingletonHandle
/** Base interface for all handle classes. */
typealias Handle = Handle
/** A singleton handle with read access. */
typealias ReadSingletonHandle<E> = ReadSingletonHandle<E>
/** A singleton handle with write access. */
typealias WriteSingletonHandle<I> = WriteSingletonHandle<I>
/** A singleton handle with read and write access. */
typealias ReadWriteSingletonHandle<E, I> = ReadWriteSingletonHandle<E, I>
/** A collection handle with read access. */
typealias ReadCollectionHandle<E> = ReadCollectionHandle<E>
/** A collection handle with write access. */
typealias WriteCollectionHandle<I> = WriteCollectionHandle<I>
/** A collection handle with query access. */
typealias QueryCollectionHandle<E, QueryArgs> = QueryCollectionHandle<E, QueryArgs>
/** A collection handle with read and write access. */
typealias ReadWriteCollectionHandle<E, I> = ReadWriteCollectionHandle<E, I>
/** A collection handle with read and query access. */
typealias ReadQueryCollectionHandle<E, QueryArgs> = ReadQueryCollectionHandle<E, QueryArgs>
/** A collection handle with write and query access. */
typealias WriteQueryCollectionHandle<I, QueryArgs> = WriteQueryCollectionHandle<I, QueryArgs>
/** A collection handle with read, write and query access. */
typealias ReadWriteQueryCollectionHandle<E, I, QueryArgs> =
ReadWriteQueryCollectionHandle<E, I, QueryArgs>
| bsd-3-clause | e9e6bdd6dbd42ffd944ca888c5f247d7 | 36.87931 | 96 | 0.796541 | 4.465447 | false | false | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/storage/messages/CopyMessageOperations.kt | 1 | 11358 | package com.fsck.k9.storage.messages
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import androidx.core.database.getBlobOrNull
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull
import com.fsck.k9.K9
import com.fsck.k9.mailstore.LockableDatabase
import java.util.UUID
internal class CopyMessageOperations(
private val lockableDatabase: LockableDatabase,
private val attachmentFileManager: AttachmentFileManager,
private val threadMessageOperations: ThreadMessageOperations
) {
fun copyMessage(messageId: Long, destinationFolderId: Long): Long {
return lockableDatabase.execute(true) { database ->
val newMessageId = copyMessage(database, messageId, destinationFolderId)
copyFulltextEntry(database, newMessageId, messageId)
newMessageId
}
}
private fun copyMessage(
database: SQLiteDatabase,
messageId: Long,
destinationFolderId: Long
): Long {
val rootMessagePart = copyMessageParts(database, messageId)
val threadInfo = threadMessageOperations.doMessageThreading(
database,
folderId = destinationFolderId,
threadHeaders = threadMessageOperations.getMessageThreadHeaders(database, messageId)
)
return if (threadInfo?.messageId != null) {
updateMessageRow(
database,
sourceMessageId = messageId,
destinationMessageId = threadInfo.messageId,
destinationFolderId,
rootMessagePart
)
} else {
val newMessageId = insertMessageRow(
database,
sourceMessageId = messageId,
destinationFolderId = destinationFolderId,
rootMessagePartId = rootMessagePart
)
if (threadInfo?.threadId == null) {
threadMessageOperations.createThreadEntry(
database,
newMessageId,
threadInfo?.rootId,
threadInfo?.parentId
)
}
newMessageId
}
}
private fun copyMessageParts(database: SQLiteDatabase, messageId: Long): Long {
return database.rawQuery(
"""
SELECT
message_parts.id,
message_parts.type,
message_parts.root,
message_parts.parent,
message_parts.seq,
message_parts.mime_type,
message_parts.decoded_body_size,
message_parts.display_name,
message_parts.header,
message_parts.encoding,
message_parts.charset,
message_parts.data_location,
message_parts.data,
message_parts.preamble,
message_parts.epilogue,
message_parts.boundary,
message_parts.content_id,
message_parts.server_extra
FROM messages
JOIN message_parts ON (message_parts.root = messages.message_part_id)
WHERE messages.id = ?
ORDER BY message_parts.seq
""".trimIndent(),
arrayOf(messageId.toString())
).use { cursor ->
if (!cursor.moveToNext()) error("No message part found for message with ID $messageId")
val rootMessagePart = cursor.readMessagePart()
val rootMessagePartId = writeMessagePart(
database = database,
databaseMessagePart = rootMessagePart,
newRootId = null,
newParentId = -1
)
val messagePartIdMapping = mutableMapOf<Long, Long>()
messagePartIdMapping[rootMessagePart.id] = rootMessagePartId
while (cursor.moveToNext()) {
val messagePart = cursor.readMessagePart()
messagePartIdMapping[messagePart.id] = writeMessagePart(
database = database,
databaseMessagePart = messagePart,
newRootId = rootMessagePartId,
newParentId = messagePartIdMapping[messagePart.parent] ?: error("parent ID not found")
)
}
rootMessagePartId
}
}
private fun writeMessagePart(
database: SQLiteDatabase,
databaseMessagePart: DatabaseMessagePart,
newRootId: Long?,
newParentId: Long
): Long {
val values = ContentValues().apply {
put("type", databaseMessagePart.type)
put("root", newRootId)
put("parent", newParentId)
put("seq", databaseMessagePart.seq)
put("mime_type", databaseMessagePart.mimeType)
put("decoded_body_size", databaseMessagePart.decodedBodySize)
put("display_name", databaseMessagePart.displayName)
put("header", databaseMessagePart.header)
put("encoding", databaseMessagePart.encoding)
put("charset", databaseMessagePart.charset)
put("data_location", databaseMessagePart.dataLocation)
put("data", databaseMessagePart.data)
put("preamble", databaseMessagePart.preamble)
put("epilogue", databaseMessagePart.epilogue)
put("boundary", databaseMessagePart.boundary)
put("content_id", databaseMessagePart.contentId)
put("server_extra", databaseMessagePart.serverExtra)
}
val messagePartId = database.insert("message_parts", null, values)
if (databaseMessagePart.dataLocation == DataLocation.ON_DISK) {
attachmentFileManager.copyFile(databaseMessagePart.id, messagePartId)
}
return messagePartId
}
private fun updateMessageRow(
database: SQLiteDatabase,
sourceMessageId: Long,
destinationMessageId: Long,
destinationFolderId: Long,
rootMessagePartId: Long
): Long {
val values = readMessageToContentValues(database, sourceMessageId, destinationFolderId, rootMessagePartId)
database.update("messages", values, "id = ?", arrayOf(destinationMessageId.toString()))
return destinationMessageId
}
private fun insertMessageRow(
database: SQLiteDatabase,
sourceMessageId: Long,
destinationFolderId: Long,
rootMessagePartId: Long
): Long {
val values = readMessageToContentValues(database, sourceMessageId, destinationFolderId, rootMessagePartId)
return database.insert("messages", null, values)
}
private fun readMessageToContentValues(
database: SQLiteDatabase,
sourceMessageId: Long,
destinationFolderId: Long,
rootMessagePartId: Long
): ContentValues {
val values = readMessageToContentValues(database, sourceMessageId)
return values.apply {
put("folder_id", destinationFolderId)
put("uid", K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString())
put("message_part_id", rootMessagePartId)
}
}
private fun copyFulltextEntry(database: SQLiteDatabase, newMessageId: Long, messageId: Long) {
database.execSQL(
"""
INSERT OR REPLACE INTO messages_fulltext (docid, fulltext)
SELECT ?, fulltext FROM messages_fulltext WHERE docid = ?
""".trimIndent(),
arrayOf(newMessageId.toString(), messageId.toString())
)
}
private fun readMessageToContentValues(database: SQLiteDatabase, messageId: Long): ContentValues {
return database.query(
"messages",
arrayOf(
"deleted",
"subject",
"date",
"flags",
"sender_list",
"to_list",
"cc_list",
"bcc_list",
"reply_to_list",
"attachment_count",
"internal_date",
"message_id",
"preview_type",
"preview",
"mime_type",
"normalized_subject_hash",
"empty",
"read",
"flagged",
"answered",
"forwarded",
"encryption_type"
),
"id = ?",
arrayOf(messageId.toString()),
null, null, null
).use { cursor ->
if (!cursor.moveToNext()) error("Message with ID $messageId not found")
ContentValues().apply {
put("deleted", cursor.getInt(0))
put("subject", cursor.getStringOrNull(1))
put("date", cursor.getLong(2))
put("flags", cursor.getStringOrNull(3))
put("sender_list", cursor.getStringOrNull(4))
put("to_list", cursor.getStringOrNull(5))
put("cc_list", cursor.getStringOrNull(6))
put("bcc_list", cursor.getStringOrNull(7))
put("reply_to_list", cursor.getStringOrNull(8))
put("attachment_count", cursor.getInt(9))
put("internal_date", cursor.getLong(10))
put("message_id", cursor.getStringOrNull(11))
put("preview_type", cursor.getStringOrNull(12))
put("preview", cursor.getStringOrNull(13))
put("mime_type", cursor.getStringOrNull(14))
put("normalized_subject_hash", cursor.getLong(15))
put("empty", cursor.getInt(16))
put("read", cursor.getInt(17))
put("flagged", cursor.getInt(18))
put("answered", cursor.getInt(19))
put("forwarded", cursor.getInt(20))
put("encryption_type", cursor.getStringOrNull(21))
}
}
}
private fun Cursor.readMessagePart(): DatabaseMessagePart {
return DatabaseMessagePart(
id = getLong(0),
type = getInt(1),
root = getLong(2),
parent = getLong(3),
seq = getInt(4),
mimeType = getString(5),
decodedBodySize = getLongOrNull(6),
displayName = getStringOrNull(7),
header = getBlobOrNull(8),
encoding = getStringOrNull(9),
charset = getStringOrNull(10),
dataLocation = getInt(11),
data = getBlobOrNull(12),
preamble = getBlobOrNull(13),
epilogue = getBlobOrNull(14),
boundary = getStringOrNull(15),
contentId = getStringOrNull(16),
serverExtra = getStringOrNull(17)
)
}
}
private class DatabaseMessagePart(
val id: Long,
val type: Int,
val root: Long,
val parent: Long,
val seq: Int,
val mimeType: String?,
val decodedBodySize: Long?,
val displayName: String?,
val header: ByteArray?,
val encoding: String?,
val charset: String?,
val dataLocation: Int,
val data: ByteArray?,
val preamble: ByteArray?,
val epilogue: ByteArray?,
val boundary: String?,
val contentId: String?,
val serverExtra: String?
)
| apache-2.0 | aebf995fb0b16a73b3b97a9087985758 | 35.057143 | 114 | 0.575101 | 5.253469 | false | false | false | false |
DanilaFe/abacus | core/src/main/kotlin/org/nwapw/abacus/number/NumberInterface.kt | 1 | 8572 | package org.nwapw.abacus.number
import org.nwapw.abacus.exception.ComputationInterruptedException
import org.nwapw.abacus.number.range.NumberRangeBuilder
abstract class NumberInterface: Comparable<NumberInterface> {
/**
* Check if the thread was interrupted and
* throw an exception to end the computation.
*/
private fun checkInterrupted(){
if(Thread.currentThread().isInterrupted)
throw ComputationInterruptedException()
}
/**
* Returns the integer representation of this number, discarding any fractional part,
* if int can hold the value.
*
* @return the integer value of this number.
*/
abstract fun intValue(): Int
/**
* Same as Math.signum().
*
* @return 1 if this number is positive, -1 if this number is negative, 0 if this number is 0.
*/
abstract fun signum(): Int
/**
* The maximum precision to which this number operates.
*/
abstract val maxPrecision: Int
/**
* Returns the smallest error this instance can tolerate depending
* on its precision and value.
*/
abstract val maxError: NumberInterface
/**
* Adds this number to another, returning
* a new number instance.
*
* @param summand the summand
* @return the result of the summation.
*/
abstract fun addInternal(summand: NumberInterface): NumberInterface
/**
* Subtracts another number from this number,
* a new number instance.
*
* @param subtrahend the subtrahend.
* @return the result of the subtraction.
*/
abstract fun subtractInternal(subtrahend: NumberInterface): NumberInterface
/**
* Multiplies this number by another, returning
* a new number instance.
*
* @param multiplier the multiplier
* @return the result of the multiplication.
*/
abstract fun multiplyInternal(multiplier: NumberInterface): NumberInterface
/**
* Divides this number by another, returning
* a new number instance.
*
* @param divisor the divisor
* @return the result of the division.
*/
abstract fun divideInternal(divisor: NumberInterface): NumberInterface
/**
* Returns a new instance of this number with
* the sign flipped.
*
* @return the new instance.
*/
abstract fun negateInternal(): NumberInterface
/**
* Raises this number to an integer power.
*
* @param exponent the exponent to which to take the number.
* @return the resulting value.
*/
abstract fun intPowInternal(pow: Int): NumberInterface
/**
* Returns the least integer greater than or equal to the number.
*
* @return the least integer greater or equal to the number, if int can hold the value.
*/
abstract fun ceilingInternal(): NumberInterface
/**
* Return the greatest integer less than or equal to the number.
*
* @return the greatest integer smaller or equal the number.
*/
abstract fun floorInternal(): NumberInterface
/**
* Returns the fractional part of the number.
*
* @return the fractional part of the number.
*/
abstract fun fractionalPartInternal(): NumberInterface
/**
* Adds this number to another, returning
* a new number instance. Also, checks if the
* thread has been interrupted, and if so, throws
* an exception.
*
* @param summand the summand
* @return the result of the summation.
*/
fun add(summand: NumberInterface): NumberInterface {
checkInterrupted()
return addInternal(summand)
}
/**
* Subtracts another number from this number,
* a new number instance. Also, checks if the
* thread has been interrupted, and if so, throws
* an exception.
*
* @param subtrahend the subtrahend.
* @return the result of the subtraction.
*/
fun subtract(subtrahend: NumberInterface): NumberInterface {
checkInterrupted()
return subtractInternal(subtrahend)
}
/**
* Multiplies this number by another, returning
* a new number instance. Also, checks if the
* thread has been interrupted, and if so, throws
* an exception.
*
* @param multiplier the multiplier
* @return the result of the multiplication.
*/
fun multiply(multiplier: NumberInterface): NumberInterface {
checkInterrupted()
return multiplyInternal(multiplier)
}
/**
* Divides this number by another, returning
* a new number instance. Also, checks if the
* thread has been interrupted, and if so, throws
* an exception.
*
* @param divisor the divisor
* @return the result of the division.
*/
fun divide(divisor: NumberInterface): NumberInterface {
checkInterrupted()
return divideInternal(divisor)
}
/**
* Returns a new instance of this number with
* the sign flipped. Also, checks if the
* thread has been interrupted, and if so, throws
* an exception.
*
* @return the new instance.
*/
fun negate(): NumberInterface {
checkInterrupted()
return negateInternal()
}
/**
* Raises this number to an integer power. Also, checks if the
* thread has been interrupted, and if so, throws
* an exception.
*
* @param exponent the exponent to which to take the number.
* @return the resulting value.
*/
fun intPow(exponent: Int): NumberInterface {
checkInterrupted()
return intPowInternal(exponent)
}
/**
* Returns the least integer greater than or equal to the number.
* Also, checks if the thread has been interrupted, and if so, throws
* an exception.
*
* @return the least integer bigger or equal to the number.
*/
fun ceiling(): NumberInterface {
checkInterrupted()
return ceilingInternal()
}
/**
* Return the greatest integer less than or equal to the number.
* Also, checks if the thread has been interrupted, and if so, throws
* an exception.
*
* @return the greatest int smaller than or equal to the number.
*/
fun floor(): NumberInterface {
checkInterrupted()
return floorInternal()
}
/**
* Returns the fractional part of the number, specifically x - floor(x).
* Also, checks if the thread has been interrupted,
* and if so, throws an exception.
*
* @return the fractional part of the number.
*/
fun fractionalPart(): NumberInterface {
checkInterrupted()
return fractionalPartInternal()
}
/**
* Checks whether the given number is an integer or not.
*
* @return whether the number is an integer or not.
*/
fun isInteger() = fractionalPart().signum() == 0
/**
* Returns a NumberRangeBuilder object, which is used to create a range.
* The reason that this returns a builder and not an actual range is that
* the NumberRange needs to promote values passed to it, which
* requires an abacus instance.
* @param other the value at the bottom of the range.
* @return the resulting range builder.
*/
operator fun rangeTo(other: NumberInterface) = NumberRangeBuilder(this, other)
/**
* Plus operator overloaded to allow "nice" looking math.
* @param other the value to add to this number.
* @return the result of the addition.
*/
operator fun plus(other: NumberInterface) = add(other)
/**
* Minus operator overloaded to allow "nice" looking math.
* @param other the value to subtract to this number.
* @return the result of the subtraction.
*/
operator fun minus(other: NumberInterface) = subtract(other)
/**
* Times operator overloaded to allow "nice" looking math.
* @param other the value to multiply this number by.
* @return the result of the multiplication.
*/
operator fun times(other: NumberInterface) = multiply(other)
/**
* Divide operator overloaded to allow "nice" looking math.
* @param other the value to divide this number by.
* @return the result of the division.
*/
operator fun div(other: NumberInterface) = divide(other)
/**
* The plus operator.
* @return this number.
*/
operator fun unaryPlus() = this
/**
* The minus operator.
* @return the negative of this number.
*/
operator fun unaryMinus() = negate()
} | mit | 2c3bfb6f49ea5bb076dc3a61a8327ef1 | 30.061594 | 98 | 0.641857 | 4.653637 | false | false | false | false |
DiUS/pact-jvm | core/model/src/main/kotlin/au/com/dius/pact/core/model/messaging/Message.kt | 1 | 6258 | package au.com.dius.pact.core.model.messaging
import au.com.dius.pact.core.model.ContentType
import au.com.dius.pact.core.model.Interaction
import au.com.dius.pact.core.model.OptionalBody
import au.com.dius.pact.core.model.PactSpecVersion
import au.com.dius.pact.core.model.ProviderState
import au.com.dius.pact.core.model.generators.Generators
import au.com.dius.pact.core.model.matchingrules.MatchingRules
import au.com.dius.pact.core.model.matchingrules.MatchingRulesImpl
import au.com.dius.pact.core.support.Json
import au.com.dius.pact.core.support.json.JsonException
import au.com.dius.pact.core.support.json.JsonParser
import au.com.dius.pact.core.support.json.JsonValue
import mu.KLogging
import org.apache.commons.codec.binary.Base64
import org.apache.commons.lang3.StringUtils
/**
* Message in a Message Pact
*/
class Message @JvmOverloads constructor(
override val description: String,
override val providerStates: List<ProviderState> = listOf(),
var contents: OptionalBody = OptionalBody.missing(),
var matchingRules: MatchingRules = MatchingRulesImpl(),
var generators: Generators = Generators(),
var metaData: MutableMap<String, Any?> = mutableMapOf(),
override val interactionId: String? = null
) : Interaction {
fun contentsAsBytes() = contents.orEmpty()
fun contentsAsString() = contents.valueAsString()
fun getContentType() = contentType(metaData).or(contents.contentType)
override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any?> {
val map: MutableMap<String, Any?> = mutableMapOf(
"description" to description,
"metaData" to metaData
)
if (!contents.isMissing()) {
map["contents"] = when {
isJsonContents() -> {
try {
val json = JsonParser.parseString(contents.valueAsString())
if (json is JsonValue.StringValue) {
contents.valueAsString()
} else {
Json.fromJson(json)
}
} catch (ex: JsonException) {
logger.trace(ex) { "Failed to parse JSON body" }
contents.valueAsString()
}
}
else -> formatContents()
}
}
if (providerStates.isNotEmpty()) {
map["providerStates"] = providerStates.map { it.toMap() }
}
if (matchingRules.isNotEmpty()) {
map["matchingRules"] = matchingRules.toMap(pactSpecVersion)
}
if (generators.isNotEmpty()) {
map["generators"] = generators.toMap(pactSpecVersion)
}
return map
}
private fun isJsonContents(): Boolean {
return if (contents.isPresent()) {
contentType(metaData).or(contents.contentType).isJson()
} else {
false
}
}
fun formatContents(): String {
return if (contents.isPresent()) {
val contentType = contentType(metaData).or(contents.contentType)
when {
contentType.isJson() -> JsonParser.parseString(contents.valueAsString()).prettyPrint()
contentType.isOctetStream() -> Base64.encodeBase64String(contentsAsBytes())
else -> contents.valueAsString()
}
} else {
""
}
}
override fun uniqueKey(): String {
return StringUtils.defaultIfEmpty(providerStates.joinToString { it.name.toString() }, "None") +
"_$description"
}
override fun conflictsWith(other: Interaction) = other !is Message
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Message
if (description != other.description) return false
if (providerStates != other.providerStates) return false
if (contents != other.contents) return false
if (matchingRules != other.matchingRules) return false
if (generators != other.generators) return false
return true
}
override fun hashCode(): Int {
var result = description.hashCode()
result = 31 * result + providerStates.hashCode()
result = 31 * result + contents.hashCode()
result = 31 * result + matchingRules.hashCode()
result = 31 * result + generators.hashCode()
return result
}
override fun toString(): String {
return "Message(description='$description', providerStates=$providerStates, contents=$contents, " +
"matchingRules=$matchingRules, generators=$generators, metaData=$metaData)"
}
fun withMetaData(metadata: Map<String, Any>): Message {
this.metaData = metadata.toMutableMap()
return this
}
companion object : KLogging() {
/**
* Builds a message from a Map
*/
@JvmStatic
fun fromJson(json: JsonValue.Object): Message {
val providerStates = when {
json.has("providerStates") -> json["providerStates"].asArray().values.map { ProviderState.fromJson(it) }
json.has("providerState") -> listOf(ProviderState(Json.toString(json["providerState"])))
else -> listOf()
}
val metaData = if (json.has("metaData"))
json["metaData"].asObject().entries.entries.associate { it.key to Json.fromJson(it.value) }
else
emptyMap()
val contentType = contentType(metaData)
val contents = if (json.has("contents")) {
when (val contents = json["contents"]) {
is JsonValue.Null -> OptionalBody.nullBody()
is JsonValue.StringValue -> OptionalBody.body(contents.asString().toByteArray(contentType.asCharset()),
contentType)
else -> OptionalBody.body(contents.serialise().toByteArray(contentType.asCharset()), contentType)
}
} else {
OptionalBody.missing()
}
val matchingRules = if (json.has("matchingRules"))
MatchingRulesImpl.fromJson(json["matchingRules"])
else MatchingRulesImpl()
val generators = if (json.has("generators"))
Generators.fromJson(json["generators"])
else Generators()
return Message(Json.toString(json["description"]), providerStates,
contents, matchingRules, generators, metaData.toMutableMap(), Json.toString(json["_id"]))
}
fun contentType(metaData: Map<String, Any?>): ContentType {
return ContentType.fromString(metaData.entries.find {
it.key.toLowerCase() == "contenttype" || it.key.toLowerCase() == "content-type"
}?.value?.toString())
}
}
}
| apache-2.0 | 68933cbd02ef076b5d082d249f251dc5 | 33.574586 | 113 | 0.672419 | 4.342817 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/viewmodel/posts/PostListEmptyUiState.kt | 1 | 5155 | package org.wordpress.android.viewmodel.posts
import androidx.annotation.DrawableRes
import org.wordpress.android.R
import org.wordpress.android.fluxc.store.ListStore.ListError
import org.wordpress.android.fluxc.store.ListStore.ListErrorType.PERMISSION_ERROR
import org.wordpress.android.ui.posts.PostListType
import org.wordpress.android.ui.posts.PostListType.DRAFTS
import org.wordpress.android.ui.posts.PostListType.PUBLISHED
import org.wordpress.android.ui.posts.PostListType.SCHEDULED
import org.wordpress.android.ui.posts.PostListType.SEARCH
import org.wordpress.android.ui.posts.PostListType.TRASHED
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
sealed class PostListEmptyUiState(
val title: UiString? = null,
@DrawableRes val imgResId: Int? = null,
val buttonText: UiString? = null,
val onButtonClick: (() -> Unit)? = null,
val emptyViewVisible: Boolean = true
) {
class EmptyList(
title: UiString,
buttonText: UiString? = null,
onButtonClick: (() -> Unit)? = null,
@DrawableRes imageResId: Int = R.drawable.img_illustration_posts_75dp
) : PostListEmptyUiState(
title = title,
imgResId = imageResId,
buttonText = buttonText,
onButtonClick = onButtonClick
)
object DataShown : PostListEmptyUiState(emptyViewVisible = false)
object Loading : PostListEmptyUiState(
title = UiStringRes(R.string.posts_fetching),
imgResId = R.drawable.img_illustration_posts_75dp
)
class RefreshError(
title: UiString,
buttonText: UiString? = null,
onButtonClick: (() -> Unit)? = null
) : PostListEmptyUiState(
title = title,
imgResId = R.drawable.img_illustration_empty_results_216dp,
buttonText = buttonText,
onButtonClick = onButtonClick
)
object PermissionsError : PostListEmptyUiState(
title = UiStringRes(R.string.error_refresh_unauthorized_posts),
imgResId = R.drawable.img_illustration_posts_75dp
)
}
@Suppress("LongParameterList")
fun createEmptyUiState(
postListType: PostListType,
isNetworkAvailable: Boolean,
isLoadingData: Boolean,
isListEmpty: Boolean,
isSearchPromptRequired: Boolean,
error: ListError?,
fetchFirstPage: () -> Unit,
newPost: () -> Unit
): PostListEmptyUiState {
return if (isListEmpty) {
when {
error != null -> createErrorListUiState(
isNetworkAvailable = isNetworkAvailable,
error = error,
fetchFirstPage = fetchFirstPage
)
isLoadingData -> {
// don't show intermediate screen when loading search results
if (postListType == SEARCH) {
PostListEmptyUiState.DataShown
} else {
PostListEmptyUiState.Loading
}
}
else -> createEmptyListUiState(
postListType = postListType,
newPost = newPost,
isSearchPromptRequired = isSearchPromptRequired
)
}
} else {
PostListEmptyUiState.DataShown
}
}
private fun createErrorListUiState(
isNetworkAvailable: Boolean,
error: ListError,
fetchFirstPage: () -> Unit
): PostListEmptyUiState {
return if (error.type == PERMISSION_ERROR) {
PostListEmptyUiState.PermissionsError
} else {
val errorText = if (isNetworkAvailable) {
UiStringRes(R.string.error_refresh_posts)
} else {
UiStringRes(R.string.no_network_message)
}
PostListEmptyUiState.RefreshError(
errorText,
UiStringRes(R.string.retry),
fetchFirstPage
)
}
}
private fun createEmptyListUiState(
postListType: PostListType,
newPost: () -> Unit,
isSearchPromptRequired: Boolean
): PostListEmptyUiState.EmptyList {
return when (postListType) {
PUBLISHED -> PostListEmptyUiState.EmptyList(
UiStringRes(R.string.posts_published_empty),
UiStringRes(R.string.posts_empty_list_button),
newPost
)
DRAFTS -> PostListEmptyUiState.EmptyList(
UiStringRes(R.string.posts_draft_empty),
UiStringRes(R.string.posts_empty_list_button),
newPost
)
SCHEDULED -> PostListEmptyUiState.EmptyList(
UiStringRes(R.string.posts_scheduled_empty),
UiStringRes(R.string.posts_empty_list_button),
newPost
)
SEARCH -> {
val messageResId = if (isSearchPromptRequired) {
R.string.post_list_search_prompt
} else {
R.string.post_list_search_nothing_found
}
PostListEmptyUiState.EmptyList(title = UiStringRes(messageResId), imageResId = 0)
}
TRASHED -> PostListEmptyUiState.EmptyList(UiStringRes(R.string.posts_trashed_empty))
}
}
| gpl-2.0 | 77c21497b8e61d6ca0e8f5ac6864b029 | 33.597315 | 93 | 0.62968 | 4.813259 | false | false | false | false |
MER-GROUP/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfo.kt | 3 | 5061 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.updateSettings.impl
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.SystemInfo
import org.jdom.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class UpdatesInfo(node: Element) {
private val products = node.children.map { Product(it) }
val productsCount: Int
get() = products.size
fun getProduct(code: String): Product? = products.find { it.hasCode(code) }
}
class Product(node: Element) {
val name: String = node.getAttributeValue("name")!!
val channels: List<UpdateChannel> = node.getChildren("channel").map { UpdateChannel(it) }
private val codes = node.getChildren("code").map { it.value }.toSet()
fun hasCode(code: String): Boolean = codes.contains(code)
fun findUpdateChannelById(id: String): UpdateChannel? = channels.find { it.id == id }
fun getAllChannelIds(): List<String> = channels.map { it.id }
}
class UpdateChannel(node: Element) {
companion object {
const val LICENSING_EAP = "eap"
const val LICENSING_PRODUCTION = "production"
}
val id: String = node.getAttributeValue("id")!!
val name: String = node.getAttributeValue("name")!!
val status: ChannelStatus = ChannelStatus.fromCode(node.getAttributeValue("status"))
val licensing: String = node.getAttributeValue("licensing", LICENSING_PRODUCTION)
val majorVersion: Int = node.getAttributeValue("majorVersion")?.toInt() ?: -1
val homePageUrl: String? = node.getAttributeValue("url")
val feedbackUrl: String? = node.getAttributeValue("feedback")
val evalDays: Int = node.getAttributeValue("evalDays")?.toInt() ?: 30
private val builds = node.getChildren("build").map { BuildInfo(it) }
fun getLatestBuild(): BuildInfo? =
builds.fold(null as BuildInfo?) { best, candidate -> if (best == null || best.compareTo(candidate) < 0) candidate else best }
}
class BuildInfo(node: Element) : Comparable<BuildInfo> {
val number: BuildNumber = BuildNumber.fromString(node.getAttributeValue("number")!!)
val apiVersion: BuildNumber = node.getAttributeValue("apiVersion")?.let { BuildNumber.fromString(it, number.productCode) } ?: number
val version: String = node.getAttributeValue("version") ?: ""
val message: String = node.getChild("message")?.value ?: ""
val releaseDate: Date? = node.getAttributeValue("releaseDate")?.let {
try { SimpleDateFormat("yyyyMMdd", Locale.US).parse(it) } // same as the 'majorReleaseDate' in ApplicationInfo.xml
catch (e: ParseException) {
Logger.getInstance(BuildInfo::class.java).info("Failed to parse build release date " + it)
null
}
}
val buttons: List<ButtonInfo> = node.getChildren("button").map { ButtonInfo(it) }
private val patches = node.getChildren("patch").map { PatchInfo(it) }
/**
* Returns -1 if version information is missing or does not match to expected format "majorVer.minorVer"
*/
val majorVersion: Int
get() {
val dotIndex = version.indexOf('.')
if (dotIndex > 0) {
try {
return version.substring(0, dotIndex).toInt()
}
catch (ignored: NumberFormatException) { }
}
return -1
}
fun findPatchForCurrentBuild(): PatchInfo? = findPatchForBuild(ApplicationInfo.getInstance().build)
fun findPatchForBuild(currentBuild: BuildNumber): PatchInfo? =
patches.find { it.isAvailable && it.fromBuild.asStringWithoutProductCode() == currentBuild.asStringWithoutProductCode() }
override fun compareTo(other: BuildInfo): Int = number.compareTo(other.number)
override fun toString(): String = "BuildInfo(number=$number)"
}
class ButtonInfo(node: Element) {
val name: String = node.getAttributeValue("name")!!
val url: String = node.getAttributeValue("url")!!
val isDownload: Boolean = node.getAttributeValue("download") != null // a button marked with this attribute is hidden when a patch is available
}
class PatchInfo(node: Element) {
val fromBuild: BuildNumber = BuildNumber.fromString(node.getAttributeValue("from")!!)
val size: String? = node.getAttributeValue("size")
val isAvailable: Boolean = node.getAttributeValue("exclusions")?.split(",")?.none { it.trim() == osSuffix } ?: true
val osSuffix: String
get() = if (SystemInfo.isWindows) "win" else if (SystemInfo.isMac) "mac" else if (SystemInfo.isUnix) "unix" else "unknown"
}
| apache-2.0 | afffedad3fa87e122da0affadb08f4fd | 40.483607 | 146 | 0.720609 | 4.179191 | false | false | false | false |
JetBrains/teamcity-nuget-support | nuget-agent/src/jetbrains/buildServer/nuget/agent/serviceMessages/NuGetPackageServiceFeedPublisherImpl.kt | 1 | 3719 | package jetbrains.buildServer.nuget.agent.serviceMessages
import jetbrains.buildServer.BuildAuthUtil
import jetbrains.buildServer.agent.*
import jetbrains.buildServer.log.Loggers
import jetbrains.buildServer.messages.DefaultMessagesInfo
import jetbrains.buildServer.nuget.common.PackagePublishException
import jetbrains.buildServer.nuget.common.index.NuGetPackageData
import jetbrains.buildServer.serverSide.crypt.EncryptUtil
import jetbrains.buildServer.util.EventDispatcher
import jetbrains.buildServer.util.StringUtil
import org.jetbrains.annotations.NotNull
import java.io.File
class NuGetPackageServiceFeedPublisherImpl (
@NotNull private val myDispatcher: EventDispatcher<AgentLifeCycleListener>,
@NotNull private val myFeedTransportProvider: NuGetPackageServiceFeedTransportProvider
) : NuGetPackageServiceFeedPublisher {
private var myBuild: AgentRunningBuild? = null
init {
myDispatcher.addListener(object : AgentLifeCycleAdapter() {
override fun buildStarted(runningBuild: AgentRunningBuild) {
myBuild = runningBuild
}
override fun buildFinished(build: AgentRunningBuild, buildStatus: BuildFinishedStatus) {
myBuild = null
}
})
}
override fun publishPackages(packages: Collection<NuGetPackageData>) {
val build = myBuild
if (build == null) {
Loggers.AGENT.warn("Trying to publish packages for finished build")
return
}
logInProgressBlock(build.buildLogger.getFlowLogger(FLOW_ID)) { logger ->
try {
val apiKey = createApiKey(build)
val transport = myFeedTransportProvider.createTransport(build)
val failedToPublish = mutableListOf<NuGetPackageData>()
for (nuGetPackage in packages) {
logger.message("Publishing ${nuGetPackage.path} package")
val file = File(nuGetPackage.path)
val response = transport.sendPackage(apiKey, file)
if (!response.isSuccessful) {
failedToPublish.add(nuGetPackage)
Loggers.AGENT.debug("Failed publishing ${nuGetPackage.path} package StatusCode: ${response.statusCode}, response: ${response.message}")
}
}
if (failedToPublish.any()) {
throw PackagePublishException("Failed to publish NuGet package(s) ${failedToPublish.joinToString(", ") { "\"${it.path}\"" }}.")
}
}
catch (e: Throwable) {
logger.error(e.message)
Loggers.AGENT.warnAndDebugDetails("Failed to publish NuGet packages", e)
}
}
}
private fun createApiKey(build: AgentRunningBuild): String {
val buildToken = String.format("%s:%s", BuildAuthUtil.makeUserId(build.buildId), build.accessCode)
return EncryptUtil.scramble(buildToken)
}
private fun logInProgressBlock(progressLogger: FlowLogger, action: (progressLogger: BuildProgressLogger) -> Unit) {
progressLogger.startFlow()
progressLogger.logMessage(DefaultMessagesInfo.createBlockStart(BLOCK_NAME, BLOCK_TYPE))
try {
action(progressLogger)
}
finally {
progressLogger.logMessage(DefaultMessagesInfo.createBlockEnd(BLOCK_NAME, BLOCK_TYPE))
progressLogger.disposeFlow()
}
}
private companion object {
const val BLOCK_TYPE = "publish-nuget-packages"
const val BLOCK_NAME = "Publishing NuGet packages"
const val FLOW_ID = "publish-nuget-packages-flow-id"
}
}
| apache-2.0 | 679fef4f953b59dcd41f05b1f0f5198a | 40.786517 | 159 | 0.659048 | 4.906332 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/util/MarkdownPsiUtil.kt | 4 | 1307 | package org.intellij.plugins.markdown.util
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.psi.util.hasType
internal object MarkdownPsiUtil {
object WhiteSpaces {
/** Check if element is new line */
@JvmStatic
fun isNewLine(element: PsiElement): Boolean {
return element.hasType(MarkdownTokenTypeSets.WHITE_SPACES) && element.text == "\n"
}
/** Check if element is whitespace -- not a new line, not `>` blockquote */
@JvmStatic
fun isWhiteSpace(element: PsiElement): Boolean {
return element.hasType(MarkdownTokenTypeSets.WHITE_SPACES) && element.text.all { it.isWhitespace() && it != '\n' }
}
}
fun findNonWhiteSpacePrevSibling(file: PsiFile, offset: Int): PsiElement? {
var offset = offset
while (offset > 0) {
val element = file.findElementAt(offset)
if (element == null) {
offset--
continue
}
if (!MarkdownTokenTypeSets.WHITE_SPACES.contains(element.node.elementType)) {
return element
}
val newOffset = element.textOffset
if (newOffset < offset) {
offset = newOffset
}
else {
offset--
}
}
return null
}
}
| apache-2.0 | 46e4206d79be43e7ee353bc7299ab322 | 28.704545 | 120 | 0.662586 | 4.342193 | false | false | false | false |
GunoH/intellij-community | plugins/stats-collector/test/com/intellij/stats/completion/tracker/FileLoggerTest.kt | 4 | 3573 | // Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.stats.completion.tracker
import com.intellij.codeInsight.lookup.LookupManagerListener
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.CaretModel
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.stats.completion.storage.FilePathProvider
import com.intellij.testFramework.HeavyPlatformTestCase
import com.intellij.testFramework.replaceService
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.StandardWatchEventKinds
import java.util.*
import java.util.concurrent.TimeUnit
class FileLoggerTest : HeavyPlatformTestCase() {
private lateinit var dir: File
private lateinit var logFile: File
private lateinit var pathProvider: FilePathProvider
override fun setUp() {
super.setUp()
dir = createTempDirectory()
logFile = File(dir, "unique_1")
pathProvider = mock(FilePathProvider::class.java).apply {
`when`(getStatsDataDirectory()).thenReturn(dir)
`when`(getUniqueFile()).thenReturn(logFile)
}
project.messageBus.connect(testRootDisposable).subscribe(LookupManagerListener.TOPIC, CompletionLoggerInitializer())
}
override fun tearDown() {
try {
dir.deleteRecursively()
}
finally {
super.tearDown()
}
}
@Test
fun testLogging() {
val fileLengthBefore = logFile.length()
val uidProvider = mock(InstallationIdProvider::class.java).apply {
`when`(installationId()).thenReturn(UUID.randomUUID().toString())
}
ApplicationManager.getApplication().replaceService(FilePathProvider::class.java, pathProvider, testRootDisposable)
ApplicationManager.getApplication().replaceService(InstallationIdProvider::class.java, uidProvider, testRootDisposable)
val loggerProvider = CompletionFileLoggerProvider()
val logger = loggerProvider.newCompletionLogger(Language.ANY.displayName, shouldLogElementFeatures = true)
val documentMock = mock(Document::class.java).apply {
`when`(text).thenReturn("")
}
val editorMock = mock(Editor::class.java).apply {
`when`(caretModel).thenReturn(mock(CaretModel::class.java))
`when`(document).thenReturn(documentMock)
}
val lookup = mock(LookupImpl::class.java).apply {
`when`(getRelevanceObjects(ArgumentMatchers.any(), ArgumentMatchers.anyBoolean())).thenReturn(emptyMap())
`when`(items).thenReturn(emptyList())
`when`(psiFile).thenReturn(null)
`when`(editor).thenReturn(editorMock)
}
val watchService = FileSystems.getDefault().newWatchService()
val key = dir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY)
logger.completionStarted(lookup, 0, true, 2, System.currentTimeMillis())
logger.completionCancelled(true, emptyMap(), System.currentTimeMillis())
loggerProvider.dispose()
var attemps = 0
while (!logFile.exists() && attemps < 5) {
watchService.poll(15, TimeUnit.SECONDS)
attemps += 1
}
key.cancel()
watchService.close()
assertThat(logFile.length()).isGreaterThan(fileLengthBefore)
}
} | apache-2.0 | 6f2d338ce8fd789f74353492bb13e936 | 34.386139 | 140 | 0.754828 | 4.592545 | false | true | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/GHSuggestedChange.kt | 8 | 1835 | // 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.github.pullrequest.comment
import com.intellij.openapi.diff.impl.patch.PatchHunk
import com.intellij.openapi.diff.impl.patch.PatchLine
import com.intellij.openapi.diff.impl.patch.PatchReader
import org.jetbrains.plugins.github.util.GHPatchHunkUtil
data class GHSuggestedChange(
val commentBody: String,
val patchHunk: PatchHunk,
val filePath: String,
val startLine: Int,
val endLine: Int
) {
fun cutContextContent(): List<String> = patchHunk.lines
.filter { it.type != PatchLine.Type.REMOVE }
.dropLast(endLine - startLine + 1)
.takeLast(3)
.map { it.text }
fun cutChangedContent(): List<String> = patchHunk.lines
.filter { it.type != PatchLine.Type.REMOVE }
.takeLast(endLine - startLine + 1)
.map { it.text }
fun cutSuggestedChangeContent(): List<String> {
return commentBody.lines()
.dropWhile { !it.startsWith("```suggestion") }
.drop(1)
.takeWhile { !it.startsWith("```") }
}
companion object {
fun create(commentBody: String, diffHunk: String, filePath: String, startLine: Int, endLine: Int): GHSuggestedChange {
val patchHunk = parseDiffHunk(diffHunk, filePath)
return GHSuggestedChange(commentBody, patchHunk, filePath, startLine - 1, endLine - 1)
}
fun containsSuggestedChange(markdownText: String): Boolean = markdownText.lines().any { it.startsWith("```suggestion") }
private fun parseDiffHunk(diffHunk: String, filePath: String): PatchHunk {
val patchReader = PatchReader(GHPatchHunkUtil.createPatchFromHunk(filePath, diffHunk))
patchReader.readTextPatches()
return patchReader.textPatches[0].hunks.lastOrNull() ?: PatchHunk(0, 0, 0, 0)
}
}
} | apache-2.0 | 993e3f03a713939a6fba4cfcb6362cad | 36.469388 | 124 | 0.718256 | 3.626482 | false | false | false | false |
neverwoodsS/MagicPen | lib/src/main/java/com/lab/zhangll/magicpen/lib/shapes/MagicCircle.kt | 1 | 1288 | package com.lab.zhangll.magicpen.lib.shapes
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import com.lab.zhangll.magicpen.lib.base.centerX
import com.lab.zhangll.magicpen.lib.base.centerY
/**
* Created by zhangll on 2017/5/20.
*/
class MagicCircle : MagicShape() {
var center: PointF? = PointF(0f, 0f)
set(value) {
field = value
reLocate()
}
var radius: Float = 0f
set(value) {
width = value * 2
height = value * 2
field = value
reLocate()
}
override var paint: Paint = Paint()
override fun containPoint(x: Float, y: Float): Boolean {
if (containInRect(x, y)) {
val dx = x - centerX
val dy = y - centerY
return dx * dx + dy * dy <= width * width / 4
}
return false
}
override fun drawOn(canvas: Canvas?) = canvas?.drawCircle(centerX, centerY, width / 2, paint)
fun reLocate() {
if (center != null) {
start = PointF(center!!.x - radius, center!!.y - radius)
end = PointF(center!!.x + radius, center!!.y + radius)
}
}
override fun reBounds() {
reLocate()
super.reBounds()
}
} | mit | f67ff1dfc05702d1dfee4cba0852c4b8 | 24.78 | 97 | 0.557453 | 3.856287 | false | false | false | false |
marukami/RxKotlin-Android-Samples | app/src/main/kotlin/au/com/tilbrook/android/rxkotlin/fragments/DebounceSearchEmitterFragment.kt | 1 | 5026 | package au.com.tilbrook.android.rxkotlin.fragments
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.*
import android.view.inputmethod.EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.LinearLayout.HORIZONTAL
import android.widget.ListView
import au.com.tilbrook.android.rxkotlin.R
import au.com.tilbrook.android.rxkotlin.utils.unSubscribeIfNotNull
import com.jakewharton.rxbinding.widget.RxTextView
import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.ctx
import rx.Observer
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.lang.kotlin.subscriber
import timber.log.Timber
import java.util.*
import java.util.concurrent.TimeUnit
class DebounceSearchEmitterFragment : BaseFragment() {
private lateinit var _logsList: ListView
private lateinit var _inputSearchText: EditText
private lateinit var _adapter: LogAdapter
private lateinit var _logs: ArrayList<String>
private lateinit var _subscription: Subscription
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
_setupLogger()
_subscription = RxTextView.textChangeEvents(_inputSearchText)
.debounce(400, TimeUnit.MILLISECONDS) // default Scheduler is Computation
.observeOn(AndroidSchedulers.mainThread())
.subscribe(_getSearchObserver())
}
override fun onCreateView(inflater: LayoutInflater?,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return with(ctx) {
verticalLayout {
lparams(width = matchParent, height = matchParent)
textView(R.string.msg_demo_debounce) {
lparams(width = matchParent)
padding = dip(10)
gravity = Gravity.CENTER
}
linearLayout {
lparams(width = matchParent)
orientation = HORIZONTAL
_inputSearchText = editText {
lparams {
weight = 7f
height = matchParent
width = 0
}
textSize = 16f
hint = "Enter some search text"
inputType = TYPE_TEXT_FLAG_NO_SUGGESTIONS
}
imageButton(android.R.drawable.ic_menu_close_clear_cancel) {
lparams(width = 0, weight = 1f)
onClick {
onClearLog()
}
}
}
_logsList = listView {
lparams(width = matchParent, height = matchParent)
}
}
}
}
override fun onDestroy() {
super.onDestroy()
_subscription.unSubscribeIfNotNull()
}
fun onClearLog() {
_logs = ArrayList<String>()
_adapter.clear()
}
// -----------------------------------------------------------------------------------
// Main Rx entities
private fun _getSearchObserver(): Observer<TextViewTextChangeEvent> {
return subscriber<TextViewTextChangeEvent>()
.onCompleted { Timber.d("--------- onComplete") }
.onError {
Timber.e(it, "--------- Woops on error!")
_log("Dang error. check your logs")
}
.onNext {
_log("Searching for ${it.text().toString()}")
}
}
// -----------------------------------------------------------------------------------
// Method that help wiring up the example (irrelevant to RxJava)
private fun _setupLogger() {
_logs = ArrayList<String>()
_adapter = LogAdapter(activity, ArrayList<String>())
_logsList.adapter = _adapter
}
private fun _log(logMsg: String) {
if (_isCurrentlyOnMainThread()) {
_logs.add(0, "$logMsg (main thread) ")
_adapter.clear()
_adapter.addAll(_logs)
} else {
_logs.add(0, "$logMsg (NOT main thread) ")
// You can only do below stuff on main thread.
Handler(Looper.getMainLooper()).post(object : Runnable {
override fun run() {
_adapter.clear()
_adapter.addAll(_logs)
}
})
}
}
private fun _isCurrentlyOnMainThread(): Boolean {
return Looper.myLooper() == Looper.getMainLooper()
}
private inner class LogAdapter(context: Context, logs: List<String>) : ArrayAdapter<String>(
context, R.layout.item_log, R.id.item_log, logs)
} | apache-2.0 | beea5ae997aca6d89285cb10e9966341 | 33.431507 | 96 | 0.553522 | 5.307286 | false | false | false | false |
airbnb/lottie-android | sample-compose/src/main/java/com/airbnb/lottie/sample/compose/examples/TransitionsExamplesPage.kt | 1 | 4211 | package com.airbnb.lottie.sample.compose.examples
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.compose.rememberLottieAnimatable
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCancellationBehavior
import com.airbnb.lottie.compose.LottieClipSpec
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
import com.airbnb.lottie.sample.compose.R
import kotlinx.coroutines.flow.collectLatest
enum class TransitionSection {
Intro,
LoopMiddle,
Outro;
fun next(): TransitionSection = when (this) {
Intro -> LoopMiddle
LoopMiddle -> Outro
Outro -> Intro
}
}
@Composable
fun TransitionsExamplesPage() {
var state by remember { mutableStateOf(TransitionSection.Intro) }
UsageExamplePageScaffold { padding ->
Column(
modifier = Modifier
.padding(padding)
) {
Text(
"Single composition",
modifier = Modifier
.padding(8.dp)
)
SingleCompositionTransition(state)
Text(
"Multiple compositions",
modifier = Modifier
.padding(8.dp)
)
SplitCompositionTransition(state)
TextButton(
onClick = { state = state.next() }
) {
Text("State: $state")
}
}
}
}
@Composable
fun SingleCompositionTransition(section: TransitionSection) {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.bar))
val animatable = rememberLottieAnimatable()
val state by rememberUpdatedState(section)
LaunchedEffect(composition, animatable) {
composition ?: return@LaunchedEffect
snapshotFlow { state }.collectLatest { s ->
val clipSpec = when (s) {
TransitionSection.Intro -> LottieClipSpec.Progress(0f, 0.301f)
TransitionSection.LoopMiddle -> LottieClipSpec.Progress(0.301f, 2f / 3f)
TransitionSection.Outro -> LottieClipSpec.Progress(2f / 3f, 1f)
}
do {
animatable.animate(
composition,
clipSpec = clipSpec,
cancellationBehavior = LottieCancellationBehavior.OnIterationFinish,
)
} while (s == TransitionSection.LoopMiddle)
}
}
LottieAnimation(composition, { animatable.progress })
}
@Composable
fun SplitCompositionTransition(section: TransitionSection) {
val introComposition = rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.bar_1))
val loopMiddleComposition = rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.bar_2))
val outroComposition = rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.bar_3))
val animatable = rememberLottieAnimatable()
LaunchedEffect(section) {
val composition = when (section) {
TransitionSection.Intro -> introComposition
TransitionSection.LoopMiddle -> loopMiddleComposition
TransitionSection.Outro -> outroComposition
}.await()
animatable.animate(
composition,
iterations = if (section == TransitionSection.LoopMiddle) LottieConstants.IterateForever else 1,
cancellationBehavior = LottieCancellationBehavior.OnIterationFinish,
)
}
LottieAnimation(animatable.composition, { animatable.progress })
} | apache-2.0 | 42286d27b3bbe213ab7d0fc39181e572 | 35 | 108 | 0.684873 | 5.031063 | false | false | false | false |
oldergod/android-architecture | app/src/test/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsViewModelTest.kt | 1 | 4852 | /*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.statistics
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import com.example.android.architecture.blueprints.todoapp.util.schedulers.BaseSchedulerProvider
import com.example.android.architecture.blueprints.todoapp.util.schedulers.ImmediateSchedulerProvider
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.observers.TestObserver
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
/**
* Unit tests for the implementation of [StatisticsViewModel]
*/
class StatisticsViewModelTest {
@Mock
private lateinit var tasksRepository: TasksRepository
private lateinit var schedulerProvider: BaseSchedulerProvider
private lateinit var statisticsViewModel: StatisticsViewModel
private lateinit var testObserver: TestObserver<StatisticsViewState>
private lateinit var tasks: List<Task>
@Before
fun setupStatisticsViewModel() {
// Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
// inject the mocks in the test the initMocks method needs to be called.
MockitoAnnotations.initMocks(this)
// Make the sure that all schedulers are immediate.
schedulerProvider = ImmediateSchedulerProvider()
// Get a reference to the class under test
statisticsViewModel =
StatisticsViewModel(StatisticsActionProcessorHolder(tasksRepository, schedulerProvider))
// We subscribe the tasks to 3, with one active and two completed
tasks = listOf(
Task(title = "Title1", description = "Description1"),
Task(title = "Title2", description = "Description2", completed = true),
Task(title = "Title3", description = "Description3", completed = true))
testObserver = statisticsViewModel.states().test()
}
@Test
fun loadEmptyTasksFromRepository_CallViewToDisplay() {
// Given an initialized StatisticsViewModel with no tasks
tasks = emptyList()
setTasksAvailable(tasks)
// When loading of tasks is initiated by first initial intent
statisticsViewModel.processIntents(Observable.just(StatisticsIntent.InitialIntent))
// Then loading state is emitted
testObserver.assertValueAt(1, StatisticsViewState::isLoading)
// Callback is captured and invoked with stubbed tasks
verify<TasksRepository>(tasksRepository).getTasks()
// Then not loading, data furnished state in emitted to the view
testObserver.assertValueAt(2) { (isLoading, activeCount, completedCount) ->
!isLoading && activeCount == 0 && completedCount == 0
}
}
@Test
fun loadNonEmptyTasksFromRepository_CallViewToDisplay() {
// Given an initialized StatisticsViewModel with 1 active and 2 completed tasks
setTasksAvailable(tasks)
// When loading of tasks is initiated by first initial intent
statisticsViewModel.processIntents(Observable.just(StatisticsIntent.InitialIntent))
// Then progress indicator is shown
testObserver.assertValueAt(1, StatisticsViewState::isLoading)
// Then progress indicator is hidden and correct data is passed on to the view
testObserver.assertValueAt(2) { (isLoading, activeCount, completedCount) ->
!isLoading && activeCount == 1 && completedCount == 2
}
}
@Test
fun loadStatisticsWhenTasksAreUnavailable_CallErrorToDisplay() {
// Given that tasks data isn't available
setTasksNotAvailable()
// When loading of tasks is initiated by first initial intent
statisticsViewModel.processIntents(Observable.just(StatisticsIntent.InitialIntent))
// Then an error message is shown
testObserver.assertValueAt(2) { (_, _, _, error) -> error != null }
}
private fun setTasksAvailable(tasks: List<Task>?) {
`when`(tasksRepository.getTasks()).thenReturn(Single.just(tasks))
}
private fun setTasksNotAvailable() {
// TODO(benoit) RxJava would print the stacktrace. I'd like to hide that
`when`(tasksRepository.getTasks()).thenReturn(Single.error(Throwable("not available")))
}
}
| apache-2.0 | b7561048cc127c92ac3206ff1e997811 | 38.129032 | 101 | 0.758656 | 4.747554 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywherePsiElementFeaturesProvider.kt | 7 | 5184 | package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.ide.actions.searcheverywhere.ClassSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.FileSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.PSIPresentationBgRendererWrapper.PsiItemWithPresentation
import com.intellij.ide.actions.searcheverywhere.RecentFilesSEContributor
import com.intellij.ide.actions.searcheverywhere.SymbolSearchEverywhereContributor
import com.intellij.internal.statistic.collectors.fus.LangCustomRuleValidator
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.local.LanguageUsageStatistics
import com.intellij.lang.Language
import com.intellij.lang.LanguageUtil
import com.intellij.openapi.application.ReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.util.Time.DAY
import com.intellij.util.Time.WEEK
internal class SearchEverywherePsiElementFeaturesProvider : SearchEverywhereElementFeaturesProvider(
FileSearchEverywhereContributor::class.java,
RecentFilesSEContributor::class.java,
ClassSearchEverywhereContributor::class.java,
SymbolSearchEverywhereContributor::class.java,
) {
companion object {
@JvmStatic
val IS_INVALID_DATA_KEY = EventFields.Boolean("isInvalid")
private val LANGUAGE_DATA_KEY = EventFields.StringValidatedByCustomRule("language", LangCustomRuleValidator::class.java)
private val LANGUAGE_USE_COUNT_DATA_KEY = EventFields.Int("langUseCount")
private val LANGUAGE_IS_MOST_USED_DATA_KEY = EventFields.Boolean("langIsMostUsed")
private val LANGUAGE_IS_IN_TOP_3_MOST_USED_DATA_KEY = EventFields.Boolean("langIsInTop3MostUsed")
private val LANGUAGE_USED_IN_LAST_DAY = EventFields.Boolean("langUsedInLastDay")
private val LANGUAGE_USED_IN_LAST_WEEK = EventFields.Boolean("langUsedInLastWeek")
private val LANGUAGE_USED_IN_LAST_MONTH = EventFields.Boolean("langUsedInLastMonth")
private val LANGUAGE_NEVER_USED_DATA_KEY = EventFields.Boolean("langNeverUsed")
private val LANGUAGE_IS_SAME_AS_OPENED_FILE = EventFields.Boolean("langSameAsOpenedFile")
fun getPsiElement(element: Any) = when (element) {
is PsiItemWithPresentation -> element.item
is PsiElement -> element
else -> null
}
}
override fun getFeaturesDeclarations(): List<EventField<*>> = listOf(
IS_INVALID_DATA_KEY,
LANGUAGE_DATA_KEY, LANGUAGE_USE_COUNT_DATA_KEY, LANGUAGE_IS_MOST_USED_DATA_KEY,
LANGUAGE_IS_IN_TOP_3_MOST_USED_DATA_KEY, LANGUAGE_USED_IN_LAST_DAY, LANGUAGE_USED_IN_LAST_WEEK,
LANGUAGE_USED_IN_LAST_MONTH, LANGUAGE_NEVER_USED_DATA_KEY, LANGUAGE_IS_SAME_AS_OPENED_FILE
)
override fun getElementFeatures(element: Any,
currentTime: Long,
searchQuery: String,
elementPriority: Int,
cache: FeaturesProviderCache?): List<EventPair<*>> {
val psiElement = getPsiElement(element) ?: return emptyList()
return getLanguageFeatures(psiElement, cache) + getNameFeatures(element, searchQuery)
}
private fun getLanguageFeatures(element: PsiElement, cache: FeaturesProviderCache?): List<EventPair<*>> {
if (cache == null) return emptyList()
val elementLanguage = ReadAction.compute<Language, Nothing> { element.language }
val stats = cache.usageSortedLanguageStatistics.getOrDefault(elementLanguage.id, LanguageUsageStatistics.NEVER_USED)
val languageUsageIndex = cache.usageSortedLanguageStatistics
.values
.take(3)
.indexOf(stats)
val isMostUsed = languageUsageIndex == 0
val isInTop3MostUsed = languageUsageIndex < 3
val timeSinceLastUsage = System.currentTimeMillis() - stats.lastUsed
val features = mutableListOf(
LANGUAGE_DATA_KEY.with(elementLanguage.id),
LANGUAGE_IS_MOST_USED_DATA_KEY.with(isMostUsed),
LANGUAGE_IS_IN_TOP_3_MOST_USED_DATA_KEY.with(isInTop3MostUsed),
LANGUAGE_USED_IN_LAST_DAY.with(timeSinceLastUsage <= DAY),
LANGUAGE_USED_IN_LAST_WEEK.with(timeSinceLastUsage <= WEEK),
LANGUAGE_USED_IN_LAST_MONTH.with(timeSinceLastUsage <= WEEK * 4L),
LANGUAGE_NEVER_USED_DATA_KEY.with(stats == LanguageUsageStatistics.NEVER_USED),
)
if (cache.currentlyOpenedFile != null) {
val openedFileLanguage = LanguageUtil.getFileLanguage(cache.currentlyOpenedFile)
features.add(LANGUAGE_IS_SAME_AS_OPENED_FILE.with(openedFileLanguage == elementLanguage))
}
return features
}
private fun getNameFeatures(element: Any, searchQuery: String): Collection<EventPair<*>> {
return getElementName(element)?.let {
getNameMatchingFeatures(it, searchQuery)
} ?: emptyList()
}
private fun getElementName(element: Any) = when (element) {
is PsiItemWithPresentation -> element.presentation.presentableText
is PsiNamedElement -> ReadAction.compute<String, Nothing> { element.name }
else -> null
}
}
| apache-2.0 | 424714b9dc3d871f58453360bb30acf5 | 46.559633 | 124 | 0.757909 | 4.345348 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/ObsoleteKotlinJsPackagesInspection.kt | 5 | 5580 | // 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.migration
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.backend.common.serialization.findPackage
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
internal class ObsoleteKotlinJsPackagesInspection : ObsoleteCodeMigrationInspection() {
override val fromVersion: LanguageVersion = LanguageVersion.KOTLIN_1_3
override val toVersion: LanguageVersion = LanguageVersion.KOTLIN_1_4
override val problemReporters: List<ObsoleteCodeProblemReporter> = listOf(
KotlinBrowserFullyQualifiedUsageReporter,
KotlinBrowserImportUsageReporter,
KotlinDomImportUsageReporter
)
}
private object ObsoleteKotlinJsPackagesUsagesInWholeProjectFix : ObsoleteCodeInWholeProjectFix() {
override val inspectionName: String = ObsoleteKotlinJsPackagesInspection().shortName
override fun getFamilyName(): String = KotlinBundle.message("obsolete.kotlin.js.packages.usage.in.whole.fix.family.name")
}
private const val KOTLIN_BROWSER_PACKAGE = "kotlin.browser"
private const val KOTLINX_BROWSER_PACKAGE = "kotlinx.browser"
private const val KOTLIN_DOM_PACKAGE = "kotlin.dom"
private class ObsoleteKotlinBrowserUsageFix(delegate: ObsoleteCodeFix) : ObsoleteCodeFixDelegateQuickFix(delegate) {
override fun getFamilyName(): String = KotlinBundle.message("obsolete.package.usage.fix.family.name", KOTLIN_BROWSER_PACKAGE)
}
private class ObsoleteKotlinDomUsageFix(delegate: ObsoleteCodeFix) : ObsoleteCodeFixDelegateQuickFix(delegate) {
override fun getFamilyName(): String = KotlinBundle.message("obsolete.package.usage.fix.family.name", KOTLIN_DOM_PACKAGE)
}
/**
* We have such inspection only for 'kotlin.browser' package; it is because 'kotlin.dom' package has only extension functions. Such
* functions cannot be used with fully qualified name.
*/
private object KotlinBrowserFullyQualifiedUsageReporter : ObsoleteCodeProblemReporter {
override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean {
val fullyQualifiedExpression = simpleNameExpression.parent as? KtDotQualifiedExpression ?: return false
val kotlinBrowserQualifier = fullyQualifiedExpression.receiverExpression as? KtDotQualifiedExpression ?: return false
if (kotlinBrowserQualifier.text != KOTLIN_BROWSER_PACKAGE) return false
if (!resolvesToKotlinBrowserPackage(simpleNameExpression)) return false
holder.registerProblem(
kotlinBrowserQualifier,
KotlinBundle.message("package.usages.are.obsolete.since.1.4", KOTLIN_DOM_PACKAGE),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixesWithWholeProject(
isOnTheFly,
fix = ObsoleteKotlinBrowserUsageFix(KotlinBrowserFullyQualifiedUsageFix),
wholeProjectFix = ObsoleteKotlinJsPackagesUsagesInWholeProjectFix
)
)
return true
}
private fun resolvesToKotlinBrowserPackage(simpleNameExpression: KtSimpleNameExpression): Boolean {
val referencedDescriptor =
simpleNameExpression.resolveMainReferenceToDescriptors().singleOrNull() as? CallableDescriptor ?: return false
return referencedDescriptor.findPackage().fqName.asString() == KOTLIN_BROWSER_PACKAGE
}
object KotlinBrowserFullyQualifiedUsageFix : ObsoleteCodeFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val oldQualifier = descriptor.psiElement as? KtDotQualifiedExpression ?: return
val newQualifier = KtPsiFactory(oldQualifier).createExpression(KOTLINX_BROWSER_PACKAGE)
oldQualifier.replace(newQualifier)
}
}
}
private object KotlinBrowserImportUsageReporter : ObsoleteImportsUsageReporter() {
override val textMarker: String = "browser"
override val packageBindings: Map<String, String> = mapOf(KOTLIN_BROWSER_PACKAGE to KOTLINX_BROWSER_PACKAGE)
override val wholeProjectFix: LocalQuickFix = ObsoleteKotlinJsPackagesUsagesInWholeProjectFix
override fun problemMessage(): String = KotlinBundle.message("package.usages.are.obsolete.since.1.4", KOTLIN_BROWSER_PACKAGE)
override fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix = ObsoleteKotlinBrowserUsageFix(fix)
}
private object KotlinDomImportUsageReporter : ObsoleteImportsUsageReporter() {
override val textMarker: String = "dom"
override val packageBindings: Map<String, String> = mapOf(KOTLIN_DOM_PACKAGE to "kotlinx.dom")
override val wholeProjectFix: LocalQuickFix = ObsoleteKotlinJsPackagesUsagesInWholeProjectFix
override fun problemMessage(): String = KotlinBundle.message("package.usages.are.obsolete.since.1.4", KOTLIN_DOM_PACKAGE)
override fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix = ObsoleteKotlinDomUsageFix(fix)
}
| apache-2.0 | 1cd8785ac47e855aaa67bcea65256ba5 | 50.192661 | 158 | 0.788351 | 4.907652 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/settings-sync/tests/com/intellij/settingsSync/SettingsSyncTestInfra.kt | 2 | 2738 | package com.intellij.settingsSync
import com.intellij.configurationStore.getDefaultStoragePathSpec
import com.intellij.configurationStore.serializeStateInto
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.settingsSync.SettingsSnapshot.MetaInfo
import com.intellij.util.toBufferExposingByteArray
import com.intellij.util.xmlb.Constants
import org.jdom.Element
import org.junit.Assert
import java.nio.charset.StandardCharsets
import java.time.Instant
internal fun SettingsSnapshot.assertSettingsSnapshot(build: SettingsSnapshotBuilder.() -> Unit) {
val settingsSnapshotBuilder = SettingsSnapshotBuilder()
settingsSnapshotBuilder.build()
val transformation = { fileState: FileState ->
val content = if (fileState is FileState.Modified) String(fileState.content, StandardCharsets.UTF_8) else DELETED_FILE_MARKER
fileState.file to content
}
val actualMap = this.fileStates.associate(transformation)
val expectedMap = settingsSnapshotBuilder.fileStates.associate(transformation)
Assert.assertEquals(expectedMap, actualMap)
}
internal fun PersistentStateComponent<*>.toFileState() : FileState {
val file = PathManager.OPTIONS_DIRECTORY + "/" + getDefaultStoragePathSpec(this::class.java)
val content = this.serialize()
return FileState.Modified(file, content, content.size)
}
internal val <T> PersistentStateComponent<T>.name: String
get() = (this::class.annotations.find { it is State } as? State)?.name!!
internal fun PersistentStateComponent<*>.serialize(): ByteArray {
val compElement = Element("component")
compElement.setAttribute(Constants.NAME, this.name)
serializeStateInto(this, compElement)
val appElement = Element("application")
appElement.addContent(compElement)
return appElement.toBufferExposingByteArray().toByteArray()
}
internal fun settingsSnapshot(metaInfo: MetaInfo = MetaInfo(Instant.now(), getLocalApplicationInfo()),
build: SettingsSnapshotBuilder.() -> Unit) : SettingsSnapshot {
val builder = SettingsSnapshotBuilder()
builder.build()
return SettingsSnapshot(metaInfo, builder.fileStates.toSet())
}
internal class SettingsSnapshotBuilder {
val fileStates = mutableListOf<FileState>()
fun fileState(function: () -> PersistentStateComponent<*>) {
val component : PersistentStateComponent<*> = function()
fileStates.add(component.toFileState())
}
fun fileState(fileState: FileState) {
fileStates.add(fileState)
}
fun fileState(file: String, content: String) {
val byteArray = content.toByteArray()
fileState(FileState.Modified(file, byteArray, byteArray.size))
}
}
| apache-2.0 | d8c0d110777bb087da6e11a6a76f4eed | 38.114286 | 129 | 0.783053 | 4.617201 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/Label.kt | 1 | 2741 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.Instructions
/**
* Label.
*
* Labels with empty name will be treated as a scope block.
*/
data class Label(override val name: String, override val body: Instructions) : BodyHolder, Named,
Instruction {
init {
BodyHolder.checkBody(this)
}
override fun builder(): Builder = Builder(this)
class Builder() :
BodyHolder.Builder<Label, Builder>,
Named.Builder<Label, Builder> {
lateinit var name: String
var body: Instructions = Instructions.empty()
constructor(defaults: Label) : this() {
this.name = defaults.name
this.body = defaults.body
}
override fun name(value: String): Builder {
this.name = value
return this
}
override fun body(value: Instructions): Builder {
this.body = value
return this
}
override fun build(): Label = Label(this.name, this.body)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: Label): Builder = Builder(defaults)
}
}
} | mit | 0729c0a8cef9a72864c8cd1cccc41b12 | 33.708861 | 118 | 0.655965 | 4.59129 | false | false | false | false |
DreierF/MyTargets | wearable/src/main/java/de/dreier/mytargets/RoundActivity.kt | 1 | 8873 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.RecyclerView
import android.support.wearable.activity.WearableActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.evernote.android.state.State
import com.evernote.android.state.StateSaver
import de.dreier.mytargets.databinding.ActivityRoundBinding
import de.dreier.mytargets.shared.models.TrainingInfo
import de.dreier.mytargets.shared.models.augmented.AugmentedEnd
import de.dreier.mytargets.shared.models.augmented.AugmentedRound
import de.dreier.mytargets.shared.views.EndView
import de.dreier.mytargets.shared.wearable.WearableClientBase.Companion.BROADCAST_TIMER_SETTINGS_FROM_REMOTE
import de.dreier.mytargets.utils.WearSettingsManager
import de.dreier.mytargets.utils.WearWearableClient
import de.dreier.mytargets.utils.WearWearableClient.Companion.BROADCAST_TRAINING_UPDATED
import java.text.DateFormat
import java.util.*
class RoundActivity : WearableActivity() {
private lateinit var binding: ActivityRoundBinding
@State
internal lateinit var round: AugmentedRound
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
BROADCAST_TRAINING_UPDATED -> {
val (_, _, round1) = intent.getParcelableExtra<TrainingInfo>(WearWearableClient.EXTRA_INFO)
round = round1
showRoundData()
}
BROADCAST_TIMER_SETTINGS_FROM_REMOTE -> applyTimerState()
else -> {
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_round)
setAmbientEnabled()
StateSaver.restoreInstanceState(this, savedInstanceState)
if (savedInstanceState == null) {
val intent = intent
if (intent != null && intent.extras != null) {
round = intent.getParcelableExtra(EXTRA_ROUND)
}
}
showRoundData()
binding.wearableDrawerView.controller.peekDrawer()
// Replaces the on click behaviour that open the (empty) drawer
val peekView = binding.primaryActionTimer.parent as LinearLayout
val peekContainer = peekView.parent as ViewGroup
peekContainer.setOnClickListener { toggleTimer() }
applyTimerState()
val filter = IntentFilter()
filter.addAction(BROADCAST_TRAINING_UPDATED)
filter.addAction(BROADCAST_TIMER_SETTINGS_FROM_REMOTE)
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter)
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
StateSaver.saveInstanceState(this, outState)
}
override fun onDestroy() {
super.onDestroy()
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
}
override fun onEnterAmbient(ambientDetails: Bundle?) {
super.onEnterAmbient(ambientDetails)
binding.drawerLayout.setBackgroundResource(R.color.md_black_1000)
binding.recyclerViewEnds.adapter?.notifyDataSetChanged()
binding.wearableDrawerView.visibility = View.INVISIBLE
binding.clock!!.time.visibility = View.VISIBLE
binding.clock!!.time.text = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date())
}
override fun onUpdateAmbient() {
super.onUpdateAmbient()
binding.clock!!.time.text = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date())
}
override fun onExitAmbient() {
super.onExitAmbient()
binding.drawerLayout.setBackgroundResource(R.color.md_wear_green_dark_background)
binding.recyclerViewEnds.adapter?.notifyDataSetChanged()
binding.wearableDrawerView.visibility = View.VISIBLE
binding.clock!!.time.visibility = View.GONE
}
private fun showRoundData() {
val showAddEnd = round.round.maxEndCount == null || round.round.maxEndCount!! > round.ends.size
binding.recyclerViewEnds.adapter = EndAdapter(round.ends, showAddEnd)
binding.recyclerViewEnds.scrollToPosition(round.ends.size)
}
private fun addEnd() {
val intent = Intent(this, InputActivity::class.java)
intent.putExtra(InputActivity.EXTRA_ROUND, round)
intent.flags = Intent.FLAG_ACTIVITY_NO_ANIMATION
startActivity(intent)
val timerSettings = WearSettingsManager.timerSettings
if (timerSettings.enabled) {
val intentTimer = Intent(this, TimerActivity::class.java)
intentTimer.putExtra(TimerActivity.EXTRA_TIMER_SETTINGS, timerSettings)
startActivity(intentTimer)
}
}
private fun toggleTimer() {
val timerSettings = WearSettingsManager.timerSettings
timerSettings.enabled = !timerSettings.enabled
ApplicationInstance.wearableClient.sendTimerSettingsFromLocal(timerSettings)
applyTimerState()
}
private fun applyTimerState() {
val timerSettings = WearSettingsManager.timerSettings
binding.primaryActionTimer.setImageResource(
if (timerSettings.enabled)
R.drawable.ic_traffic_white_24dp
else
R.drawable.ic_timer_off_white_24dp)
}
private inner class EndAdapter(private val ends: List<AugmentedEnd>, private val showAddEnd: Boolean) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return if (viewType == 0) {
val view = inflater.inflate(R.layout.item_end, parent, false)
ViewHolder(view)
} else {
val view = inflater.inflate(R.layout.item_inline_button, parent, false)
InlineButtonViewHolder(view)
}
}
override fun getItemViewType(position: Int): Int {
return if (position == ends.size) 1 else 0
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ViewHolder) {
val end = ends[position]
holder.end.text = getString(R.string.end_n, end.end.index + 1)
holder.shots.setShots(round.round.target, end.shots)
holder.end.setTextColor(ContextCompat.getColor(this@RoundActivity,
if (isAmbient)
R.color.md_white_1000
else
R.color.md_wear_green_active_ui_element))
holder.shots.setAmbientMode(isAmbient)
holder.itemView.setBackgroundColor(ContextCompat.getColor(this@RoundActivity,
if (isAmbient)
R.color.md_black_1000
else
R.color.md_wear_green_lighter_background))
} else if (holder is InlineButtonViewHolder) {
holder.itemView.visibility = if (isAmbient) View.INVISIBLE else View.VISIBLE
}
}
override fun getItemCount(): Int {
return ends.size + if (showAddEnd) 1 else 0
}
}
private inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val end: TextView = itemView.findViewById(R.id.end)
val shots: EndView = itemView.findViewById(R.id.shoots)
}
private inner class InlineButtonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener { addEnd() }
}
}
companion object {
const val EXTRA_ROUND = "round"
}
}
| gpl-2.0 | 47342d466170cefe2b2ffbb03b133749 | 38.789238 | 157 | 0.676209 | 4.822283 | false | false | false | false |
Pagejects/pagejects-core | src/main/kotlin/net/pagejects/core/element/html/HtmlInputTextImpl.kt | 1 | 829 | package net.pagejects.core.element.html
import com.codeborne.selenide.SelenideElement
/**
* Default implementation of the [HtmlInputText]
*
* @author Andrey Paslavsky
* @since 0.1
*/
class HtmlInputTextImpl(private val selenideElement: SelenideElement) : HtmlInputText{
override fun getSelenideElement(): SelenideElement = selenideElement
override fun getText(): String? = selenideElement.value
override fun setText(text: String?) {
selenideElement.value = text
}
override fun append(text: String) {
selenideElement.append(text)
}
override fun isDisabled(): Boolean = !selenideElement.isEnabled
override fun isReadonly(): Boolean {
val readonly = selenideElement.attr("readonly")
return if (readonly.isNotBlank()) readonly.toBoolean() else false
}
} | apache-2.0 | 7aa37e36b169b9957fd5dfa158bcce2e | 26.666667 | 86 | 0.716526 | 4.791908 | false | false | false | false |
imageprocessor/cv4j | rxcv4j/src/main/java/com/cv4j/rxjava/RxThreshold.kt | 1 | 1870 | /*
* Copyright (c) 2017 - present, CV4J 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
*
* 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.cv4j.rxjava
import com.cv4j.core.binary.Threshold
import com.cv4j.core.datamodel.ByteProcessor
import com.cv4j.core.datamodel.CV4JImage
import io.reactivex.Flowable
import io.reactivex.functions.Function
class RxThreshold private constructor(image: CV4JImage) {
private val flowable: Flowable<CV4JImage>
private var type: Int = 0
private var method: Int = 0
private var thresh: Int = 0
init {
flowable = Flowable.just(image)
}
fun type(type: Int): RxThreshold {
this.type = type
return this
}
fun method(method: Int): RxThreshold {
this.method = method
return this
}
fun thresh(thresh: Int): RxThreshold {
this.thresh = thresh
return this
}
fun process(): Flowable<ByteProcessor> {
return flowable.map(Function<CV4JImage, ByteProcessor> { cv4JImage ->
val threshold = Threshold()
threshold.process(cv4JImage.convert2Gray().processor as ByteProcessor, type, method, thresh)
cv4JImage.processor as ByteProcessor
})
}
companion object {
@JvmStatic
fun image(image: CV4JImage): RxThreshold {
return RxThreshold(image)
}
}
} | apache-2.0 | b90549d1f9a8aaa13d7833d0c17e5604 | 24.630137 | 104 | 0.674866 | 4.082969 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/network/ResponseCacheController.kt | 1 | 3848 | package com.esafirm.androidplayground.network
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.esafirm.androidplayground.common.BaseController
import com.esafirm.androidplayground.network.services.HttpBin
import com.esafirm.androidplayground.network.services.response.HttpBinResponse
import com.esafirm.androidplayground.libs.Logger
import com.esafirm.androidplayground.utils.button
import com.esafirm.androidplayground.utils.logger
import com.esafirm.androidplayground.utils.row
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.system.measureTimeMillis
class ResponseCacheController : BaseController() {
private val request by lazy {
Net.getCacheService(requiredContext, "https://httpbin.org/", HttpBin::class.java)
}
private val cacheRequest by lazy {
Net.getCacheService(requiredContext, "https://httpbin.org/", HttpBin::class.java, true)
}
private val simpleCache by lazy {
SharedPrefCache(requiredContext)
}
private val scope = CoroutineScope(Dispatchers.IO)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
return row {
button("Request HTTP with Cache Control") {
scope.launch {
val start = System.currentTimeMillis()
val res = request.getCache()
val isCache = res.raw().cacheResponse != null
measureTimeMillis {
val body = res.body()
if (body != null) {
simpleCache.set(body)
}
}.also {
Logger.log("Simple cache save took $it ms")
}
val delta = System.currentTimeMillis() - start
Logger.log("Request took $delta ms. Is cache response: $isCache")
}
}
button("Request Force Cache Only") {
scope.launch {
val start = System.currentTimeMillis()
val res = cacheRequest.getCache()
val isCache = res.raw().cacheResponse != null
val delta = System.currentTimeMillis() - start
Logger.log("Cache request took $delta. Is Cache response: $isCache")
Logger.log("Data: ${res.body()?.url}")
}
}
button("Request From Simple Cache") {
scope.launch {
val start = System.currentTimeMillis()
val cache = simpleCache.get()
val delta = System.currentTimeMillis() - start
Logger.log("Simple cache took $delta")
Logger.log("Data: ${cache?.url}")
}
}
logger()
}
}
}
private interface SimpleCache {
fun set(response: HttpBinResponse)
fun get(): HttpBinResponse?
}
class SharedPrefCache(context: Context) : SimpleCache {
companion object {
private const val KEY_CACHE = "Key.Cache"
}
private val sharedPref by lazy { context.getSharedPreferences("SimpleSharedPref", Context.MODE_PRIVATE) }
private val gson by lazy { Gson() }
override fun set(response: HttpBinResponse) {
sharedPref.edit()
.putString(KEY_CACHE, gson.toJson(response))
.apply()
}
override fun get(): HttpBinResponse? {
val rawString = sharedPref.getString(KEY_CACHE, null)
if (rawString != null) {
return gson.fromJson(rawString, HttpBinResponse::class.java)
}
return null
}
}
| mit | 99c580cdb0b145cacf692c976f1e7c4d | 33.053097 | 109 | 0.599012 | 5.04325 | false | false | false | false |
deso88/TinyGit | src/main/kotlin/hamburg/remme/tinygit/gui/CommitLogView.kt | 1 | 9347 | package hamburg.remme.tinygit.gui
import hamburg.remme.tinygit.I18N
import hamburg.remme.tinygit.State
import hamburg.remme.tinygit.TaskListener
import hamburg.remme.tinygit.TinyGit
import hamburg.remme.tinygit.asFilteredList
import hamburg.remme.tinygit.domain.Commit
import hamburg.remme.tinygit.domain.service.BranchService
import hamburg.remme.tinygit.domain.service.CommitLogService
import hamburg.remme.tinygit.domain.service.TagService
import hamburg.remme.tinygit.gui.builder.Action
import hamburg.remme.tinygit.gui.builder.ActionGroup
import hamburg.remme.tinygit.gui.builder.HBoxBuilder
import hamburg.remme.tinygit.gui.builder.addClass
import hamburg.remme.tinygit.gui.builder.alignment
import hamburg.remme.tinygit.gui.builder.comboBox
import hamburg.remme.tinygit.gui.builder.confirmWarningAlert
import hamburg.remme.tinygit.gui.builder.contextMenu
import hamburg.remme.tinygit.gui.builder.errorAlert
import hamburg.remme.tinygit.gui.builder.label
import hamburg.remme.tinygit.gui.builder.managedWhen
import hamburg.remme.tinygit.gui.builder.progressIndicator
import hamburg.remme.tinygit.gui.builder.splitPane
import hamburg.remme.tinygit.gui.builder.stackPane
import hamburg.remme.tinygit.gui.builder.textField
import hamburg.remme.tinygit.gui.builder.textInputDialog
import hamburg.remme.tinygit.gui.builder.toolBar
import hamburg.remme.tinygit.gui.builder.tooltip
import hamburg.remme.tinygit.gui.builder.vbox
import hamburg.remme.tinygit.gui.builder.vgrow
import hamburg.remme.tinygit.gui.builder.visibleWhen
import hamburg.remme.tinygit.gui.component.Icons
import javafx.beans.binding.Bindings
import javafx.beans.property.SimpleBooleanProperty
import javafx.collections.ListChangeListener
import javafx.geometry.Pos
import javafx.scene.control.Tab
import javafx.scene.layout.Priority
private const val DEFAULT_STYLE_CLASS = "commit-log-view"
private const val CONTENT_STYLE_CLASS = "${DEFAULT_STYLE_CLASS}__content"
private const val INDICATOR_STYLE_CLASS = "${DEFAULT_STYLE_CLASS}__indicator"
private const val SEARCH_STYLE_CLASS = "${DEFAULT_STYLE_CLASS}__search"
private const val OVERLAY_STYLE_CLASS = "overlay"
/**
* Displaying basically the output of `git log`. Each log entry can be selected to display the details of that
* [Commit].
* This is relying heavily on the [GraphListView] and its skin for displaying the log graph and commit list.
*
* There is also a context menu added to the [GraphListView] for commit related actions.
*
*
* ```
* ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
* ┃ ToolBar ┃
* ┠──────────────────────────────────────┨
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ GraphListView ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
* ┃ ┃
* ┃ CommitDetailsView ┃
* ┃ ┃
* ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
* ```
*
*
* @todo should the actions be exposed and used in the menu bar as well?!
* @todo loading more commits while scrolling down is buggy
*
* @see GraphListView
* @see CommitDetailsView
*/
class CommitLogView : Tab() {
private val state = TinyGit.get<State>()
private val logService = TinyGit.get<CommitLogService>()
private val filterableCommits = logService.commits.asFilteredList()
private val branchService = TinyGit.get<BranchService>()
private val tagService = TinyGit.get<TagService>()
private val graph = GraphListView(filterableCommits)
private val graphSelection get() = graph.selectionModel.selectedItem
init {
text = I18N["commitLog.tab"]
graphic = Icons.list()
isClosable = false
val checkoutCommit = Action(I18N["commitLog.checkout"], { Icons.check() }, disabled = state.canCheckoutCommit.not(),
handler = { checkoutCommit(graphSelection) })
val resetToCommit = Action(I18N["commitLog.reset"], { Icons.refresh() }, disabled = state.canResetToCommit.not(),
handler = { resetToCommit(graphSelection) })
val tagCommit = Action(I18N["commitLog.tag"], { Icons.tag() }, disabled = state.canTagCommit.not(),
handler = { tagCommit(graphSelection) })
graph.items.addListener(ListChangeListener { graph.selectionModel.selectedItem ?: graph.selectionModel.selectFirst() })
graph.selectionModel.selectedItemProperty().addListener { _, _, it -> logService.activeCommit.set(it) }
graph.contextMenu = contextMenu {
isAutoHide = true
+ActionGroup(checkoutCommit, resetToCommit, tagCommit)
}
// TODO
// graph.setOnScroll {
// if (it.deltaY < 0) {
// val index = graph.items.size - 1
// service.logMore()
// graph.scrollTo(index)
// }
// }
// graph.setOnKeyPressed {
// if (it.code == KeyCode.DOWN && graph.selectionModel.selectedItem == graph.items.last()) {
// service.logMore()
// graph.scrollTo(graph.selectionModel.selectedItem)
// }
// }
val indicator = FetchIndicator()
content = vbox {
addClass(DEFAULT_STYLE_CLASS)
+toolBar {
+stackPane {
addClass(SEARCH_STYLE_CLASS)
+Icons.search().alignment(Pos.CENTER_LEFT)
+textField {
promptText = "${I18N["commitLog.search"]} (beta)"
textProperty().addListener { _, _, it -> filterCommits(it) }
}
}
addSpacer()
+indicator
+comboBox<CommitLogService.CommitType> {
items.addAll(CommitLogService.CommitType.values())
valueProperty().bindBidirectional(logService.commitType)
valueProperty().addListener { _, _, it -> graph.isGraphVisible = !it.isNoMerges }
}
+comboBox<CommitLogService.Scope> {
items.addAll(CommitLogService.Scope.values())
valueProperty().bindBidirectional(logService.scope)
}
}
+stackPane {
vgrow(Priority.ALWAYS)
+splitPane {
addClass(CONTENT_STYLE_CLASS)
vgrow(Priority.ALWAYS)
+graph
+CommitDetailsView()
}
+stackPane {
addClass(OVERLAY_STYLE_CLASS)
visibleWhen(Bindings.isEmpty(graph.items))
managedWhen(visibleProperty())
+label { text = I18N["commitLog.noCommits"] }
}
}
}
logService.logListener = indicator
logService.logErrorHandler = { errorAlert(TinyGit.window, I18N["dialog.cannotFetch.header"], it) }
}
private fun filterCommits(value: String?) {
if (value != null && value.isNotBlank()) filterableCommits.setPredicate {
it.author.contains(value, true)
|| it.shortId.contains(value, true)
|| it.fullMessage.contains(value, true)
}
else filterableCommits.setPredicate { true }
}
private fun checkoutCommit(commit: Commit) {
branchService.checkoutCommit(
commit,
{ errorAlert(TinyGit.window, I18N["dialog.cannotCheckout.header"], I18N["dialog.cannotCheckout.text"]) })
}
private fun resetToCommit(commit: Commit) {
if (!confirmWarningAlert(TinyGit.window, I18N["dialog.resetBranch.header"], I18N["dialog.resetBranch.button"], I18N["dialog.resetBranch.text", commit.shortId])) return
branchService.reset(commit)
}
private fun tagCommit(commit: Commit) {
textInputDialog(TinyGit.window, I18N["dialog.tag.header"], I18N["dialog.tag.button"], Icons.tag()) {
tagService.tag(
commit,
it,
{ errorAlert(TinyGit.window, I18N["dialog.cannotTag.header"], I18N["dialog.cannotTag.text", it]) })
}
}
/**
* An indicator to be shown in the toolbar while fetching from remote.
*/
private class FetchIndicator : HBoxBuilder(), TaskListener {
private val visible = SimpleBooleanProperty()
init {
addClass(INDICATOR_STYLE_CLASS)
visibleWhen(visible)
managedWhen(visibleProperty())
+progressIndicator(0.5).tooltip(I18N["commitLog.fetching"])
}
override fun started() = visible.set(true)
override fun done() = visible.set(false)
}
}
| bsd-3-clause | bae7ffe1861a4ceb41e9a6306776ad23 | 40.206422 | 175 | 0.602694 | 4.003119 | false | false | false | false |
ewrfedf/Bandhook-Kotlin | app/src/main/java/com/antonioleiva/bandhookkotlin/ui/activity/scrollwrapper/RecyclerViewScrollWrapper.kt | 4 | 1441 | /*
* Copyright (C) 2015 Antonio Leiva
*
* 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.antonioleiva.bandhookkotlin.ui.activity.scrollwrapper
import android.support.v7.widget.RecyclerView
import java.util.ArrayList
class RecyclerViewScrollWrapper(recyclerView: RecyclerView) : ScrollWrapper {
override var scrollX: Int = 0
override var scrollY: Int = 0
override var dX: Int = 0
override var dY: Int = 0
override var scrollObservers: MutableList<((ScrollWrapper) -> Unit)> = ArrayList()
init {
recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
scrollX += dx
scrollY += dy
dX = dx
dY = dy
scrollObservers forEach { it.invoke(this@RecyclerViewScrollWrapper)}
}
})
}
} | apache-2.0 | 98dfcd482d2047511aa3e2f37242d180 | 34.170732 | 86 | 0.680777 | 4.603834 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2016/Day21.kt | 1 | 1941 | package com.nibado.projects.advent.y2016
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.collect.*
import com.nibado.projects.advent.resourceRegex
object Day21 : Day {
private val matchers = mapOf(
"rotr" to Regex("rotate right ([0-9]+) steps?"),
"rotl" to Regex("rotate left ([0-9]+) steps?"),
"swapl" to Regex("swap letter ([a-z]) with letter ([a-z])"),
"movep" to Regex("move position ([0-9]+) to position ([0-9]+)"),
"swapp" to Regex("swap position ([0-9]+) with position ([0-9]+)"),
"rotp" to Regex("rotate based on position of letter ([a-z])"),
"reverse" to Regex("reverse positions ([0-9]+) through ([0-9]+)"))
val input = resourceRegex(2016, 21, matchers)
override fun part1() = scramble("abcdefgh")
override fun part2() = "abcdefgh".toCharArray().toList().permutations().map { it.joinToString("") }.find { scramble(it) == "fbgdceah" }!!
private fun scramble(password: String) : String {
var list = password.toCharArray().toList()
input.forEach {
when(it.first) {
"rotr" -> list = list.rotateRight(it.second[1].toInt())
"rotl" -> list = list.rotateLeft(it.second[1].toInt())
"swapp" -> list = list.swap(it.second[1].toInt(), it.second[2].toInt())
"swapl" -> list = list.swapByValue(it.second[1][0], it.second[2][0])
"reverse" -> list = list.reverse(it.second[1].toInt(), it.second[2].toInt() - it.second[1].toInt() + 1 )
"movep" -> list = list.move(it.second[1].toInt(), it.second[2].toInt())
"rotp" -> {
val pos = list.indexOf(it.second[1][0])
list = list.rotateRight(if(pos >= 4) pos + 2 else pos + 1)
}
else -> {}
}
}
return list.joinToString("")
}
} | mit | 6e98d8e3f9e351ee55c7fc0640368be2 | 45.238095 | 141 | 0.543019 | 3.621269 | false | false | false | false |
zpao/buck | test/com/facebook/buck/multitenant/query/FsAgnosticSourcePathTest.kt | 1 | 2772 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.multitenant.query
import org.hamcrest.Matchers
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThat
import org.junit.Test
class FsAgnosticSourcePathTest {
@Test
fun toStringIsPath() {
val emptyPath = FsAgnosticSourcePath.of("")
assertEquals("", emptyPath.toString())
val fooBar = FsAgnosticSourcePath.of("foo/bar")
assertEquals("foo/bar", fooBar.toString())
}
@Test
fun compareToIdenticalObject() {
val fooBar = FsAgnosticSourcePath.of("foo/bar")
assertEquals(0, fooBar.compareTo(fooBar))
}
@Test
fun compareFsAgnosticSourcePathsToEachOther() {
val alpha = FsAgnosticSourcePath.of("alpha/foo")
val beta = FsAgnosticSourcePath.of("beta/foo")
assertThat(alpha.compareTo(beta), Matchers.lessThan(0))
assertThat(beta.compareTo(alpha), Matchers.greaterThan(0))
}
/**
* This is designed to exercise the "compareClasses" logic in [FsAgnosticSourcePath.compareTo].
*/
@Test
fun compareFsAgnosticSourcePathToPathSourcePath() {
val fooPath = DummySourcePath("foo")
val fooFsAgnostic = FsAgnosticSourcePath.of("foo")
assertEquals(
"This test assumes FsAgnosticSourcePath has a specific fully-qualified name, " +
"so this test should be updated if that assumption no longer holds.",
"com.facebook.buck.multitenant.query.FsAgnosticSourcePath",
fooFsAgnostic.javaClass.name
)
assertThat(
"com.facebook.buck.multitenant.query.DummySourcePath is before " +
"com.facebook.buck.multitenant.query.FsAgnosticSourcePath lexicographically",
fooPath.compareTo(fooFsAgnostic),
Matchers.lessThan(0))
assertThat(
"com.facebook.buck.multitenant.query.DummySourcePath is before " +
"com.facebook.buck.multitenant.query.FsAgnosticSourcePath lexicographically",
fooFsAgnostic.compareTo(fooPath),
Matchers.greaterThan(0))
}
}
| apache-2.0 | 9ee567576394d1f2ef74545ea05982b0 | 36.459459 | 101 | 0.669553 | 4.559211 | false | true | false | false |
RichoDemus/chronicler | server/persistence/filesystem/src/main/kotlin/com/richodemus/chronicler/persistence/DiskEventPersister.kt | 1 | 2239 | package com.richodemus.chronicler.persistence
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.richodemus.chronicler.server.core.Event
import com.richodemus.chronicler.server.core.EventPersister
import java.io.File
import javax.inject.Inject
class DiskEventPersister @Inject internal constructor(val configuration: com.richodemus.chronicler.server.core.Configuration) : EventPersister {
init {
if (!configuration.dataDirectory().exists()) {
configuration.dataDirectory().mkdirs()
}
}
override fun getNumberOfEvents(): Int {
return configuration.dataDirectory().listFiles().size
}
override fun readEvents(): Iterator<Event> {
if (!configuration.saveToDisk()) {
return listOf<Event>().iterator()
}
return object : Iterator<Event> {
private var nextPage = 1L
override fun hasNext() = File(configuration.dataDirectory(), nextPage.toString()).exists()
override fun next(): Event {
val eventDiskDTO = ObjectMapper().readValue(File(configuration.dataDirectory(), nextPage.toString()), EventDiskDTO::class.java)
nextPage++
return eventDiskDTO.toEvent()
}
}
}
override fun persist(event: Event) {
if (!configuration.saveToDisk()) {
return
}
val path = File(configuration.dataDirectory(), event.page.toString())
ObjectMapper().writeValue(path, event.toDto())
}
private data class EventDiskDTO
@JsonCreator constructor(@JsonProperty("id") val id: String,
@JsonProperty("type") val type: String,
@JsonProperty("page") val page: Long,
@JsonProperty("data") val data: String)
private fun Event.toDto(): EventDiskDTO {
val page = this.page ?: throw IllegalStateException("Can't save event without page")
return EventDiskDTO(this.id, this.type, page, this.data)
}
private fun EventDiskDTO.toEvent() = Event(this.id, this.type, this.page, this.data)
}
| gpl-3.0 | 304ff3e3c5a6c0dd9d6710fd7e00e889 | 36.316667 | 144 | 0.649397 | 4.784188 | false | true | false | false |
zdary/intellij-community | platform/platform-tests/testSrc/com/intellij/lang/LanguageExtensionCacheTest.kt | 2 | 6193 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang
import com.intellij.codeInsight.completion.CompletionExtension
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.mock.MockLanguageFileType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.PlainTextLanguage
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.registerExtension
import com.intellij.util.KeyedLazyInstance
import java.util.*
class LanguageExtensionCacheTest : LightPlatformTestCase() {
private val myExtensionPointName = ExtensionPointName<KeyedLazyInstance<String>>("testLangExt")
private val myCompletionExtensionPointName = ExtensionPointName<KeyedLazyInstance<String>>("testCompletionExt")
private val myExtensionPointXML = """
<extensionPoint qualifiedName="$myExtensionPointName" beanClass="com.intellij.lang.LanguageExtensionPoint">
<with attribute="implementationClass" implements="java.lang.String"/>
</extensionPoint>
"""
private val myCompletionExtensionPointXML = """
<extensionPoint qualifiedName="$myCompletionExtensionPointName" beanClass="com.intellij.lang.LanguageExtensionPoint">
<with attribute="implementationClass" implements="java.lang.String"/>
</extensionPoint>
"""
private val descriptor = DefaultPluginDescriptor(PluginId.getId(""), javaClass.classLoader)
private lateinit var area: ExtensionsAreaImpl
private lateinit var extension: LanguageExtension<String>
private lateinit var completionExtension: CompletionExtension<String>
override fun setUp() {
super.setUp()
area = ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl
area.registerExtensionPoints(descriptor, listOf(JDOMUtil.load(myExtensionPointXML), JDOMUtil.load(myCompletionExtensionPointXML)))
Disposer.register(testRootDisposable, Disposable {
area.unregisterExtensionPoint(myExtensionPointName.name)
area.unregisterExtensionPoint(myCompletionExtensionPointName.name)
})
extension = LanguageExtension(myExtensionPointName, null)
completionExtension = CompletionExtension(myCompletionExtensionPointName.name)
}
private fun registerExtension(extensionPointName: ExtensionPointName<KeyedLazyInstance<String>>,
languageID: String,
implementationFqn: String
): Disposable {
val disposable = Disposer.newDisposable(testRootDisposable, "registerExtension")
val languageExtensionPoint = LanguageExtensionPoint<String>(languageID, implementationFqn, PluginManagerCore.getPlugin(PluginManagerCore.CORE_ID)!!)
ApplicationManager.getApplication().registerExtension(extensionPointName, languageExtensionPoint, disposable)
return disposable
}
fun `test extensions are cleared when explicit extension is added`() {
val language = PlainTextLanguage.INSTANCE
val unregisterDialectDisposable = Disposer.newDisposable(testRootDisposable, getTestName(false))
val plainTextDialect = registerLanguageDialect(unregisterDialectDisposable)
val extensionRegistrationDisposable = registerExtension(myExtensionPointName, language.id, String::class.java.name) // emulate registration via plugin.xml
assertSize(1, extension.allForLanguage(language))
assertEquals("", extension.forLanguage(language)) // empty because created with new String(); it is cached within forLanguage()
extension.addExplicitExtension(language, "hello")
assertSize(2, extension.allForLanguage(language))
assertEquals("hello", extension.forLanguage(language)) // explicit extension takes precedence over extension from plugin.xml
assertSize(2, extension.allForLanguage(plainTextDialect))
extension.removeExplicitExtension(language, "hello")
assertSize(1, extension.allForLanguage(language))
assertSize(1, extension.allForLanguage(plainTextDialect))
assertEquals("", extension.forLanguage(language))
Disposer.dispose(unregisterDialectDisposable)
Disposer.dispose(extensionRegistrationDisposable)
}
private fun registerLanguageDialect(parentDisposable: Disposable): Language {
val language: Language = object : Language(PlainTextLanguage.INSTANCE, "PlainTextDialect" + getTestName(false)) {
override fun getDisplayName(): String = "uniq blah-blah" + System.identityHashCode(this)
}
val plainTextDialectFileType = object: MockLanguageFileType(language, "xxxx") {
override fun getDescription(): String {
return "blah-blah" + System.identityHashCode(this)
}
}
FileTypeManager.getInstance().registerFileType(plainTextDialectFileType)
Disposer.register(parentDisposable, Disposable { FileTypeManagerEx.getInstanceEx().unregisterFileType(plainTextDialectFileType) })
return plainTextDialectFileType.language
}
fun `test CompletionExtension extensions are cleared when explicit extension is added`() {
val unregisterDialectDisposable = Disposer.newDisposable(testRootDisposable, getTestName(false))
val plainTextDialect = registerLanguageDialect(unregisterDialectDisposable)
val extensionRegistrationDisposable = registerExtension(myCompletionExtensionPointName, PlainTextLanguage.INSTANCE.id, String::class.java.name)
assertSize(1, completionExtension.forKey(PlainTextLanguage.INSTANCE))
assertSize(1, completionExtension.forKey(plainTextDialect))
Disposer.dispose(unregisterDialectDisposable)
Disposer.dispose(extensionRegistrationDisposable)
assertSize(0, completionExtension.forKey(plainTextDialect))
}
}
| apache-2.0 | 38f2e8d8cd0d357b03c7e7def4941a4b | 51.483051 | 160 | 0.805425 | 5.389904 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/MapTest/createFrom.kt | 2 | 607 | import kotlin.test.*
fun box() {
val pairs = arrayOf("a" to 1, "b" to 2)
val expected = mapOf(*pairs)
assertEquals(expected, pairs.toMap())
assertEquals(expected, pairs.asIterable().toMap())
assertEquals(expected, pairs.asSequence().toMap())
assertEquals(expected, expected.toMap())
assertEquals(mapOf("a" to 1), expected.filterKeys { it == "a" }.toMap())
assertEquals(emptyMap(), expected.filter { false }.toMap())
val mutableMap = expected.toMutableMap()
assertEquals(expected, mutableMap)
mutableMap += "c" to 3
assertNotEquals(expected, mutableMap)
}
| apache-2.0 | cf4e1bc613e10720d847ffbf2050d346 | 30.947368 | 76 | 0.675453 | 4.215278 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/secondaryConstructors/superCallSecondary.kt | 5 | 1682 | var sideEffects: String = ""
internal abstract class B {
val parentProp: String
init {
sideEffects += "minus-one#"
}
protected constructor(arg: Int) {
parentProp = (arg).toString()
sideEffects += "0.5#"
}
protected constructor(arg1: Int, arg2: Int) {
parentProp = (arg1 + arg2).toString()
sideEffects += "0.7#"
}
init {
sideEffects += "zero#"
}
}
internal class A : B {
var prop: String = ""
init {
sideEffects += prop + "first"
}
constructor(x1: Int, x2: Int): super(x1, x2) {
prop = x1.toString()
sideEffects += "#third"
}
init {
sideEffects += prop + "#second"
}
constructor(x: Int): super(3 + x) {
prop += "${x}#int"
sideEffects += "#fourth"
}
constructor(): this(7) {
sideEffects += "#fifth"
}
}
fun box(): String {
val a1 = A(5, 10)
if (a1.prop != "5") return "fail0: ${a1.prop}"
if (a1.parentProp != "15") return "fail1: ${a1.parentProp}"
if (sideEffects != "minus-one#zero#0.7#first#second#third") return "fail2: ${sideEffects}"
sideEffects = ""
val a2 = A(123)
if (a2.prop != "123#int") return "fail3: ${a2.prop}"
if (a2.parentProp != "126") return "fail4: ${a2.parentProp}"
if (sideEffects != "minus-one#zero#0.5#first#second#fourth") return "fail5: ${sideEffects}"
sideEffects = ""
val a3 = A()
if (a3.prop != "7#int") return "fail6: ${a3.prop}"
if (a3.parentProp != "10") return "fail7: ${a3.parentProp}"
if (sideEffects != "minus-one#zero#0.5#first#second#fourth#fifth") return "fail8: ${sideEffects}"
return "OK"
}
| apache-2.0 | d7cf786cf7710eb0335b8ee2e9a077ef | 25.28125 | 101 | 0.549346 | 3.222222 | false | false | false | false |
AndroidX/androidx | text/text/src/androidTest/java/androidx/compose/ui/text/android/animation/SegmentBreakerBreakSegmentTest.kt | 3 | 54409 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.android.animation
import android.text.TextDirectionHeuristic
import android.text.TextDirectionHeuristics
import android.text.TextPaint
import androidx.compose.ui.text.android.InternalPlatformTextApi
import androidx.compose.ui.text.android.LayoutHelper
import androidx.compose.ui.text.android.StaticLayoutFactory
import androidx.core.content.res.ResourcesCompat
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.testutils.fonts.R
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import androidx.test.ext.junit.runners.AndroidJUnit4
/**
* In this test cases, use following notations:
*
* - L1-LF shows an example strong LTR character.
* - R1-RF shows an example strong RTL character
* - SP shows whitespace character (U+0020)
* - LF shows line-feed character (U+000A)
*/
@SmallTest
@OptIn(InternalPlatformTextApi::class)
@RunWith(AndroidJUnit4::class)
class SegmentBreakerBreakSegmentTest {
private val sampleTypeface = ResourcesCompat.getFont(
InstrumentationRegistry.getInstrumentation().targetContext,
R.font.sample_font
)
// Reference Strong LTR character. All characters are supported by sample_font.ttf and they
// have 1em width.
private val L1 = "\u0061"
private val L2 = "\u0062"
private val L3 = "\u0063"
private val L4 = "\u0064"
private val L5 = "\u0065"
private val L6 = "\u0066"
private val L7 = "\u0067"
private val L8 = "\u0068"
private val L9 = "\u0069"
private val LA = "\u006A"
// Reference Strong RTL character. All characters are supported by sample_font.ttf and they
// have 1em width.
private val R1 = "\u05D1"
private val R2 = "\u05D2"
private val R3 = "\u05D3"
private val R4 = "\u05D4"
private val R5 = "\u05D5"
private val R6 = "\u05D6"
private val R7 = "\u05D7"
private val R8 = "\u05D8"
private val R9 = "\u05D9"
private val RA = "\u05DA"
// White space character. This is supported by sample_font.ttf and this has 1em width.
private val SP = " "
private val LF = "\n"
private val LTR = TextDirectionHeuristics.LTR
private val RTL = TextDirectionHeuristics.RTL
// sample_font.ttf has ascent=1000 and descent=-200, hence the line height is 1.2em.
private val TEXT_SIZE = 10f
private val LINE_HEIGHT = TEXT_SIZE.toInt()
private fun getLayout(
text: String,
dir: TextDirectionHeuristic
): LayoutHelper {
val paint = TextPaint().apply {
textSize = TEXT_SIZE
typeface = sampleTypeface
}
val layout = StaticLayoutFactory.create(
text = text,
paint = paint,
width = 50,
textDir = dir,
includePadding = false
)
return LayoutHelper(layout)
}
private fun getSegments(
text: String,
dir: TextDirectionHeuristic,
type: SegmentType,
dropSpaces: Boolean
): List<Segment> {
val layout = getLayout(text = text, dir = dir)
return SegmentBreaker.breakSegments(
layoutHelper = layout, segmentType = type, dropSpaces = dropSpaces
)
}
@Test
fun document_LTRText_LTRPara() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 SP L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6 SP L7 L8| (SP)
// |L9 LA |
//
// Note that trailing whitespace is not counted in line width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$SP$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Document, dropSpaces = false)
assertThat(segments.size).isEqualTo(1)
assertThat(segments[0]).isEqualTo(
Segment(
startOffset = 0,
endOffset = text.length,
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
}
@Test
fun document_LTRText_RTLPara() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 SP L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6 SP L7 L8| (SP)
// | L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$SP$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Document, dropSpaces = false)
assertThat(segments.size).isEqualTo(1)
assertThat(segments[0]).isEqualTo(
Segment(
startOffset = 0,
endOffset = text.length,
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
}
@Test
fun document_RTLText_LTRPara() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 SP R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (SP) |R8 R7 SP R6 R5|
// |RA R9 |
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$SP$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Document, dropSpaces = false)
assertThat(segments.size).isEqualTo(1)
assertThat(segments[0]).isEqualTo(
Segment(
startOffset = 0,
endOffset = text.length,
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
}
@Test
fun document_RTLText_RTLPara() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 SP R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (SP) |R8 R7 SP R6 R5|
// | RA R9|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$SP$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Document, dropSpaces = false)
assertThat(segments.size).isEqualTo(1)
assertThat(segments[0]).isEqualTo(
Segment(
startOffset = 0,
endOffset = text.length,
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
}
@Test
fun paragraph_LTRText_LTRPara() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6 (LF) |
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Paragraph, dropSpaces = false)
assertThat(segments.size).isEqualTo(2)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 9, // LF char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun paragraph_LTRText_RTLPara() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// | L5 L6| (LF)
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Paragraph, dropSpaces = false)
assertThat(segments.size).isEqualTo(2)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 9, // LF char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun paragraph_RTLText_LTRPara() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (LF) |R6 R5 |
// |R8 R7 SP RA R9|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Paragraph, dropSpaces = false)
assertThat(segments.size).isEqualTo(2)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 9, // LF char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun paragraph_RTLText_RTLPara() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// | (LF)R6 R5|
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Paragraph, dropSpaces = false)
assertThat(segments.size).isEqualTo(2)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 9, // LF char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_LTRText_LTRPara_includeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6(LF) |
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Line, dropSpaces = false)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_LTRText_RTLPara_includeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// | L5 L6| (LF)
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Line, dropSpaces = false)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_RTLText_LTRPara_includeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (LF) |R6 R5 |
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Line, dropSpaces = false)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_RTLText_RTLPara_includeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// | (LF)R6 R5|
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Line, dropSpaces = false)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_LTRText_LTRPara_excludeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6(LF) |
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Line, dropSpaces = true)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_LTRText_RTLPara_excludeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// | L5 L6| (LF)
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Line, dropSpaces = true)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 30,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_RTLText_LTRPara_excludeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (LF) |R6 R5 |
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Line, dropSpaces = true)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_RTLText_RTLPara_excludeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// | (LF)R6 R5|
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Line, dropSpaces = true)
assertThat(segments.size).isEqualTo(3)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 30,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun line_Bidi() {
// input (Logical): L1 L2 SP R1 R2 SP R3 R4 SP L3 L4
//
// |L1 L2 SP (SP) R2 R1|
// |R4 R3 SP L3 L4|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$R1$R2$SP$R3$R4$SP$L3$L4"
val segments = getSegments(text, LTR, SegmentType.Line, dropSpaces = false)
assertThat(segments.size).isEqualTo(2)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 6, // 2nd SP char offset
left = 0,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
)
)
)
}
@Test
fun word_LTRText_LTRPara_includeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6(LF) |
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Word, dropSpaces = false)
assertThat(segments.size).isEqualTo(5)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 0,
top = 0,
right = 30,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 30,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 0,
top = LINE_HEIGHT * 2,
right = 30,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 30,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun word_LTRText_RTLPara_includeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// | L5 L6| (LF)
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Word, dropSpaces = false)
assertThat(segments.size).isEqualTo(5)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 0,
top = 0,
right = 30,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 30,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 30,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 0,
top = LINE_HEIGHT * 2,
right = 30,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 30,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun word_RTLText_LTRPara_includeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (LF) |R6 R5 |
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Word, dropSpaces = false)
assertThat(segments.size).isEqualTo(6)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 20,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 0,
top = 0,
right = 20,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 8,
left = 0,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
// Bidi assigns LF character to LTR. Do we want to include preceding run?
Segment(
startOffset = 8,
endOffset = 9,
left = 20,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 20,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 20,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun word_RTLText_RTLPara_includeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// | (LF)R6 R5|
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Word, dropSpaces = false)
assertThat(segments.size).isEqualTo(5)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 20,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 0,
top = 0,
right = 20,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 30,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 20,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 20,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun word_LTRText_LTRPara_excludeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6(LF) |
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Word, dropSpaces = true)
assertThat(segments.size).isEqualTo(5)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 0,
top = 0,
right = 20,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 30,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 0,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 0,
top = LINE_HEIGHT * 2,
right = 20,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 30,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun word_LTRText_RTLPara_excludeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// | L5 L6| (LF)
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Word, dropSpaces = true)
assertThat(segments.size).isEqualTo(5)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 0,
top = 0,
right = 20,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 30,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 30,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 0,
top = LINE_HEIGHT * 2,
right = 20,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 30,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun word_RTLText_LTRPara_excludeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (LF) |R6 R5 |
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Word, dropSpaces = true)
assertThat(segments.size).isEqualTo(6)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 30,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 0,
top = 0,
right = 20,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 8,
left = 0,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
// Bidi assigns LF character to LTR. Do we want to include preceding run?
Segment(
startOffset = 8,
endOffset = 9,
left = 20,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 30,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 20,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun word_RTLText_RTLPara_excludeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// | (LF)R6 R5|
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Word, dropSpaces = true)
assertThat(segments.size).isEqualTo(5)
assertThat(segments).isEqualTo(
listOf(
Segment(
startOffset = 0,
endOffset = 3, // 1st SP char offset
left = 30,
top = 0,
right = 50,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 3,
endOffset = 6, // 2st SP char offset
left = 0,
top = 0,
right = 20,
bottom = LINE_HEIGHT
),
Segment(
startOffset = 6,
endOffset = 9, // LF char offset
left = 30,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
),
Segment(
startOffset = 9,
endOffset = 12, // 3rd SP char offset
left = 30,
top = LINE_HEIGHT * 2,
right = 50,
bottom = LINE_HEIGHT * 3
),
Segment(
startOffset = 12,
endOffset = text.length,
left = 0,
top = LINE_HEIGHT * 2,
right = 20,
bottom = LINE_HEIGHT * 3
)
)
)
}
@Test
fun char_LTRText_LTRPara_includeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6(LF) |
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Character, dropSpaces = false)
assertThat(segments.size).isEqualTo(14)
assertThat(segments[0]).isEqualTo(
Segment( // L1 character
startOffset = 0,
endOffset = 1,
left = 0,
top = 0,
right = 10,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP location
startOffset = 2,
endOffset = 3,
left = 20,
top = 0,
right = 30,
bottom = LINE_HEIGHT
)
)
assertThat(segments[5]).isEqualTo(
Segment( // 2nd SP location. not rendered.
startOffset = 5,
endOffset = 6,
left = 50,
top = 0,
right = 50,
bottom = LINE_HEIGHT
)
)
}
@Test
fun char_LTRText_RTLPara_includeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// (SP) |L1 L2 SP L3 L4|
// | (LF)L5 L6|
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Character, dropSpaces = false)
assertThat(segments.size).isEqualTo(14)
assertThat(segments[0]).isEqualTo(
Segment( // L1 character
startOffset = 0,
endOffset = 1,
left = 0,
top = 0,
right = 10,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP location
startOffset = 2,
endOffset = 3,
left = 20,
top = 0,
right = 30,
bottom = LINE_HEIGHT
)
)
assertThat(segments[5]).isEqualTo(
Segment( // 2nd SP location. not rendered.
startOffset = 5,
endOffset = 6,
left = 0,
top = 0,
right = 0,
bottom = LINE_HEIGHT
)
)
}
@Test
fun char_RTLText_LTRPara_includeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// |R4 R3 SP R2 R1| (SP)
// |R6 R5(LF) |
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Character, dropSpaces = false)
assertThat(segments.size).isEqualTo(14)
assertThat(segments[0]).isEqualTo(
Segment( // R1 character
startOffset = 0,
endOffset = 1,
left = 40,
top = 0,
right = 50,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP location
startOffset = 2,
endOffset = 3,
left = 20,
top = 0,
right = 30,
bottom = LINE_HEIGHT
)
)
assertThat(segments[5]).isEqualTo(
Segment( // 2nd SP location. not rendered.
startOffset = 5,
endOffset = 6,
left = 50,
top = 0,
right = 50,
bottom = LINE_HEIGHT
)
)
}
@Test
fun char_RTLText_RTLPara_includeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// | (LF)R6 R5|
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Character, dropSpaces = false)
assertThat(segments.size).isEqualTo(14)
assertThat(segments[0]).isEqualTo(
Segment( // R1 character
startOffset = 0,
endOffset = 1,
left = 40,
top = 0,
right = 50,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP location
startOffset = 2,
endOffset = 3,
left = 20,
top = 0,
right = 30,
bottom = LINE_HEIGHT
)
)
assertThat(segments[5]).isEqualTo(
Segment( // 2nd SP location. not rendered.
startOffset = 5,
endOffset = 6,
left = 0,
top = 0,
right = 0,
bottom = LINE_HEIGHT
)
)
}
@Test
fun char_LTRText_LTRPara_excludeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// |L1 L2 SP L3 L4| (SP)
// |L5 L6(LF) |
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, LTR, SegmentType.Character, dropSpaces = true)
assertThat(segments.size).isEqualTo(10) // three spaces and one line feeds are excluded
assertThat(segments[0]).isEqualTo(
Segment( // L1 character
startOffset = 0,
endOffset = 1,
left = 0,
top = 0,
right = 10,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP is skipped. L3 character
startOffset = 3,
endOffset = 4,
left = 30,
top = 0,
right = 40,
bottom = LINE_HEIGHT
)
)
assertThat(segments[4]).isEqualTo(
Segment( // 2nd SP is skipped. L5 character
startOffset = 6,
endOffset = 7,
left = 0,
top = LINE_HEIGHT,
right = 10,
bottom = LINE_HEIGHT * 2
)
)
}
@Test
fun char_LTRText_RTLPara_excludeSpaces() {
// input (Logical): L1 L2 SP L3 L4 SP L5 L6 LF L7 L8 SP L9 LA
//
// (SP) |L1 L2 SP L3 L4|
// | (LF)L5 L6|
// |L7 L8 SP L9 LA|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$L1$L2$SP$L3$L4$SP$L5$L6$LF$L7$L8$SP$L9$LA"
val segments = getSegments(text, RTL, SegmentType.Character, dropSpaces = true)
assertThat(segments.size).isEqualTo(10) // three spaces and one line feeds are excluded
assertThat(segments[0]).isEqualTo(
Segment( // L1 character
startOffset = 0,
endOffset = 1,
left = 0,
top = 0,
right = 10,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP is skipped. L3 character
startOffset = 3,
endOffset = 4,
left = 30,
top = 0,
right = 40,
bottom = LINE_HEIGHT
)
)
assertThat(segments[4]).isEqualTo(
Segment( // 2nd SP is skipped. L5 character
startOffset = 6,
endOffset = 7,
left = 30,
top = LINE_HEIGHT,
right = 40,
bottom = LINE_HEIGHT * 2
)
)
}
@Test
fun char_RTLText_LTRPara_excludeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// (LF) |R6 R5 |
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, LTR, SegmentType.Character, dropSpaces = true)
assertThat(segments.size).isEqualTo(10) // three spaces and one line feeds are excluded
assertThat(segments[0]).isEqualTo(
Segment( // R1 character
startOffset = 0,
endOffset = 1,
left = 40,
top = 0,
right = 50,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP is skipped. R3 character
startOffset = 3,
endOffset = 4,
left = 10,
top = 0,
right = 20,
bottom = LINE_HEIGHT
)
)
assertThat(segments[4]).isEqualTo(
Segment( // 2nd SP is skipped. R5 character
startOffset = 6,
endOffset = 7,
left = 10,
top = LINE_HEIGHT,
right = 20,
bottom = LINE_HEIGHT * 2
)
)
}
@Test
fun char_RTLText_RTLPara_excludeSpaces() {
// input (Logical): R1 R2 SP R3 R4 SP R5 R6 LF R7 T8 SP R9 RA
//
// (SP) |R4 R3 SP R2 R1|
// | (LF)R6 R5|
// |RA R9 SP R8 R7|
//
// Note that trailing whitespace is not counted in line width. The characters with
// parenthesis are not counted as width.
val text = "$R1$R2$SP$R3$R4$SP$R5$R6$LF$R7$R8$SP$R9$RA"
val segments = getSegments(text, RTL, SegmentType.Character, dropSpaces = true)
assertThat(segments.size).isEqualTo(10) // three spaces and one line feeds are excluded
assertThat(segments[0]).isEqualTo(
Segment( // R1 character
startOffset = 0,
endOffset = 1,
left = 40,
top = 0,
right = 50,
bottom = LINE_HEIGHT
)
)
assertThat(segments[2]).isEqualTo(
Segment( // 1st SP is skipped. R3 character
startOffset = 3,
endOffset = 4,
left = 10,
top = 0,
right = 20,
bottom = LINE_HEIGHT
)
)
assertThat(segments[4]).isEqualTo(
Segment( // 2nd SP is skipped. R5 character
startOffset = 6,
endOffset = 7,
left = 40,
top = LINE_HEIGHT,
right = 50,
bottom = LINE_HEIGHT * 2
)
)
}
} | apache-2.0 | d397c4ceb9e1642145e4ce3d3be88977 | 33.349747 | 95 | 0.432208 | 4.377585 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceRangeStartEndInclusiveWithFirstLastInspection.kt | 2 | 3463 | // 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.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.dotQualifiedExpressionVisitor
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
class ReplaceRangeStartEndInclusiveWithFirstLastInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return dotQualifiedExpressionVisitor(fun(expression: KtDotQualifiedExpression) {
val selectorExpression = expression.selectorExpression ?: return
if (selectorExpression.text != "start" && selectorExpression.text != "endInclusive") return
val resolvedCall = expression.resolveToCall() ?: return
val containing = resolvedCall.resultingDescriptor.containingDeclaration as? ClassDescriptor ?: return
if (!containing.isRange()) return
if (selectorExpression.text == "start") {
holder.registerProblem(
expression,
KotlinBundle.message("could.be.replaced.with.unboxed.first"),
ReplaceIntRangeStartWithFirstQuickFix()
)
} else if (selectorExpression.text == "endInclusive") {
holder.registerProblem(
expression,
KotlinBundle.message("could.be.replaced.with.unboxed.last"),
ReplaceIntRangeEndInclusiveWithLastQuickFix()
)
}
})
}
}
private val rangeTypes = setOf(
"kotlin.ranges.IntRange",
"kotlin.ranges.CharRange",
"kotlin.ranges.LongRange",
"kotlin.ranges.UIntRange",
"kotlin.ranges.ULongRange"
)
private fun ClassDescriptor.isRange(): Boolean {
return rangeTypes.any { this.fqNameUnsafe.asString() == it }
}
class ReplaceIntRangeStartWithFirstQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.int.range.start.with.first.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtDotQualifiedExpression
val selector = element.selectorExpression ?: return
selector.replace(KtPsiFactory(element).createExpression("first"))
}
}
class ReplaceIntRangeEndInclusiveWithLastQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.int.range.end.inclusive.with.last.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtDotQualifiedExpression
val selector = element.selectorExpression ?: return
selector.replace(KtPsiFactory(element).createExpression("last"))
}
} | apache-2.0 | a42083050412b1827f7f178a8a2904bb | 42.848101 | 158 | 0.726538 | 5.215361 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/dataClass.1.kt | 9 | 535 | import pack.A
fun test(javaClass: JavaClass) {
val a = A(1, "2", Any())
a.n
a.component1()
val (x, y, z) = a
val (x1, y1, z1) = f()
val (x2, y2, z2) = g()
val (x3, y3, z3) = h()
val (x4, y4, z4) = listOfA()[0]
val (x5, y5, z5) = javaClass.getA()[0]
}
fun f(): A = TODO()
fun g() = A(1, "2", Any())
fun h() = g()
fun listOfA() = listOf<A>(A(1, "", ""))
fun test2(p1: JavaClass2, p2: JavaClass3) {
val (x1, y1) = p1[0]
val (x2, y2) = p2[0]
val (x3, y3) = JavaClass4.getNested()[0]
} | apache-2.0 | 0a757590f81e557f65bf56b59378dd36 | 18.142857 | 44 | 0.482243 | 2.157258 | false | true | false | false |
android/compose-samples | Owl/app/src/main/java/com/example/owl/ui/course/CourseDetails.kt | 1 | 20038 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.owl.ui.course
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation.Vertical
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FractionalThreshold
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.contentColorFor
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.ExpandMore
import androidx.compose.material.icons.rounded.PlayCircleOutline
import androidx.compose.material.icons.rounded.PlaylistPlay
import androidx.compose.material.primarySurface
import androidx.compose.material.rememberSwipeableState
import androidx.compose.material.swipeable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.owl.R
import com.example.owl.model.Course
import com.example.owl.model.CourseRepo
import com.example.owl.model.Lesson
import com.example.owl.model.LessonsRepo
import com.example.owl.model.courses
import com.example.owl.ui.common.CourseListItem
import com.example.owl.ui.common.OutlinedAvatar
import com.example.owl.ui.theme.BlueTheme
import com.example.owl.ui.theme.PinkTheme
import com.example.owl.ui.theme.pink500
import com.example.owl.ui.utils.NetworkImage
import com.example.owl.ui.utils.lerp
import com.example.owl.ui.utils.scrim
import java.util.Locale
import kotlinx.coroutines.launch
private val FabSize = 56.dp
private const val ExpandedSheetAlpha = 0.96f
@Composable
fun CourseDetails(
courseId: Long,
selectCourse: (Long) -> Unit,
upPress: () -> Unit
) {
// Simplified for the sample
val course = remember(courseId) { CourseRepo.getCourse(courseId) }
// TODO: Show error if course not found.
CourseDetails(course, selectCourse, upPress)
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun CourseDetails(
course: Course,
selectCourse: (Long) -> Unit,
upPress: () -> Unit
) {
PinkTheme {
BoxWithConstraints {
val sheetState = rememberSwipeableState(SheetState.Closed)
val fabSize = with(LocalDensity.current) { FabSize.toPx() }
val dragRange = constraints.maxHeight - fabSize
val scope = rememberCoroutineScope()
BackHandler(
enabled = sheetState.currentValue == SheetState.Open,
onBack = {
scope.launch {
sheetState.animateTo(SheetState.Closed)
}
}
)
Box(
// The Lessons sheet is initially closed and appears as a FAB. Make it openable by
// swiping or clicking the FAB.
Modifier.swipeable(
state = sheetState,
anchors = mapOf(
0f to SheetState.Closed,
-dragRange to SheetState.Open
),
thresholds = { _, _ -> FractionalThreshold(0.5f) },
orientation = Vertical
)
) {
val openFraction = if (sheetState.offset.value.isNaN()) {
0f
} else {
-sheetState.offset.value / dragRange
}.coerceIn(0f, 1f)
CourseDescription(course, selectCourse, upPress)
LessonsSheet(
course,
openFraction,
[email protected](),
[email protected]()
) { state ->
scope.launch {
sheetState.animateTo(state)
}
}
}
}
}
}
@Composable
private fun CourseDescription(
course: Course,
selectCourse: (Long) -> Unit,
upPress: () -> Unit
) {
Surface(modifier = Modifier.fillMaxSize()) {
LazyColumn {
item { CourseDescriptionHeader(course, upPress) }
item { CourseDescriptionBody(course) }
item { RelatedCourses(course.id, selectCourse) }
}
}
}
@Composable
private fun CourseDescriptionHeader(
course: Course,
upPress: () -> Unit
) {
Box {
NetworkImage(
url = course.thumbUrl,
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.scrim(colors = listOf(Color(0x80000000), Color(0x33000000)))
.aspectRatio(4f / 3f)
)
TopAppBar(
backgroundColor = Color.Transparent,
elevation = 0.dp,
contentColor = Color.White, // always white as image has dark scrim
modifier = Modifier.statusBarsPadding()
) {
IconButton(onClick = upPress) {
Icon(
imageVector = Icons.Rounded.ArrowBack,
contentDescription = stringResource(R.string.label_back)
)
}
Image(
painter = painterResource(id = R.drawable.ic_logo),
contentDescription = null,
modifier = Modifier
.padding(bottom = 4.dp)
.size(24.dp)
.align(Alignment.CenterVertically)
)
Spacer(modifier = Modifier.weight(1f))
}
OutlinedAvatar(
url = course.instructor,
modifier = Modifier
.size(40.dp)
.align(Alignment.BottomCenter)
.offset(y = 20.dp) // overlap bottom of image
)
}
}
@Composable
private fun CourseDescriptionBody(course: Course) {
Text(
text = course.subject.uppercase(Locale.getDefault()),
color = MaterialTheme.colors.primary,
style = MaterialTheme.typography.body2,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(
start = 16.dp,
top = 36.dp,
end = 16.dp,
bottom = 16.dp
)
)
Text(
text = course.name,
style = MaterialTheme.typography.h4,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
Spacer(modifier = Modifier.height(16.dp))
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = stringResource(id = R.string.course_desc),
style = MaterialTheme.typography.body1,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
Divider(modifier = Modifier.padding(16.dp))
Text(
text = stringResource(id = R.string.what_you_ll_need),
style = MaterialTheme.typography.h6,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = stringResource(id = R.string.needs),
style = MaterialTheme.typography.body1,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(
start = 16.dp,
top = 16.dp,
end = 16.dp,
bottom = 32.dp
)
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun RelatedCourses(
courseId: Long,
selectCourse: (Long) -> Unit
) {
val relatedCourses = remember(courseId) { CourseRepo.getRelated(courseId) }
BlueTheme {
Surface(
color = MaterialTheme.colors.primarySurface,
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.navigationBarsPadding()) {
Text(
text = stringResource(id = R.string.you_ll_also_like),
style = MaterialTheme.typography.h6,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(
horizontal = 16.dp,
vertical = 24.dp
)
)
LazyRow(
contentPadding = PaddingValues(
start = 16.dp,
bottom = 32.dp,
end = FabSize + 8.dp
)
) {
items(
items = relatedCourses,
key = { it.id }
) { related ->
CourseListItem(
course = related,
onClick = { selectCourse(related.id) },
titleStyle = MaterialTheme.typography.body2,
modifier = Modifier
.padding(end = 8.dp)
.size(288.dp, 80.dp),
iconSize = 14.dp
)
}
}
}
}
}
}
@Composable
private fun LessonsSheet(
course: Course,
openFraction: Float,
width: Float,
height: Float,
updateSheet: (SheetState) -> Unit
) {
// Use the fraction that the sheet is open to drive the transformation from FAB -> Sheet
val fabSize = with(LocalDensity.current) { FabSize.toPx() }
val fabSheetHeight = fabSize + WindowInsets.systemBars.getBottom(LocalDensity.current)
val offsetX = lerp(width - fabSize, 0f, 0f, 0.15f, openFraction)
val offsetY = lerp(height - fabSheetHeight, 0f, openFraction)
val tlCorner = lerp(fabSize, 0f, 0f, 0.15f, openFraction)
val surfaceColor = lerp(
startColor = pink500,
endColor = MaterialTheme.colors.primarySurface.copy(alpha = ExpandedSheetAlpha),
startFraction = 0f,
endFraction = 0.3f,
fraction = openFraction
)
Surface(
color = surfaceColor,
contentColor = contentColorFor(backgroundColor = MaterialTheme.colors.primarySurface),
shape = RoundedCornerShape(topStart = tlCorner),
modifier = Modifier.graphicsLayer {
translationX = offsetX
translationY = offsetY
}
) {
Lessons(course, openFraction, surfaceColor, updateSheet)
}
}
@Composable
private fun Lessons(
course: Course,
openFraction: Float,
surfaceColor: Color = MaterialTheme.colors.surface,
updateSheet: (SheetState) -> Unit
) {
val lessons: List<Lesson> = remember(course.id) { LessonsRepo.getLessons(course.id) }
Box(modifier = Modifier.fillMaxWidth()) {
// When sheet open, show a list of the lessons
val lessonsAlpha = lerp(0f, 1f, 0.2f, 0.8f, openFraction)
Column(
modifier = Modifier
.fillMaxSize()
.graphicsLayer { alpha = lessonsAlpha }
.statusBarsPadding()
) {
val scroll = rememberLazyListState()
val appBarElevation by animateDpAsState(if (scroll.isScrolled) 4.dp else 0.dp)
val appBarColor = if (appBarElevation > 0.dp) surfaceColor else Color.Transparent
TopAppBar(
backgroundColor = appBarColor,
elevation = appBarElevation
) {
Text(
text = course.name,
style = MaterialTheme.typography.subtitle1,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(16.dp)
.weight(1f)
.align(Alignment.CenterVertically)
)
IconButton(
onClick = { updateSheet(SheetState.Closed) },
modifier = Modifier.align(Alignment.CenterVertically)
) {
Icon(
imageVector = Icons.Rounded.ExpandMore,
contentDescription = stringResource(R.string.label_collapse_lessons)
)
}
}
LazyColumn(
state = scroll,
contentPadding = WindowInsets.systemBars
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom)
.asPaddingValues()
) {
items(
items = lessons,
key = { it.title }
) { lesson ->
Lesson(lesson)
Divider(startIndent = 128.dp)
}
}
}
// When sheet closed, show the FAB
val fabAlpha = lerp(1f, 0f, 0f, 0.15f, openFraction)
Box(
modifier = Modifier
.size(FabSize)
.padding(start = 16.dp, top = 8.dp) // visually center contents
.graphicsLayer { alpha = fabAlpha }
) {
IconButton(
modifier = Modifier.align(Alignment.Center),
onClick = { updateSheet(SheetState.Open) }
) {
Icon(
imageVector = Icons.Rounded.PlaylistPlay,
tint = MaterialTheme.colors.onPrimary,
contentDescription = stringResource(R.string.label_expand_lessons)
)
}
}
}
}
@Composable
private fun Lesson(lesson: Lesson) {
Row(
modifier = Modifier
.clickable(onClick = { /* todo */ })
.padding(vertical = 16.dp)
) {
NetworkImage(
url = lesson.imageUrl,
contentDescription = null,
modifier = Modifier.size(112.dp, 64.dp)
)
Column(
modifier = Modifier
.weight(1f)
.padding(start = 16.dp)
) {
Text(
text = lesson.title,
style = MaterialTheme.typography.subtitle2,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Row(
modifier = Modifier.padding(top = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Rounded.PlayCircleOutline,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Text(
modifier = Modifier.padding(start = 4.dp),
text = lesson.length,
style = MaterialTheme.typography.caption
)
}
}
}
Text(
text = lesson.formattedStepNumber,
style = MaterialTheme.typography.subtitle2,
modifier = Modifier.padding(horizontal = 16.dp)
)
}
}
private enum class SheetState { Open, Closed }
private val LazyListState.isScrolled: Boolean
get() = firstVisibleItemIndex > 0 || firstVisibleItemScrollOffset > 0
@Preview(name = "Course Details")
@Composable
private fun CourseDetailsPreview() {
val courseId = courses.first().id
CourseDetails(
courseId = courseId,
selectCourse = { },
upPress = { }
)
}
@Preview(name = "Lessons Sheet — Closed")
@Composable
private fun LessonsSheetClosedPreview() {
LessonsSheetPreview(0f)
}
@Preview(name = "Lessons Sheet — Open")
@Composable
private fun LessonsSheetOpenPreview() {
LessonsSheetPreview(1f)
}
@Preview(name = "Lessons Sheet — Open – Dark")
@Composable
private fun LessonsSheetOpenDarkPreview() {
LessonsSheetPreview(1f, true)
}
@Composable
private fun LessonsSheetPreview(
openFraction: Float,
darkTheme: Boolean = false
) {
PinkTheme(darkTheme) {
val color = MaterialTheme.colors.primarySurface
Surface(color = color) {
Lessons(
course = courses.first(),
openFraction = openFraction,
surfaceColor = color,
updateSheet = { }
)
}
}
}
@Preview(name = "Related")
@Composable
private fun RelatedCoursesPreview() {
val related = courses.random()
RelatedCourses(
courseId = related.id,
selectCourse = { }
)
}
| apache-2.0 | 58b17a87c9b0b8557cf2573a53490464 | 33.834783 | 98 | 0.592611 | 4.916544 | false | false | false | false |
lsmaira/gradle | buildSrc/subprojects/plugins/src/main/kotlin/org/gradle/modules/ClasspathManifestPatcher.kt | 1 | 3594 | package org.gradle.modules
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ResolvedDependency
import org.gradle.util.GUtil
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.commons.ClassRemapper
import org.objectweb.asm.commons.Remapper
import java.io.File
import org.gradle.kotlin.dsl.*
// Map of internal APIs that have been renamed since the last release
val REMAPPINGS = mapOf(
"org/gradle/plugin/use/internal/PluginRequests" to "org/gradle/plugin/management/internal/PluginRequests")
open class ClasspathManifestPatcher(
private val project: Project,
private val temporaryDir: File,
private val runtime: Configuration,
private val moduleNames: Set<String>
) {
fun writePatchedFilesTo(outputDir: File) =
resolveExternalModuleJars().forEach {
val originalFile = mainArtifactFileOf(it)
val patchedFile = outputDir.resolve(originalFile.name)
val unpackDir = unpack(originalFile)
patchManifestOf(it, unpackDir)
patchClassFilesIn(unpackDir)
pack(unpackDir, patchedFile)
}
/**
* Resolves each external module against the runtime configuration.
*/
private
fun resolveExternalModuleJars(): Collection<ResolvedDependency> =
runtime.resolvedConfiguration.firstLevelModuleDependencies
.filter { it.moduleName in moduleNames }
private
fun patchManifestOf(module: ResolvedDependency, unpackDir: File) {
val classpathManifestFile = unpackDir.resolve("${module.moduleName}-classpath.properties")
val classpathManifest = GUtil.loadProperties(classpathManifestFile)
classpathManifest["runtime"] = runtimeManifestOf(module)
classpathManifestFile.writeText(classpathManifest.toMap().asSequence()
.joinToString(separator = "\n") { "${it.key}=${it.value}" })
}
private
fun patchClassFilesIn(dir: File) =
dir.walkTopDown().forEach {
if (it.name.endsWith(".class")) {
remapTypesOf(it, REMAPPINGS)
}
}
private
fun remapTypesOf(classFile: File, remappings: Map<String, String>) {
val classWriter = ClassWriter(0)
ClassReader(classFile.readBytes()).accept(
ClassRemapper(classWriter, remapperFor(remappings)),
ClassReader.EXPAND_FRAMES)
classFile.writeBytes(classWriter.toByteArray())
}
private
fun remapperFor(typeNameRemappings: Map<String, String>) =
object : Remapper() {
override fun map(typeName: String): String =
typeNameRemappings[typeName] ?: typeName
}
private
fun runtimeManifestOf(module: ResolvedDependency) =
(module.allModuleArtifacts - module.moduleArtifacts)
.map { it.file.name }.sorted().joinToString(",")
private
fun unpack(file: File) =
unpackDirFor(file).also { unpackDir ->
project.run {
sync {
into(unpackDir)
from(zipTree(file))
}
}
}
private
fun unpackDirFor(file: File) =
temporaryDir.resolve(file.name)
private
fun pack(baseDir: File, destFile: File): Unit = project.run {
ant.withGroovyBuilder {
"zip"("basedir" to baseDir, "destfile" to destFile)
}
}
private
fun mainArtifactFileOf(module: ResolvedDependency) =
module.moduleArtifacts.single().file
}
| apache-2.0 | 04c0752e47f82a6509e39fbe08055b7d | 31.378378 | 110 | 0.661937 | 4.601793 | false | false | false | false |
danielgindi/android-helpers | Helpers/src/main/java/com/dg/controls/InfiniteScrollingListView.kt | 1 | 3768 | package com.dg.controls
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.AbsListView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.ProgressBar
@Suppress("unused")
class InfiniteScrollingListView : ListView
{
private var mIsLoadingMore: Boolean = false
private var mSuspendInfiniteScroll: Boolean = false
private var mProgressBar: ProgressBar? = null
private var mInfiniteScrollActionHandler: InfiniteScrollActionHandler? = null
private var mInfiniteScrollFooter: LinearLayout? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context,
attrs: AttributeSet,
defStyle: Int) : super(context, attrs, defStyle)
fun infiniteScrollLoadCompleted()
{
mIsLoadingMore = false
if (mProgressBar != null)
{
mProgressBar!!.visibility = View.GONE
}
}
fun suspendInfiniteScroll(suspend: Boolean)
{
mSuspendInfiniteScroll = suspend
}
fun addInfiniteScrollingWithActionHandler(infiniteScrollActionHandler: InfiniteScrollActionHandler)
{
mIsLoadingMore = false
this.mInfiniteScrollActionHandler = infiniteScrollActionHandler
if (mProgressBar == null)
{
mProgressBar = ProgressBar(context, null, android.R.attr.progressBarStyleSmall)
val progressBarParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT)
mProgressBar!!.layoutParams = progressBarParams
mProgressBar!!.setPadding(6, 6, 6, 6)
mInfiniteScrollFooter = LinearLayout(context)
val layoutParams = LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT)
mInfiniteScrollFooter!!.gravity = Gravity.CENTER
mInfiniteScrollFooter!!.layoutParams = layoutParams
mInfiniteScrollFooter!!.addView(mProgressBar)
mProgressBar!!.visibility = View.GONE
addFooterView(mInfiniteScrollFooter)
}
setOnScrollListener(object : OnScrollListener
{
override fun onScrollStateChanged(view: AbsListView, scrollState: Int)
{
}
override fun onScroll(view: AbsListView,
firstVisibleItem: Int,
visibleItemCount: Int,
totalItemCount: Int)
{
if (mSuspendInfiniteScroll) return
val loadMore: Boolean = 0 != totalItemCount && firstVisibleItem + visibleItemCount >= totalItemCount
if (!mIsLoadingMore && loadMore && null != [email protected])
{
if ([email protected]!!.infiniteScrollAction())
{
mIsLoadingMore = true
mProgressBar!!.visibility = View.VISIBLE
}
}
}
})
}
fun removeInfiniteScrolling()
{
if (mInfiniteScrollFooter != null)
{
removeFooterView(mInfiniteScrollFooter)
}
mInfiniteScrollFooter = null
mProgressBar = null
mInfiniteScrollActionHandler = null
}
interface InfiniteScrollActionHandler
{
fun infiniteScrollAction(): Boolean
}
}
| mit | 948b0c42c3404d0bad8b357f4b9022e2 | 31.482759 | 119 | 0.628981 | 5.691843 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainTransformerImpl.kt | 4 | 3946 | // 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.debugger.sequence.psi.impl
import com.intellij.debugger.streams.psi.ChainTransformer
import com.intellij.debugger.streams.trace.impl.handler.type.GenericType
import com.intellij.debugger.streams.wrapper.CallArgument
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
import com.intellij.debugger.streams.wrapper.QualifierExpression
import com.intellij.debugger.streams.wrapper.StreamChain
import com.intellij.debugger.streams.wrapper.impl.*
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.debugger.sequence.psi.CallTypeExtractor
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.callName
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
class KotlinChainTransformerImpl(private val typeExtractor: CallTypeExtractor) : ChainTransformer<KtCallExpression> {
override fun transform(callChain: List<KtCallExpression>, context: PsiElement): StreamChain {
val intermediateCalls = mutableListOf<IntermediateStreamCall>()
for (call in callChain.subList(0, callChain.size - 1)) {
val (typeBefore, typeAfter) = typeExtractor.extractIntermediateCallTypes(call)
intermediateCalls += IntermediateStreamCallImpl(
call.callName(), call.valueArguments.map { createCallArgument(call, it) },
typeBefore, typeAfter,
call.textRange
)
}
val terminationsPsiCall = callChain.last()
val (typeBeforeTerminator, resultType) = typeExtractor.extractTerminalCallTypes(terminationsPsiCall)
val terminationCall = TerminatorStreamCallImpl(
terminationsPsiCall.callName(),
terminationsPsiCall.valueArguments.map { createCallArgument(terminationsPsiCall, it) },
typeBeforeTerminator, resultType, terminationsPsiCall.textRange
)
val typeAfterQualifier =
if (intermediateCalls.isEmpty()) typeBeforeTerminator else intermediateCalls.first().typeBefore
val qualifier = createQualifier(callChain.first(), typeAfterQualifier)
return StreamChainImpl(qualifier, intermediateCalls, terminationCall, context)
}
private fun createCallArgument(callExpression: KtCallExpression, arg: KtValueArgument): CallArgument {
fun KtValueArgument.toCallArgument(): CallArgument {
val argExpression = getArgumentExpression()!!
return CallArgumentImpl(KotlinPsiUtil.getTypeName(argExpression.resolveType()!!), this.text)
}
val bindingContext = callExpression.getResolutionFacade().analyzeWithAllCompilerChecks(callExpression).bindingContext
val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return arg.toCallArgument()
val parameter = resolvedCall.getParameterForArgument(arg) ?: return arg.toCallArgument()
return CallArgumentImpl(KotlinPsiUtil.getTypeName(parameter.type), arg.text)
}
private fun createQualifier(expression: PsiElement, typeAfter: GenericType): QualifierExpression {
val parent = expression.parent as? KtDotQualifiedExpression ?: return QualifierExpressionImpl("", TextRange.EMPTY_RANGE, typeAfter)
val receiver = parent.receiverExpression
return QualifierExpressionImpl(receiver.text, receiver.textRange, typeAfter)
}
}
| apache-2.0 | e616e95693aece743e30937cdd88fac7 | 54.577465 | 158 | 0.773695 | 4.994937 | false | false | false | false |
androidx/androidx | camera/integration-tests/timingtestapp/src/main/java/androidx/camera/integration/antelope/CameraUtils.kt | 3 | 12096 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.antelope
import android.graphics.ImageFormat
import android.graphics.Rect
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CameraMetadata
import android.hardware.camera2.CaptureRequest
import android.media.ImageReader
import android.os.Build
import android.util.SparseIntArray
import android.view.Surface
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.integration.antelope.MainActivity.Companion.FIXED_FOCUS_DISTANCE
import androidx.camera.integration.antelope.MainActivity.Companion.cameraParams
import androidx.camera.integration.antelope.MainActivity.Companion.logd
import androidx.camera.integration.antelope.cameracontrollers.Camera2CaptureSessionCallback
import androidx.camera.integration.antelope.cameracontrollers.Camera2DeviceStateCallback
import java.util.Arrays
import java.util.Collections
/** The camera API to use */
enum class CameraAPI(private val api: String) {
/** Camera 1 API */
CAMERA1("Camera1"),
/** Camera 2 API */
CAMERA2("Camera2"),
/** Camera X API */
CAMERAX("CameraX")
}
/** The output capture size to request for captures */
enum class ImageCaptureSize(private val size: String) {
/** Request captures to be the maximum supported size for this camera sensor */
MAX("Max"),
/** Request captures to be the minimum supported size for this camera sensor */
MIN("Min"),
}
/** The focus mechanism to request for captures */
enum class FocusMode(private val mode: String) {
/** Auto-focus */
AUTO("Auto"),
/** Continuous auto-focus */
CONTINUOUS("Continuous"),
/** For fixed-focus lenses */
FIXED("Fixed")
}
/**
* For all the cameras associated with the device, populate the CameraParams values and add them to
* the companion object for the activity.
*/
fun initializeCameras(activity: MainActivity) {
val manager = activity.getSystemService(AppCompatActivity.CAMERA_SERVICE) as CameraManager
try {
val numCameras = manager.cameraIdList.size
for (cameraId in manager.cameraIdList) {
var cameraParamsValid = true
val tempCameraParams = CameraParams().apply {
val cameraChars = manager.getCameraCharacteristics(cameraId)
val cameraCapabilities =
cameraChars.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)
?: IntArray(0)
// Check supported format.
val map = cameraChars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
if (map == null || map.isOutputSupportedFor(ImageFormat.JPEG) == false) {
cameraParamsValid = false
logd(
"Null streamConfigurationMap or not supporting JPEG output format " +
"in cameraId:" + cameraId
)
return@apply
}
// Multi-camera
for (capability in cameraCapabilities) {
if (capability ==
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA
) {
hasMulti = true
} else if (capability ==
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR
) {
hasManualControl = true
}
}
logd("Camera " + cameraId + " of " + numCameras)
id = cameraId
isOpen = false
hasFlash = cameraChars.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) ?: false
isFront = CameraCharacteristics.LENS_FACING_FRONT ==
cameraChars.get(CameraCharacteristics.LENS_FACING)
isExternal = (
Build.VERSION.SDK_INT >= 23 &&
CameraCharacteristics.LENS_FACING_EXTERNAL ==
cameraChars.get(CameraCharacteristics.LENS_FACING)
)
characteristics = cameraChars
focalLengths =
cameraChars.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
?: FloatArray(0)
smallestFocalLength = smallestFocalLength(focalLengths)
minDeltaFromNormal = focalLengthMinDeltaFromNormal(focalLengths)
apertures = cameraChars.get(CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES)
?: FloatArray(0)
largestAperture = largestAperture(apertures)
minFocusDistance =
cameraChars.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE)
?: MainActivity.FIXED_FOCUS_DISTANCE
for (focalLength in focalLengths) {
logd("In " + id + " found focalLength: " + focalLength)
}
logd("Smallest smallestFocalLength: " + smallestFocalLength)
logd("minFocusDistance: " + minFocusDistance)
for (aperture in apertures) {
logd("In " + id + " found aperture: " + aperture)
}
logd("Largest aperture: " + largestAperture)
if (hasManualControl) {
logd("Has Manual, minFocusDistance: " + minFocusDistance)
}
// Autofocus
hasAF = minFocusDistance != FIXED_FOCUS_DISTANCE // If camera is fixed focus, no AF
effects = cameraChars.get(CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS)
?: IntArray(0)
hasSepia = effects.contains(CameraMetadata.CONTROL_EFFECT_MODE_SEPIA)
hasMono = effects.contains(CameraMetadata.CONTROL_EFFECT_MODE_MONO)
if (hasSepia)
logd("WE HAVE Sepia!")
if (hasMono)
logd("WE HAVE Mono!")
isLegacy = cameraChars.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) ==
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY
val activeSensorRect: Rect = cameraChars.get(SENSOR_INFO_ACTIVE_ARRAY_SIZE)!!
megapixels = (activeSensorRect.width() * activeSensorRect.height()) / 1000000
camera2DeviceStateCallback =
Camera2DeviceStateCallback(this, activity, TestConfig())
camera2CaptureSessionCallback =
Camera2CaptureSessionCallback(activity, this, TestConfig())
previewSurfaceView = activity.binding.surfacePreview
cameraXPreviewTexture = activity.binding.texturePreview
cameraXPreviewBuilder = Preview.Builder()
cameraXCaptureBuilder = ImageCapture.Builder()
imageAvailableListener =
ImageAvailableListener(activity, this, TestConfig())
if (Build.VERSION.SDK_INT >= 28) {
physicalCameras = cameraChars.physicalCameraIds
}
// Get Camera2 and CameraX image capture sizes.
cam2MaxSize = Collections.max(
Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)),
CompareSizesByArea()
)
cam2MinSize = Collections.min(
Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)),
CompareSizesByArea()
)
// Use minimum image size for preview
previewSurfaceView?.holder?.setFixedSize(cam2MinSize.width, cam2MinSize.height)
setupImageReader(activity, this, TestConfig())
}
if (cameraParamsValid == false) {
logd("Don't put Camera " + cameraId + "of " + numCameras)
continue
} else {
cameraParams.put(cameraId, tempCameraParams)
}
} // For all camera devices
} catch (accessError: CameraAccessException) {
accessError.printStackTrace()
}
}
/**
* Convenience method to configure the ImageReaders required for Camera1 and Camera2 APIs.
*
* Uses JPEG image format, checks the current test configuration to determine the needed size.
*/
fun setupImageReader(activity: MainActivity, params: CameraParams, testConfig: TestConfig) {
// Only use ImageReader for Camera1 and Camera2
if (CameraAPI.CAMERAX != testConfig.api) {
params.imageAvailableListener = ImageAvailableListener(activity, params, testConfig)
val useLargest = testConfig.imageCaptureSize == ImageCaptureSize.MAX
val size = if (useLargest)
params.cam2MaxSize
else
params.cam2MinSize
params.imageReader?.close()
params.imageReader = ImageReader.newInstance(
size.width, size.height,
ImageFormat.JPEG, 5
)
params.imageReader?.setOnImageAvailableListener(
params.imageAvailableListener, params.backgroundHandler
)
}
}
/** Finds the smallest focal length in the given array, useful for finding the widest angle lens */
fun smallestFocalLength(focalLengths: FloatArray): Float = focalLengths.minOrNull()
?: MainActivity.INVALID_FOCAL_LENGTH
/** Finds the largest aperture in the array of focal lengths */
fun largestAperture(apertures: FloatArray): Float = apertures.maxOrNull()
?: MainActivity.NO_APERTURE
/** Finds the most "normal" focal length in the array of focal lengths */
fun focalLengthMinDeltaFromNormal(focalLengths: FloatArray): Float =
focalLengths.minByOrNull { Math.abs(it - MainActivity.NORMAL_FOCAL_LENGTH) }
?: Float.MAX_VALUE
/** Adds automatic flash to the given CaptureRequest.Builder */
fun setAutoFlash(params: CameraParams, requestBuilder: CaptureRequest.Builder?) {
try {
if (params.hasFlash) {
requestBuilder?.set(
CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH
)
// Force flash always on
// requestBuilder?.set(CaptureRequest.CONTROL_AE_MODE,
// CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH)
}
} catch (e: Exception) {
// Do nothing
}
}
/**
* We have to take sensor orientation into account and rotate JPEG properly.
*/
fun getOrientation(params: CameraParams, rotation: Int): Int {
val orientations = SparseIntArray()
orientations.append(Surface.ROTATION_0, 90)
orientations.append(Surface.ROTATION_90, 0)
orientations.append(Surface.ROTATION_180, 270)
orientations.append(Surface.ROTATION_270, 180)
logd(
"Orientation: sensor: " +
params.characteristics?.get(CameraCharacteristics.SENSOR_ORIENTATION) +
" and current rotation: " + orientations.get(rotation)
)
val sensorRotation: Int =
params.characteristics?.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
return (orientations.get(rotation) + sensorRotation + 270) % 360
}
| apache-2.0 | a1cc38812c367cf9f2add4ca7bb07837 | 39.32 | 99 | 0.633598 | 5.023256 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/Task.kt | 5 | 1979 | // 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.tools.projectWizard.core.entity
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import kotlin.reflect.KProperty1
sealed class Task : EntityBase()
data class Task1<A, B : Any>(
override val path: String,
val action: Writer.(A) -> TaskResult<B>
) : Task() {
class Builder<A, B : Any>(private val name: String) {
private var action: Writer.(A) -> TaskResult<B> = { Failure() }
fun withAction(action: Writer.(A) -> TaskResult<B>) {
this.action = action
}
fun build(): Task1<A, B> = Task1(name, action)
}
}
data class PipelineTask(
override val path: String,
val action: Writer.() -> TaskResult<Unit>,
val before: List<PipelineTask>,
val after: List<PipelineTask>,
val phase: GenerationPhase,
val isAvailable: Checker,
@Nls val title: String?
) : Task() {
class Builder(
private val name: String,
private val phase: GenerationPhase
) {
private var action: Writer.() -> TaskResult<Unit> = { UNIT_SUCCESS }
private val before = mutableListOf<PipelineTask>()
private val after = mutableListOf<PipelineTask>()
var isAvailable: Checker = ALWAYS_AVAILABLE_CHECKER
@Nls
var title: String? = null
fun withAction(action: Writer.() -> TaskResult<Unit>) {
this.action = action
}
fun runBefore(vararg before: PipelineTask) {
this.before.addAll(before)
}
fun runAfter(vararg after: PipelineTask) {
this.after.addAll(after)
}
fun build(): PipelineTask = PipelineTask(name, action, before, after, phase, isAvailable, title)
}
} | apache-2.0 | 787b8fe49268a47305d4afa7797ca7ef | 30.428571 | 158 | 0.648307 | 4.210638 | false | false | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/KonanFqNames.kt | 1 | 1749 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
internal const val NATIVE_PTR_NAME = "NativePtr"
internal const val NON_NULL_NATIVE_PTR_NAME = "NonNullNativePtr"
internal const val VECTOR128 = "Vector128"
object KonanFqNames {
val function = FqName("kotlin.Function")
val kFunction = FqName("kotlin.reflect.KFunction")
val packageName = FqName("kotlin.native")
val internalPackageName = FqName("kotlin.native.internal")
val nativePtr = internalPackageName.child(Name.identifier(NATIVE_PTR_NAME)).toUnsafe()
val nonNullNativePtr = internalPackageName.child(Name.identifier(NON_NULL_NATIVE_PTR_NAME)).toUnsafe()
val Vector128 = packageName.child(Name.identifier(VECTOR128))
val throws = FqName("kotlin.Throws")
val cancellationException = FqName("kotlin.coroutines.cancellation.CancellationException")
val threadLocal = FqName("kotlin.native.concurrent.ThreadLocal")
val sharedImmutable = FqName("kotlin.native.concurrent.SharedImmutable")
val frozen = FqName("kotlin.native.internal.Frozen")
val leakDetectorCandidate = FqName("kotlin.native.internal.LeakDetectorCandidate")
val canBePrecreated = FqName("kotlin.native.internal.CanBePrecreated")
val typedIntrinsic = FqName("kotlin.native.internal.TypedIntrinsic")
val objCMethod = FqName("kotlinx.cinterop.ObjCMethod")
val hasFinalizer = FqName("kotlin.native.internal.HasFinalizer")
val hasFreezeHook = FqName("kotlin.native.internal.HasFreezeHook")
}
| apache-2.0 | 5819863645c0fd37d3109b6793e84cab | 48.971429 | 106 | 0.772441 | 4.154394 | false | false | false | false |
GunoH/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/problems/FileStateUpdater.kt | 7 | 7112 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.daemon.problems
import com.intellij.openapi.project.DumbService
import com.intellij.psi.*
/**
* Mapping between psi members and their properties model.
* These properties are used to determine if member state has changed or not.
*/
internal typealias Snapshot = Map<SmartPsiElementPointer<PsiMember>, ScopedMember>
/**
* Pair of snapshot and changes.
* Changes contain mapping between psi members and their previous state.
*/
internal data class FileState(val snapshot: Snapshot, val changes: Map<PsiMember, ScopedMember?>)
internal class FileStateUpdater(private val prevState: FileState?) : JavaElementVisitor() {
private val snapshot = mutableMapOf<SmartPsiElementPointer<PsiMember>, ScopedMember>()
private val changes = mutableMapOf<PsiMember, ScopedMember?>()
override fun visitEnumConstant(psiEnumConstant: PsiEnumConstant) = visitMember(psiEnumConstant)
override fun visitClass(psiClass: PsiClass) = visitMember(psiClass)
override fun visitField(psiField: PsiField) = visitMember(psiField)
override fun visitMethod(psiMethod: PsiMethod) = visitMember(psiMethod)
private fun visitMember(psiMember: PsiMember) {
val member = ScopedMember.create(psiMember) ?: return
val pointer = SmartPointerManager.createPointer(psiMember)
snapshot[pointer] = member
if (prevState == null) return
val prevMember = prevState.snapshot[pointer]
if (prevMember != null && !member.hasChanged(prevMember)) return
changes[psiMember] = prevMember
collectRelatedChanges(psiMember, member, prevMember, changes, prevState.changes)
}
companion object {
/**
* Extracts current file state from cache or creates a new one if it is not in cache.
*/
@JvmStatic
@JvmName("getState")
internal fun getState(psiFile: PsiFile): FileState? {
if (DumbService.isDumb(psiFile.project)) return null
val storedState = FileStateCache.getInstance(psiFile.project).getState(psiFile)
if (storedState != null) return storedState
val updater = FileStateUpdater(null)
publicApi(psiFile).forEach { it.accept(updater) }
val snapshot = updater.snapshot
return FileState(snapshot, emptyMap())
}
/**
* Constructs new state based on a previous one
*
* Construction contains three stages:
* 1. analyze current state of psi file. for each member that already was in a snapshot check if it changed.
* 2. put elements that were removed from psi file into set of changes
* 3. add related changes to set of changes
* (e.g. if additional method was added to functional interface then it cannot be used in lambdas and we have to check its usages)
*/
@JvmStatic
@JvmName("findState")
internal fun findState(psiFile: PsiFile, prevSnapshot: Snapshot, prevChanges: Map<PsiMember, ScopedMember?>): FileState {
val updater = FileStateUpdater(FileState(prevSnapshot, prevChanges))
publicApi(psiFile).forEach { it.accept(updater) }
val snapshot = updater.snapshot
val changes = updater.changes
for ((memberPointer, prevMember) in prevSnapshot) {
if (memberPointer in snapshot) continue
val psiMember = memberPointer.element ?: continue
val member = ScopedMember.create(psiMember) ?: continue
changes[psiMember] = prevMember
collectRelatedChanges(psiMember, member, prevMember, changes, prevChanges)
}
return FileState(snapshot, changes)
}
/**
* Restore file state based on changes in snapshot
*/
@JvmStatic
@JvmName("setPreviousState")
internal fun setPreviousState(psiFile: PsiFile) {
val project = psiFile.project
val fileStateCache = FileStateCache.getInstance(project)
val (snapshot, changes) = fileStateCache.getState(psiFile) ?: return
if (changes.isEmpty()) return
val manager = SmartPointerManager.getInstance(project)
val oldSnapshot = snapshot.toMutableMap()
changes.forEach { (psiMember, prevMember) ->
val memberPointer = manager.createSmartPsiElementPointer(psiMember)
if (prevMember == null) oldSnapshot.remove(memberPointer)
else oldSnapshot[memberPointer] = prevMember
}
fileStateCache.setState(psiFile, oldSnapshot, emptyMap())
}
@JvmStatic
@JvmName("updateState")
internal fun updateState(psiFile: PsiFile, fileState: FileState) {
FileStateCache.getInstance(psiFile.project).setState(psiFile, fileState.snapshot, fileState.changes)
}
@JvmStatic
@JvmName("removeState")
internal fun removeState(psiFile: PsiFile) {
FileStateCache.getInstance(psiFile.project).removeState(psiFile)
}
private fun collectRelatedChanges(
psiMember: PsiMember,
member: ScopedMember,
prevMember: ScopedMember?,
changes: MutableMap<PsiMember, ScopedMember?>,
prevChanges: Map<PsiMember, ScopedMember?>
) {
// new member, maybe it is recreated
val recreated = prevChanges.entries.find {
val changedMember = it.value ?: return@find false
return@find member::class == changedMember::class && member.name == changedMember.name
}
if (recreated != null) changes.putIfAbsent(recreated.key, recreated.value)
when (psiMember) {
is PsiMethod -> {
val containingClass = psiMember.containingClass ?: return
// anonymous classes and lambdas creation might be broken, need to check class usages
changes.putIfAbsent(containingClass, prevChanges[containingClass])
}
is PsiClass -> {
val prevClass = prevMember?.member as? Member.Class ?: return
val curClass = member.member as? Member.Class ?: return
when {
prevClass.name != psiMember.name -> {
// some reported problems might be fixed after such change, need to recheck them
prevChanges.forEach { changes.putIfAbsent(it.key, it.value) }
}
prevClass.isInterface != psiMember.isInterface -> {
// members usages might be broken, need to check them all
publicApi(psiMember).forEach { changes.putIfAbsent(it, prevChanges[it]) }
}
prevClass.extendsList != curClass.extendsList || prevClass.implementsList != curClass.implementsList -> {
// maybe some parent members were referenced instead of current class overrides
// also maybe this overrides now reference something else in current class (e.g. private method)
MemberCollector.collectMembers(psiMember) { it is PsiMethod }.forEach { changes.putIfAbsent(it, prevChanges[it]) }
}
}
}
}
}
private fun publicApi(psiElement: PsiElement) = MemberCollector.collectMembers(psiElement) { !it.hasModifier(PsiModifier.PRIVATE) }
private fun PsiMember.hasModifier(modifier: String) = modifierList?.hasModifierProperty(modifier) ?: false
}
} | apache-2.0 | 30392a56a72a38581bac413747eaf5a0 | 42.109091 | 135 | 0.700928 | 4.805405 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/hmppLibAndConsumer/published-lib-consumer/src/commonMain/kotlin/UseLibCommonMainExpect.kt | 10 | 534 | package com.h0tk3y.hmpp.klib.demo.app
import com.h0tk3y.hmpp.klib.demo.*
fun useExpect(e: <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: LibCommonMainExpect'")!>LibCommonMainExpect<!>) {
println(<!HIGHLIGHTING("severity='ERROR'; descr='[DEBUG] Resolved to error element'")!>e<!>.<!HIGHLIGHTING("severity='ERROR'; descr='[DEBUG] Reference is not resolved to anything, but is not marked unresolved'")!>libCommonMainExpectFun<!>())
// println(e.additionalFunInActual()) // won't resolve
}
| apache-2.0 | 888a921187fe58fbdc4125386718f5c2 | 65.75 | 245 | 0.7397 | 3.657534 | false | false | false | false |
mglukhikh/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/uast/GroovyUastPlugin.kt | 1 | 5379 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.uast
import com.intellij.lang.Language
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parents
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.uast.*
/**
* This is a very limited implementation of UastPlugin for Groovy,
* provided only to make Groovy play with UAST-based reference contributors and spring class annotators
*/
class GroovyUastPlugin : UastLanguagePlugin {
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { parent }, requiredType)
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { makeUParent(element) }, requiredType)
private fun convertElementWithParent(element: PsiElement,
parentProvider: () -> UElement?,
requiredType: Class<out UElement>?): UElement? =
when (element) {
is GroovyFile -> GrUFile(element, this)
is GrLiteral -> GrULiteral(element, parentProvider)
is GrAnnotationNameValuePair -> GrUNamedExpression(element, parentProvider)
is GrAnnotation -> GrUAnnotation(element, parentProvider)
is GrTypeDefinition -> GrUClass(element, parentProvider)
is GrMethod -> GrUMethod(element, parentProvider)
is GrParameter -> GrUParameter(element, parentProvider)
else -> null
}?.takeIf { requiredType?.isAssignableFrom(it.javaClass) ?: true }
private fun makeUParent(element: PsiElement) =
element.parent.parents().mapNotNull { convertElementWithParent(it, null) }.firstOrNull()
override fun getMethodCallExpression(element: PsiElement,
containingClassFqName: String?,
methodName: String): UastLanguagePlugin.ResolvedMethod? = null //not implemented
override fun getConstructorCallExpression(element: PsiElement,
fqName: String): UastLanguagePlugin.ResolvedConstructor? = null //not implemented
override fun isExpressionValueUsed(element: UExpression): Boolean = TODO("not implemented")
override val priority = 0
override fun isFileSupported(fileName: String) = fileName.endsWith(".groovy", ignoreCase = true)
override val language: Language = GroovyLanguage
}
class GrULiteral(val grElement: GrLiteral, val parentProvider: () -> UElement?) : ULiteralExpression, JvmDeclarationUElement {
override val value: Any?
get() = grElement.value
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUNamedExpression(val grElement: GrAnnotationNameValuePair, val parentProvider: () -> UElement?) : UNamedExpression, JvmDeclarationUElement {
override val name: String?
get() = grElement.name
override val expression: UExpression
get() = grElement.value.toUElementOfType() ?: GrUnknownUExpression(grElement.value, this)
override val uastParent by lazy(parentProvider)
override val psi = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUAnnotation(val grElement: GrAnnotation,
val parentProvider: () -> UElement?) : UAnnotationEx, JvmDeclarationUElement, UAnchorOwner {
override val javaPsi: PsiAnnotation = grElement
override val qualifiedName: String?
get() = grElement.qualifiedName
override fun resolve(): PsiClass? = grElement.nameReferenceElement?.resolve() as PsiClass?
override val uastAnchor: UIdentifier?
get() = grElement.classReference.referenceNameElement?.let { UIdentifier(it, this) }
override val attributeValues: List<UNamedExpression> by lazy {
grElement.parameterList.attributes.map {
GrUNamedExpression(it, { this })
}
}
override fun findAttributeValue(name: String?): UExpression? = null //not implemented
override fun findDeclaredAttributeValue(name: String?): UExpression? = null //not implemented
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
}
class GrUnknownUExpression(override val psi: PsiElement?, override val uastParent: UElement?) : UExpression, JvmDeclarationUElement {
override fun asLogString(): String = "GrUnknownUExpression(grElement)"
override val annotations: List<UAnnotation> = emptyList() //not implemented
} | apache-2.0 | a458d1bf271cbd8f11b605a32a35dbad | 43.833333 | 148 | 0.749582 | 5.064972 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinPreFormatProcessor.kt | 6 | 2857 | // 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.formatter
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.nextSiblingOfSameType
import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull
private class Visitor(var range: TextRange) : KtTreeVisitorVoid() {
override fun visitNamedDeclaration(declaration: KtNamedDeclaration) {
fun PsiElement.containsToken(type: IElementType) = allChildren.any { it.node.elementType == type }
if (!range.contains(declaration.textRange)) return
val classBody = declaration.parent as? KtClassBody ?: return
val klass = classBody.parent as? KtClass ?: return
if (!klass.isEnum()) return
var delta = 0
val psiFactory = KtPsiFactory(klass)
if (declaration is KtEnumEntry) {
val comma = psiFactory.createComma()
val nextEntry = declaration.nextSiblingOfSameType()
if (nextEntry != null && !declaration.containsToken(KtTokens.COMMA)) {
declaration.add(comma)
delta += comma.textLength
}
} else {
val lastEntry = klass.declarations.lastIsInstanceOrNull<KtEnumEntry>()
if (lastEntry != null &&
(lastEntry.containsToken(KtTokens.SEMICOLON) || lastEntry.nextSibling?.node?.elementType == KtTokens.SEMICOLON)
) return
if (lastEntry == null && classBody.containsToken(KtTokens.SEMICOLON)) return
val semicolon = psiFactory.createSemicolon()
delta += if (lastEntry != null) {
classBody.addAfter(semicolon, lastEntry)
semicolon.textLength
} else {
val newLine = psiFactory.createNewLine()
classBody.addAfter(semicolon, classBody.lBrace)
classBody.addAfter(psiFactory.createNewLine(), classBody.lBrace)
semicolon.textLength + newLine.textLength
}
}
range = TextRange(range.startOffset, range.endOffset + delta)
}
}
class KotlinPreFormatProcessor : PreFormatProcessor {
override fun process(element: ASTNode, range: TextRange): TextRange {
val psi = element.psi ?: return range
if (!psi.isValid) return range
if (psi.containingFile !is KtFile) return range
return Visitor(range).apply { psi.accept(this) }.range
}
}
| apache-2.0 | a859e6e4b7d18bfc962bb48222f97820 | 41.641791 | 158 | 0.677284 | 4.925862 | false | false | false | false |
mglukhikh/intellij-community | platform/projectModel-api/src/com/intellij/util/io/path.kt | 2 | 7312 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.util.io
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.FileTime
import java.util.*
fun Path.exists() = Files.exists(this)
fun Path.createDirectories(): Path {
// symlink or existing regular file - Java SDK do this check, but with as `isDirectory(dir, LinkOption.NOFOLLOW_LINKS)`, i.e. links are not checked
if (!Files.isDirectory(this)) {
doCreateDirectories(toAbsolutePath())
}
return this
}
private fun doCreateDirectories(path: Path) {
path.parent?.let {
if (!Files.isDirectory(it)) {
doCreateDirectories(it)
}
}
Files.createDirectory(path)
}
/**
* Opposite to Java, parent directories will be created
*/
fun Path.outputStream(): OutputStream {
parent?.createDirectories()
return Files.newOutputStream(this)
}
fun Path.inputStream(): InputStream = Files.newInputStream(this)
fun Path.inputStreamIfExists(): InputStream? {
try {
return inputStream()
}
catch (e: NoSuchFileException) {
return null
}
}
/**
* Opposite to Java, parent directories will be created
*/
fun Path.createSymbolicLink(target: Path): Path {
parent?.createDirectories()
Files.createSymbolicLink(this, target)
return this
}
fun Path.delete() {
val attributes = basicAttributesIfExists() ?: return
try {
if (attributes.isDirectory) {
deleteRecursively()
}
else {
Files.delete(this)
}
}
catch (e: Exception) {
FileUtil.delete(toFile())
}
}
fun Path.deleteWithParentsIfEmpty(root: Path, isFile: Boolean = true): Boolean {
var parent = if (isFile) this.parent else null
try {
delete()
}
catch (e: NoSuchFileException) {
return false
}
// remove empty directories
while (parent != null && parent != root) {
try {
// must be only Files.delete, but not our delete (Files.delete throws DirectoryNotEmptyException)
Files.delete(parent)
}
catch (e: IOException) {
break
}
parent = parent.parent
}
return true
}
fun Path.deleteChildrenStartingWith(prefix: String) {
directoryStreamIfExists({ it.fileName.toString().startsWith(prefix) }) { it.toList() }?.forEach {
it.delete()
}
}
private fun Path.deleteRecursively() = Files.walkFileTree(this, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
try {
Files.delete(file)
}
catch (e: Exception) {
FileUtil.delete(file.toFile())
}
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
try {
Files.delete(dir)
}
catch (e: Exception) {
FileUtil.delete(dir.toFile())
}
return FileVisitResult.CONTINUE
}
})
fun Path.lastModified(): FileTime = Files.getLastModifiedTime(this)
val Path.systemIndependentPath: String
get() = toString().replace(File.separatorChar, '/')
val Path.parentSystemIndependentPath: String
get() = parent!!.toString().replace(File.separatorChar, '/')
fun Path.readBytes(): ByteArray = Files.readAllBytes(this)
fun Path.readText(): String = readBytes().toString(Charsets.UTF_8)
fun Path.readChars() = inputStream().reader().readCharSequence(size().toInt())
fun Path.writeChild(relativePath: String, data: ByteArray) = resolve(relativePath).write(data)
fun Path.writeChild(relativePath: String, data: String) = writeChild(relativePath, data.toByteArray())
fun Path.write(data: ByteArray, offset: Int = 0, size: Int = data.size): Path {
outputStream().use { it.write(data, offset, size) }
return this
}
fun Path.writeSafe(data: ByteArray, offset: Int = 0, size: Int = data.size): Path {
val tempFile = parent.resolve("${fileName}.${UUID.randomUUID()}.tmp")
tempFile.write(data, offset, size)
try {
Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
}
catch (e: IOException) {
LOG.warn(e)
FileUtil.rename(tempFile.toFile(), this.toFile())
}
return this
}
fun Path.writeSafe(outConsumer: (OutputStream) -> Unit): Path {
val tempFile = parent.resolve("${fileName}.${UUID.randomUUID()}.tmp")
tempFile.outputStream().use(outConsumer)
try {
Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
}
catch (e: IOException) {
LOG.warn(e)
FileUtil.rename(tempFile.toFile(), this.toFile())
}
return this
}
fun Path.write(data: String): Path {
parent?.createDirectories()
Files.write(this, data.toByteArray())
return this
}
fun Path.size() = Files.size(this)
fun Path.basicAttributesIfExists(): BasicFileAttributes? {
try {
return Files.readAttributes(this, BasicFileAttributes::class.java)
}
catch (ignored: NoSuchFileException) {
return null
}
}
fun Path.sizeOrNull() = basicAttributesIfExists()?.size() ?: -1
fun Path.isHidden() = Files.isHidden(this)
fun Path.isDirectory() = Files.isDirectory(this)
fun Path.isFile() = Files.isRegularFile(this)
fun Path.move(target: Path): Path = Files.move(this, target, StandardCopyOption.REPLACE_EXISTING)
fun Path.copy(target: Path): Path {
parent?.createDirectories()
return Files.copy(this, target, StandardCopyOption.REPLACE_EXISTING)
}
/**
* Opposite to Java, parent directories will be created
*/
fun Path.createFile() {
parent?.createDirectories()
Files.createFile(this)
}
inline fun <R> Path.directoryStreamIfExists(task: (stream: DirectoryStream<Path>) -> R): R? {
try {
return Files.newDirectoryStream(this).use(task)
}
catch (ignored: NoSuchFileException) {
}
return null
}
inline fun <R> Path.directoryStreamIfExists(noinline filter: ((path: Path) -> Boolean), task: (stream: DirectoryStream<Path>) -> R): R? {
try {
return Files.newDirectoryStream(this, DirectoryStream.Filter { filter(it) }).use(task)
}
catch (ignored: NoSuchFileException) {
}
return null
}
private val LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil")
private val illegalChars = setOf('/', '\\', '?', '<', '>', ':', '*', '|', '"', ':')
// https://github.com/parshap/node-sanitize-filename/blob/master/index.js
fun sanitizeFileName(name: String, replacement: String? = "_", isTruncate: Boolean = true): String {
var result: StringBuilder? = null
var last = 0
val length = name.length
for (i in 0 until length) {
val c = name.get(i)
if (!illegalChars.contains(c) && !c.isISOControl()) {
continue
}
if (result == null) {
result = StringBuilder()
}
if (last < i) {
result.append(name, last, i)
}
if (replacement != null) {
result.append(replacement)
}
last = i + 1
}
fun String.truncateFileName() = if (isTruncate) substring(0, Math.min(length, 255)) else this
if (result == null) {
return name.truncateFileName()
}
if (last < length) {
result.append(name, last, length)
}
return result.toString().truncateFileName()
} | apache-2.0 | 908e3d62059c969980026e33903c8cdd | 25.21147 | 149 | 0.69256 | 3.883165 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-api/src/org/jetbrains/kotlin/idea/frontend/api/KtAnalysisSession.kt | 1 | 9085 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.frontend.api.calls.KtCall
import org.jetbrains.kotlin.idea.frontend.api.components.*
import org.jetbrains.kotlin.idea.frontend.api.scopes.*
import org.jetbrains.kotlin.idea.frontend.api.symbols.*
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSymbolWithDeclarations
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSymbolWithMembers
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSymbolWithKind
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.types.KtType
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
/**
* The entry point into all frontend-related work. Has the following contracts:
* - Should not be accessed from event dispatch thread
* - Should not be accessed outside read action
* - Should not be leaked outside read action it was created in
* - To be sure that session is not leaked it is forbidden to store it in a variable, consider working with it only in [analyze] context
* - All entities retrieved from analysis session should not be leaked outside the read action KtAnalysisSession was created in
*
* To pass a symbol from one read action to another use [KtSymbolPointer] which can be created from a symbol by [KtSymbol.createPointer]
*
* To create analysis session consider using [analyze]
*/
abstract class KtAnalysisSession(final override val token: ValidityToken) : ValidityTokenOwner {
protected abstract val smartCastProvider: KtSmartCastProvider
protected abstract val diagnosticProvider: KtDiagnosticProvider
protected abstract val scopeProvider: KtScopeProvider
protected abstract val containingDeclarationProvider: KtSymbolContainingDeclarationProvider
protected abstract val symbolProvider: KtSymbolProvider
protected abstract val callResolver: KtCallResolver
protected abstract val completionCandidateChecker: KtCompletionCandidateChecker
protected abstract val symbolDeclarationOverridesProvider: KtSymbolDeclarationOverridesProvider
@Suppress("LeakingThis")
protected open val typeRenderer: KtTypeRenderer = KtDefaultTypeRenderer(this, token)
protected abstract val expressionTypeProvider: KtExpressionTypeProvider
protected abstract val typeProvider: KtTypeProvider
protected abstract val subtypingComponent: KtSubtypingComponent
protected abstract val expressionHandlingComponent: KtExpressionHandlingComponent
abstract fun createContextDependentCopy(originalKtFile: KtFile, fakeKtElement: KtElement): KtAnalysisSession
fun KtCallableSymbol.getOverriddenSymbols(containingDeclaration: KtClassOrObjectSymbol): List<KtCallableSymbol> =
symbolDeclarationOverridesProvider.getOverriddenSymbols(this, containingDeclaration)
fun KtCallableSymbol.getIntersectionOverriddenSymbols(): Collection<KtCallableSymbol> =
symbolDeclarationOverridesProvider.getIntersectionOverriddenSymbols(this)
fun KtExpression.getSmartCasts(): Collection<KtType> = smartCastProvider.getSmartCastedToTypes(this)
fun KtExpression.getImplicitReceiverSmartCasts(): Collection<ImplicitReceiverSmartCast> =
smartCastProvider.getImplicitReceiverSmartCasts(this)
fun KtExpression.getKtType(): KtType = expressionTypeProvider.getKtExpressionType(this)
fun KtDeclaration.getReturnKtType(): KtType = expressionTypeProvider.getReturnTypeForKtDeclaration(this)
infix fun KtType.isEqualTo(other: KtType): Boolean = subtypingComponent.isEqualTo(this, other)
infix fun KtType.isSubTypeOf(superType: KtType): Boolean = subtypingComponent.isSubTypeOf(this, superType)
fun PsiElement.getExpectedType(): KtType? = expressionTypeProvider.getExpectedType(this)
fun KtType.isBuiltInFunctionalType(): Boolean = typeProvider.isBuiltinFunctionalType(this)
val builtinTypes: KtBuiltinTypes get() = typeProvider.builtinTypes
fun KtElement.getDiagnostics(): Collection<Diagnostic> = diagnosticProvider.getDiagnosticsForElement(this)
fun KtFile.collectDiagnosticsForFile(): Collection<Diagnostic> = diagnosticProvider.collectDiagnosticsForFile(this)
fun KtSymbolWithKind.getContainingSymbol(): KtSymbolWithKind? = containingDeclarationProvider.getContainingDeclaration(this)
fun KtSymbolWithMembers.getMemberScope(): KtMemberScope = scopeProvider.getMemberScope(this)
fun KtSymbolWithMembers.getDeclaredMemberScope(): KtDeclaredMemberScope = scopeProvider.getDeclaredMemberScope(this)
fun KtFileSymbol.getFileScope(): KtDeclarationScope<KtSymbolWithDeclarations> = scopeProvider.getFileScope(this)
fun KtPackageSymbol.getPackageScope(): KtPackageScope = scopeProvider.getPackageScope(this)
fun List<KtScope>.asCompositeScope(): KtCompositeScope = scopeProvider.getCompositeScope(this)
fun KtType.getTypeScope(): KtScope? = scopeProvider.getTypeScope(this)
fun KtFile.getScopeContextForPosition(positionInFakeFile: KtElement): KtScopeContext =
scopeProvider.getScopeContextForPosition(this, positionInFakeFile)
fun KtDeclaration.getSymbol(): KtSymbol = symbolProvider.getSymbol(this)
fun KtParameter.getParameterSymbol(): KtParameterSymbol = symbolProvider.getParameterSymbol(this)
fun KtNamedFunction.getFunctionSymbol(): KtFunctionSymbol = symbolProvider.getFunctionSymbol(this)
fun KtConstructor<*>.getConstructorSymbol(): KtConstructorSymbol = symbolProvider.getConstructorSymbol(this)
fun KtTypeParameter.getTypeParameterSymbol(): KtTypeParameterSymbol = symbolProvider.getTypeParameterSymbol(this)
fun KtTypeAlias.getTypeAliasSymbol(): KtTypeAliasSymbol = symbolProvider.getTypeAliasSymbol(this)
fun KtEnumEntry.getEnumEntrySymbol(): KtEnumEntrySymbol = symbolProvider.getEnumEntrySymbol(this)
fun KtNamedFunction.getAnonymousFunctionSymbol(): KtAnonymousFunctionSymbol = symbolProvider.getAnonymousFunctionSymbol(this)
fun KtLambdaExpression.getAnonymousFunctionSymbol(): KtAnonymousFunctionSymbol = symbolProvider.getAnonymousFunctionSymbol(this)
fun KtProperty.getVariableSymbol(): KtVariableSymbol = symbolProvider.getVariableSymbol(this)
fun KtObjectLiteralExpression.getAnonymousObjectSymbol(): KtAnonymousObjectSymbol = symbolProvider.getAnonymousObjectSymbol(this)
fun KtClassOrObject.getClassOrObjectSymbol(): KtClassOrObjectSymbol = symbolProvider.getClassOrObjectSymbol(this)
fun KtPropertyAccessor.getPropertyAccessorSymbol(): KtPropertyAccessorSymbol = symbolProvider.getPropertyAccessorSymbol(this)
fun KtFile.getFileSymbol(): KtFileSymbol = symbolProvider.getFileSymbol(this)
/**
* @return symbol with specified [this@getClassOrObjectSymbolByClassId] or `null` in case such symbol is not found
*/
fun ClassId.getCorrespondingToplevelClassOrObjectSymbol(): KtClassOrObjectSymbol? = symbolProvider.getClassOrObjectSymbolByClassId(this)
fun FqName.getContainingCallableSymbolsWithName(name: Name): Sequence<KtSymbol> = symbolProvider.getTopLevelCallableSymbols(this, name)
fun <S : KtSymbol> KtSymbolPointer<S>.restoreSymbol(): S? = restoreSymbol(this@KtAnalysisSession)
fun KtCallExpression.resolveCall(): KtCall? = callResolver.resolveCall(this)
fun KtBinaryExpression.resolveCall(): KtCall? = callResolver.resolveCall(this)
fun KtReference.resolveToSymbols(): Collection<KtSymbol> {
check(this is KtSymbolBasedReference) { "To get reference symbol the one should be KtSymbolBasedReference" }
return [email protected]()
}
fun KtSimpleReference<*>.resolveToSymbol(): KtSymbol? {
check(this is KtSymbolBasedReference) { "To get reference symbol the one should be KtSymbolBasedReference but was ${this::class}" }
return resolveToSymbols().singleOrNull()
}
fun KtCallableSymbol.checkExtensionIsSuitable(
originalPsiFile: KtFile,
psiFakeCompletionExpression: KtSimpleNameExpression,
psiReceiverExpression: KtExpression?,
): Boolean = completionCandidateChecker.checkExtensionFitsCandidate(
this,
originalPsiFile,
psiFakeCompletionExpression,
psiReceiverExpression
)
@NlsSafe
fun KtType.render(options: KtTypeRendererOptions = KtTypeRendererOptions.DEFAULT): String =
typeRenderer.render(this, options)
fun KtReturnExpression.getReturnTargetSymbol(): KtCallableSymbol? =
expressionHandlingComponent.getReturnExpressionTargetSymbol(this)
}
| apache-2.0 | fc95554ce8edfc534266c0610c9a4ca9 | 51.514451 | 140 | 0.810787 | 5.391691 | false | false | false | false |
smmribeiro/intellij-community | platform/built-in-server/src/org/jetbrains/ide/RestService.kt | 2 | 11542 | // 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.ide
import com.github.benmanes.caffeine.cache.CacheLoader
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.MalformedJsonException
import com.intellij.ide.IdeBundle
import com.intellij.ide.impl.ProjectUtil.showYesNoDialog
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.AppIcon
import com.intellij.util.ExceptionUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.origin
import com.intellij.util.io.referrer
import com.intellij.util.net.NetUtils
import com.intellij.util.text.nullize
import com.intellij.xml.util.XmlStringUtil
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import org.jetbrains.annotations.NonNls
import org.jetbrains.builtInWebServer.isSignedRequest
import org.jetbrains.io.addCommonHeaders
import org.jetbrains.io.addNoCache
import org.jetbrains.io.response
import org.jetbrains.io.send
import java.awt.Window
import java.io.IOException
import java.io.OutputStream
import java.lang.reflect.InvocationTargetException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.URI
import java.net.URISyntaxException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
/**
* Document your service using [apiDoc](http://apidocjs.com).
* To extract a big example from source code, consider adding a *.coffee file near the sources
* (or Python/Ruby, but CoffeeScript is recommended because it's plugin is lightweight).
* See [AboutHttpService] for example.
*
* Don't create [JsonReader]/[JsonWriter] directly, use only provided [createJsonReader] and [createJsonWriter] methods
* (to ensure that you handle in/out according to REST API guidelines).
*
* @see <a href="http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api">Best Practices for Designing a Pragmatic REST API</a>.
*/
@Suppress("HardCodedStringLiteral")
abstract class RestService : HttpRequestHandler() {
companion object {
@JvmField
val LOG = logger<RestService>()
const val PREFIX = "api"
@JvmStatic
fun activateLastFocusedFrame() {
(IdeFocusManager.getGlobalInstance().lastFocusedFrame as? Window)?.toFront()
}
@JvmStatic
fun createJsonReader(request: FullHttpRequest): JsonReader {
val reader = JsonReader(ByteBufInputStream(request.content()).reader())
reader.isLenient = true
return reader
}
@JvmStatic
fun createJsonWriter(out: OutputStream): JsonWriter {
val writer = JsonWriter(out.writer())
writer.setIndent(" ")
return writer
}
@JvmStatic
fun getLastFocusedOrOpenedProject(): Project? {
return IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: ProjectManager.getInstance().openProjects.firstOrNull()
}
@JvmStatic
fun sendOk(request: FullHttpRequest, context: ChannelHandlerContext) {
sendStatus(HttpResponseStatus.OK, HttpUtil.isKeepAlive(request), context.channel())
}
@JvmStatic
fun sendStatus(status: HttpResponseStatus, keepAlive: Boolean, channel: Channel) {
val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status)
HttpUtil.setContentLength(response, 0)
response.addCommonHeaders()
response.addNoCache()
if (keepAlive) {
HttpUtil.setKeepAlive(response, true)
}
response.headers().set("X-Frame-Options", "Deny")
response.send(channel, !keepAlive)
}
@JvmStatic
fun send(byteOut: BufferExposingByteArrayOutputStream, request: HttpRequest, context: ChannelHandlerContext) {
val response = response("application/json", Unpooled.wrappedBuffer(byteOut.internalBuffer, 0, byteOut.size()))
sendResponse(request, context, response)
}
@JvmStatic
fun sendResponse(request: HttpRequest, context: ChannelHandlerContext, response: HttpResponse) {
response.addNoCache()
response.headers().set("X-Frame-Options", "Deny")
response.send(context.channel(), request)
}
@Suppress("SameParameterValue")
@JvmStatic
fun getStringParameter(name: String, urlDecoder: QueryStringDecoder): String? {
return urlDecoder.parameters()[name]?.lastOrNull()
}
@JvmStatic
fun getIntParameter(name: String, urlDecoder: QueryStringDecoder): Int {
return StringUtilRt.parseInt(getStringParameter(name, urlDecoder).nullize(nullizeSpaces = true), -1)
}
@JvmOverloads
@JvmStatic
fun getBooleanParameter(name: String, urlDecoder: QueryStringDecoder, defaultValue: Boolean = false): Boolean {
val values = urlDecoder.parameters()[name] ?: return defaultValue
// if just name specified, so, true
val value = values.lastOrNull() ?: return true
return value.toBoolean()
}
fun parameterMissedErrorMessage(name: String) = "Parameter \"$name\" is not specified"
}
protected val gson: Gson by lazy {
GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create()
}
private val abuseCounter = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.build<InetAddress, AtomicInteger>(CacheLoader { AtomicInteger() })
private val trustedOrigins = Caffeine.newBuilder()
.maximumSize(1024)
.expireAfterWrite(1, TimeUnit.DAYS)
.build<String, Boolean>()
private val hostLocks = ContainerUtil.createConcurrentWeakKeyWeakValueMap<String, Any>()
private var isBlockUnknownHosts = false
/**
* Service url must be "/api/$serviceName", but to preserve backward compatibility, prefixless path could be also supported
*/
protected open val isPrefixlessAllowed: Boolean
get() = false
/**
* Use human-readable name or UUID if it is an internal service.
*/
@NlsSafe
protected abstract fun getServiceName(): String
override fun isSupported(request: FullHttpRequest): Boolean {
if (!isMethodSupported(request.method())) {
return false
}
val uri = request.uri()
if (isPrefixlessAllowed && checkPrefix(uri, getServiceName())) {
return true
}
val serviceName = getServiceName()
val minLength = 1 + PREFIX.length + 1 + serviceName.length
if (uri.length >= minLength &&
uri[0] == '/' &&
uri.regionMatches(1, PREFIX, 0, PREFIX.length, ignoreCase = true) &&
uri.regionMatches(2 + PREFIX.length, serviceName, 0, serviceName.length, ignoreCase = true)) {
if (uri.length == minLength) {
return true
}
else {
val c = uri[minLength]
return c == '/' || c == '?'
}
}
return false
}
protected open fun isMethodSupported(method: HttpMethod): Boolean {
return method === HttpMethod.GET
}
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
try {
val counter = abuseCounter.get((context.channel().remoteAddress() as InetSocketAddress).address)!!
if (counter.incrementAndGet() > Registry.intValue("ide.rest.api.requests.per.minute", 30)) {
HttpResponseStatus.TOO_MANY_REQUESTS.orInSafeMode(HttpResponseStatus.OK).send(context.channel(), request)
return true
}
if (!isHostTrusted(request, urlDecoder)) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.OK).send(context.channel(), request)
return true
}
val error = execute(urlDecoder, request, context)
if (error != null) {
HttpResponseStatus.BAD_REQUEST.send(context.channel(), request, error)
}
}
catch (e: Throwable) {
val status: HttpResponseStatus?
// JsonReader exception
if (e is MalformedJsonException || e is IllegalStateException && e.message!!.startsWith("Expected a ")) {
LOG.warn(e)
status = HttpResponseStatus.BAD_REQUEST
}
else {
LOG.error(e)
status = HttpResponseStatus.INTERNAL_SERVER_ERROR
}
status.send(context.channel(), request, XmlStringUtil.escapeString(ExceptionUtil.getThrowableText(e)))
}
return true
}
@Throws(InterruptedException::class, InvocationTargetException::class)
protected open fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean {
@Suppress("DEPRECATION")
return isHostTrusted(request)
}
@Deprecated("Use {@link #isHostTrusted(FullHttpRequest, QueryStringDecoder)}")
@Throws(InterruptedException::class, InvocationTargetException::class)
// e.g. upsource trust to configured host
protected open fun isHostTrusted(request: FullHttpRequest): Boolean {
if (request.isSignedRequest() || isOriginAllowed(request) == OriginCheckResult.ALLOW) {
return true
}
val referrer = request.origin ?: request.referrer
val host = try {
if (referrer == null) null else URI(referrer).host.nullize()
}
catch (ignored: URISyntaxException) {
return false
}
val lock = hostLocks.computeIfAbsent(host ?: "") { Object() }
synchronized(lock) {
if (host != null) {
if (NetUtils.isLocalhost(host)) {
return true
}
else {
trustedOrigins.getIfPresent(host)?.let {
return it
}
}
}
else {
if (isBlockUnknownHosts) return false
}
var isTrusted = false
ApplicationManager.getApplication().invokeAndWait(
{
AppIcon.getInstance().requestAttention(null, true)
val message = when (host) {
null -> IdeBundle.message("warning.use.rest.api.0.and.trust.host.unknown", getServiceName())
else -> IdeBundle.message("warning.use.rest.api.0.and.trust.host.1", getServiceName(), host)
}
isTrusted = showYesNoDialog(message, "title.use.rest.api")
if (host != null) {
trustedOrigins.put(host, isTrusted)
}
else {
if (!isTrusted) {
isBlockUnknownHosts = showYesNoDialog(IdeBundle.message("warning.use.rest.api.block.unknown.hosts"), "title.use.rest.api")
}
}
}, ModalityState.any())
return isTrusted
}
}
/**
* Return error or send response using [sendOk], [send]
*/
@Throws(IOException::class)
@NonNls
abstract fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String?
}
internal fun HttpResponseStatus.orInSafeMode(safeStatus: HttpResponseStatus): HttpResponseStatus {
return if (Registry.`is`("ide.http.server.response.actual.status", true) || ApplicationManager.getApplication()?.isUnitTestMode == true) this else safeStatus
}
| apache-2.0 | 4992b270ba0a5021838c7050f44b6aad | 35.295597 | 159 | 0.712008 | 4.5245 | false | false | false | false |
erdo/asaf-project | example-kt-02coroutine/src/androidTest/java/foo/bar/example/forecoroutine/ui/CounterViewTest.kt | 1 | 5001 | package foo.bar.example.forecoroutine.ui
import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
import android.view.View
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.isEnabled
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import foo.bar.example.forecoroutine.App
import foo.bar.example.forecoroutine.ProgressBarIdler
import foo.bar.example.forecoroutine.R
import foo.bar.example.forecoroutine.feature.counter.Counter
import foo.bar.example.forecoroutine.feature.counter.CounterWithProgress
import io.mockk.MockKAnnotations
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import org.hamcrest.Matchers.not
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* Copyright © 2019 early.co. All rights reserved.
*
* Here we make sure that the view elements accurately reflect the state of the models
* and that clicking the buttons results in the correct action being performed
*/
@RunWith(AndroidJUnit4::class)
class CounterViewTest {
@MockK
private lateinit var mockCounter: Counter
@MockK
private lateinit var mockCounterWithProgress: CounterWithProgress
@Before
fun setup() {
MockKAnnotations.init(this, relaxed = true)
val app: App = ApplicationProvider.getApplicationContext() as App
app.registerActivityLifecycleCallbacks(ProgressBarIdler())
}
@Test
@Throws(Exception::class)
fun initialState() {
//arrange
StateBuilder(mockCounter, mockCounterWithProgress)
.counterWithProgressIsBusy(true)
.counterWithProgressProgressValue(7)
.counterWithProgressCount(40)
.counterBasicIsBusy(false)
.counterBasicCount(0)
.createRule()
.launchActivity(null)
//act
//assert
onView(withId(R.id.counterwprog_increase_btn)).check(matches(not<View>(isEnabled())))
onView(withId(R.id.counterwprog_busy_progress)).check(matches(isDisplayed()))
onView(withId(R.id.counterwprog_progress_txt)).check(matches(withText("7")))
onView(withId(R.id.counterwprog_current_txt)).check(matches(withText("40")))
onView(withId(R.id.counter_increase_btn)).check(matches(isEnabled()))
onView(withId(R.id.counter_busy_progress)).check(matches(not<View>(isDisplayed())))
onView(withId(R.id.counter_current_txt)).check(matches(withText("0")))
}
@Test
@Throws(Exception::class)
fun rotationState() {
//arrange
val activity = StateBuilder(mockCounter, mockCounterWithProgress)
.counterWithProgressIsBusy(true)
.counterWithProgressProgressValue(7)
.counterWithProgressCount(40)
.counterBasicIsBusy(false)
.counterBasicCount(0)
.createRule()
.launchActivity(null)
activity.requestedOrientation = SCREEN_ORIENTATION_LANDSCAPE
//act
activity.requestedOrientation = SCREEN_ORIENTATION_PORTRAIT
//assert
onView(withId(R.id.counterwprog_increase_btn)).check(matches(not<View>(isEnabled())))
onView(withId(R.id.counterwprog_busy_progress)).check(matches(isDisplayed()))
onView(withId(R.id.counterwprog_progress_txt)).check(matches(withText("7")))
onView(withId(R.id.counterwprog_current_txt)).check(matches(withText("40")))
onView(withId(R.id.counter_increase_btn)).check(matches(isEnabled()))
onView(withId(R.id.counter_busy_progress)).check(matches(not<View>(isDisplayed())))
onView(withId(R.id.counter_current_txt)).check(matches(withText("0")))
}
@Test
@Throws(Exception::class)
fun clickCallsBasicModel() {
//arrange
StateBuilder(mockCounter, mockCounterWithProgress)
.counterBasicIsBusy(false)
.createRule()
.launchActivity(null)
//act
onView(withId(R.id.counter_increase_btn)).perform(click())
//assert
verify(exactly = 1) {
mockCounter.increaseBy20()
}
}
@Test
@Throws(Exception::class)
fun clickCallsWithProgressModel() {
//arrange
StateBuilder(mockCounter, mockCounterWithProgress)
.counterWithProgressIsBusy(false)
.createRule()
.launchActivity(null)
//act
onView(withId(R.id.counterwprog_increase_btn)).perform(click())
//assert
verify(exactly = 1) {
mockCounterWithProgress.increaseBy20()
}
}
}
| apache-2.0 | 236c2d634526e78d9ea68c5439c8f28c | 34.211268 | 93 | 0.6984 | 4.262575 | false | true | false | false |
blan4/MangaReader | api/src/main/kotlin/org/seniorsigan/mangareader/sources/NetworkRepository.kt | 1 | 1787 | package org.seniorsigan.mangareader.sources
import io.reactivex.Observable
import io.reactivex.rxkotlin.toObservable
import okhttp3.*
import org.seniorsigan.mangareader.models.ChapterItem
import org.seniorsigan.mangareader.models.MangaItem
import org.seniorsigan.mangareader.models.PageItem
import org.seniorsigan.mangareader.sources.readmanga.ReadmangaMangaApiConverter
import org.seniorsigan.mangareader.sources.readmanga.Urls
import java.io.IOException
import java.net.URI
class NetworkRepository(
private val urls: Urls,
private val converter: ReadmangaMangaApiConverter,
private val client: OkHttpClient = OkHttpClient()
) {
fun getPopular(offset: Int = 0): Observable<MangaItem> {
return wrap(urls.mangaList(offset)).map {
converter.parseList(it, urls.base)
}.flatMap {
it.toObservable()
}.concatMap {
getMangaItem(it.url)
}
}
fun getMangaItem(itemURL: URI): Observable<MangaItem> {
return wrap(itemURL).map {
converter.parseManga(it, urls.base)
}
}
fun getPages(url: URI): Observable<List<PageItem>> {
return wrap(url).map {
converter.parseChapter(it)
}
}
private fun wrap(uri: URI): Observable<String> = Observable.create { subscriber ->
val req = Request.Builder().url(uri.toURL()).build()
client.newCall(req).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
subscriber.onError(e)
}
override fun onResponse(call: Call, res: Response) {
val html = res.body().string()
subscriber.onNext(html)
subscriber.onComplete()
}
})
}
} | mit | b210f1104a2f714b4f92cd7ce9b29d5e | 30.928571 | 86 | 0.646894 | 4.434243 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Module/Search/SearchPetalResultBoardFragment.kt | 1 | 4703 | package stan.androiddemo.project.petal.Module.Search
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.FrameLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseViewHolder
import com.facebook.drawee.view.SimpleDraweeView
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.UI.BasePetalRecyclerFragment
import stan.androiddemo.project.petal.API.SearchAPI
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnBoardFragmentInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Model.BoardPinsInfo
import stan.androiddemo.project.petal.Observable.ErrorHelper
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
class SearchPetalResultBoardFragment : BasePetalRecyclerFragment<BoardPinsInfo>() {
lateinit var mAttentionFormat :String
lateinit var mGatherFormat :String
lateinit var mUsernameFormat :String
var mLimit = Config.LIMIT
private var mListener: OnBoardFragmentInteractionListener<BoardPinsInfo>? = null
override fun getTheTAG(): String {
return this.toString()
}
companion object {
fun newInstance(type:String): SearchPetalResultBoardFragment {
val fragment = SearchPetalResultBoardFragment()
val bundle = Bundle()
bundle.putString("key",type)
fragment.arguments = bundle
return fragment
}
}
override fun getLayoutManager(): RecyclerView.LayoutManager {
return GridLayoutManager(context,2)
}
override fun initView() {
super.initView()
mAttentionFormat = context.resources.getString(R.string.text_attention_number)
mGatherFormat = context.resources.getString(R.string.text_gather_number)
mUsernameFormat = context.resources.getString(R.string.text_by_username)
}
override fun getItemLayoutId(): Int {
return R.layout.petal_cardview_board_item
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnBoardFragmentInteractionListener<*>)
{
mListener = context as OnBoardFragmentInteractionListener<BoardPinsInfo>
}
}
override fun itemLayoutConvert(helper: BaseViewHolder, t: BoardPinsInfo) {
helper.getView<FrameLayout>(R.id.frame_layout_board).setOnClickListener {
mListener?.onClickBoardItemImage(t,it)
}
helper.getView<TextView>(R.id.txt_board_username).setOnClickListener {
mListener?.onClickBoardItemImage(t,it)
}
helper.setText(R.id.txt_board_title,t.title)
helper.setText(R.id.txt_board_gather, String.format(mGatherFormat,t.pin_count))
helper.setText(R.id.txt_board_attention, String.format(mAttentionFormat,t.follow_count))
helper.setText(R.id.txt_board_username, String.format(mUsernameFormat,t.user?.username))
var url = ""
if (t.pins!= null && t.pins!!.size > 0){
if (t.pins!!.first().file?.key != null){
url = t.pins!!.first().file!!.key!!
}
}
url = String.format(mUrlGeneralFormat,url)
val img = helper.getView<SimpleDraweeView>(R.id.img_card_board)
img.aspectRatio = 1F
ImageLoadBuilder.Start(context,img,url).setProgressBarImage(progressLoading).build()
}
override fun requestListData(page: Int): Subscription {
return RetrofitClient.createService(SearchAPI::class.java).httpsBoardSearchRx(mAuthorization!!,mKey,page, mLimit)
.flatMap {
ErrorHelper.getCheckNetError(it)
}.map { it.boards }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object: Subscriber<List<BoardPinsInfo>>(){
override fun onCompleted() {
}
override fun onError(e: Throwable?) {
e?.printStackTrace()
loadError()
checkException(e)
}
override fun onNext(t: List<BoardPinsInfo>?) {
if (t == null){
loadError()
return
}
loadSuccess(t!!)
}
})
}
}
| mit | c87580b821fbb68be3fa422d7f1d6329 | 35.176923 | 121 | 0.654263 | 4.726633 | false | false | false | false |
softappeal/yass | kotlin/yass/test/ch/softappeal/yass/serialize/ReaderWriterTest.kt | 1 | 10626 | package ch.softappeal.yass.serialize
import java.io.*
import java.util.*
import kotlin.test.*
class ReaderWriterTest {
@Test
fun adaptorByte() {
val p0 = 0
val p100 = 100
val p127 = 127
val m100 = -100
val m128 = -128
val out = ByteArrayOutputStream()
val writer = writer(out).stream()
writer.write(p0)
writer.write(p100)
writer.write(p127)
writer.write(m100)
writer.write(m128)
val buffer = out.toByteArray()
assertEquals(p0.toByte(), buffer[0])
assertEquals(p100.toByte(), buffer[1])
assertEquals(p127.toByte(), buffer[2])
assertEquals(m100.toByte(), buffer[3])
assertEquals(m128.toByte(), buffer[4])
val reader = reader(ByteArrayInputStream(buffer)).stream()
assertEquals((p0 and 0b1111_1111), reader.read())
assertEquals((p100 and 0b1111_1111), reader.read())
assertEquals((p127 and 0b1111_1111), reader.read())
assertEquals((m100 and 0b1111_1111), reader.read())
assertEquals((m128 and 0b1111_1111), reader.read())
assertEquals(
"end of stream reached",
assertFailsWith<IllegalStateException> { reader.read() }.message
)
}
@Test
fun adaptorBytes() {
val input = byteArrayOf(0, 100, 127, -100, -128)
val out = ByteArrayOutputStream()
val writer = writer(out).stream()
writer.write(input, 0, input.size)
val buffer = out.toByteArray()
assertTrue(Arrays.equals(input, buffer))
val reader = reader(ByteArrayInputStream(buffer)).stream()
val output = ByteArray(input.size)
assertEquals(input.size, reader.read(output, 0, output.size))
assertTrue(Arrays.equals(output, input))
assertEquals(
"end of stream reached",
assertFailsWith<IllegalStateException> { reader.read() }.message
)
}
@Test
fun bytes() {
val out = ByteArrayOutputStream()
val writer = writer(out)
writer.writeBytes(byteArrayOf(-1, 0, 1))
val reader = reader(ByteArrayInputStream(out.toByteArray()))
val bytes = ByteArray(3)
reader.readBytes(bytes)
assertTrue(Arrays.equals(bytes, byteArrayOf(-1, 0, 1)))
}
@Test
fun numbers() {
val out = ByteArrayOutputStream()
val writer = writer(out)
writer.writeShort(12.toShort())
writer.writeShort(0.toShort())
writer.writeShort((-34).toShort())
writer.writeShort(0x1234.toShort())
writer.writeShort(0xFEDC.toShort())
writer.writeShort(Short.MIN_VALUE)
writer.writeShort(Short.MAX_VALUE)
writer.writeInt(12)
writer.writeInt(0)
writer.writeInt(-34)
writer.writeInt(0x1234_5678)
writer.writeInt(-0x123_4568)
writer.writeInt(Integer.MIN_VALUE)
writer.writeInt(Integer.MAX_VALUE)
writer.writeLong(12)
writer.writeLong(0)
writer.writeLong(-34)
writer.writeLong(0x1234_5678_9ABC_DEF0)
writer.writeLong(-0x123_4567_89ab_cdf0)
writer.writeLong(Long.MIN_VALUE)
writer.writeLong(Long.MAX_VALUE)
writer.writeChar('\u1234')
writer.writeChar('\uFEDC')
writer.writeChar(Character.MIN_VALUE)
writer.writeChar(Character.MAX_VALUE)
writer.writeFloat(1.2345e-12f)
writer.writeFloat(Float.MAX_VALUE)
writer.writeFloat(Float.MIN_VALUE)
writer.writeFloat(java.lang.Float.MIN_NORMAL)
writer.writeFloat(Float.NEGATIVE_INFINITY)
writer.writeFloat(Float.POSITIVE_INFINITY)
writer.writeFloat(Float.NaN)
writer.writeDouble(1.2345e-12)
writer.writeDouble(Double.MAX_VALUE)
writer.writeDouble(Double.MIN_VALUE)
writer.writeDouble(java.lang.Double.MIN_NORMAL)
writer.writeDouble(Double.NEGATIVE_INFINITY)
writer.writeDouble(Double.POSITIVE_INFINITY)
writer.writeDouble(Double.NaN)
val reader = reader(ByteArrayInputStream(out.toByteArray()))
assertEquals(12.toShort(), reader.readShort())
assertEquals(0.toShort(), reader.readShort())
assertEquals((-34).toShort(), reader.readShort())
assertEquals(0x1234.toShort(), reader.readShort())
assertEquals((-0x124).toShort(), reader.readShort())
assertEquals(Short.MIN_VALUE, reader.readShort())
assertEquals(Short.MAX_VALUE, reader.readShort())
assertEquals(12, reader.readInt())
assertEquals(0, reader.readInt())
assertEquals(-34, reader.readInt())
assertEquals(0x1234_5678, reader.readInt())
assertEquals(-0x123_4568, reader.readInt())
assertEquals(Integer.MIN_VALUE, reader.readInt())
assertEquals(Integer.MAX_VALUE, reader.readInt())
assertEquals(12L, reader.readLong())
assertEquals(0L, reader.readLong())
assertEquals(-34L, reader.readLong())
assertEquals(0x1234_5678_9ABC_DEF0, reader.readLong())
assertEquals(-0x123_4567_89ab_cdf0, reader.readLong())
assertEquals(Long.MIN_VALUE, reader.readLong())
assertEquals(Long.MAX_VALUE, reader.readLong())
assertEquals('\u1234', reader.readChar())
assertEquals('\uFEDC', reader.readChar())
assertEquals(Character.MIN_VALUE, reader.readChar())
assertEquals(Character.MAX_VALUE, reader.readChar())
assertEquals(1.2345e-12f, reader.readFloat())
assertEquals(Float.MAX_VALUE, reader.readFloat())
assertEquals(Float.MIN_VALUE, reader.readFloat())
assertEquals(java.lang.Float.MIN_NORMAL, reader.readFloat())
assertEquals(Float.NEGATIVE_INFINITY, reader.readFloat())
assertEquals(Float.POSITIVE_INFINITY, reader.readFloat())
assertEquals("NaN", reader.readFloat().toString())
assertEquals(1.2345e-12, reader.readDouble())
assertEquals(Double.MAX_VALUE, reader.readDouble())
assertEquals(Double.MIN_VALUE, reader.readDouble())
assertEquals(java.lang.Double.MIN_NORMAL, reader.readDouble())
assertEquals(Double.NEGATIVE_INFINITY, reader.readDouble())
assertEquals(Double.POSITIVE_INFINITY, reader.readDouble())
assertEquals("NaN", reader.readDouble().toString())
}
@Test
fun varInt() {
val out = ByteArrayOutputStream()
val writer = writer(out)
writer.writeVarInt(12)
writer.writeVarInt(0)
writer.writeVarInt(128)
writer.writeVarInt(60000)
writer.writeVarInt(60000000)
writer.writeVarInt(-34)
writer.writeVarInt(0x12345678)
writer.writeVarInt(-0x1234568)
writer.writeVarInt(Integer.MIN_VALUE)
writer.writeVarInt(Integer.MAX_VALUE)
writer.writeZigZagInt(12)
writer.writeZigZagInt(0)
writer.writeZigZagInt(128)
writer.writeZigZagInt(60000)
writer.writeZigZagInt(60000000)
writer.writeZigZagInt(-34)
writer.writeZigZagInt(0x12345678)
writer.writeZigZagInt(-0x1234568)
writer.writeZigZagInt(Integer.MIN_VALUE)
writer.writeZigZagInt(Integer.MAX_VALUE)
val reader = reader(ByteArrayInputStream(out.toByteArray()))
assertEquals(12, reader.readVarInt())
assertEquals(0, reader.readVarInt())
assertEquals(128, reader.readVarInt())
assertEquals(60000, reader.readVarInt())
assertEquals(60000000, reader.readVarInt())
assertEquals(-34, reader.readVarInt())
assertEquals(0x12345678, reader.readVarInt())
assertEquals(-0x1234568, reader.readVarInt())
assertEquals(Integer.MIN_VALUE, reader.readVarInt())
assertEquals(Integer.MAX_VALUE, reader.readVarInt())
assertEquals(12, reader.readZigZagInt())
assertEquals(0, reader.readZigZagInt())
assertEquals(128, reader.readZigZagInt())
assertEquals(60000, reader.readZigZagInt())
assertEquals(60000000, reader.readZigZagInt())
assertEquals(-34, reader.readZigZagInt())
assertEquals(0x12345678, reader.readZigZagInt())
assertEquals(-0x1234568, reader.readZigZagInt())
assertEquals(Integer.MIN_VALUE, reader.readZigZagInt())
assertEquals(Integer.MAX_VALUE, reader.readZigZagInt())
}
@Test
fun varLong() {
val out = ByteArrayOutputStream()
val writer = writer(out)
writer.writeVarLong(12)
writer.writeVarLong(0)
writer.writeVarLong(128)
writer.writeVarLong(-34)
writer.writeVarLong(0x123456789ABCDEF0)
writer.writeVarLong(-0x123456789abcdf0)
writer.writeVarLong(Long.MIN_VALUE)
writer.writeVarLong(Long.MAX_VALUE)
writer.writeZigZagLong(12)
writer.writeZigZagLong(0)
writer.writeZigZagLong(128)
writer.writeZigZagLong(-34)
writer.writeZigZagLong(0x123456789ABCDEF0)
writer.writeZigZagLong(-0x123456789abcdf0)
writer.writeZigZagLong(Long.MIN_VALUE)
writer.writeZigZagLong(Long.MAX_VALUE)
val reader = reader(ByteArrayInputStream(out.toByteArray()))
assertEquals(12L, reader.readVarLong())
assertEquals(0L, reader.readVarLong())
assertEquals(128L, reader.readVarLong())
assertEquals(-34L, reader.readVarLong())
assertEquals(0x123456789ABCDEF0, reader.readVarLong())
assertEquals(-0x123456789abcdf0, reader.readVarLong())
assertEquals(Long.MIN_VALUE, reader.readVarLong())
assertEquals(Long.MAX_VALUE, reader.readVarLong())
assertEquals(12L, reader.readZigZagLong())
assertEquals(0L, reader.readZigZagLong())
assertEquals(128L, reader.readZigZagLong())
assertEquals(-34L, reader.readZigZagLong())
assertEquals(0x123456789ABCDEF0, reader.readZigZagLong())
assertEquals(-0x123456789abcdf0, reader.readZigZagLong())
assertEquals(Long.MIN_VALUE, reader.readZigZagLong())
assertEquals(Long.MAX_VALUE, reader.readZigZagLong())
}
private fun string(utf8Length: Int, value: String) {
val bytes = utf8toBytes(value)
assertEquals(utf8Length, bytes.size)
assertEquals(value, utf8toString(bytes))
}
@Test
fun string() {
string(2, "><")
string(3, ">\u0000<")
string(3, ">\u0001<")
string(3, ">\u0012<")
string(3, ">\u007F<")
string(4, ">\u0080<")
string(4, ">\u0234<")
string(4, ">\u07FF<")
string(5, ">\u0800<")
string(5, ">\u4321<")
string(5, ">\uFFFF<")
}
}
| bsd-3-clause | 1787d4dbefe89cbd4094867513db1277 | 39.869231 | 76 | 0.647751 | 4.008299 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/auth/EditProfileFragment.kt | 1 | 17671 | package org.fossasia.openevent.general.auth
import android.Manifest
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import org.fossasia.openevent.general.utils.ImageUtils.decodeBitmap
import android.os.Bundle
import android.provider.MediaStore
import android.util.Base64
import android.util.Patterns
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.material.textfield.TextInputEditText
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_edit_profile.view.updateButton
import kotlinx.android.synthetic.main.fragment_edit_profile.view.toolbar
import kotlinx.android.synthetic.main.fragment_edit_profile.view.firstName
import kotlinx.android.synthetic.main.fragment_edit_profile.view.details
import kotlinx.android.synthetic.main.fragment_edit_profile.view.facebook
import kotlinx.android.synthetic.main.fragment_edit_profile.view.twitter
import kotlinx.android.synthetic.main.fragment_edit_profile.view.instagram
import kotlinx.android.synthetic.main.fragment_edit_profile.view.phone
import com.squareup.picasso.MemoryPolicy
import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.editImage
import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.takeImage
import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.replaceImage
import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.removeImage
import kotlinx.android.synthetic.main.fragment_edit_profile.view.lastName
import kotlinx.android.synthetic.main.fragment_edit_profile.view.profilePhoto
import kotlinx.android.synthetic.main.fragment_edit_profile.view.progressBar
import kotlinx.android.synthetic.main.fragment_edit_profile.view.profilePhotoFab
import kotlinx.android.synthetic.main.fragment_edit_profile.view.firstNameLayout
import kotlinx.android.synthetic.main.fragment_edit_profile.view.lastNameLayout
import org.fossasia.openevent.general.CircleTransform
import org.fossasia.openevent.general.MainActivity
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.RotateBitmap
import org.fossasia.openevent.general.ComplexBackPressFragment
import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard
import org.fossasia.openevent.general.utils.Utils.requireDrawable
import org.fossasia.openevent.general.utils.extensions.nonNull
import org.fossasia.openevent.general.utils.nullToEmpty
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.FileNotFoundException
import org.fossasia.openevent.general.utils.Utils.setToolbar
import org.fossasia.openevent.general.utils.emptyToNull
import org.fossasia.openevent.general.utils.setRequired
import org.jetbrains.anko.design.snackbar
class EditProfileFragment : Fragment(), ComplexBackPressFragment {
private val profileViewModel by viewModel<ProfileViewModel>()
private val editProfileViewModel by viewModel<EditProfileViewModel>()
private val safeArgs: EditProfileFragmentArgs by navArgs()
private lateinit var rootView: View
private var storagePermissionGranted = false
private val PICK_IMAGE_REQUEST = 100
private val READ_STORAGE = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
private val READ_STORAGE_REQUEST_CODE = 1
private var cameraPermissionGranted = false
private val TAKE_IMAGE_REQUEST = 101
private val CAMERA_REQUEST = arrayOf(Manifest.permission.CAMERA)
private val CAMERA_REQUEST_CODE = 2
private lateinit var userFirstName: String
private lateinit var userLastName: String
private lateinit var userDetails: String
private lateinit var userAvatar: String
private lateinit var userPhone: String
private lateinit var userFacebook: String
private lateinit var userTwitter: String
private lateinit var userInstagram: String
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
rootView = inflater.inflate(R.layout.fragment_edit_profile, container, false)
setToolbar(activity, show = false)
rootView.toolbar.setNavigationOnClickListener {
handleBackPress()
}
profileViewModel.user
.nonNull()
.observe(viewLifecycleOwner, Observer {
loadUserUI(it)
})
val currentUser = editProfileViewModel.user.value
if (currentUser == null) profileViewModel.getProfile() else loadUserUI(currentUser)
editProfileViewModel.progress
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.progressBar.isVisible = it
})
editProfileViewModel.getUpdatedTempFile()
.nonNull()
.observe(viewLifecycleOwner, Observer { file ->
// prevent picasso from storing tempAvatar cache,
// if user select another image picasso will display tempAvatar instead of its own cache
Picasso.get()
.load(file)
.placeholder(requireDrawable(requireContext(), R.drawable.ic_person_black))
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.transform(CircleTransform())
.into(rootView.profilePhoto)
})
storagePermissionGranted = (ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
cameraPermissionGranted = (ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
rootView.updateButton.setOnClickListener {
hideSoftKeyboard(context, rootView)
if (isValidInput()) {
updateUser()
} else {
rootView.snackbar(getString(R.string.fill_required_fields_message))
}
}
editProfileViewModel.message
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.snackbar(it)
if (it == getString(R.string.user_update_success_message)) {
val thisActivity = activity
if (thisActivity is MainActivity) thisActivity.onSuperBackPressed()
}
})
rootView.profilePhotoFab.setOnClickListener {
showEditPhotoDialog()
}
rootView.firstNameLayout.setRequired()
rootView.lastNameLayout.setRequired()
return rootView
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intentData: Intent?) {
super.onActivityResult(requestCode, resultCode, intentData)
if (resultCode != Activity.RESULT_OK) return
if (requestCode == PICK_IMAGE_REQUEST && intentData?.data != null) {
val imageUri = intentData.data ?: return
try {
val selectedImage = RotateBitmap().handleSamplingAndRotationBitmap(requireContext(), imageUri)
editProfileViewModel.encodedImage = selectedImage?.let { encodeImage(it) }
editProfileViewModel.avatarUpdated = true
} catch (e: FileNotFoundException) {
Timber.d(e, "File Not Found Exception")
}
} else if (requestCode == TAKE_IMAGE_REQUEST) {
val imageBitmap = intentData?.extras?.get("data")
if (imageBitmap is Bitmap) {
editProfileViewModel.encodedImage = imageBitmap.let { encodeImage(it) }
editProfileViewModel.avatarUpdated = true
}
}
}
private fun isValidInput(): Boolean {
var valid = true
if (rootView.firstName.text.isNullOrBlank()) {
rootView.firstName.error = getString(R.string.empty_field_error_message)
valid = false
}
if (rootView.lastName.text.isNullOrBlank()) {
rootView.lastName.error = getString(R.string.empty_field_error_message)
valid = false
}
if (!rootView.instagram.text.isNullOrEmpty() && !Patterns.WEB_URL.matcher(rootView.instagram.text).matches()) {
rootView.instagram.error = getString(R.string.invalid_url_message)
valid = false
}
if (!rootView.facebook.text.isNullOrEmpty() && !Patterns.WEB_URL.matcher(rootView.facebook.text).matches()) {
rootView.facebook.error = getString(R.string.invalid_url_message)
valid = false
}
if (!rootView.twitter.text.isNullOrEmpty() && !Patterns.WEB_URL.matcher(rootView.twitter.text).matches()) {
rootView.twitter.error = getString(R.string.invalid_url_message)
valid = false
}
return valid
}
private fun loadUserUI(user: User) {
userFirstName = user.firstName.nullToEmpty()
userLastName = user.lastName.nullToEmpty()
userDetails = user.details.nullToEmpty()
userAvatar = user.avatarUrl.nullToEmpty()
userPhone = user.contact.nullToEmpty()
userFacebook = user.facebookUrl.nullToEmpty()
userTwitter = user.twitterUrl.nullToEmpty()
userInstagram = user.instagramUrl.nullToEmpty()
if (safeArgs.croppedImage.isEmpty()) {
if (userAvatar.isNotEmpty() && !editProfileViewModel.avatarUpdated) {
val drawable = requireDrawable(requireContext(), R.drawable.ic_account_circle_grey)
Picasso.get()
.load(userAvatar)
.placeholder(drawable)
.transform(CircleTransform())
.into(rootView.profilePhoto)
}
} else {
val croppedImage = decodeBitmap(safeArgs.croppedImage)
editProfileViewModel.encodedImage = encodeImage(croppedImage)
editProfileViewModel.avatarUpdated = true
}
setTextIfNull(rootView.firstName, userFirstName)
setTextIfNull(rootView.lastName, userLastName)
setTextIfNull(rootView.details, userDetails)
setTextIfNull(rootView.phone, userPhone)
setTextIfNull(rootView.facebook, userFacebook)
setTextIfNull(rootView.twitter, userTwitter)
setTextIfNull(rootView.instagram, userInstagram)
}
private fun setTextIfNull(input: TextInputEditText, text: String) {
if (input.text.isNullOrBlank()) input.setText(text)
}
private fun showEditPhotoDialog() {
val editImageView = layoutInflater.inflate(R.layout.dialog_edit_profile_image, null)
val dialog = AlertDialog.Builder(requireContext())
.setView(editImageView)
.create()
editImageView.editImage.setOnClickListener {
if (!userAvatar.isNullOrEmpty()) {
if (this::userAvatar.isInitialized) {
findNavController(rootView).navigate(
EditProfileFragmentDirections.actionEditProfileToCropImage(userAvatar))
} else {
rootView.snackbar(getString(R.string.error_editting_image_message))
}
} else {
rootView.snackbar(getString(R.string.image_not_found))
}
dialog.cancel()
}
editImageView.removeImage.setOnClickListener {
dialog.cancel()
clearAvatar()
}
editImageView.takeImage.setOnClickListener {
dialog.cancel()
if (cameraPermissionGranted) {
takeImage()
} else {
requestPermissions(CAMERA_REQUEST, CAMERA_REQUEST_CODE)
}
}
editImageView.replaceImage.setOnClickListener {
dialog.cancel()
if (storagePermissionGranted) {
showFileChooser()
} else {
requestPermissions(READ_STORAGE, READ_STORAGE_REQUEST_CODE)
}
}
dialog.show()
}
private fun clearAvatar() {
val drawable = requireDrawable(requireContext(), R.drawable.ic_account_circle_grey)
Picasso.get()
.load(R.drawable.ic_account_circle_grey)
.placeholder(drawable)
.transform(CircleTransform())
.into(rootView.profilePhoto)
editProfileViewModel.encodedImage = encodeImage(drawable.toBitmap(120, 120))
editProfileViewModel.avatarUpdated = true
}
private fun encodeImage(bitmap: Bitmap): String {
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val bytes = baos.toByteArray()
// create temp file
try {
val tempAvatar = File(context?.cacheDir, "tempAvatar")
if (tempAvatar.exists()) {
tempAvatar.delete()
}
val fos = FileOutputStream(tempAvatar)
fos.write(bytes)
fos.flush()
fos.close()
editProfileViewModel.setUpdatedTempFile(tempAvatar)
} catch (e: IOException) {
e.printStackTrace()
}
return "data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT)
}
private fun takeImage() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, TAKE_IMAGE_REQUEST)
}
private fun showFileChooser() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)), PICK_IMAGE_REQUEST)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == READ_STORAGE_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
storagePermissionGranted = true
rootView.snackbar(getString(R.string.permission_granted_message, getString(R.string.external_storage)))
showFileChooser()
} else {
rootView.snackbar(getString(R.string.permission_denied_message, getString(R.string.external_storage)))
}
} else if (requestCode == CAMERA_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
cameraPermissionGranted = true
rootView.snackbar(getString(R.string.permission_granted_message, getString(R.string.camera)))
takeImage()
} else {
rootView.snackbar(getString(R.string.permission_denied_message, getString(R.string.camera)))
}
}
}
/**
* Handles back press when up button or back button is pressed
*/
override fun handleBackPress() {
val thisActivity = activity
if (noDataChanged()) {
findNavController(rootView).popBackStack()
} else {
hideSoftKeyboard(context, rootView)
val dialog = AlertDialog.Builder(requireContext())
dialog.setMessage(getString(R.string.changes_not_saved))
dialog.setNegativeButton(getString(R.string.discard)) { _, _ ->
if (thisActivity is MainActivity) thisActivity.onSuperBackPressed()
}
dialog.setPositiveButton(getString(R.string.save)) { _, _ ->
if (isValidInput()) {
updateUser()
} else {
rootView.snackbar(getString(R.string.fill_required_fields_message))
} }
dialog.create().show()
}
}
private fun updateUser() {
val newUser = User(
id = editProfileViewModel.getId(),
firstName = rootView.firstName.text.toString(),
lastName = rootView.lastName.text.toString(),
details = rootView.details.text.toString(),
facebookUrl = rootView.facebook.text.toString().emptyToNull(),
twitterUrl = rootView.twitter.text.toString().emptyToNull(),
contact = rootView.phone.text.toString().emptyToNull()
)
editProfileViewModel.updateProfile(newUser)
}
private fun noDataChanged() = !editProfileViewModel.avatarUpdated &&
rootView.lastName.text.toString() == userLastName &&
rootView.firstName.text.toString() == userFirstName &&
rootView.details.text.toString() == userDetails &&
rootView.facebook.text.toString() == userFacebook &&
rootView.twitter.text.toString() == userTwitter &&
rootView.instagram.text.toString() == userInstagram &&
rootView.phone.text.toString() == userPhone
override fun onDestroyView() {
val activity = activity as? AppCompatActivity
activity?.supportActionBar?.setDisplayHomeAsUpEnabled(false)
setHasOptionsMenu(false)
super.onDestroyView()
}
}
| apache-2.0 | c18c63dfeceeed9b1aa560be2b3aaca1 | 40.775414 | 119 | 0.667478 | 4.919543 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/NotificationBroadcastReceiver.kt | 1 | 3056 | package com.orgzly.android
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import com.orgzly.BuildConfig
import com.orgzly.android.data.logs.AppLogsRepository
import com.orgzly.android.reminders.RemindersScheduler
import com.orgzly.android.ui.notifications.Notifications
import com.orgzly.android.ui.util.getNotificationManager
import com.orgzly.android.usecase.NoteUpdateStateDone
import com.orgzly.android.usecase.UseCaseRunner.run
import com.orgzly.android.util.LogUtils.d
import com.orgzly.android.util.async
import javax.inject.Inject
class NotificationBroadcastReceiver : BroadcastReceiver() {
@Inject
lateinit var remindersScheduler: RemindersScheduler
override fun onReceive(context: Context, intent: Intent) {
App.appComponent.inject(this)
if (BuildConfig.LOG_DEBUG) d(TAG, intent, intent.extras)
async {
dismissNotification(context, intent)
when (intent.action) {
AppIntent.ACTION_NOTE_MARK_AS_DONE -> {
val noteId = intent.getLongExtra(AppIntent.EXTRA_NOTE_ID, 0)
run(NoteUpdateStateDone(noteId))
}
AppIntent.ACTION_REMINDER_SNOOZE_REQUESTED -> {
val noteId = intent.getLongExtra(AppIntent.EXTRA_NOTE_ID, 0)
val noteTimeType = intent.getIntExtra(AppIntent.EXTRA_NOTE_TIME_TYPE, 0)
val timestamp = intent.getLongExtra(AppIntent.EXTRA_SNOOZE_TIMESTAMP, 0)
// Pass true as hasTime to use the alarm clock
remindersScheduler.scheduleSnoozeEnd(noteId, noteTimeType, timestamp, true)
}
}
}
}
/**
* If notification ID was passed as an extra,
* it means this action was performed from the notification.
* Cancel the notification here.
*/
private fun dismissNotification(context: Context, intent: Intent) {
val tag = intent.getStringExtra(AppIntent.EXTRA_NOTIFICATION_TAG)
val id = intent.getIntExtra(AppIntent.EXTRA_NOTIFICATION_ID, 0)
if (id > 0) {
context.getNotificationManager().let {
it.cancel(tag, id)
cancelRemindersSummary(it)
}
}
}
private fun cancelRemindersSummary(notificationManager: NotificationManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val notifications = notificationManager.activeNotifications
var reminders = 0
for (notification in notifications) {
if (notification.id == Notifications.REMINDER_ID) {
reminders++
}
}
if (reminders == 0) {
notificationManager.cancel(Notifications.REMINDERS_SUMMARY_ID)
}
}
}
companion object {
val TAG: String = NotificationBroadcastReceiver::class.java.name
}
} | gpl-3.0 | 307c3d8729c33e24ca0c74cf9381c852 | 34.964706 | 95 | 0.649869 | 4.789969 | false | false | false | false |
yousuf-haque/Titan | app/src/main/kotlin/com/yohaq/titan/ui/mainScreen/MainActivity.kt | 1 | 2314 | package com.yohaq.titan.ui.mainScreen
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.roughike.bottombar.BottomBar
import com.roughike.bottombar.OnMenuTabClickListener
import com.yohaq.titan.R
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.view_exercises.view.*
class MainActivity : AppCompatActivity() {
companion object {
fun createIntent(context: Context) =
Intent(context, MainActivity::class.java)
}
private var bottomBar: BottomBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initBottomBar(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
bottomBar?.onSaveInstanceState(outState)
}
private fun initBottomBar(savedInstanceState: Bundle?) {
bottomBar = BottomBar.attach(this, savedInstanceState)
bottomBar!!.setItems(R.menu.bottom_bar_menu)
bottomBar!!.setOnMenuTabClickListener(object : OnMenuTabClickListener {
override fun onMenuTabReSelected(menuItemId: Int) {
handleTabNavigation(menuItemId)
}
override fun onMenuTabSelected(menuItemId: Int) {
handleTabNavigation(menuItemId)
}
})
}
private fun handleTabNavigation(menuItemId: Int) {
when (menuItemId) {
R.id.history_nav_button -> {
with(supportFragmentManager.beginTransaction()) {
show(supportFragmentManager.findFragmentById(R.id.workout_list_fragment))
commit()
}
content.exercise_list_container.visibility = View.GONE
}
R.id.exercise_nav_button -> {
content.exercise_list_container.visibility = View.VISIBLE
with(supportFragmentManager.beginTransaction()) {
hide(supportFragmentManager.findFragmentById(R.id.workout_list_fragment))
commit()
}
}
}
}
}
| apache-2.0 | 3d452e77bc98adf312862ccbb5f4efb3 | 29.853333 | 93 | 0.651253 | 4.99784 | false | false | false | false |
like5188/Common | common/src/main/java/com/like/common/util/BindingUtils.kt | 1 | 4402 | package com.like.common.util
import android.databinding.BindingAdapter
import android.widget.TextView
import com.like.common.view.chart.pieChartView.entity.MonthData
import com.like.common.view.chart.pieChartView.entity.PieData
object BindingUtils {
// 显示年份文本
@BindingAdapter("pieChartViewShowYear")
@JvmStatic
fun pieChartViewShowYear(tv: TextView, data: PieData?) {
try {
tv.text = if (data != null && data.year > 0) {
data.year.toString()
} else {
""
}
} catch (e: Exception) {
e.printStackTrace()
}
}
// 显示季度文本
@BindingAdapter("pieChartViewShowQuarter")
@JvmStatic
fun pieChartViewShowQuarter(tv: TextView, data: PieData?) {
try {
tv.text = when (data?.quarter) {
1 -> "一季度"
2 -> "二季度"
3 -> "三季度"
4 -> "四季度"
else -> ""
}
} catch (e: Exception) {
e.printStackTrace()
}
}
// 显示月份文本
@BindingAdapter("pieChartViewShowMonth0")
@JvmStatic
fun pieChartViewShowMonth0(tv: TextView, data: PieData?) {
pieChartViewShowMonth(tv, data?.monthDataList?.get(0))
}
// 显示月份文本
@BindingAdapter("pieChartViewShowMonth1")
@JvmStatic
fun pieChartViewShowMonth1(tv: TextView, data: PieData?) {
pieChartViewShowMonth(tv, data?.monthDataList?.get(1))
}
// 显示月份文本
@BindingAdapter("pieChartViewShowMonth2")
@JvmStatic
fun pieChartViewShowMonth2(tv: TextView, data: PieData?) {
pieChartViewShowMonth(tv, data?.monthDataList?.get(2))
}
fun pieChartViewShowMonth(tv: TextView, monthData: MonthData?) {
try {
tv.text = if (monthData != null) {
"${monthData.month}月"
} else {
""
}
} catch (e: Exception) {
e.printStackTrace()
}
}
// 显示年份占比标签文本
@BindingAdapter("pieChartViewShowMonthRatioText0")
@JvmStatic
fun pieChartViewShowMonthRatioText0(tv: TextView, data: PieData?) {
pieChartViewShowMonthRatioText(tv, data?.monthDataList?.get(0))
}
// 显示年份占比标签文本
@BindingAdapter("pieChartViewShowMonthRatioText1")
@JvmStatic
fun pieChartViewShowMonthRatioText1(tv: TextView, data: PieData?) {
pieChartViewShowMonthRatioText(tv, data?.monthDataList?.get(1))
}
// 显示年份占比标签文本
@BindingAdapter("pieChartViewShowMonthRatioText2")
@JvmStatic
fun pieChartViewShowMonthRatioText2(tv: TextView, data: PieData?) {
pieChartViewShowMonthRatioText(tv, data?.monthDataList?.get(2))
}
fun pieChartViewShowMonthRatioText(tv: TextView, monthData: MonthData?) {
try {
tv.text = if (monthData != null) {
"${monthData.month}月占比"
} else {
""
}
} catch (e: Exception) {
e.printStackTrace()
}
}
// 显示年份占比文本
@BindingAdapter("pieChartViewShowMonthRatio0")
@JvmStatic
fun pieChartViewShowMonthRatio0(tv: TextView, data: PieData?) {
pieChartViewShowMonthRatio(tv, data?.monthDataList, 0)
}
// 显示年份占比文本
@BindingAdapter("pieChartViewShowMonthRatio1")
@JvmStatic
fun pieChartViewShowMonthRatio1(tv: TextView, data: PieData?) {
pieChartViewShowMonthRatio(tv, data?.monthDataList, 1)
}
// 显示年份占比文本
@BindingAdapter("pieChartViewShowMonthRatio2")
@JvmStatic
fun pieChartViewShowMonthRatio2(tv: TextView, data: PieData?) {
pieChartViewShowMonthRatio(tv, data?.monthDataList, 2)
}
fun pieChartViewShowMonthRatio(tv: TextView, monthDataList: List<MonthData>?, index: Int) {
try {
tv.text = if (monthDataList != null) {
val totalElectricity = monthDataList.sumByDouble { it.data1.toDouble() }.toFloat()
"${MoneyFormatUtils.formatTwoDecimals((monthDataList[index].data1 / totalElectricity).toDouble() * 100)}%"
} else {
""
}
} catch (e: Exception) {
e.printStackTrace()
}
}
} | apache-2.0 | 0ac213bb74cff8188ff13da762fefd6c | 28.808511 | 122 | 0.597811 | 3.964151 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/external/service/ApiExternalServiceAction.kt | 1 | 2483 | package org.evomaster.core.problem.external.service
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.external.service.param.ResponseParam
import org.evomaster.core.search.Action
abstract class ApiExternalServiceAction(
/**
* response to return if the external service is accessed
*
* To Andrea,
* a type of external service might contain a certain type of response
* eg, HTTP response
* Do we need to make the response as a generic type T where T extends ResponseParam
* and bind the ApiExternalServiceAction with the T?
*/
response: ResponseParam,
active : Boolean = false,
used : Boolean = false
) : Action(listOf(response)){
val responses : List<ResponseParam>
get() { return children.filterIsInstance<ResponseParam>()}
val response : ResponseParam
get() {
val responses = children.filterIsInstance<ResponseParam>()
if (responses.isEmpty())
throw IllegalStateException("there does not exist any responses")
if (responses.size > 1)
throw IllegalStateException("it should only have one response, but there exist $responses responses")
return responses.first()
}
/**
* it represents whether the external service is instanced before executing the corresponding API call
*
* Note that it should be always re-assigned based on [used] before fitness evaluation, see [resetActive]
*/
var active : Boolean = active
private set
/**
* it represents whether the external service is used when executing the corresponding API call
*
* Note that it should be updated after the fitness evaluation based on whether the external service is used during the API execution
*/
var used : Boolean = used
private set
/**
* reset active based on [used]
* it should be used before fitness evaluation
*/
fun resetActive() {
this.active = this.used
}
/**
* based on the feedback from the mocked service,
* the external service is confirmed that it is used during the API execution
*/
fun confirmUsed() {
this.used = true
}
/**
* based on the feedback from the mocked service,
* the external service is confirmed that it is not used during the API execution
*/
fun confirmNotUsed() {
this.used = false
}
} | lgpl-3.0 | 51d4e04595c4c40bcf2693ecd5756bc1 | 30.443038 | 137 | 0.662102 | 4.907115 | false | false | false | false |
TheContext/podcast-ci | src/main/kotlin/io/thecontext/podcaster/validation/PodcastValidator.kt | 1 | 2366 | package io.thecontext.podcaster.validation
import io.reactivex.Single
import io.thecontext.podcaster.value.Person
import io.thecontext.podcaster.value.Podcast
import java.util.*
class PodcastValidator(
private val urlValidator: Validator<String>,
private val people: List<Person>
) : Validator<Podcast> {
companion object {
const val MAXIMUM_DESCRIPTION_LENGTH = 1000
}
override fun validate(value: Podcast): Single<ValidationResult> {
val urlResults = listOfNotNull(value.url, value.artworkUrl, value.migrationFeedUrl)
.map {
urlValidator.validate(it)
}
val peopleResults = emptyList<String>()
.plus(value.people.ownerId)
.plus(value.people.authorIds)
.map { personId ->
Single.fromCallable {
if (people.find { it.id == personId } == null) {
ValidationResult.Failure("Podcast person [$personId] is not defined.")
} else {
ValidationResult.Success
}
}
}
val ownerResults = Single.fromCallable {
if (people.find { it.id == value.people.ownerId }?.email == null) {
ValidationResult.Failure("Podcast owner should have an email address.")
} else {
ValidationResult.Success
}
}
val descriptionResult = Single.fromCallable {
if (value.description.length > MAXIMUM_DESCRIPTION_LENGTH) {
ValidationResult.Failure("Podcast description length is [${value.description.length}] symbols but should less than [$MAXIMUM_DESCRIPTION_LENGTH].")
} else {
ValidationResult.Success
}
}
val languageResult = Single.fromCallable {
if (!Locale.getISOLanguages().contains(value.language)) {
ValidationResult.Failure("Podcast language should be ISO 639 code.")
} else {
ValidationResult.Success
}
}
return Single
.merge(urlResults + peopleResults + ownerResults + descriptionResult + languageResult)
.toList()
.map { it.merge() }
}
}
| apache-2.0 | 0b495dd142fd031fefce5ee091e024b3 | 35.4 | 163 | 0.559172 | 5.389522 | false | false | false | false |
dmitryustimov/weather-kotlin | app/src/main/java/ru/ustimov/weather/content/impl/external/DefaultExternalDatasource.kt | 1 | 2915 | package ru.ustimov.weather.content.impl.external
import android.content.Context
import android.text.TextUtils
import io.reactivex.Single
import ru.ustimov.weather.R
import ru.ustimov.weather.content.ExternalDatasource
import ru.ustimov.weather.content.Schedulers
import ru.ustimov.weather.content.data.Country
import ru.ustimov.weather.content.data.CurrentWeather
import ru.ustimov.weather.util.Logger
import ru.ustimov.weather.util.println
class DefaultExternalDatasource(
context: Context,
private val schedulers: Schedulers,
private val logger: Logger
) : ExternalDatasource {
private companion object {
private val TAG = "DefaultExternalDatasource"
}
private val openWeatherMapApi: OpenWeatherMapApi
private val restCountriesApi: RestCountriesApi
init {
val openWeatherMapBaseUrl = context.getString(R.string.org_openweathermap_base_url)
val openWeatherMapAppId = context.getString(R.string.org_openweathermap_app_id)
val openWeatherMapInterceptor = RetrofitFactory.createOpenWeatherMapInterceptor(openWeatherMapAppId)
val openWeatherMapLoggingInterceptor = RetrofitFactory.createLoggingInterceptor(logger, "OpenWeatherMap")
val openWeatherMapInterceptors = arrayOf(openWeatherMapInterceptor, openWeatherMapLoggingInterceptor)
openWeatherMapApi = RetrofitFactory
.build(openWeatherMapBaseUrl, openWeatherMapInterceptors)
.create(OpenWeatherMapApi::class.java)
val restCountriesBaseUrl = context.getString(R.string.eu_restcountries_base_url)
val restCountriesInterceptor = RetrofitFactory.createRestCountriesInterceptor()
val restCountriesLoggingInterceptor = RetrofitFactory.createLoggingInterceptor(logger, "RestCountries")
val restCountriesInterceptors = arrayOf(restCountriesInterceptor, restCountriesLoggingInterceptor)
restCountriesApi = RetrofitFactory
.build(restCountriesBaseUrl, restCountriesInterceptors)
.create(RestCountriesApi::class.java)
}
override fun findCities(query: String): Single<out List<CurrentWeather>> =
openWeatherMapApi.find(query)
.doOnSuccess({ logger.d(TAG, "Loaded $it") })
.doOnError({ it.println(logger) })
.onErrorResumeNext({ RetrofitExceptionFactory.single(it) })
.flatMap({ Single.just(it.list) })
.subscribeOn(schedulers.network())
override fun getCountries(codes: List<String>): Single<out List<Country>> =
restCountriesApi.getCountries(TextUtils.join(";", codes))
.doOnSuccess({ logger.d(TAG, "Loaded $it") })
.doOnError({ it.println(logger) })
.onErrorResumeNext({ RetrofitExceptionFactory.single(it) })
.subscribeOn(schedulers.network())
} | apache-2.0 | 14bc5bfd08d3b962c190d82cab5bb659 | 46.803279 | 113 | 0.71458 | 4.974403 | false | false | false | false |
tonyofrancis/Fetch | fetch2/src/main/java/com/tonyodev/fetch2/fetch/ListenerCoordinator.kt | 1 | 34516 | package com.tonyodev.fetch2.fetch
import android.os.Handler
import android.os.HandlerThread
import com.tonyodev.fetch2.*
import com.tonyodev.fetch2.provider.DownloadProvider
import com.tonyodev.fetch2.provider.GroupInfoProvider
import com.tonyodev.fetch2core.DownloadBlock
import com.tonyodev.fetch2core.FetchObserver
import com.tonyodev.fetch2core.Reason
import java.lang.ref.WeakReference
class ListenerCoordinator(val namespace: String,
private val groupInfoProvider: GroupInfoProvider,
private val downloadProvider: DownloadProvider,
private val uiHandler: Handler) {
private val lock = Any()
private val fetchListenerMap = mutableMapOf<Int, MutableSet<WeakReference<FetchListener>>>()
private val fetchGroupListenerMap = mutableMapOf<Int, MutableSet<WeakReference<FetchGroupListener>>>()
private val fetchNotificationManagerList = mutableListOf<FetchNotificationManager>()
private val fetchNotificationHandler = {
val handlerThread = HandlerThread("FetchNotificationsIO")
handlerThread.start()
Handler(handlerThread.looper)
}()
private val downloadsObserverMap = mutableMapOf<Int, MutableList<WeakReference<FetchObserver<Download>>>>()
fun addListener(id: Int, fetchListener: FetchListener) {
synchronized(lock) {
val set = fetchListenerMap[id] ?: mutableSetOf()
set.add(WeakReference(fetchListener))
fetchListenerMap[id] = set
if (fetchListener is FetchGroupListener) {
val groupSet = fetchGroupListenerMap[id] ?: mutableSetOf()
groupSet.add(WeakReference(fetchListener))
fetchGroupListenerMap[id] = groupSet
}
}
}
fun removeListener(id: Int, fetchListener: FetchListener) {
synchronized(lock) {
val iterator = fetchListenerMap[id]?.iterator()
if (iterator != null) {
while (iterator.hasNext()) {
val reference = iterator.next()
if (reference.get() == fetchListener) {
iterator.remove()
break
}
}
}
if (fetchListener is FetchGroupListener) {
val groupIterator = fetchGroupListenerMap[id]?.iterator()
if (groupIterator != null) {
while (groupIterator.hasNext()) {
val reference = groupIterator.next()
if (reference.get() == fetchListener) {
groupIterator.remove()
break
}
}
}
}
}
}
fun addNotificationManager(fetchNotificationManager: FetchNotificationManager) {
synchronized(lock) {
if (!fetchNotificationManagerList.contains(fetchNotificationManager)) {
fetchNotificationManagerList.add(fetchNotificationManager)
}
}
}
fun removeNotificationManager(fetchNotificationManager: FetchNotificationManager) {
synchronized(lock) {
fetchNotificationManagerList.remove(fetchNotificationManager)
}
}
fun cancelOnGoingNotifications(fetchNotificationManager: FetchNotificationManager) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
fetchNotificationManager.cancelOngoingNotifications()
}
}
}
}
val mainListener: FetchListener = object : FetchListener {
override fun onAdded(download: Download) {
synchronized(lock) {
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onAdded(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_ADDED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onAdded(groupId, download, fetchGroup)
}
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_ADDED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_ADDED)
}
}
}
}
}
override fun onQueued(download: Download, waitingOnNetwork: Boolean) {
synchronized(lock) {
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onQueued(download, waitingOnNetwork)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_QUEUED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onQueued(groupId, download, waitingOnNetwork, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_QUEUED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_QUEUED)
}
}
}
}
}
override fun onWaitingNetwork(download: Download) {
synchronized(lock) {
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onWaitingNetwork(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_WAITING_ON_NETWORK)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onWaitingNetwork(groupId, download, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_WAITING_ON_NETWORK)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_WAITING_ON_NETWORK)
}
}
}
}
}
override fun onCompleted(download: Download) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onCompleted(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_COMPLETED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onCompleted(groupId, download, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_COMPLETED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_COMPLETED)
}
}
}
}
}
override fun onError(download: Download, error: Error, throwable: Throwable?) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onError(download, error, throwable)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_ERROR)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onError(groupId, download, error, throwable, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_ERROR)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_ERROR)
}
}
}
}
}
override fun onDownloadBlockUpdated(download: Download, downloadBlock: DownloadBlock, totalBlocks: Int) {
synchronized(lock) {
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onDownloadBlockUpdated(download, downloadBlock, totalBlocks)
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_BLOCK_UPDATED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onDownloadBlockUpdated(groupId, download, downloadBlock, totalBlocks, fetchGroup)
}
}
}
}
}
}
override fun onStarted(download: Download, downloadBlocks: List<DownloadBlock>, totalBlocks: Int) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onStarted(download, downloadBlocks, totalBlocks)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_STARTED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onStarted(groupId, download, downloadBlocks, totalBlocks, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_STARTED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_STARTED)
}
}
}
}
}
override fun onProgress(download: Download, etaInMilliSeconds: Long, downloadedBytesPerSecond: Long) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onProgress(download, etaInMilliSeconds, downloadedBytesPerSecond)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_PROGRESS_CHANGED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onProgress(groupId, download, etaInMilliSeconds, downloadedBytesPerSecond, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_PROGRESS_CHANGED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_PROGRESS_CHANGED)
}
}
}
}
}
override fun onPaused(download: Download) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onPaused(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_PAUSED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onPaused(groupId, download, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_PAUSED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_PAUSED)
}
}
}
}
}
override fun onResumed(download: Download) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onResumed(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_RESUMED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onResumed(groupId, download, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_RESUMED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_RESUMED)
}
}
}
}
}
override fun onCancelled(download: Download) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onCancelled(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_CANCELLED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onCancelled(groupId, download, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_CANCELLED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_CANCELLED)
}
}
}
}
}
override fun onRemoved(download: Download) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onRemoved(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_REMOVED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onRemoved(groupId, download, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_REMOVED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_REMOVED)
}
}
}
}
}
override fun onDeleted(download: Download) {
synchronized(lock) {
fetchNotificationHandler.post {
synchronized(lock) {
for (fetchNotificationManager in fetchNotificationManagerList) {
if (fetchNotificationManager.postDownloadUpdate(download)) break
}
}
}
fetchListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
uiHandler.post {
fetchListener.onDeleted(download)
}
}
}
}
if (fetchGroupListenerMap.isNotEmpty()) {
val groupId = download.group
val fetchGroup = groupInfoProvider.getGroupReplace(groupId, download, Reason.DOWNLOAD_DELETED)
fetchGroupListenerMap.values.forEach {
val iterator = it.iterator()
while (iterator.hasNext()) {
val fetchListener = iterator.next().get()
if (fetchListener == null) {
iterator.remove()
} else {
fetchListener.onDeleted(groupId, download, fetchGroup)
}
}
}
} else {
groupInfoProvider.postGroupReplace(download.group, download, Reason.DOWNLOAD_DELETED)
}
val downloadObserverSet = downloadsObserverMap[download.id]
downloadObserverSet?.forEach {
val observer = it.get()
if (observer != null) {
uiHandler.post {
observer.onChanged(download, Reason.DOWNLOAD_DELETED)
}
}
}
}
}
}
fun clearAll() {
synchronized(lock) {
fetchListenerMap.clear()
fetchGroupListenerMap.clear()
fetchNotificationManagerList.clear()
downloadsObserverMap.clear()
}
}
fun addFetchObserversForDownload(downloadId: Int, vararg fetchObservers: FetchObserver<Download>) {
synchronized(lock) {
val newFetchObservers = fetchObservers.distinct()
val set = downloadsObserverMap[downloadId] ?: mutableListOf()
val attachedObservers = set.mapNotNull { it.get() }
val addedObservers = mutableListOf<FetchObserver<Download>>()
for (fetchObserver in newFetchObservers) {
if (!attachedObservers.contains(fetchObserver)) {
set.add(WeakReference(fetchObserver))
addedObservers.add(fetchObserver)
}
}
val download = downloadProvider.getDownload(downloadId)
if (download != null) {
uiHandler.post {
for (addedObserver in addedObservers) {
addedObserver.onChanged(download, Reason.OBSERVER_ATTACHED)
}
}
}
downloadsObserverMap[downloadId] = set
}
}
fun removeFetchObserversForDownload(downloadId: Int, vararg fetchObservers: FetchObserver<Download>) {
synchronized(lock) {
for (fetchObserver in fetchObservers) {
val iterator = downloadsObserverMap[downloadId]?.iterator()
if (iterator != null) {
while (iterator.hasNext()) {
val reference = iterator.next()
if (reference.get() == fetchObserver) {
iterator.remove()
break
}
}
}
}
}
}
} | apache-2.0 | 63551a6c5c922473e709fbdfc746773c | 43.827273 | 132 | 0.448604 | 6.552012 | false | false | false | false |
ColaGom/KtGitCloner | src/main/kotlin/newdata/SourceData.kt | 1 | 1564 | package newdata
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.body.MethodDeclaration
import common.Stopwords
import nlp.PreProcessor
import opennlp.tools.cmdline.postag.POSModelLoader
import opennlp.tools.postag.POSTaggerME
import java.io.File
class ProjectDataGenerator(val root:File)
{
fun generate()
{
}
}
class SourceDataGenerator(val source:File)
{
companion object {
val model = POSModelLoader().load(File("nlp/en-pos-maxent.bin"))
val tagger = POSTaggerME(model)
}
fun generate()
{
val parser = JavaParser.parse(source)
parser.findAll(MethodDeclaration::class.java).forEach {
it.nameAsString.preprocessing()
}
parser.comments.forEach {
it.content.lines().forEach {
it.preprocessing()
}
}
}
val regexAnno = Regex("\\{.*?\\}")
fun String.preprocessing() : List<String>
{
var str = PreProcessor.regCamelCase.replace(this," ")
str = PreProcessor.regHtml.replace(str, "")
str = regexAnno.replace(str,"")
println(str)
str = com.sun.deploy.util.StringUtils.trimWhitespace(str)
val result = PreProcessor.regNonAlphanum.split(str.toLowerCase()).filter { !Stopwords.instance.contains(it) && it.length > 2 && it.length < 15 }
println("$this -> $result")
return result
}
}
data class ProjectData(val root:String, val sourceList:List<SourceData>)
data class SourceData(val path:String, val pairs:List<String>)
| apache-2.0 | 92618be6cea9759dda5175f96fab7538 | 25.066667 | 152 | 0.654731 | 4 | false | false | false | false |
ColaGom/KtGitCloner | src/main/kotlin/Main.kt | 1 | 61290 | import com.github.javaparser.JavaParser
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import common.*
import data.ProjectModel
import data.Repository
import data.SourceFile
import git.Cloner
import git.CommitExtractor
import javafx.beans.binding.StringBinding
import ml.Cluster
import ml.Kmeans
import ml.Node
import net.ProjectExtractor
import newdata.CountMap
import newdata.Project
import newdata.SourceAnalyst
import newdata.SourceDataGenerator
import nlp.PreProcessor
import opennlp.tools.cmdline.postag.POSModelLoader
import opennlp.tools.postag.POSTaggerME
import org.knowm.xchart.BitmapEncoder
import org.knowm.xchart.SwingWrapper
import org.knowm.xchart.XYChartBuilder
import org.knowm.xchart.style.Styler
import org.tartarus.snowball.ext.englishStemmer
import vop.DataManager
import vop.toPairList
import java.io.File
import java.nio.file.Paths
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class Main
{
companion object {
lateinit var DF_MAP : HashMap<String, Int>
lateinit var FILTER_WORD : HashSet<String>
}
}
//소스 파일 bag of words
//count of list, count of set
//count of line
fun File.toSaveFile(): File {
return Paths.get(this.path.replace("Research\\Repository", "Research\\data"), NAME_PROJECT_MODEL).toFile()
}
fun printAllCloneCommand() {
val cloneDir = "E:/Repository";
val map: HashMap<String, Repository> = Gson().fromJson(File(PATH_PROJECT_MAP).readText(), object : TypeToken<HashMap<String, Repository>>() {}.type)
println("total : ${map.size}")
map.values.forEach { target ->
if (target.language != null && target.language.equals("Java") && target.size < 2048000) {
val path = "$cloneDir/${target.full_name}"
if (!File(path).exists()) {
val cmd = "git clone ${target.clone_url} ${path}";
println(cmd)
}
}
}
}
fun loadAllProjectModelFile(name: String): Sequence<File> {
return File(PATH_DATA).walk().filter {
it.name.equals(name)
}
}
fun searchNew(target:String, query:String, saveFile:File, k:Int = 1000)
{
val result: SortedSet<Pair<String, Double>> = sortedSetOf(compareBy { it.second })
val analyst = SourceAnalyst(File(query))
analyst.analysis()
val queryMap = analyst.sourceFile.tfIdfMap()
val startTime = System.currentTimeMillis()
loadAllProjectModelFile(target).forEach {
val project = Project.load(it)
project.sourceList.forEach {
source->
val sourceMap = source.tfIdfMap()
val distance = cosineDistance(queryMap, sourceMap)
if (result.size < k) {
result.add(Pair(source.path, distance))
} else {
val last = result.last()
if (last.second > distance) {
result.remove(last)
result.add(Pair(source.path, distance))
}
}
}
}
println("elapsed : ${System.currentTimeMillis() - startTime}")
saveFile.printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(result))
}
}
fun cosineDistance(v1:HashMap<String, Double>, v2:HashMap<String, Double>) : Double
{
if (v1 != null && v2 != null) {
val both = v1.keys.toHashSet()
both.retainAll(v2.keys.toHashSet())
var sclar = 0.0
var norm1 = 0.0
var norm2 = 0.0
for (k in both)
sclar += v1.get(k)!! * v2.get(k)!!
for (k in v1.keys)
norm1 += v1.get(k)!! * v1.get(k)!!
for (k in v2.keys)
norm2 += v2.get(k)!! * v2.get(k)!!
val result = sclar / Math.sqrt(norm1 * norm2)
return if (result.isNaN()) 1.0 else 1.0 - result
} else
return 1.0
}
fun searchTest(query: File, saveFile: File, idfMap: HashMap<String, Int>, k: Int = 1000) {
val startTime = System.currentTimeMillis()
val target = PreProcessor(query.readText()).toSourceFile(query.path)
val node = Node("query", target.getMergedMap()!!.tfidfDoc(idfMap))
val result: SortedSet<Pair<String, Double>> = sortedSetOf(compareByDescending { it.second })
loadAllProjectModelFile(NAME_PROJECT_MODEL_CLEAN).forEach {
val project = ProjectModel.load(it)
project.sourceList.map { Node(it.path, it.getMergedMap()!!.tfidfDoc(idfMap)) }.forEach {
if (result.size < k) {
result.add(Pair(it.fileName, it.distanceTo(node)))
} else {
val last = result.last()
val distance = it.distanceTo(node)
if (last.second < distance) {
result.remove(last)
result.add(Pair(it.fileName, distance))
}
}
}
}
println("elapsed : ${System.currentTimeMillis() - startTime}")
saveFile.printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(result))
}
}
fun analysis() {
val dfMap: HashMap<String, Long> = Gson().fromJson(File("df_map.json").readText(), object : TypeToken<HashMap<String, Long>>() {}.type)
val pfMap: HashMap<String, Long> = Gson().fromJson(File("pf_map.json").readText(), object : TypeToken<HashMap<String, Long>>() {}.type)
println(dfMap.filter { it.value > 20 }.size)
return
println("${dfMap.size} / ${pfMap.size}")
val fileCountLimit = (4000000 * 0.15).toInt() // 10%
val diff = (4000000 * 0.01).toInt() // 1%
val projectCount = 28000
val thresholdList = diff..fileCountLimit step diff
val countList: MutableList<Int> = mutableListOf()
thresholdList.forEach { limit ->
val size = dfMap.filter { it.value > limit }.size
countList.add(size)
println("$limit : $size")
}
val chart = XYChartBuilder().width(800).height(600).title("Title").xAxisTitle("threshold").yAxisTitle("number of word").theme(Styler.ChartTheme.Matlab).build()
chart.styler.setMarkerSize(5)
chart.styler.setLegendVisible(false)
chart.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart.styler.setChartTitleVisible(false)
chart.addSeries("com", thresholdList.toList(), countList)
SwingWrapper(chart).displayChart()
}
fun analysis1(limit: Int = 0, thr: Int = 0, suffix: String) {
val srcLenList: MutableList<Double> = mutableListOf()
val wordLenList: MutableList<Double> = mutableListOf()
val wordSet: HashMap<String, Int> = hashMapOf()
val srcWordLenList: MutableList<Double> = mutableListOf()
val srcWordSet: HashMap<String, Int> = hashMapOf()
val comWordLenList: MutableList<Double> = mutableListOf()
val comWordSet: HashMap<String, Int> = hashMapOf()
val addSrcLenList: MutableList<Double> = mutableListOf()
val addComLenList: MutableList<Double> = mutableListOf()
var srcLen = 0.0;
var pSrcLen = 0.0;
File(PATH_DATA).walkTopDown().filter {
it.name.equals(NAME_PROJECT_MODEL_CLEAN)
}.forEach {
val project = ProjectModel.load(it)
val projectWordSet: MutableSet<String> = mutableSetOf()
val projectSrcWordSet: MutableSet<String> = mutableSetOf()
val projectComWordSet: MutableSet<String> = mutableSetOf()
projectWordSet.clear()
projectSrcWordSet.clear()
projectComWordSet.clear()
project.sourceList.forEach {
it.wordMap.get(KEY_COMMENT)?.forEach {
if (it.value > thr) {
val key = it.key
if (!projectWordSet.contains(key))
projectWordSet.add(key)
if (!projectComWordSet.contains(key))
projectComWordSet.add(key)
}
}
it.wordMap.get(KEY_SOURCE)?.forEach {
if (it.value > thr) {
val key = it.key
if (!projectWordSet.contains(key))
projectWordSet.add(key)
if (!projectSrcWordSet.contains(key))
projectSrcWordSet.add(key)
}
}
srcLen += it.wordMapSize() / 1000000.0
}
projectComWordSet.forEach {
if (comWordSet.containsKey(it))
comWordSet.set(it, comWordSet.get(it)!! + 1)
else
comWordSet.put(it, 1)
}
projectSrcWordSet.forEach {
if (srcWordSet.containsKey(it))
srcWordSet.set(it, srcWordSet.get(it)!! + 1)
else
srcWordSet.put(it, 1)
}
projectWordSet.forEach {
if (wordSet.containsKey(it))
wordSet.set(it, wordSet.get(it)!! + 1)
else
wordSet.put(it, 1)
}
if (srcLen - pSrcLen >= 100) {
println("add ${srcLen}")
val preSrcLen = if (srcWordLenList.isEmpty()) 0.0 else srcWordLenList.last()
val preComLen = if (comWordLenList.isEmpty()) 0.0 else comWordLenList.last()
pSrcLen = srcLen
srcLenList.add(srcLen)
wordLenList.add(wordSet.filter { it.value >= limit }.size / 1000.0)
srcWordLenList.add(srcWordSet.filter { it.value >= limit }.size / 1000.0)
comWordLenList.add(comWordSet.filter { it.value >= limit }.size / 1000.0)
addSrcLenList.add(srcWordLenList.last() - preSrcLen)
addComLenList.add(comWordLenList.last() - preComLen)
}
}
println("last ${srcLen.toInt()}")
val preSrcLen = srcWordLenList.last()
val preComLen = comWordLenList.last()
pSrcLen = srcLen
srcLenList.add(srcLen)
wordLenList.add(wordSet.filter { it.value >= limit }.size / 1000.0)
srcWordLenList.add(srcWordSet.filter { it.value >= limit }.size / 1000.0)
comWordLenList.add(comWordSet.filter { it.value >= limit }.size / 1000.0)
addSrcLenList.add(srcWordLenList.last() - preSrcLen)
addComLenList.add(comWordLenList.last() - preComLen)
//
val chart = XYChartBuilder().width(800).height(600).title("Title").xAxisTitle("length of words in source code (m)").yAxisTitle("size of wordset (k)").theme(Styler.ChartTheme.Matlab).build()
chart.styler.setMarkerSize(5)
chart.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart.styler.setChartTitleVisible(false)
chart.addSeries("src+com", srcLenList.toDoubleArray(), wordLenList.toDoubleArray())
chart.addSeries("src", srcLenList.toDoubleArray(), srcWordLenList.toDoubleArray())
chart.addSeries("com", srcLenList.toDoubleArray(), comWordLenList.toDoubleArray())
// SwingWrapper(chart).displayChart()
val resultDir = "C:\\Research\\Result"
BitmapEncoder.saveBitmapWithDPI(chart, "$resultDir\\${limit}_${suffix}.png", BitmapEncoder.BitmapFormat.PNG, 200);
File(resultDir, "${limit}_srcWordSet_${suffix}.json").printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(srcWordSet.filter { it.value > limit }.toList().sortedBy { it.second }.reversed()))
}
File(resultDir, "${limit}_comWordSet_${suffix}.json").printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(comWordSet.filter { it.value > limit }.toList().sortedBy { it.second }.reversed()))
}
val chart2 = XYChartBuilder().width(800).height(600).title("Title").xAxisTitle("length of words in source code (m)").yAxisTitle("size of wordset (k)").theme(Styler.ChartTheme.Matlab).build()
chart.styler.setMarkerSize(5)
chart.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart.styler.setChartTitleVisible(false)
chart2.addSeries("add-src", srcLenList.toDoubleArray(), addSrcLenList.toDoubleArray())
chart2.addSeries("add-com", srcLenList.toDoubleArray(), addComLenList.toDoubleArray())
BitmapEncoder.saveBitmapWithDPI(chart2, "$resultDir\\${limit}_${suffix}_add.png", BitmapEncoder.BitmapFormat.PNG, 200);
}
fun cleanSourceFile(source: SourceFile) {
source.wordMap.values.forEach {
val iter = it.iterator()
while (iter.hasNext()) {
val value = iter.next()
val key = value.key
if (key.length <= 2 || key.length >= 20) {
iter.remove()
}
}
}
}
fun printBaseInfo() {
var totalSrcLen: Long = 0
var totalComLen: Long = 0
var totalFileCount: Long = 0
var projectCount = 0
var totalWordCount: Long = 0
loadAllProjectModelFile(NAME_PROJECT_MODEL_CLEAN).forEach {
val project = ProjectModel.load(it);
project.sourceList.forEach {
totalFileCount++
totalComLen += it.comLen
totalSrcLen += it.srcLen
totalWordCount += it.wordMapSize()
}
++projectCount
}
println("src Len : $totalSrcLen / com Len : $totalComLen / fileCount : $totalFileCount / project Count : $projectCount / wordCount : $totalWordCount")
}
fun cleanProject(root: File) {
println("[cleanProject]${root.path}")
root.walkTopDown().filter {
it.isFile && (it.nameWithoutExtension.length == 1 || (it.nameWithoutExtension.toLowerCase().matches(Regex("r|package-info"))) || (!it.path.contains(".git") && !it.extension.equals("java") && !it.extension.equals("md")))
}.forEach {
// println(it.path)
it.delete()
}
}
fun getAllDirectories(root: File): List<File> {
return root.walk().filter { it.isDirectory }.toList()
}
fun getAllFilesExt(root: File, ext: String): List<File> {
return root.walk().filter { it.extension.equals(ext) }.toList()
}
data class Source(val path: String, val imports: MutableList<String> = mutableListOf(), val methodCalls: MutableList<String> = mutableListOf())
data class Project(val projectName: String, val sourceList: MutableList<Source> = mutableListOf())
fun normValue(map: HashMap<String, Int>, idfMap: HashMap<String, Int>): Double {
var norm = 0.0;
map.filter { idfMap.containsKey(it.key) }.forEach {
norm += Math.pow(tfidf(it, idfMap), 2.0)
}
return 1 / Math.sqrt(norm)
}
fun tfidf(entry: Map.Entry<String, Int>, idfMap: HashMap<String, Int>): Double {
return (1 + Math.log(entry.value.toDouble())) * Math.log(1 + idfMap.size / idfMap.get(entry.key)!!.toDouble())
}
fun HashMap<String, Int>.tfidfDoc(idfMap: HashMap<String, Int>): HashMap<String, Double> {
val result: HashMap<String, Double> = hashMapOf()
this.filter { idfMap.containsKey(it.key) }.forEach {
result.put(it.key, tfidf(it, idfMap))
}
return result;
}
fun createIdfMap(size: Int): HashMap<String, Double> {
val result: HashMap<String, Double> = hashMapOf()
run extract@ {
loadAllProjectModelFile(NAME_PROJECT_MODEL_CLEAN).forEach {
val project = ProjectModel.load(it);
var count = 0;
project.sourceList.filter { it.wordCount() > 20 }.forEach {
it.getMergedMap()!!.keys.forEach {
if (result.containsKey(it))
result.set(it, result.get(it)!! + 1)
else
result.put(it, 1.0);
}
count++;
}
if (count > size)
return@extract
}
}
return result
}
fun getNodeList(size: Int, idfMap: HashMap<String, Int>): List<Node> {
val nodeList: MutableList<Node> = mutableListOf()
run extract@ {
loadAllProjectModelFile(NAME_PROJECT_MODEL_CLEAN).forEach {
val project = ProjectModel.load(it);
nodeList.addAll(project.sourceList.filter { it.wordCount() > 10 }.map { Node(it.path, it.getMergedMap()!!.tfidfDoc(idfMap)) })
if (nodeList.size > size)
return@extract
}
}
println("getNode ${nodeList.size}")
return nodeList
}
fun kmeanClustering(nodeList: List<Node>) {
val kmean = Kmeans(Math.sqrt(nodeList.size.toDouble()).toInt())
kmean.clustering(nodeList)
Paths.get(PATH_RESULT, "cluster", "kmean_${nodeList.size}.json").toFile().printWriter().use {
it.print(Gson().toJson(kmean.clusters))
}
}
fun searchTopK(k: Int = 300, query: File): SortedSet<Pair<String, Double>> {
val idfMap: HashMap<String, Int> = Gson().fromJson(File("map_idf.json").readText(), object : TypeToken<HashMap<String, Int>>() {}.type);
val startTime = System.currentTimeMillis()
println("start Search $startTime / ${idfMap.size}")
val target = PreProcessor(query.readText()).toSourceFile(query.path)
val node = Node("query", target.getMergedMap()!!.tfidfDoc(idfMap))
val result: SortedSet<Pair<String, Double>> = sortedSetOf(compareByDescending { it.second })
loadAllProjectModelFile(NAME_PROJECT_MODEL_CLEAN).forEach {
val project = ProjectModel.load(it);
project.sourceList.map { Node(it.path, it.getMergedMap()!!.tfidfDoc(idfMap)) }.forEach {
if (result.size < k) {
result.add(Pair(it.fileName, it.distanceTo(node)))
} else {
val last = result.last()
val distance = it.distanceTo(node)
if (last.second < distance) {
result.remove(last)
result.add(Pair(it.fileName, distance))
}
}
}
}
println("elapsed milli sec ${System.currentTimeMillis() - startTime}")
return result
}
fun extractTargetCommit() {
val target: HashMap<String, Repository> = Gson().fromJson(File("target_map.json").readText(), object : TypeToken<HashMap<String, Repository>>() {}.type)
target.values.forEach {
println("extract ${it.toRoot().path}")
val saveFile = File("D:\\gitExp_gameengine\\${it.full_name.replace("/", "_")}.json")
if (saveFile.exists())
return@forEach
val data = CommitExtractor(it.toRoot().path).extractCommitMetaData(500)
saveFile.printWriter().use {
it.print(Gson().toJson(data))
}
}
}
fun searchInClusters(clusters: List<Cluster>, node: Node) {
var matchDis = Double.MIN_VALUE
var matchIdx = 0
val startTime = System.currentTimeMillis()
clusters.forEachIndexed { index, cluster ->
val dis = node.distanceTo(cluster.getCentroid())
if (dis > matchDis) {
matchDis = dis;
matchIdx = index
}
}
val result: SortedSet<Pair<String, Double>> = sortedSetOf(compareByDescending { it.second })
val selectedCluster = clusters.get(matchIdx)
selectedCluster.memberList.forEach {
val current = selectedCluster.getNodes().get(it)
if (result.size < 100) {
result.add(Pair(current.fileName, current.distanceTo(node)))
} else {
val last = result.last()
val distance = current.distanceTo(node)
if (last.second < distance) {
result.remove(last)
result.add(Pair(current.fileName, distance))
}
}
}
println("elapsed : ${System.currentTimeMillis() - startTime}")
Paths.get(PATH_RESULT, "searchClusters_${node.fileName}.json").toFile().printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(result))
}
}
fun searchInNode(nodes: List<Node>, query: Node) {
val result: SortedSet<Pair<String, Double>> = sortedSetOf(compareByDescending { it.second })
val startTime = System.currentTimeMillis()
nodes.forEach {
if (result.size < 100) {
result.add(Pair(it.fileName, it.distanceTo(query)))
} else {
val last = result.last()
val distance = it.distanceTo(query)
if (last.second < distance) {
result.remove(last)
result.add(Pair(it.fileName, distance))
}
}
}
println("elapsed : ${System.currentTimeMillis() - startTime}")
Paths.get(PATH_RESULT, "searchSeq_${query.fileName}.json").toFile().printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(result))
}
}
fun mbToKB(mb: Int): Int = mb * 1024;
fun cleanAllProjectModels() {
loadAllProjectModelFile(NAME_PROJECT_MODEL).forEach {
val p = ProjectModel.load(it)
p.sourceList.parallelStream().forEach {
cleanSourceFile(it)
}
val regex = Regex("r.java|package-info.java|test")
p.sourceList = p.sourceList.filter { it.wordCount() > 10 && !regex.containsMatchIn(it.path.toLowerCase()) }.toMutableList()
val saveFile = File(it.path.replace(NAME_PROJECT_MODEL, NAME_PROJECT_MODEL_CLEAN))
if (saveFile.exists())
saveFile.delete()
if (p.sourceList.size > 0) {
println("saved ${saveFile.path}")
saveFile.printWriter().use {
it.print(Gson().toJson(p))
}
}
}
}
val regCamelCase = Regex(String.format("%s|%s|%s",
"(?<=[A-Z])(?=[A-Z][a-z])(\\B)",
"(?<=[^A-Z])(?=[A-Z])(\\B)",
"(?<=[A-Za-z])(?=[^A-Za-z])(\\B)"
))
fun similarity(a: String, b: String): Double {
val aSet = regCamelCase.replace(a, " ").toLowerCase().split(" ").toHashSet()
val bSet = regCamelCase.replace(b, " ").toLowerCase().split(" ").toHashSet()
val union: HashSet<String> = hashSetOf()
union.addAll(aSet)
union.addAll(bSet)
aSet.retainAll(bSet) // 교집합
val inter = aSet.size
return inter.toDouble() / union.size
}
fun expandableScore(querySet: List<String>, resultSet: List<String>, threshold: Double = 0.35): Int {
var count = 0
resultSet.forEach { current ->
var max = Double.MIN_VALUE
querySet.forEach {
val sim = similarity(current, it)
if (sim > max)
max = sim;
}
if (max <= threshold)
count++
}
return count
}
fun methodSim(querySet: List<String>, resultSet: List<String>): Double {
var totalMax = 0.0
querySet.forEach { current ->
var max = 0.0
resultSet.forEach {
val sim = similarity(current, it)
if (sim > max)
max = sim;
}
totalMax += max;
}
return totalMax / querySet.size.toDouble()
}
fun analysisNew2(filterSet:Set<String>) {
val importsMap: HashMap<String, Int> = hashMapOf()
val cmtClassMap: HashMap<String, Int> = hashMapOf()
val cmtMethodMap: HashMap<String, Int> = hashMapOf()
val cmtVarMap: HashMap<String, Int> = hashMapOf()
val nameParamMap: HashMap<String, Int> = hashMapOf()
val nameMethodMap: HashMap<String, Int> = hashMapOf()
val nameClassMap: HashMap<String, Int> = hashMapOf()
val nameVarMap: HashMap<String, Int> = hashMapOf()
val typeMethodMap: HashMap<String, Int> = hashMapOf()
val typeParamMap: HashMap<String, Int> = hashMapOf()
val typeVarMap: HashMap<String, Int> = hashMapOf()
loadAllProjectModelFile(NAME_PROJECT).forEach {
val project = Project.load(it)
project.sourceList.forEach {
it.commentsClassOrInterface.filterKeys { filterSet.contains(it) }.forEach {
cmtClassMap.increase(it.key, it.value)
}
it.commentsMethod.filterKeys { filterSet.contains(it) }.forEach {
cmtMethodMap.increase(it.key, it.value)
}
it.commentsVariable.filterKeys { filterSet.contains(it) }.forEach {
cmtVarMap.increase(it.key, it.value)
}
it.imports.filterKeys { filterSet.contains(it) }.forEach {
importsMap.increase(it.key, it.value)
}
it.nameClassOrInterface.filterKeys { filterSet.contains(it) }.forEach {
nameClassMap.increase(it.key, it.value)
}
it.nameMethod.filterKeys { filterSet.contains(it) }.forEach {
nameMethodMap.increase(it.key, it.value)
}
it.nameVariable.filterKeys { filterSet.contains(it) }.forEach {
nameVarMap.increase(it.key, it.value)
}
it.nameParameter.filterKeys { filterSet.contains(it) }.forEach {
nameParamMap.increase(it.key, it.value)
}
it.typeMethod.filterKeys { filterSet.contains(it) }.forEach {
typeMethodMap.increase(it.key, it.value)
}
it.typeParameter.filterKeys { filterSet.contains(it) }.forEach {
typeParamMap.increase(it.key, it.value)
}
it.typeVariable.filterKeys { filterSet.contains(it) }.forEach {
typeVarMap.increase(it.key, it.value)
}
}
}
println("${importsMap.size}/${importsMap.values.sum()},${cmtClassMap.size}/${cmtClassMap.values.sum()}, ${cmtVarMap.size}/${cmtVarMap.values.sum()}, ${cmtMethodMap.size}/${cmtMethodMap.values.sum()}")
println("${nameClassMap.size}/${nameClassMap.values.sum()}, ${nameMethodMap.size}/${nameMethodMap.values.sum()}, ${nameParamMap.size}/${nameParamMap.values.sum()}, ${nameVarMap.size}/${nameVarMap.values.sum()}")
println("${typeMethodMap.size}/${typeMethodMap.values.sum()}, ${typeParamMap.size}/${typeParamMap.values.sum()}, ${typeVarMap.size}/${typeVarMap.values.sum()}")
}
fun test() {
var count = 0
var idfMap = CountMap()
var dfMap = CountMap()
var ndfMap = CountMap()
var tdfMap = CountMap()
loadAllProjectModelFile(NAME_PROJECT).forEach {
val project = Project.load(it)
val iset : MutableSet<String> = mutableSetOf()
val set: MutableSet<String> = mutableSetOf()
val nset: MutableSet<String> = mutableSetOf()
val tset: MutableSet<String> = mutableSetOf()
project.sourceList.forEach {
iset.addAll(it.imports.keys)
set.addAll(it.commentsClassOrInterface.keys)
set.addAll(it.commentsMethod.keys)
set.addAll(it.commentsVariable.keys)
nset.addAll(it.nameVariable.keys)
nset.addAll(it.nameParameter.keys)
nset.addAll(it.nameMethod.keys)
nset.addAll(it.nameClassOrInterface.keys)
//
tset.addAll(it.typeMethod.keys)
tset.addAll(it.typeParameter.keys)
tset.addAll(it.typeVariable.keys)
}
++count
iset.forEach {
idfMap.put(it)
}
set.forEach {
dfMap.put(it)
}
nset.forEach {
ndfMap.put(it)
}
tset.forEach {
tdfMap.put(it)
}
}
println("$count / ${idfMap.size} / ${dfMap.size} / ${tdfMap.size} / ${ndfMap.size}")
File("res_imports.json").printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(idfMap.toList().sortedByDescending { it.second }))
}
File("res_comment.json").printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(dfMap.toList().sortedByDescending { it.second }))
}
File("res_type.json").printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(tdfMap.toList().sortedByDescending { it.second }))
}
File("res_name.json").printWriter().use {
it.print(GsonBuilder().setPrettyPrinting().create().toJson(ndfMap.toList().sortedByDescending { it.second }))
}
}
fun analysisNew3() {
val importsMap= CountMap()
val cmtClassMap= CountMap()
val cmtMethodMap= CountMap()
val cmtVarMap= CountMap()
val nameParamMap= CountMap()
val nameMethodMap= CountMap()
val nameClassMap= CountMap()
val nameVarMap= CountMap()
val typeMethodMap= CountMap()
val typeParamMap= CountMap()
val typeVarMap= CountMap()
val srcLenList: MutableList<Int> = mutableListOf()
val wsCmtList1: MutableList<Double> = mutableListOf()
val wsCmtList2: MutableList<Double> = mutableListOf()
val wsCmtList3: MutableList<Double> = mutableListOf()
val wsNameList1: MutableList<Double> = mutableListOf()
val wsNameList2: MutableList<Double> = mutableListOf()
val wsNameList3: MutableList<Double> = mutableListOf()
val wsNameList4: MutableList<Double> = mutableListOf()
val wsTypeList1: MutableList<Double> = mutableListOf()
val wsTypeList2: MutableList<Double> = mutableListOf()
val wsTypeList3: MutableList<Double> = mutableListOf()
val wsImportList: MutableList<Double> = mutableListOf()
var pre = 0
var current = 0
val step = 400000
val limit = 100
var count = 0
val pfMap = CountMap()
loadAllProjectModelFile(NAME_PROJECT).forEach {
val project = Project.load(it)
val importsSet : MutableSet<String> = mutableSetOf()
val cmtClassSet : MutableSet<String> = mutableSetOf()
val cmtVarSet : MutableSet<String> = mutableSetOf()
val cmtMethodSet : MutableSet<String> = mutableSetOf()
val nameClassSet : MutableSet<String> = mutableSetOf()
val nameParamSet : MutableSet<String> = mutableSetOf()
val nameMethodSet : MutableSet<String> = mutableSetOf()
val nameVarSet : MutableSet<String> = mutableSetOf()
val typeMethodSet : MutableSet<String> = mutableSetOf()
val typeParamSet : MutableSet<String> = mutableSetOf()
val typeVarSet : MutableSet<String> = mutableSetOf()
++count
project.sourceList.forEach {
importsSet.addAll(it.imports.keys)
cmtClassSet.addAll(it.commentsClassOrInterface.keys)
cmtVarSet.addAll(it.commentsVariable.keys)
cmtMethodSet.addAll(it.commentsMethod.keys)
nameParamSet.addAll(it.nameParameter.keys)
nameMethodSet.addAll(it.nameMethod.keys)
nameVarSet.addAll(it.nameVariable.keys)
nameClassSet.addAll(it.nameClassOrInterface.keys)
typeMethodSet.addAll(it.typeMethod.keys)
typeParamSet.addAll(it.typeParameter.keys)
typeVarSet.addAll(it.typeVariable.keys)
++current
if (current - pre > step) {
pre = current
srcLenList.add(current / 1000)
wsCmtList1.add(cmtClassMap.filter { it.value > limit }.size / 1000.0)
wsCmtList2.add(cmtMethodMap.filter { it.value > limit }.size / 1000.0)
wsCmtList3.add(cmtVarMap.filter { it.value > limit }.size / 1000.0)
wsNameList1.add(nameClassMap.filter { it.value > limit }.size / 1000.0)
wsNameList2.add(nameMethodMap.filter { it.value > limit }.size / 1000.0)
wsNameList3.add(nameParamMap.filter { it.value > limit }.size / 1000.0)
wsNameList4.add(nameVarMap.filter { it.value > limit }.size / 1000.0)
wsTypeList1.add(typeMethodMap.filter { it.value > limit }.size / 1000.0)
wsTypeList2.add(typeParamMap.filter { it.value > limit }.size / 1000.0)
wsTypeList3.add(typeVarMap.filter { it.value > limit }.size / 1000.0)
wsImportList.add(importsMap.filter { it.value > limit }.size / 1000.0)
}
}
importsSet.forEach {
importsMap.put(it)
}
cmtClassSet.forEach {
cmtClassMap.put(it)
}
cmtVarSet.forEach {
cmtVarMap.put(it)
}
cmtMethodSet.forEach {
cmtMethodMap.put(it)
}
nameParamSet.forEach {
nameParamMap.put(it)
}
nameMethodSet.forEach {
nameMethodMap.put(it)
}
nameVarSet.forEach {
nameVarMap.put(it)
}
nameClassSet.forEach {
nameClassMap.put(it)
}
typeMethodSet.forEach {
typeMethodMap.put(it)
}
typeParamSet.forEach {
typeParamMap.put(it)
}
typeVarSet.forEach {
typeVarMap.put(it)
}
}
println(count)
if (current != pre) {
pre = current
srcLenList.add(current / 1000)
wsCmtList1.add(cmtClassMap.filter { it.value > limit }.size / 1000.0)
wsCmtList2.add(cmtMethodMap.filter { it.value > limit }.size / 1000.0)
wsCmtList3.add(cmtVarMap.filter { it.value > limit }.size / 1000.0)
wsNameList1.add(nameClassMap.filter { it.value > limit }.size / 1000.0)
wsNameList2.add(nameMethodMap.filter { it.value > limit }.size / 1000.0)
wsNameList3.add(nameParamMap.filter { it.value > limit }.size / 1000.0)
wsNameList4.add(nameVarMap.filter { it.value > limit }.size / 1000.0)
wsTypeList1.add(typeMethodMap.filter { it.value > limit }.size / 1000.0)
wsTypeList2.add(typeParamMap.filter { it.value > limit }.size / 1000.0)
wsTypeList3.add(typeVarMap.filter { it.value > limit }.size / 1000.0)
wsImportList.add(importsMap.filter { it.value > limit }.size / 1000.0)
}
val chart = XYChartBuilder().width(800).height(600).title("Title")
.xAxisTitle("#source file (k)")
.yAxisTitle("size of wordset (k)").theme(Styler.ChartTheme.Matlab).build()
chart.styler.setMarkerSize(5)
chart.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart.styler.setChartTitleVisible(false)
chart.addSeries("comment_class", srcLenList, wsCmtList1)
chart.addSeries("comment_method", srcLenList, wsCmtList2)
chart.addSeries("comment_var", srcLenList, wsCmtList3)
SwingWrapper(chart).displayChart()
BitmapEncoder.saveBitmapWithDPI(chart, Paths.get(PATH_RESULT, "new_analysis_1.png").toString(), BitmapEncoder.BitmapFormat.PNG, 200);
val chart2 = XYChartBuilder().width(800).height(600).title("Title")
.xAxisTitle("#source file (k)")
.yAxisTitle("size of wordset (k)").theme(Styler.ChartTheme.Matlab).build()
chart2.styler.setMarkerSize(5)
chart2.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart2.styler.setChartTitleVisible(false)
chart2.addSeries("name_class", srcLenList, wsNameList1)
chart2.addSeries("name_method", srcLenList, wsNameList2)
chart2.addSeries("name_param", srcLenList, wsNameList3)
chart2.addSeries("name_value", srcLenList, wsNameList4)
SwingWrapper(chart2).displayChart()
BitmapEncoder.saveBitmapWithDPI(chart2, Paths.get(PATH_RESULT, "new_analysis_2.png").toString(), BitmapEncoder.BitmapFormat.PNG, 200);
val chart3 = XYChartBuilder().width(800).height(600).title("Title")
.xAxisTitle("#source file (k)")
.yAxisTitle("size of wordset (k)").theme(Styler.ChartTheme.Matlab).build()
chart3.styler.setMarkerSize(5)
chart3.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart3.styler.setChartTitleVisible(false)
chart3.addSeries("type_method", srcLenList, wsTypeList1)
chart3.addSeries("type_param", srcLenList, wsTypeList2)
chart3.addSeries("type_value", srcLenList, wsTypeList3)
SwingWrapper(chart3).displayChart()
BitmapEncoder.saveBitmapWithDPI(chart, Paths.get(PATH_RESULT, "new_analysis_3.png").toString(), BitmapEncoder.BitmapFormat.PNG, 200);
val chart4 = XYChartBuilder().width(800).height(600).title("Title")
.xAxisTitle("#source file (k)")
.yAxisTitle("size of wordset (k)").theme(Styler.ChartTheme.Matlab).build()
chart4.styler.setMarkerSize(5)
chart4.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart4.styler.setChartTitleVisible(false)
chart4.addSeries("import", srcLenList, wsImportList)
SwingWrapper(chart4).displayChart()
BitmapEncoder.saveBitmapWithDPI(chart, Paths.get(PATH_RESULT, "new_analysis_3.png").toString(), BitmapEncoder.BitmapFormat.PNG, 200);
}
fun analysisNew() {
val importsMap: HashMap<String, Int> = hashMapOf()
val cmtClassMap: HashMap<String, Int> = hashMapOf()
val cmtMethodMap: HashMap<String, Int> = hashMapOf()
val cmtVarMap: HashMap<String, Int> = hashMapOf()
val nameParamMap: HashMap<String, Int> = hashMapOf()
val nameMethodMap: HashMap<String, Int> = hashMapOf()
val nameClassMap: HashMap<String, Int> = hashMapOf()
val nameVarMap: HashMap<String, Int> = hashMapOf()
val typeMethodMap: HashMap<String, Int> = hashMapOf()
val typeParamMap: HashMap<String, Int> = hashMapOf()
val typeVarMap: HashMap<String, Int> = hashMapOf()
val srcLenList: MutableList<Int> = mutableListOf()
val wsCmtList: MutableList<Double> = mutableListOf()
val wsNameList: MutableList<Double> = mutableListOf()
val wsTypeList: MutableList<Double> = mutableListOf()
val wsImportList: MutableList<Double> = mutableListOf()
var pre = 0
var current = 0
val step = 450000
val limit = 0
val dfMap = CountMap()
loadAllProjectModelFile(NAME_PROJECT).forEach {
val project = Project.load(it)
val set: MutableSet<String> = mutableSetOf()
project.sourceList.forEach {
set.addAll(it.commentsClassOrInterface.keys)
it.commentsClassOrInterface.forEach {
cmtClassMap.increase(it.key, it.value)
}
set.addAll(it.commentsMethod.keys)
it.commentsMethod.forEach {
cmtMethodMap.increase(it.key, it.value)
}
set.addAll(it.commentsVariable.keys)
it.commentsVariable.forEach {
cmtVarMap.increase(it.key, it.value)
}
set.addAll(it.imports.keys)
it.imports.forEach {
importsMap.increase(it.key, it.value)
}
set.addAll(it.nameClassOrInterface.keys)
it.nameClassOrInterface.forEach {
nameClassMap.increase(it.key, it.value)
}
set.addAll(it.nameMethod.keys)
it.nameMethod.forEach {
nameMethodMap.increase(it.key, it.value)
}
set.addAll(it.nameVariable.keys)
it.nameVariable.forEach {
nameVarMap.increase(it.key, it.value)
}
set.addAll(it.nameParameter.keys)
it.nameParameter.forEach {
nameParamMap.increase(it.key, it.value)
}
set.addAll(it.typeMethod.keys)
it.typeMethod.forEach {
typeMethodMap.increase(it.key, it.value)
}
set.addAll(it.typeParameter.keys)
it.typeParameter.forEach {
typeParamMap.increase(it.key, it.value)
}
set.addAll(it.typeVariable.keys)
it.typeVariable.forEach {
typeVarMap.increase(it.key, it.value)
}
++current
if (current - pre > step) {
pre = current
srcLenList.add(current / 1000)
wsCmtList.add((cmtClassMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + cmtMethodMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + cmtVarMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size) / 1000.0)
wsNameList.add((nameClassMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + nameMethodMap.size + nameParamMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + nameVarMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size) / 1000.0)
wsTypeList.add((typeMethodMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + typeParamMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + typeVarMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size) / 1000.0)
wsImportList.add(importsMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size / 1000.0)
}
}
println(set.size)
set.forEach {
dfMap.put(it)
}
}
if (current != pre) {
pre = current
srcLenList.add(current / 1000)
wsCmtList.add((cmtClassMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + cmtMethodMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + cmtVarMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size) / 1000.0)
wsNameList.add((nameClassMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + nameMethodMap.size + nameParamMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + nameVarMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size) / 1000.0)
wsTypeList.add((typeMethodMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + typeParamMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size + typeVarMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size) / 1000.0)
wsImportList.add(importsMap.filter { dfMap.getOrDefault(it.key, 0) > limit }.size / 1000.0)
}
val chart = XYChartBuilder().width(800).height(600).title("Title")
.xAxisTitle("#source file (k)")
.yAxisTitle("size of wordset (k)").theme(Styler.ChartTheme.Matlab).build()
chart.styler.setMarkerSize(5)
chart.styler.setLegendPosition(Styler.LegendPosition.InsideNW)
chart.styler.setChartTitleVisible(false)
chart.addSeries("comment", srcLenList, wsCmtList)
chart.addSeries("type", srcLenList, wsTypeList)
chart.addSeries("name", srcLenList, wsNameList)
chart.addSeries("import", srcLenList, wsImportList)
SwingWrapper(chart).displayChart()
BitmapEncoder.saveBitmapWithDPI(chart, Paths.get(PATH_RESULT, "new_analysis.png").toString(), BitmapEncoder.BitmapFormat.PNG, 200);
}
val T1 = "E:\\Repository\\spring-projects\\spring-framework\\spring-core\\src\\main\\java\\org\\springframework\\util\\StringUtils.java" // 51
val T2 = "E:\\Repository\\zxing\\zxing\\core\\src\\main\\java\\com\\google\\zxing\\common\\detector\\MathUtils.java"
val T3 = "E:\\Repository\\zyuanming\\MusicMan\\src\\org\\ming\\util\\FileUtils.java" // 20
val T4 = "E:\\Repository\\spring-projects\\spring-framework\\spring-core\\src\\main\\java\\org\\springframework\\util\\Base64Utils.java"
val T5 = "E:\\Repository\\spring-projects\\spring-framework\\spring-core\\src\\main\\java\\org\\springframework\\util\\SocketUtils.java"
val T6 = "E:\\Repository\\google\\guava\\guava\\src\\com\\google\\common\\base\\CharMatcher.java"
fun HashMap<String, Int>.increase(key: String, value: Int) {
if (containsKey(key))
set(key, get(key)!! + value)
else
put(key, value)
}
fun projectInfoFiltering()
{
val filterSet = Main.DF_MAP.keys.toSet()
loadAllProjectModelFile(NAME_PROJECT).forEach {
try {
val project = Project.load(it)
project.sourceList.forEach {
it.imports.keys.removeIf{ !filterSet.contains(it) }
it.typeParameter.keys.removeIf{ !filterSet.contains(it) }
it.typeVariable.keys.removeIf{ !filterSet.contains(it) }
it.typeMethod.keys.removeIf{ !filterSet.contains(it) }
it.commentsMethod.keys.removeIf{ !filterSet.contains(it) }
it.commentsClassOrInterface.keys.removeIf{ !filterSet.contains(it) }
it.commentsVariable.keys.removeIf{ !filterSet.contains(it) }
it.nameVariable.keys.removeIf{ !filterSet.contains(it) }
it.nameParameter.keys.removeIf{ !filterSet.contains(it) }
it.nameMethod.keys.removeIf{ !filterSet.contains(it) }
it.nameClassOrInterface.keys.removeIf{ !filterSet.contains(it) }
}
project.sourceList.removeIf {
it.getAllWords().size < 5
}
val saveFile = File(it.path.replace(NAME_PROJECT, NAME_PROJECT_FILTERED))
if(project.sourceList.size > 0)
{
saveFile.printWriter().use {
println("CREATE - ${saveFile.path}")
it.print(Gson().toJson(project))
}
}
else
{
if(saveFile.exists()) {
println("DEL - ${saveFile.path}")
saveFile.delete()
}
}
}
catch (e:Exception)
{
println("EXPCEPTION - ${it.path}")
}
}
}
fun createDFMap(target:String, saveFile:File)
{
val dfMap = CountMap()
var count = 0
loadAllProjectModelFile(target).forEach {
try {
val project = Project.load(it)
project.sourceList.forEach {
count++
it.imports.keys.forEach {
dfMap.put(it)
}
it.typeMethod.keys.forEach {
dfMap.put(it)
}
it.typeVariable.keys.forEach {
dfMap.put(it)
}
it.typeParameter.keys.forEach {
dfMap.put(it)
}
it.commentsVariable.keys.forEach {
dfMap.put(it)
}
it.commentsClassOrInterface.keys.forEach {
dfMap.put(it)
}
it.commentsMethod.keys.forEach {
dfMap.put(it)
}
it.nameClassOrInterface.keys.forEach {
dfMap.put(it)
}
it.nameMethod.keys.forEach {
dfMap.put(it)
}
it.nameParameter.keys.forEach {
dfMap.put(it)
}
it.nameVariable.keys.forEach {
dfMap.put(it)
}
}
} catch (e:Exception)
{
it.delete()
println("${it.path} exception")
}
}
println("Source Count : $count dfMap keys : ${dfMap.keys.size}")
saveFile.printWriter().use {
it.println(Gson().toJson(dfMap))
}
}
fun evalSearchResult(target:String, resultFile:File)
{
val searchMap: Set<Pair<String, Double>> = Gson().fromJson(resultFile.readText(), object : TypeToken<Set<Pair<String, Double>>>() {}.type)
val queryParser = JavaParser.parse(File(target))
val set = queryParser.findAll(MethodDeclaration::class.java).map { it.name.toString() }.toHashSet()
var maxES = Int.MIN_VALUE
var minES = Int.MAX_VALUE
var totalES = 0
var maxMas = Double.MIN_VALUE
var minMas = Double.MAX_VALUE
var totalMas = 0.0
var size = 50;
searchMap.filter { !it.first.equals(target) }.take(50).forEach {
try {
val parser = JavaParser.parse(File(it.first))
val currentSet = parser.findAll(MethodDeclaration::class.java).map { it.name.toString() }.toSet()
var es = expandableScore(set.toList(), currentSet.toList())
val ms = methodSim(set.toList(), currentSet.toList())
if (es > maxES)
maxES = es
if (es < minES)
minES = es
if (ms > maxMas)
maxMas = ms
if (ms < minMas)
minMas = ms
totalMas += ms
totalES += es
} catch (e: Exception) {
size--
println("[error]${it.first}")
return@forEach
}
}
println("$minES / $maxES / ${totalES / size.toDouble()} / $minMas / $maxMas / ${totalMas / size}")
}
fun loadProjectMap() : HashMap<String,Repository>
{
return Gson().fromJson(File(PATH_PROJECT_MAP).readText(), object : TypeToken<HashMap<String, Repository>>() {}.type)
}
val stemmer = englishStemmer()
fun String.preprocessing() : List<String>
{
var str = PreProcessor.regCamelCase.replace(this," ")
str = PreProcessor.regHtml.replace(str, "")
str = com.sun.deploy.util.StringUtils.trimWhitespace(str)
return PreProcessor.regNonAlphanum.split(str.toLowerCase()).filter { it.length > 2 && it.length < 20 && !Stopwords.instance.contains(it.toLowerCase()) }.map {
stemmer.setCurrent(it)
stemmer.stem()
stemmer.current
}
}
//
//fun String.preprocessing() : String
//{
// var str = PreProcessor.regCamelCase.replace(this," ")
// str = PreProcessor.regHtml.replace(str, "")
// str = com.sun.deploy.util.StringUtils.trimWhitespace(str)
//
// val sb = StringBuilder()
// PreProcessor.regNonAlphanum.split(str.toLowerCase()).filter { it.length > 2 && it.length < 20 && !Stopwords.instance.contains(it.toLowerCase()) }.map {
// stemmer.setCurrent(it)
// stemmer.stem()
// stemmer.current
// }.forEach { sb.append(it + ' ') }
//
// return sb.toString()
//}
fun srcFileToDocument(srcFile:File) : String
{
val parser = JavaParser.parse(srcFile)
var sen : MutableList<String> = mutableListOf()
parser.findAll(MethodDeclaration::class.java).forEach {
if(it.comment.isPresent)
sen.addAll(it.comment.get().toString().preprocessing())
sen.addAll(it.nameAsString.preprocessing())
if(it.body.isPresent)
sen.addAll(it.body.get().toString().preprocessing())
}
if(sen.size <= 5)
return ""
return sen.filter { Main.FILTER_WORD.contains(it) }.joinToString(" ")
}
data class SourceDocMeta(val path:String, val doc:String)
fun extractDataSet()
{
val target = loadProjectMap().filterValues { it.size < mbToKB(2048) }.values
val regex = Regex("r.java|package-info.java|\\\\test|test\\\\|test.java")
// val gson = GsonBuilder().setPrettyPrinting().create()
val gson = Gson()
target.forEach {
val root = it.toRoot()
if(!root.exists())
return@forEach
val sources : MutableList<SourceDocMeta> = mutableListOf()
if(root.exists())
{
FileUtils.readAllFilesExt(root, "java").filter { !regex.containsMatchIn(it.path.toLowerCase()) }.forEach {
srcFile->
try {
val doc = srcFileToDocument(srcFile)
if(doc.isEmpty())
return@forEach
sources.add(SourceDocMeta(srcFile.nameWithoutExtension, doc))
}
catch (e:Exception)
{
println("${srcFile.path} exception")
}
}
val saveFile = Paths.get(PATH_DOCS,"${it.full_name.replace("/","_")}.json").toFile()
saveFile.printWriter().use {
it.print(gson.toJson(sources))
}
println("created ${saveFile.path}")
}
}
return
}
fun main(args: Array<String>) {
println(File(T1).toPairList())
return
File("E:/Repository").listFiles().map { it.listFiles() }.forEach {
it.forEach {
DataManager.create(it)
}
}
// val map : HashMap<String, Int> = Gson().fromJson(File("new_df_map.json").readText(), object:TypeToken<HashMap<String, Int>>() {}.type)
// map.values.removeIf{
// it < 30
// }
// Main.FILTER_WORD = map.keys.toHashSet()
//
// extractDataSet()
// println(srcFileToDocument(File(T1)))
return
// val j = Jaccard();
// println(j.similarity("return array empty", "set preserve returned"))
// return
Main.DF_MAP = Gson().fromJson(File("new_df_map.json").readText(), object:TypeToken<HashMap<String, Int>>() {}.type)
Main.DF_MAP.values.removeIf{
it < 20
}
println(Main.DF_MAP.toList().sortedByDescending { it.second }.take(1000))
return
evalSearchResult(T1, Paths.get(PATH_RESULT, "search_new_t1_om.json").toFile())
evalSearchResult(T2, Paths.get(PATH_RESULT, "search_new_t2_om.json").toFile())
evalSearchResult(T3, Paths.get(PATH_RESULT, "search_new_t3_om.json").toFile())
evalSearchResult(T4, Paths.get(PATH_RESULT, "search_new_t4_om.json").toFile())
evalSearchResult(T5, Paths.get(PATH_RESULT, "search_new_t5_om.json").toFile())
return
searchNew(NAME_PROJECT, T1, Paths.get(PATH_RESULT, "search_new_t1_om.json").toFile())
searchNew(NAME_PROJECT, T2, Paths.get(PATH_RESULT, "search_new_t2_om.json").toFile())
searchNew(NAME_PROJECT, T3, Paths.get(PATH_RESULT, "search_new_t3_om.json").toFile())
searchNew(NAME_PROJECT, T4, Paths.get(PATH_RESULT, "search_new_t4_om.json").toFile())
searchNew(NAME_PROJECT, T5, Paths.get(PATH_RESULT, "search_new_t5_om.json").toFile())
return
SourceDataGenerator(File(T1)).generate()
return
return
//
// projectInfoFiltering()
// searchNew(NAME_PROJECT_FILTERED, T1, Paths.get(PATH_RESULT, "new_search_T1.json").toFile())
// searchNew(NAME_PROJECT_FILTERED, T2, Paths.get(PATH_RESULT, "new_search_T2.json").toFile())
// searchNew(NAME_PROJECT_FILTERED, T3, Paths.get(PATH_RESULT, "new_search_T3.json").toFile())
// searchNew(NAME_PROJECT_FILTERED, T4, Paths.get(PATH_RESULT, "new_search_T4.json").toFile())
// searchNew(NAME_PROJECT_FILTERED, T5, Paths.get(PATH_RESULT, "new_search_T5.json").toFile())
// create
//
evalSearchResult(T4, Paths.get(PATH_RESULT, "t4_filter.json").toFile())
return
val target = T6
val searchMap: Set<Pair<String, Double>> = Gson().fromJson(Paths.get(PATH_RESULT, "t5_filter.json").toFile().readText(), object : TypeToken<Set<Pair<String, Double>>>() {}.type)
// val origin : Set<Pair<String, Double>> = Gson().fromJson(Paths.get(PATH_RESULT, "t1_search_org_result.json").toFile().readText(), object:TypeToken<Set<Pair<String,Double>>> () {}.type)
val queryParser = JavaParser.parse(File(target))
val set = queryParser.findAll(MethodDeclaration::class.java).map { it.name.toString() }.toHashSet()
var maxES = Int.MIN_VALUE
var minES = Int.MAX_VALUE
var totalES = 0
var maxMas = Double.MIN_VALUE
var minMas = Double.MAX_VALUE
var totalMas = 0.0
var size = 50;
println(set.size)
println(set)
return
searchMap.filter { !it.first.equals(target) }.take(50).forEach {
try {
val parser = JavaParser.parse(File(it.first))
val currentSet = parser.findAll(MethodDeclaration::class.java).map { it.name.toString() }.toSet()
var es = expandableScore(set.toList(), currentSet.toList())
val ms = methodSim(set.toList(), currentSet.toList())
println("${it.first} es : $es")
if (es > maxES)
maxES = es
if (es < minES)
minES = es
if (ms > maxMas)
maxMas = ms
if (ms < minMas)
minMas = ms
totalMas += ms
totalES += es
} catch (e: Exception) {
size--
println("[error]${it.first}")
return@forEach
}
}
println("$minES / $maxES / ${totalES / size.toDouble()} / $minMas / $maxMas / ${totalMas / size}")
// dfMap.filterValues { it > 19 && it < 500000}
// val analyst = SourceAnalyst(File(T2))
// analyst.analysis()
// println(GsonBuilder().setPrettyPrinting().create().toJson( analyst.sourceFile))
// return
// analysisNew3()
return
// println(GsonBuilder().setPrettyPrinting().create().toJson(newdata.SourceFile.create(File(T6))))
// val dfMap : HashMap<String, Long> = Gson().fromJson(File("df_map.json").readText(), object:TypeToken<HashMap<String, Double>>() {}.type)
// val idfMap : HashMap<String, Long> = hashMapOf()
// idfMap.putAll(dfMap.filter { it.value > 19 && it.value < 600000 })
//
// searchTest(File(T6), Paths.get(PATH_RESULT,"t6_org.json").toFile(), dfMap);
// searchTest(File(T6), Paths.get(PATH_RESULT,"t6_filter.json").toFile(), idfMap);
// val qp = JavaParser.parse(File(T6))
////
//// qp.findAll(MethodDeclaration::class.java).forEach {
//// println(it.body)
//// }
//
// qp.findAll(ClassOrInterfaceDeclaration::class.java).forEach {
// println(it.comment.get())
// }
//
// qp.findAll(ConstructorDeclaration::class.java).forEach {
// println("${it.name} : ${it.parameters}")
// }
//
// qp.findAll(MethodDeclaration::class.java).forEach {
// println("${it.name} : ${it.parameters}")
// }
return
return
val pfMap: HashMap<String, Long> = Gson().fromJson(File("pf_map.json").readText(), object : TypeToken<HashMap<String, Long>>() {}.type)
return
analysis()
return
printBaseInfo()
return
analysis1(limit = 0, suffix = "new")
analysis1(limit = 10, suffix = "new")
analysis1(limit = 100, suffix = "new")
return
printBaseInfo()
return
return
printAllCloneCommand()
return
val c = Calendar.getInstance()
val format = SimpleDateFormat("yyyy-MM-dd")
for (year in 2008..2017) {
c.set(Calendar.YEAR, year)
for (day in 1..358 step 7) {
c.set(Calendar.DAY_OF_YEAR, day)
val start = format.format(c.time)
c.add(Calendar.DAY_OF_YEAR, +7)
val end = format.format(c.time)
ProjectExtractor(Paths.get(PATH_PROJECT_MAP), start, end).extract();
}
// for(month in 1..12)
// {
// for(week in 1..5) {
// val ws = (week-1)*7 + 1;
// val we = week*7 + 1;
// val c = Calendar.getInstance()
// c.set(Calendar.YEAR, 2014)
// c.set(Calendar.MONTH, 1)
// c.set(Calendar.DAY_OF_YEAR, i)
// ProjectExtractor(Paths.get(PATH_PROJECT_MAP), "$year-$month-$ws", "$year-$month-$we").extract();
// }
// }
}
return
File("E:/Repository").listFiles().map { it.listFiles() }.forEach {
it.forEach {
cleanProject(it)
}
}
return
printAllCloneCommand()
return
// printBaseInfo()
// return
//
// val idfMap : HashMap<String, Double> = Gson().fromJson(File("map_idf.json").readText(), object:TypeToken<HashMap<String, Double>>() {}.type)
// val size = 50000
// kmeanClustering(300000, idfMap, getNodeList(size, idfMap))
// val idfMap : HashMap<String, Double> = Gson().fromJson(File("map_idf.json").readText(), object:TypeToken<HashMap<String, Double>>() {}.type);
// val query = File("C:\\Research\\Repository\\zxing\\zxing\\core\\src\\main\\java\\com\\google\\zxing\\common\\detector\\MathUtils.java")
// val target = PreProcessor(query.readText()).toSourceFile(query.path)
//
// val node = Node("query" , target.getMergedMap()!!.tfidfDoc(idfMap))
//
// val clusters : List<Cluster> = Gson().fromJson(Paths.get(PATH_RESULT, "cluster", "kmean_50319.json").toFile().readText(), object:TypeToken<List<Cluster>>() {}.type);
// val nodeList = getNodeList(50000, idfMap)
//
// searchInClusters(clusters, node)
// searchInNode(nodeList, node)
// return
// val size = 100000
// kmeanClustering(getNodeList(300000, idfMap))
// kmeanClustering(getNodeList(500000, idfMap))
// return
// val clusters : List<Cluster> = Gson().fromJson(Paths.get(PATH_RESULT, "cluster", "kmean_101418.json").toFile().readText(), object:TypeToken<List<Cluster>>() {}.type);
// val nodeList = getNodeList(size, idfMap)
//
// val query = File(T1)
// val target = PreProcessor(query.readText()).toSourceFile(query.path)
// val node = Node(query.nameWithoutExtension , target.getMergedMap()!!.tfidfDoc(idfMap))
//
// searchInClusters(clusters, node)
// searchInNode(nodeList, node)
//
// return
// kmeanClustering(50000, idfMap);
// kmeanClustering(100000, idfMap);
// kmeanClustering(150000, idfMap);
return
//
// val s = searchTopK(query = File("C:\\Research\\Repository\\spring-projects\\spring-framework\\spring-core\\src\\main\\java\\org\\springframework\\util\\StringUtils.java"))
// Paths.get(PATH_RESULT, "search_top300_tfidf.json").toFile().printWriter().use {
// it.print(GsonBuilder().setPrettyPrinting().create().toJson(s))
// }
return
// val idfMap:HashMap<String, Double> = hashMapOf()
//
// loadAllProjectModelFile(NAME_PROJECT_MODEL_CLEAN).forEach {
// val project = ProjectModel.load(it)
//
// project.sourceList.forEach {
// it.getMergedMap()!!.keys.forEach {
// if(idfMap.containsKey(it))
// idfMap.set(it, idfMap.get(it)!! + 1)
// else
// idfMap.put(it, 1.0)
// }
// }
// }
//
// File("map_idf.json").printWriter().use {
// it.print(GsonBuilder().setPrettyPrinting().create().toJson(idfMap))
// }
//
// return
}
private fun cloneAll() {
Cloner(PATH_PROJECT_MAP).cloneAll()
}
data class SearchResponse(var items: List<Repository>, var total_count: Int) {
class Deserializer : ResponseDeserializable<SearchResponse> {
override fun deserialize(content: String) = Gson().fromJson(content, SearchResponse::class.java)
}
}
inline fun <T> MutableList<T>.mapInPlace(mutator: (T) -> T) {
val iterate = this.listIterator()
while (iterate.hasNext()) {
val oldValue = iterate.next()
val newValue = mutator(oldValue)
if (newValue !== oldValue) {
iterate.set(newValue)
}
}
}
| apache-2.0 | 91267c430c0555880b9e11c649818f59 | 34.960094 | 266 | 0.612197 | 3.740904 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/amivanished/AmIVanishedCommand.kt | 1 | 2587 | /*
* 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.moderation.bukkit.command.amivanished
import com.rpkit.core.service.Services
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.vanish.RPKVanishService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class AmIVanishedCommand(private val plugin: RPKModerationBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.moderation.command.amivanished")) {
sender.sendMessage(plugin.messages["no-permission-amivanished"])
return true
}
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val vanishService = Services[RPKVanishService::class.java]
if (vanishService == null) {
sender.sendMessage(plugin.messages["no-vanish-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
vanishService.isVanished(minecraftProfile).thenAccept { isVanished ->
if (isVanished) {
sender.sendMessage(plugin.messages["amivanished-vanished"])
} else {
sender.sendMessage(plugin.messages["amivanished-unvanished"])
}
}
return true
}
} | apache-2.0 | 17af4b9223073f79dfa84c4aaad630f5 | 40.079365 | 118 | 0.696173 | 4.570671 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/PrepareItemCraftListener.kt | 1 | 3974 | /*
* Copyright 2022 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.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.bukkit.extension.addLore
import com.rpkit.core.service.Services
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQuality
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.profession.RPKCraftingAction
import com.rpkit.professions.bukkit.profession.RPKProfessionService
import org.bukkit.GameMode
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.PrepareItemCraftEvent
import kotlin.math.ceil
import kotlin.math.roundToInt
class PrepareItemCraftListener(private val plugin: RPKProfessionsBukkit) : Listener {
@EventHandler
fun onPrepareItemCraft(event: PrepareItemCraftEvent) {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val professionService = Services[RPKProfessionService::class.java] ?: return
val bukkitPlayer = event.viewers.firstOrNull() as? Player
if (bukkitPlayer == null) {
event.inventory.result = null
return
}
if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer)
if (minecraftProfile == null) {
event.inventory.result = null
return
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
event.inventory.result = null
return
}
val material = event.inventory.result?.type
if (material == null) {
event.inventory.result = null
return
}
val professions = professionService.getPreloadedProfessions(character)
if (professions == null) {
minecraftProfile.sendMessage(plugin.messages.noPreloadedProfessions)
event.inventory.result = null
return
}
val professionLevels = professions
.associateWith { profession -> professionService.getPreloadedProfessionLevel(character, profession) ?: 1 }
val amount = professionLevels.entries.maxOfOrNull { (profession, level) ->
profession.getAmountFor(
RPKCraftingAction.CRAFT,
material,
level
)
} ?: plugin.config.getDouble("default.crafting.$material.amount", 1.0)
val potentialQualities = professionLevels.entries
.mapNotNull { (profession, level) -> profession.getQualityFor(RPKCraftingAction.CRAFT, material, level) }
val quality = potentialQualities.maxByOrNull(RPKItemQuality::durabilityModifier)
val item = event.inventory.result ?: return
if (quality != null) {
item.addLore(quality.lore)
}
if (amount > 1) {
item.amount = amount.roundToInt()
} else if (amount < 1) {
item.amount = ceil(amount).toInt()
}
event.inventory.result = item
}
} | apache-2.0 | e6481d172fe215c81693a4dd9149bee0 | 41.287234 | 122 | 0.695773 | 4.924411 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/time/TimeRunnable.kt | 1 | 1601 | /*
* Copyright 2022 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.essentials.bukkit.time
import com.rpkit.essentials.bukkit.RPKEssentialsBukkit
import org.bukkit.scheduler.BukkitRunnable
import java.time.Duration
import kotlin.math.roundToInt
class TimeRunnable(
private val plugin: RPKEssentialsBukkit,
private val dayDuration: Duration,
private val nightDuration: Duration,
private val tickInterval: Int
) : BukkitRunnable() {
companion object {
const val DAY_END = 12000
val NORMAL_MINECRAFT_DAY = Duration.ofSeconds(600)
}
override fun run() {
for (world in plugin.server.worlds) {
if (world.time <= DAY_END) {
world.fullTime += ((NORMAL_MINECRAFT_DAY.toSeconds().toDouble() / dayDuration.toSeconds().toDouble()) * tickInterval.toDouble()).roundToInt()
} else {
world.fullTime += ((NORMAL_MINECRAFT_DAY.toSeconds().toDouble() / nightDuration.toSeconds().toDouble()) * tickInterval.toDouble()).roundToInt()
}
}
}
} | apache-2.0 | d9146bed26a1a6b0b6b2f286bcc560e2 | 33.826087 | 159 | 0.693941 | 4.338753 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/androidTest/kotlin/com/github/kittinunf/reactiveandroid/widget/RatingBarPropertyTest.kt | 1 | 2188 | package com.github.kittinunf.reactiveandroid.widget
import android.support.test.InstrumentationRegistry
import android.support.test.annotation.UiThreadTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import com.github.kittinunf.reactiveandroid.reactive.bindTo
import com.github.kittinunf.reactiveandroid.scheduler.AndroidThreadScheduler
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RatingBarPropertyTest {
@Rule
@JvmField
val activityRule = ActivityTestRule(RatingBarTestActivity::class.java)
val instrumentation = InstrumentationRegistry.getInstrumentation()
private val context = InstrumentationRegistry.getContext()
companion object {
@BeforeClass
@JvmStatic
fun setUp() {
AndroidThreadScheduler.main = Schedulers.trampoline()
}
}
@Test
@UiThreadTest
fun testNumStars() {
val ratingBar = activityRule.activity.ratingBar
val numStars = ratingBar.rx_numStars
Observable.just(10).bindTo(numStars)
assertThat(ratingBar.numStars, equalTo(10))
numStars.bindTo(Observable.just(5))
assertThat(ratingBar.numStars, equalTo(5))
}
@Test
@UiThreadTest
fun testRating() {
val ratingBar = activityRule.activity.ratingBar
val rating = ratingBar.rx_rating
Observable.just(1.0f).bindTo(rating)
assertThat(ratingBar.rating, equalTo(1.0f))
rating.bindTo(Observable.just(5.0f))
assertThat(ratingBar.rating, equalTo(5.0f))
}
@Test
@UiThreadTest
fun testStepSize() {
val ratingBar = activityRule.activity.ratingBar
val steps = ratingBar.rx_stepSize
Observable.just(1.0f).bindTo(steps)
assertThat(ratingBar.stepSize, equalTo(1.0f))
steps.bindTo(Observable.just(0.5f))
assertThat(ratingBar.stepSize, equalTo(0.5f))
}
}
| mit | c530e052404a4ae6d75958a4729b7ca3 | 27.789474 | 76 | 0.723949 | 4.456212 | false | true | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/generics/kotlin/test7/Test1.kt | 1 | 1627 | package com.zj.example.kotlin.shengshiyuan.helloworld.generics.kotlin.test7
/**
* 星投影
*
* Created by zhengjiong
* date: 2018/2/26 21:00
*/
/**
* star projection(星投影)
*
* 1.Star<out T>: 如果T的上界是TUpper, 那么Star<*>就相当于Star<out TUpper?>, 这表示当T的类型未知时,你
* 可以从Star<*>当中安全的读取TUpper类型的值.
*
* 2.Star<in T>: Star<*>就相当于Star<in Nothing>, 这表示你无法向其中写入任何值
*
* 3.Star<T>: 如果T的上界为TUpper, 那么Star<*>就相当于读取时的Star<out TUpper?>以及
* 写入时的Star<in Nothing>
*
*/
class Star1<out T>(private val t: T) {
fun getValue(): T {
return t
}
}
class Star2<in T> {
fun setValue(t: T) {
}
}
class Star3<T>(private var t: T) {
fun getValue(): T {
return t
}
fun setValue(t: T) {
this.t = t
}
}
fun main(vararg args: String) {
val star1 = Star1<Number>(1)
val star2: Star1<*> = star1 //Star1<*>相当于Star1<out Number>
star2.getValue() //success, 看上面的结论1
val star3 = Star2<String>()
val star4: Star2<*> = star3 //Star2<*>等价于Star2<in Nothing>
//star4.setValue("abc") //error, 看上面结论2
val star5 = Star3<String>("star5")
val star6: Star3<*> = star5 //等价于 Star3<out String>
star6.getValue() //success, 看上面结论3
//star6.setValue("star6") //error, 看上面结论3
val list:MutableList<*> = mutableListOf("a", "b", "c")
println(list[0]) //success, 看上面结论3
//list[0] = "d" //error, 看上面结论3
} | mit | 39a429e35516c098f4bbb94dd12d703f | 20.59375 | 78 | 0.598841 | 2.590994 | false | false | false | false |
googlecodelabs/android-workmanager | app/src/main/java/com/example/background/workers/CleanupWorker.kt | 1 | 2113 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.background.workers
import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.example.background.OUTPUT_PATH
import java.io.File
/**
* Cleans up temporary files generated during blurring process
*/
private const val TAG = "CleanupWorker"
class CleanupWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
override fun doWork(): Result {
// Makes a notification when the work starts and slows down the work so that
// it's easier to see each WorkRequest start, even on emulated devices
makeStatusNotification("Cleaning up old temporary files", applicationContext)
sleep()
return try {
val outputDirectory = File(applicationContext.filesDir, OUTPUT_PATH)
if (outputDirectory.exists()) {
val entries = outputDirectory.listFiles()
if (entries != null) {
for (entry in entries) {
val name = entry.name
if (name.isNotEmpty() && name.endsWith(".png")) {
val deleted = entry.delete()
Log.i(TAG, "Deleted $name - $deleted")
}
}
}
}
Result.success()
} catch (exception: Exception) {
exception.printStackTrace()
Result.failure()
}
}
}
| apache-2.0 | ed5b8b19a5ef990c0a659289558ae965 | 35.431034 | 85 | 0.627544 | 4.791383 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/fragments/PersonsListFragment.kt | 1 | 3809 | package be.digitalia.fosdem.fragments
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import be.digitalia.fosdem.R
import be.digitalia.fosdem.activities.PersonInfoActivity
import be.digitalia.fosdem.adapters.createSimpleItemCallback
import be.digitalia.fosdem.model.Person
import be.digitalia.fosdem.utils.launchAndRepeatOnLifecycle
import be.digitalia.fosdem.viewmodels.PersonsViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
@AndroidEntryPoint
class PersonsListFragment : Fragment(R.layout.recyclerview_fastscroll) {
private val viewModel: PersonsViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = PersonsAdapter()
val holder = RecyclerViewViewHolder(view).apply {
recyclerView.apply {
layoutManager = LinearLayoutManager(context)
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
}
setAdapter(adapter)
emptyText = getString(R.string.no_data)
isProgressBarVisible = true
}
viewLifecycleOwner.lifecycleScope.launch {
adapter.loadStateFlow.first { it.refresh !is LoadState.Loading }
holder.isProgressBarVisible = false
}
viewLifecycleOwner.launchAndRepeatOnLifecycle {
viewModel.persons.collectLatest { pagingData ->
adapter.submitData(pagingData)
}
}
}
private class PersonsAdapter : PagingDataAdapter<Person, PersonViewHolder>(DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PersonViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.simple_list_item_1_material, parent, false)
return PersonViewHolder(view)
}
override fun onBindViewHolder(holder: PersonViewHolder, position: Int) {
val person = getItem(position)
if (person == null) {
holder.clear()
} else {
holder.bind(person)
}
}
companion object {
private val DIFF_CALLBACK: DiffUtil.ItemCallback<Person> = createSimpleItemCallback { it.id }
}
}
private class PersonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val textView: TextView = itemView.findViewById(android.R.id.text1)
var person: Person? = null
init {
itemView.setOnClickListener(this)
}
fun clear() {
person = null
textView.text = null
}
fun bind(person: Person) {
this.person = person
textView.text = person.name
}
override fun onClick(view: View) {
person?.let {
val context = view.context
val intent = Intent(context, PersonInfoActivity::class.java)
.putExtra(PersonInfoActivity.EXTRA_PERSON, it)
context.startActivity(intent)
}
}
}
} | apache-2.0 | 75ea799222be59a6c278a9aa80a10b2a | 33.954128 | 119 | 0.683907 | 5.161247 | false | false | false | false |
sav007/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/BuilderTypeSpecBuilder.kt | 1 | 3945 | package com.apollographql.apollo.compiler
import com.apollographql.apollo.compiler.ir.TypeDeclaration
import com.squareup.javapoet.*
import javax.lang.model.element.Modifier
class BuilderTypeSpecBuilder(
val targetObjectClassName: ClassName,
val fields: List<Pair<String, TypeName>>,
val fieldDefaultValues: Map<String, Any?>,
val fieldJavaDocs: Map<String, String>,
val typeDeclarations: List<TypeDeclaration>
) {
fun build(): TypeSpec {
return TypeSpec.classBuilder(builderClassName)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addBuilderFields()
.addMethod(MethodSpec.constructorBuilder().build())
.addBuilderMethods()
.addBuilderBuildMethod()
.build()
}
private fun TypeSpec.Builder.addBuilderFields(): TypeSpec.Builder =
addFields(fields.map {
val fieldName = it.first
val fieldType = it.second
val defaultValue = fieldDefaultValues[fieldName]?.let {
(it as? Number)?.castTo(fieldType.withoutAnnotations()) ?: it
}
val initializerCode = defaultValue?.let {
if (fieldType.isEnum(typeDeclarations))
CodeBlock.of("\$T.\$L", fieldType.withoutAnnotations(), defaultValue)
else
CodeBlock.of("\$L", defaultValue)
} ?: CodeBlock.of("")
FieldSpec.builder(fieldType, fieldName)
.addModifiers(Modifier.PRIVATE)
.initializer(initializerCode)
.build()
})
private fun TypeSpec.Builder.addBuilderMethods(): TypeSpec.Builder =
addMethods(fields.map {
val fieldName = it.first
val fieldType = it.second
val javaDoc = fieldJavaDocs[fieldName]
MethodSpec.methodBuilder(fieldName)
.addModifiers(Modifier.PUBLIC)
.addParameter(ParameterSpec.builder(fieldType, fieldName).build())
.let {
if (!javaDoc.isNullOrBlank())
it.addJavadoc(CodeBlock.of("\$L\n", javaDoc))
else
it
}
.returns(builderClassName)
.addStatement("this.\$L = \$L", fieldName, fieldName)
.addStatement("return this")
.build()
})
private fun TypeSpec.Builder.addBuilderBuildMethod(): TypeSpec.Builder {
val validationCodeBuilder = fields.filter {
val fieldType = it.second
!fieldType.isPrimitive && fieldType.annotations.contains(Annotations.NONNULL)
}.map {
val fieldName = it.first
CodeBlock.of("if (\$L == null) throw new \$T(\$S);\n", fieldName,
ClassNames.ILLEGAL_STATE_EXCEPTION, "$fieldName can't be null")
}.fold(CodeBlock.builder(), CodeBlock.Builder::add)
return addMethod(MethodSpec
.methodBuilder("build")
.addModifiers(Modifier.PUBLIC)
.returns(targetObjectClassName)
.addCode(validationCodeBuilder.build())
.addStatement("return new \$T\$L", targetObjectClassName,
fields.map { it.first }.joinToString(prefix = "(", separator = ", ", postfix = ")"))
.build())
}
companion object {
private val builderClassName = ClassName.get("", "Builder")
fun builderFactoryMethod(): MethodSpec =
MethodSpec
.methodBuilder("builder")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(builderClassName)
.addStatement("return new \$T()", builderClassName)
.build()
private fun Number.castTo(type: TypeName) =
if (type == TypeName.INT || type == TypeName.INT.box()) {
toInt()
} else if (type == TypeName.FLOAT || type == TypeName.FLOAT.box()) {
toDouble()
} else {
this
}
private fun TypeName.isEnum(typeDeclarations: List<TypeDeclaration>) =
((this is ClassName) && typeDeclarations.count { it.kind == "EnumType" && it.name == simpleName() } > 0)
}
}
| mit | f7845fbfb80323b78f14cccea25267bb | 36.216981 | 112 | 0.624842 | 4.724551 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hil/psi/ILSelectFromScopeReferenceProvider.kt | 1 | 4572 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hil.psi
import com.intellij.codeInspection.LocalQuickFixProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.util.ProcessingContext
import org.intellij.plugins.hcl.psi.HCLElement
import org.intellij.plugins.hcl.terraform.config.codeinsight.ModelHelper
import org.intellij.plugins.hcl.terraform.config.model.getTerraformModule
import org.intellij.plugins.hil.codeinsight.AddVariableFix
import org.intellij.plugins.hil.psi.impl.ILVariableMixin
import org.intellij.plugins.hil.psi.impl.getHCLHost
object ILSelectFromScopeReferenceProvider : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<out PsiReference> {
return getReferencesByElement(element)
}
fun getReferencesByElement(element: PsiElement): Array<out PsiReference> {
if (element !is ILVariableMixin) return PsiReference.EMPTY_ARRAY
val host = element.getHCLHost() ?: return PsiReference.EMPTY_ARRAY
val parent = element.parent as? ILSelectExpression ?: return PsiReference.EMPTY_ARRAY
val from = parent.from as? ILVariable ?: return PsiReference.EMPTY_ARRAY
if (from === element) return PsiReference.EMPTY_ARRAY
when (from.name) {
"var" -> {
return arrayOf(VariableReference(element))
}
"count" -> {
return arrayOf(HCLElementLazyReference(from, true) { _, _ ->
listOfNotNull(
getResource(this.element)?.`object`?.findProperty("count"),
getDataSource(this.element)?.`object`?.findProperty("count")
)
})
}
"self" -> {
return arrayOf(HCLElementLazyReference(element, false) { _, fake ->
val name = this.element.name
val resource = getProvisionerResource(this.element) ?: return@HCLElementLazyReference emptyList()
val prop = resource.`object`?.findProperty(name)
if (prop != null) return@HCLElementLazyReference listOf(prop)
val blocks = resource.`object`?.blockList?.filter { it.name == name }
if (blocks != null && blocks.isNotEmpty()) return@HCLElementLazyReference blocks.map { it.nameIdentifier as HCLElement }
if (fake) {
val properties = ModelHelper.getResourceProperties(resource)
for (p in properties) {
if (p.name == name) {
return@HCLElementLazyReference listOf(FakeHCLProperty(p.name, resource))
}
}
}
emptyList()
})
}
"path" -> {
// TODO: Resolve 'cwd' and 'root' paths
if (element.name == "module") {
@Suppress("USELESS_CAST")
val file = (host as HCLElement).containingFile.originalFile
return arrayOf(PsiReferenceBase.Immediate<ILVariable>(element, true, file.containingDirectory ?: file))
}
}
"module" -> {
return arrayOf(HCLElementLazyReference(element, false) { _, _ ->
this.element.getHCLHost()?.getTerraformModule()?.findModules(this.element.name)?.map { it.nameIdentifier as HCLElement } ?: emptyList()
})
}
"local" -> {
return arrayOf(HCLElementLazyReference(element, false) { _, _ ->
this.element.getHCLHost()?.getTerraformModule()?.getAllLocals()
?.filter { this.element.name == it.first }?.map { it.second.nameElement }
?: emptyList()
})
}
}
return PsiReference.EMPTY_ARRAY
}
class VariableReference(element: ILVariableMixin) : HCLElementLazyReference<ILVariableMixin>(element, false, { _, _ ->
listOfNotNull(this.element.getHCLHost()?.getTerraformModule()?.findVariable(this.element.name)?.second?.nameIdentifier as HCLElement?)
}), LocalQuickFixProvider {
override fun getQuickFixes() = arrayOf(AddVariableFix(this.element))
}
}
| apache-2.0 | bc3271b08035c4ab96eb8df77e0da5aa | 41.728972 | 145 | 0.684602 | 4.425944 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.