repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
adgvcxz/Diycode | app/src/main/java/com/adgvcxz/diycode/ui/topic/TopicDetailViewModel.kt | 1 | 1885 | package com.adgvcxz.diycode.ui.topic
import com.adgvcxz.diycode.R
import com.adgvcxz.diycode.binding.base.BaseViewModel
import com.adgvcxz.diycode.binding.recycler.RefreshRecyclerViewModel
import com.adgvcxz.diycode.net.ApiService
import com.adgvcxz.diycode.ui.base.BaseActivityViewModel
import com.adgvcxz.diycode.util.extensions.formatList
import com.adgvcxz.diycode.util.extensions.singleToList
import com.adgvcxz.diycode.util.extensions.string
import io.reactivex.Observable
import javax.inject.Inject
/**
* zhaowei
* Created by zhaowei on 2017/2/27.
*/
class TopicDetailViewModel @Inject constructor(private val apiService: ApiService) : BaseActivityViewModel() {
val listViewModel = TopicDetailListViewModel()
var id: Int = 0
set(value) {
field = value
listViewModel.refresh.set(true)
}
init {
title.set(R.string.topic.string)
backArrow.set(true)
}
override fun contentId(): Int = R.layout.activity_topic_detail
inner class TopicDetailListViewModel : RefreshRecyclerViewModel<BaseViewModel>() {
init {
loadAll.set(false)
loadMore.set(true)
}
override fun request(offset: Int): Observable<List<BaseViewModel>> {
if (offset == 0) {
return apiService.getTopicDetail(id)
.singleToList { TopicBodyViewModel(it.body) }
.compose(httpScheduler<List<BaseViewModel>>())
} else {
return apiService.getTopicReplies(id = id, offset = offset - 1)
.formatList(::TopicReplyViewModel)
.compose(httpScheduler<List<BaseViewModel>>())
}
}
override fun updateLoadAll(it: List<BaseViewModel>) {
loadAll.set(offset > 0 && it.size < ApiService.Limit)
}
}
} | apache-2.0 | 607ebe275c65bc9656ca3701949fc832 | 30.433333 | 110 | 0.649867 | 4.498807 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/helper/PrefGetter.kt | 2 | 6255 | package ru.fantlab.android.helper
import android.content.Context
import android.content.res.Resources
import com.github.kittinunf.fuel.core.FuelManager
import ru.fantlab.android.App
import ru.fantlab.android.BuildConfig
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.User
import ru.fantlab.android.provider.rest.DataManager
object PrefGetter {
val RED = 1
val PINK = 2
val PURPLE = 3
val DEEP_PURPLE = 4
val INDIGO = 5
val BLUE = 6
val LIGHT_BLUE = 7
val CYAN = 8
val TEAL = 9
val GREEN = 10
val LIGHT_GREEN = 11
val LIME = 12
val YELLOW = 13
val AMBER = 14
val ORANGE = 15
val DEEP_ORANGE = 16
val LIGHT = 1
val DARK = 2
val AMLOD = 3
val BLUISH = 4
val MID_NIGHT_BLUE = 5
private const val TOKEN = "token"
private const val REFRESH_TOKEN = "refresh_token"
private const val WHATS_NEW_VERSION = "whats_new"
private const val APP_LANGUAGE = "app_language"
private const val NAV_DRAWER_GUIDE = "nav_drawer_guide"
private const val LOGGED_USER = "logged_user"
private const val APP_FONT_SCALE = "app_font_scale"
fun setLoggedUser(user: User) {
PrefHelper[LOGGED_USER] = DataManager.gson.toJson(user)
}
fun getLoggedUser(): User? {
val user = PrefHelper.getString(LOGGED_USER)
return DataManager.gson.fromJson(user, User::class.java)
}
fun getSessionUserId(): Int {
return FantlabHelper.currentUserId
}
fun setSessionUserId() {
FantlabHelper.currentUserId = getLoggedUser()?.id ?: -1
}
fun clearLoggedUser() {
PrefHelper.clearKey(LOGGED_USER)
}
fun setProceedWithoutLogin(proceed: Boolean) {
PrefHelper["proceed_without_login"] = proceed
}
fun proceedWithoutLogin(): Boolean = PrefHelper.getBoolean("proceed_without_login")
fun setToken(token: String?) {
PrefHelper[TOKEN] = token
FuelManager.instance.baseHeaders = mapOf(
"User-Agent" to "FantLab for Android v${BuildConfig.VERSION_NAME}",
"X-Session" to (token ?: "")
)
}
fun getToken(): String? {
return PrefHelper.getString(TOKEN)
}
fun setRefreshToken(refreshToken: String?) {
PrefHelper[REFRESH_TOKEN] = refreshToken
}
fun getRefreshToken(): String? {
return PrefHelper.getString(REFRESH_TOKEN)
}
fun getThemeType(): Int {
return getThemeType(App.instance.resources)
}
fun getThemeType(context: Context): Int = getThemeType(context.resources)
fun getThemeType(resources: Resources): Int {
val appTheme = PrefHelper.getString("appTheme")
if (!InputHelper.isEmpty(appTheme)) {
when {
appTheme.equals(resources.getString(R.string.dark_theme_mode)) -> return DARK
appTheme.equals(resources.getString(R.string.light_theme_mode)) -> return LIGHT
appTheme.equals(resources.getString(R.string.amlod_theme_mode)) -> return AMLOD
appTheme.equals(resources.getString(R.string.mid_night_blue_theme_mode)) -> return MID_NIGHT_BLUE
appTheme.equals(resources.getString(R.string.bluish_theme)) -> return BLUISH
}
}
return LIGHT
}
fun getThemeColor(context: Context): Int = getThemeColor(context.resources)
private fun getThemeColor(resources: Resources): Int {
val appColor = PrefHelper.getString("appColor")
return getThemeColor(resources, appColor)
}
fun getThemeColor(resources: Resources, appColor: String?): Int {
if (!InputHelper.isEmpty(appColor)) {
if (appColor.equals(resources.getString(R.string.red_theme_mode), ignoreCase = true))
return RED
if (appColor.equals(resources.getString(R.string.pink_theme_mode), ignoreCase = true))
return PINK.toInt()
if (appColor.equals(resources.getString(R.string.purple_theme_mode), ignoreCase = true))
return PURPLE
if (appColor.equals(resources.getString(R.string.deep_purple_theme_mode), ignoreCase = true))
return DEEP_PURPLE
if (appColor.equals(resources.getString(R.string.indigo_theme_mode), ignoreCase = true))
return INDIGO
if (appColor.equals(resources.getString(R.string.blue_theme_mode), ignoreCase = true))
return BLUE
if (appColor.equals(resources.getString(R.string.light_blue_theme_mode), ignoreCase = true))
return LIGHT_BLUE
if (appColor.equals(resources.getString(R.string.cyan_theme_mode), ignoreCase = true))
return CYAN
if (appColor.equals(resources.getString(R.string.teal_theme_mode), ignoreCase = true))
return TEAL
if (appColor.equals(resources.getString(R.string.green_theme_mode), ignoreCase = true))
return GREEN
if (appColor.equals(resources.getString(R.string.light_green_theme_mode), ignoreCase = true))
return LIGHT_GREEN
if (appColor.equals(resources.getString(R.string.lime_theme_mode), ignoreCase = true))
return LIME
if (appColor.equals(resources.getString(R.string.yellow_theme_mode), ignoreCase = true))
return YELLOW
if (appColor.equals(resources.getString(R.string.amber_theme_mode), ignoreCase = true))
return AMBER
if (appColor.equals(resources.getString(R.string.orange_theme_mode), ignoreCase = true))
return ORANGE
if (appColor.equals(resources.getString(R.string.deep_orange_theme_mode), ignoreCase = true))
return DEEP_ORANGE
}
return BLUE
}
fun getAppLanguage(): String {
val appLanguage = PrefHelper.getString(APP_LANGUAGE)
return appLanguage ?: "ru"
}
fun setAppLanguage(language: String?) {
PrefHelper[APP_LANGUAGE] = language ?: "ru"
}
fun showWhatsNew(): Boolean {
return PrefHelper.getInt(WHATS_NEW_VERSION) != BuildConfig.VERSION_CODE
}
fun isNavDrawerHintShowed(): Boolean {
val isShowed = PrefHelper.getBoolean(NAV_DRAWER_GUIDE)
PrefHelper[NAV_DRAWER_GUIDE] = true
return isShowed
}
fun isTwiceBackButtonEnabled(): Boolean {
return PrefHelper.getBoolean("back_button")
}
fun isNavBarTintingEnabled(): Boolean {
return PrefHelper.getBoolean("navigation_color")
}
fun isRVAnimationEnabled(): Boolean {
return PrefHelper.getBoolean("recylerViewAnimation")
}
fun isForumExtended(): Boolean {
return PrefHelper.getBoolean("forumExtended")
}
fun getTopicMessagesOrder(): String {
val order = PrefHelper.getString("topicOrder")
return order ?: "0"
}
fun setAppFontScale(value: Float) {
PrefHelper[APP_FONT_SCALE] = value
}
fun getAppFontScale(): Float {
val fontScale = PrefHelper.getFloat(APP_FONT_SCALE)
return if (fontScale == 0f) 1f else fontScale
}
}
| gpl-3.0 | fd07d1609d10145cf0d694f34eb8a493 | 29.512195 | 101 | 0.734452 | 3.355687 | false | false | false | false |
teobaranga/T-Tasks | t-tasks/src/main/java/com/teo/ttasks/jobs/TaskCreateJob.kt | 1 | 4780 | package com.teo.ttasks.jobs
import com.evernote.android.job.JobManager
import com.evernote.android.job.JobRequest
import com.evernote.android.job.util.support.PersistableBundleCompat
import com.google.firebase.database.FirebaseDatabase
import com.teo.ttasks.api.TasksApi
import com.teo.ttasks.data.local.TaskFields
import com.teo.ttasks.data.local.WidgetHelper
import com.teo.ttasks.data.model.Task
import com.teo.ttasks.data.remote.TasksHelper
import com.teo.ttasks.util.FirebaseUtil.getTasksDatabase
import com.teo.ttasks.util.FirebaseUtil.saveReminder
import com.teo.ttasks.util.NotificationHelper
import io.realm.Realm
import timber.log.Timber
import java.util.concurrent.TimeUnit
class TaskCreateJob(
@Transient private val tasksHelper: TasksHelper,
@Transient private val widgetHelper: WidgetHelper,
@Transient private val notificationHelper: NotificationHelper,
@Transient private val tasksApi: TasksApi
) : RealmJob() {
companion object {
const val TAG = "CREATE_TASK"
const val EXTRA_LOCAL_ID = "localId"
const val EXTRA_TASK_LIST_ID = "taskListId"
fun schedule(localTaskId: String, taskListId: String, taskFields: TaskFields? = null) {
JobManager.instance().getAllJobRequestsForTag(TAG)
.forEach {
if (it.extras[EXTRA_LOCAL_ID] as String == localTaskId) {
Timber.v("Create Task job already exists for %s, ignoring...", localTaskId)
return
}
}
val extras = PersistableBundleCompat().apply {
putString(EXTRA_LOCAL_ID, localTaskId)
putString(EXTRA_TASK_LIST_ID, taskListId)
taskFields?.forEach {
putString(it.key, it.value)
}
}
JobRequest.Builder(TAG)
.setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.EXPONENTIAL)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setExtras(extras)
.setRequirementsEnforced(true)
.setUpdateCurrent(true)
.setExecutionWindow(1, TimeUnit.DAYS.toMillis(1))
.build()
.schedule()
}
}
override fun onRunJob(params: Params, realm: Realm): Result {
// Extract params
val extras = params.extras
val localTaskId = extras[EXTRA_LOCAL_ID] as String
val taskListId = extras[EXTRA_TASK_LIST_ID] as String
val taskFields = TaskFields.fromBundle(extras)
// Use an unmanaged task so that it can be serialized by GSON
val taskManaged = tasksHelper.getTask(localTaskId, realm, false)
val localTask = taskManaged?.let { realm.copyFromRealm(it) }
// Local task was not found, it was probably deleted, no point in continuing
if (localTask == null) {
return Result.SUCCESS
}
Timber.v("Creating task: $localTask")
val onlineTask: Task
try {
onlineTask =
if (taskFields != null) {
tasksApi.createTask(taskListId, taskFields).blockingGet()
} else {
tasksApi.createTask(taskListId, localTask).blockingGet()
}
} catch (ex: Exception) {
// Handle failure
Timber.e("Failed to create the new task, will retry...")
return Result.RESCHEDULE
}
// Copy the custom attributes, since they might have changed in the meantime
onlineTask.copyCustomAttributes(localTask)
onlineTask.taskListId = taskListId
onlineTask.synced = true
// Update the local task with the full information and delete the old task
realm.executeTransaction {
it.insertOrUpdate(onlineTask)
taskManaged.deleteFromRealm()
}
// Update the widget
widgetHelper.updateWidgets(taskListId)
// Update the previous notification with the correct task ID
// as long the notification hasn't been dismissed
if (!onlineTask.notificationDismissed) {
notificationHelper.scheduleTaskNotification(onlineTask, onlineTask.notificationId)
}
// Save the reminder online
val onlineTaskId = onlineTask.id
onlineTask.reminder?.let {
val tasksDatabase = FirebaseDatabase.getInstance().getTasksDatabase()
tasksDatabase.saveReminder(onlineTaskId, it)
}
Timber.d("Create Task job success - %s", onlineTaskId)
return Result.SUCCESS
}
override fun onCancel() {
Timber.e("Create Task job cancelled")
// throwable?.let { Timber.e(it.toString()) }
}
}
| apache-2.0 | 494d6af096a95e196ccb0d9761651670 | 37.548387 | 99 | 0.6341 | 4.704724 | false | false | false | false |
java-opengl-labs/learn-OpenGL | src/main/kotlin/learnOpenGL/d_advancedOpenGL/1.1 depth testing.kt | 1 | 5413 | package learnOpenGL.d_advancedOpenGL
/**
* Created by elect on 06/05/2017.
*/
import gli_.gli
import glm_.func.rad
import glm_.glm
import glm_.mat4x4.Mat4
import gln.draw.glDrawArrays
import gln.get
import gln.glClearColor
import gln.glf.glf
import gln.glf.semantic
import gln.program.usingProgram
import gln.set
import gln.texture.glTexImage2D
import gln.uniform.glUniform
import gln.vertexArray.glBindVertexArray
import gln.vertexArray.glEnableVertexAttribArray
import gln.vertexArray.glVertexAttribPointer
import learnOpenGL.a_gettingStarted.end
import learnOpenGL.a_gettingStarted.swapAndPoll
import learnOpenGL.a_gettingStarted.verticesCube
import learnOpenGL.b_lighting.camera
import learnOpenGL.b_lighting.clearColor0
import learnOpenGL.b_lighting.initWindow0
import learnOpenGL.b_lighting.processFrame
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL13.GL_TEXTURE0
import org.lwjgl.opengl.GL13.glActiveTexture
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.glGetUniformLocation
import org.lwjgl.opengl.GL30.*
import uno.buffer.destroyBuf
import uno.buffer.intBufferBig
import uno.glsl.Program
import uno.glsl.glDeletePrograms
import uno.glsl.glUseProgram
import uno.kotlin.uri
fun main(args: Array<String>) {
with(DepthTesting()) {
run()
end()
}
}
val planeVertices = floatArrayOf(
/* positions | texture Coords (note we set these higher than 1 (together with GL_REPEAT as texture
wrapping mode). this will cause the floor texture to repeat) */
+5f, -0.5f, +5f, 2f, 0f,
-5f, -0.5f, +5f, 0f, 0f,
-5f, -0.5f, -5f, 0f, 2f,
+5f, -0.5f, +5f, 2f, 0f,
-5f, -0.5f, -5f, 0f, 2f,
+5f, -0.5f, -5f, 2f, 2f)
private class DepthTesting {
val window = initWindow0("Depth Testing")
val program = ProgramA()
enum class Object { Cube, Plane }
val vao = intBufferBig<Object>()
val vbo = intBufferBig<Object>()
val tex = intBufferBig<Object>()
inner class ProgramA : Program("shaders/d/_1_1", "depth-testing.vert", "depth-testing.frag") {
val model = glGetUniformLocation(name, "model")
val view = glGetUniformLocation(name, "view")
val proj = glGetUniformLocation(name, "projection")
init {
usingProgram(name) { "texture1".unit = semantic.sampler.DIFFUSE }
}
}
init {
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_ALWAYS) // always pass the depth test (same effect as glDisable(GL_DEPTH_TEST))
glGenVertexArrays(vao)
glGenBuffers(vbo)
for (i in Object.values()) {
glBindVertexArray(vao[i])
glBindBuffer(GL_ARRAY_BUFFER, vbo[i])
glBufferData(GL_ARRAY_BUFFER, if (i == Object.Cube) verticesCube else planeVertices, GL_STATIC_DRAW)
glEnableVertexAttribArray(glf.pos3_tc2)
glVertexAttribPointer(glf.pos3_tc2)
glBindVertexArray()
}
// load textures
tex[Object.Cube] = loadTexture("textures/marble.jpg")
tex[Object.Plane] = loadTexture("textures/metal.png")
}
fun loadTexture(path: String): Int {
val textureID = glGenTextures()
val texture = gli.load(path.uri)
val format = gli.gl.translate(texture.format, texture.swizzles)
val extent = texture.extent()
glBindTexture(GL_TEXTURE_2D, textureID)
glTexImage2D(format.internal, extent.x, extent.y, format.external, format.type, texture.data())
glGenerateMipmap(GL_TEXTURE_2D)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
texture.dispose()
return textureID
}
fun run() {
while (window.open) {
window.processFrame()
// render
glClearColor(clearColor0)
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
glUseProgram(program)
var model = Mat4()
val view = camera.viewMatrix
val projection = glm.perspective(camera.zoom.rad, window.aspect, 0.1f, 100f)
glUniform(program.proj, projection)
glUniform(program.view, view)
// cubes
glBindVertexArray(vao[Object.Cube])
glActiveTexture(GL_TEXTURE0 + semantic.sampler.DIFFUSE)
glBindTexture(GL_TEXTURE_2D, tex[Object.Cube])
model = model.translate(-1f, 0f, -1f)
glUniform(program.model, model)
glDrawArrays(GL_TRIANGLES, 36)
model = Mat4().translate(2f, 0f, 0f)
glUniform(program.model, model)
glDrawArrays(GL_TRIANGLES, 36)
// floor
glBindVertexArray(vao[Object.Plane])
glBindTexture(GL_TEXTURE_2D, tex[Object.Plane])
glUniform(program.model, model)
glDrawArrays(GL_TRIANGLES, 6)
glBindVertexArray()
window.swapAndPoll()
}
}
fun end() {
glDeletePrograms(program)
glDeleteVertexArrays(vao)
glDeleteBuffers(vbo)
glDeleteTextures(tex)
destroyBuf(vao, vbo, tex)
window.end()
}
} | mit | eb621f75101dcf5d416445bb26c38308 | 28.911602 | 114 | 0.644929 | 3.811972 | false | false | false | false |
lydia-schiff/hella-renderscript | app/src/main/java/com/lydiaschiff/hellaparallel/renderers/TrailsRenderer.kt | 1 | 1601 | package com.lydiaschiff.hellaparallel.renderers
import android.renderscript.Allocation
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlend
import androidx.annotation.RequiresApi
import com.lydiaschiff.hella.RsRenderer
import com.lydiaschiff.hella.RsUtil.createMatchingAlloc
import com.lydiaschiff.hella.renderer.ScriptC_set_alpha
/**
* Created by lydia on 10/17/17.
*/
@RequiresApi(18)
class TrailsRenderer : RsRenderer {
private var blendScript: ScriptIntrinsicBlend? = null
private var setAlphaScript: ScriptC_set_alpha? = null
private var last: Allocation? = null
override fun renderFrame(rs: RenderScript, inAlloc: Allocation, outAlloc: Allocation) {
if (blendScript == null) {
blendScript = ScriptIntrinsicBlend.create(rs, inAlloc.element)
setAlphaScript = ScriptC_set_alpha(rs)
last = createMatchingAlloc(rs, inAlloc).apply { copyFrom(inAlloc) }
}
outAlloc.copyFrom(last)
// setting the alpha here is just to trick ScriptIntrinsicBlend to do linear
// interpolation for us
// update: that is tricky past lydia! I dig it.
setAlphaScript!!._alpha_value = 200.toShort()
setAlphaScript!!.forEach_filter(outAlloc, outAlloc)
setAlphaScript!!._alpha_value = 55.toShort()
setAlphaScript!!.forEach_filter(inAlloc, inAlloc)
blendScript!!.forEachSrcAtop(inAlloc, outAlloc)
last!!.copyFrom(outAlloc)
}
override val name: String = "ScriptIntrinsicBlend (trails)"
override val canRenderInPlace = false
} | mit | 41713a5cf3aed46b92021808582a623f | 37.142857 | 91 | 0.721424 | 4.073791 | false | false | false | false |
echsylon/atlantis | library/lib/src/main/kotlin/com/echsylon/atlantis/request/Request.kt | 1 | 964 | package com.echsylon.atlantis.request
import com.echsylon.atlantis.header.Headers
import okio.Buffer
/**
* Describes an intercepted HTTP request from the client.
*
* @param verb The request method.
* @param path The full path to the requested resource.
* @param protocol The request protocol and version.
*/
data class Request(
val verb: String = "GET",
val path: String = "/",
val protocol: String = "HTTP/1.1"
) {
/**
* Holds all successfully paresed client request headers.
*/
val headers: Headers = Headers()
/**
* Holds the successfully read client request body. May be empty.
*/
var content: ByteArray = byteArrayOf()
/**
* Prints a pleasant and human readable string representation of the
* intercepted client request.
*/
override fun toString(): String {
return "$protocol $verb $path\n\t${headers.joinToString("\n\t")}\n\t${Buffer().write(content)}"
}
}
| apache-2.0 | 07b9613bc1c29399c3f2d551100bf4ed | 26.542857 | 103 | 0.654564 | 3.983471 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/course_list/ui/adapter/delegate/CourseListItemAdapterDelegate.kt | 1 | 7069 | package org.stepik.android.view.course_list.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.core.text.HtmlCompat
import androidx.core.text.buildSpannedString
import androidx.core.text.strikeThrough
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.item_course.view.*
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.ui.util.doOnGlobalLayout
import org.stepic.droid.util.DateTimeHelper
import org.stepik.android.domain.course.analytic.CourseCardSeenAnalyticEvent
import org.stepik.android.domain.course.analytic.batch.CourseCardSeenAnalyticBatchEvent
import org.stepik.android.domain.course.model.EnrollmentState
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper
import org.stepik.android.domain.course_payments.model.DefaultPromoCode
import org.stepik.android.view.course.mapper.DisplayPriceMapper
import org.stepik.android.view.course_list.ui.delegate.CoursePropertiesDelegate
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
class CourseListItemAdapterDelegate(
private val analytic: Analytic,
private val onItemClicked: (CourseListItem.Data) -> Unit,
private val onContinueCourseClicked: (CourseListItem.Data) -> Unit,
private val defaultPromoCodeMapper: DefaultPromoCodeMapper,
private val displayPriceMapper: DisplayPriceMapper,
private val isNeedExtraMargin: Boolean = false
) : AdapterDelegate<CourseListItem, DelegateViewHolder<CourseListItem>>() {
override fun isForViewType(position: Int, data: CourseListItem): Boolean =
data is CourseListItem.Data
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseListItem> {
val view = createView(parent, R.layout.item_course)
if (isNeedExtraMargin) {
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
leftMargin = view.resources.getDimensionPixelOffset(R.dimen.course_list_padding)
rightMargin = view.resources.getDimensionPixelOffset(R.dimen.course_list_padding)
}
}
return ViewHolder(view)
}
private inner class ViewHolder(root: View) : DelegateViewHolder<CourseListItem>(root) {
private val coursePropertiesDelegate = CoursePropertiesDelegate(root, root.coursePropertiesContainer as ViewGroup)
private val courseItemImage = root.courseItemImage
private val courseItemName = root.courseItemName
private val adaptiveCourseMarker = root.adaptiveCourseMarker
private val courseContinueButton = root.courseContinueButton
private val courseDescription = root.courseDescription
private val courseButtonSeparator = root.courseButtonSeparator
private val courseOldPrice = root.courseOldPrice
private val coursePrice = root.coursePrice
init {
root.setOnClickListener { (itemData as? CourseListItem.Data)?.let(onItemClicked) }
courseContinueButton.setOnClickListener { (itemData as? CourseListItem.Data)?.let(onContinueCourseClicked) }
}
override fun onBind(data: CourseListItem) {
data as CourseListItem.Data
Glide
.with(context)
.asBitmap()
.load(data.course.cover)
.placeholder(R.drawable.general_placeholder)
.fitCenter()
.into(courseItemImage)
courseItemName.text = data.course.title
val defaultPromoCode = defaultPromoCodeMapper.mapToDefaultPromoCode(data.course)
val mustShowDefaultPromoCode = defaultPromoCode != DefaultPromoCode.EMPTY &&
(defaultPromoCode.defaultPromoCodeExpireDate == null || defaultPromoCode.defaultPromoCodeExpireDate.time > DateTimeHelper.nowUtc())
val isEnrolled = data.course.enrollment != 0L
courseContinueButton.isVisible = isEnrolled
courseButtonSeparator.isVisible = isEnrolled
courseDescription.isVisible = !isEnrolled
if (!isEnrolled) {
courseDescription.text = HtmlCompat.fromHtml(data.course.summary ?: "", HtmlCompat.FROM_HTML_MODE_COMPACT).toString()
courseDescription.doOnGlobalLayout { it.post { it.maxLines = it.height / it.lineHeight } }
}
coursePrice.isVisible = !isEnrolled
val (@ColorRes textColor, displayPrice) = if (data.course.isPaid) {
if (data.courseStats.enrollmentState is EnrollmentState.NotEnrolledMobileTier) {
handleCoursePriceMobileTiers(data.courseStats.enrollmentState)
} else {
handleCoursePrice(data, defaultPromoCode)
}
} else {
R.color.color_overlay_green to context.resources.getString(R.string.course_list_free)
}
coursePrice.setTextColor(ContextCompat.getColor(context, textColor))
coursePrice.text = displayPrice
courseOldPrice.isVisible = mustShowDefaultPromoCode && !isEnrolled
courseOldPrice.text = buildSpannedString {
strikeThrough {
if (data.courseStats.enrollmentState is EnrollmentState.NotEnrolledMobileTier) {
append(data.courseStats.enrollmentState.standardLightSku.price)
} else {
append(data.course.displayPrice ?: "")
}
}
}
adaptiveCourseMarker.isVisible = data.isAdaptive
coursePropertiesDelegate.setStats(data)
analytic.report(CourseCardSeenAnalyticEvent(data.course.id, data.source))
analytic.report(CourseCardSeenAnalyticBatchEvent(data.course.id, data.source))
}
}
private fun handleCoursePrice(data: CourseListItem.Data, defaultPromoCode: DefaultPromoCode): Pair<Int, String?> =
if (defaultPromoCode != DefaultPromoCode.EMPTY && (defaultPromoCode.defaultPromoCodeExpireDate == null || defaultPromoCode.defaultPromoCodeExpireDate.time > DateTimeHelper.nowUtc())) {
R.color.color_overlay_red to displayPriceMapper.mapToDisplayPriceWithCurrency(data.course.currencyCode ?: "", defaultPromoCode.defaultPromoCodePrice)
} else {
R.color.color_overlay_violet to data.course.displayPrice
}
private fun handleCoursePriceMobileTiers(enrollmentState: EnrollmentState.NotEnrolledMobileTier?): Pair<Int, String?> =
if (enrollmentState?.promoLightSku != null) {
R.color.color_overlay_red to enrollmentState.promoLightSku.price
} else {
R.color.color_overlay_violet to enrollmentState?.standardLightSku?.price
}
} | apache-2.0 | 1d39eb9162c941276a707564afb4fd5a | 49.863309 | 192 | 0.711558 | 5.163623 | false | false | false | false |
midhunhk/random-contact | app/src/main/java/com/ae/apps/randomcontact/preferences/AppPreferences.kt | 1 | 1585 | package com.ae.apps.randomcontact.preferences
import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.ae.apps.randomcontact.utils.DEFAULT_CONTACT_GROUP
class AppPreferences {
companion object{
private const val PREF_KEY_SELECTED_CONTACT_GROUP = "pref_key_selected_contact_group"
const val PREF_KEY_VERSION_4_REDESIGN_MSG_SHOWN = "pref_key_version_4_redesign_msg_shown"
@Volatile private var instance:AppPreferences? = null
@Volatile private lateinit var preferences:SharedPreferences
fun getInstance(context: Context):AppPreferences =
instance?: synchronized(this){
preferences = PreferenceManager.getDefaultSharedPreferences(context)
instance ?: AppPreferences().also { instance = it }
}
}
/**
* Returns the selected contact group
*
* @return selected contact group id
*/
fun selectedContactGroup() = preferences.getString(
PREF_KEY_SELECTED_CONTACT_GROUP,
DEFAULT_CONTACT_GROUP)!!
/**
* Sets the selected contact group
*
* @param groupId groupId
*/
fun setSelectedContactGroup(groupId: String) = preferences.edit {
putString(PREF_KEY_SELECTED_CONTACT_GROUP, groupId)
}
fun setBooleanPref(key:String, value:Boolean) = preferences.edit{
putBoolean(key, value)
}
fun getBooleanPref(key:String, defaultValue:Boolean) = preferences.getBoolean(key, defaultValue)
} | apache-2.0 | 82e464c6d01a0e1a9b10e3698ba4d490 | 30.72 | 100 | 0.695899 | 4.620991 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/PullBow.kt | 1 | 1046 | package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import org.bukkit.entity.Arrow
import org.bukkit.entity.Player
import org.bukkit.event.entity.ProjectileHitEvent
/**
* Pulls the target toward you.
*
* @author SugarCaney
*/
open class PullBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.PULL,
canShootInProtectedRegions = true,
removeArrow = false,
description = "Pulls the target toward you."
) {
/**
* How hard to the bow pulls (quite magic value).
*/
val pullStrength = config.getDouble("$node.strength")
override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) {
val target = event.hitEntity ?: return
if (target == player) return
val direction = player.location.subtract(target.location).toVector().normalize()
target.velocity = direction.multiply(pullStrength)
}
} | gpl-3.0 | ffb0b9465cfe93fbb9d7ab4677c8da0e | 28.914286 | 88 | 0.702677 | 4.269388 | false | false | false | false |
ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/shadowmapper/gui/install/InstallDialog.kt | 1 | 6902 | package nl.shadowlink.tools.shadowmapper.gui.install
import nl.shadowlink.tools.shadowlib.utils.GameType
import nl.shadowlink.tools.shadowlib.utils.filechooser.FileChooserUtil.openFileChooser
import nl.shadowlink.tools.shadowlib.utils.filechooser.FileNameFilter
import nl.shadowlink.tools.shadowmapper.utils.GuiFunctions.centerWindow
import nl.shadowlink.tools.shadowmapper.utils.GuiFunctions.setLookAndFeel
import java.awt.Toolkit
import java.awt.event.ActionEvent
import java.awt.event.ItemEvent
import java.io.File
import javax.swing.*
import kotlin.collections.List
import java.awt.List as AwtList
/**
* @author Shadow-Link
*/
class InstallDialog(
onInstallSelectedListener: (install: Install) -> Unit
) : JDialog() {
private val installRepository = InstallRepository(IniInstallStorage())
private var selectedInstall: Install? = null
private var buttonOK = JButton()
private var buttonRemove = JButton()
private var buttonAddInstall = JButton()
private var image = JLabel()
private var listGames = AwtList()
/**
* Creates new form Select
*/
init {
setIconImage(Toolkit.getDefaultToolkit().createImage("icon.png"))
setLookAndFeel()
initComponents(onInstallSelectedListener)
this.centerWindow()
defaultCloseOperation = DISPOSE_ON_CLOSE
modalityType = ModalityType.APPLICATION_MODAL
installRepository.observeInstalls { installs: List<Install> ->
fillGameList(installs)
}
}
private fun fillGameList(installs: List<Install>) {
listGames.removeAll()
installs.forEach { install ->
val isValid = if (!install.isValid) " (Install not found)" else ""
listGames.add("${install.name}$isValid")
}
}
private fun initComponents(onInstallSelectedListener: (install: Install) -> Unit) {
title = "Select install"
isResizable = false
listGames.addItemListener { evt: ItemEvent -> listGamesItemStateChanged(evt) }
buttonOK.text = "Select"
buttonOK.isEnabled = false
buttonOK.addActionListener { e: ActionEvent? -> selectInstallButtonPressed(onInstallSelectedListener) }
buttonAddInstall.text = "Add Install"
buttonAddInstall.addActionListener { evt: ActionEvent -> addInstallButtonPressed(evt) }
image.icon = ImageIcon(javaClass.getResource("/Images/shadowmapper.png"))
buttonRemove.addActionListener { evt: ActionEvent -> removeInstallButtonPressed(evt) }
buttonRemove.text = "Remove install"
buttonRemove.isEnabled = false
val layout = GroupLayout(contentPane)
contentPane.layout = layout
layout.setHorizontalGroup(
layout
.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addContainerGap()
.addGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(
layout.createParallelGroup(
GroupLayout.Alignment.LEADING
)
.addGroup(
GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(buttonRemove)
.addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED
)
.addComponent(buttonAddInstall)
.addPreferredGap(
LayoutStyle.ComponentPlacement.UNRELATED
)
.addComponent(buttonOK)
)
.addComponent(image)
)
.addComponent(listGames, GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE.toInt())
).addContainerGap()
)
)
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
layout.createSequentialGroup()
.addComponent(image)
.addGap(1, 1, 1)
.addComponent(
listGames, GroupLayout.PREFERRED_SIZE, 196,
GroupLayout.PREFERRED_SIZE
)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(buttonAddInstall).addComponent(buttonOK).addComponent(buttonRemove)
)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt())
)
)
pack()
}
private fun removeInstallButtonPressed(evt: ActionEvent) {
selectedInstall?.let { installRepository.removeInstall(it) }
selectedInstall = null
buttonOK.isEnabled = false
buttonRemove.isEnabled = false
}
private fun selectInstallButtonPressed(onInstallSelectedListener: (install: Install) -> Unit) {
dispose()
selectedInstall?.let { onInstallSelectedListener(it) }
}
private fun addInstallButtonPressed(evt: ActionEvent) {
val file = openFileChooser(this, FileNameFilter(SUPPORTED_EXES, "IV Install Folder"))
if (file != null && file.exists() && file.isFile) {
val installName = JOptionPane.showInputDialog("Set the name of the install")
installRepository.addInstall(installName, file.parent + File.separator, GameType.GTA_IV)
}
}
private fun listGamesItemStateChanged(evt: ItemEvent) {
selectedInstall = installRepository.getInstall(listGames.selectedIndex)
val install = selectedInstall
when {
install?.isValid == true -> {
buttonOK.isEnabled = true
buttonRemove.isEnabled = true
}
install?.isValid != true -> {
buttonOK.isEnabled = false
buttonRemove.isEnabled = true
}
else -> {
buttonOK.isEnabled = false
buttonRemove.isEnabled = false
}
}
}
companion object {
private val SUPPORTED_EXES: Set<String> = setOf(GameType.GTA_IV.executableName)
}
} | gpl-2.0 | 037714b5ae8625dc98fc6bddd0efd870 | 40.836364 | 112 | 0.56969 | 5.588664 | false | false | false | false |
ScheNi/android-material-stepper | material-stepper/src/test/java/com/stepstone/stepper/internal/feedback/ContentOverlayStepperFeedbackTypeTest.kt | 2 | 3560 | package com.stepstone.stepper.internal.feedback
import android.view.View
import com.nhaarman.mockito_kotlin.*
import com.stepstone.stepper.R
import com.stepstone.stepper.StepperLayout
import com.stepstone.stepper.test.TYPE_TABS
import com.stepstone.stepper.test.assertion.StepperLayoutAssert
import com.stepstone.stepper.test.createAttributeSetWithStepperType
import com.stepstone.stepper.test.createStepperLayoutInActivity
import com.stepstone.stepper.test.runner.StepperRobolectricTestRunner
import org.assertj.android.api.Assertions
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
/**
* @author Piotr Zawadzki
*/
@RunWith(StepperRobolectricTestRunner::class)
class ContentOverlayStepperFeedbackTypeTest {
companion object {
val PROGRESS_MESSAGE = "loading..."
val CUSTOM_BACKGROUND_RESOURCE_ID = R.drawable.ms_ic_check
}
@Mock
lateinit var mockOverlayView: View
lateinit var stepperLayout: StepperLayout
lateinit var feedbackType: ContentOverlayStepperFeedbackType
@Before
fun setUp() {
stepperLayout = createStepperLayoutInActivity(createAttributeSetWithStepperType(TYPE_TABS))
}
@Test
fun `Overlay should have visibility = GONE by default when 'content_overlay' is not set`() {
val overlay = stepperLayout.findViewById(R.id.ms_stepPagerOverlay)
Assertions.assertThat(overlay)
.isNotNull
.isGone
}
@Test
fun `Should use default overlay background when a custom background was not set`() {
//given
val spyStepperLayout = spy(stepperLayout)
doReturn(mockOverlayView).whenever(spyStepperLayout).findViewById(R.id.ms_stepPagerOverlay)
//when
feedbackType = ContentOverlayStepperFeedbackType(spyStepperLayout)
//then
verify(mockOverlayView, never()).setBackgroundResource(any())
}
@Test
fun `Should use custom overlay background when a custom background was set`() {
//given
val spyStepperLayout = spy(stepperLayout)
doReturn(mockOverlayView).whenever(spyStepperLayout).findViewById(R.id.ms_stepPagerOverlay)
doReturn(CUSTOM_BACKGROUND_RESOURCE_ID).whenever(spyStepperLayout).contentOverlayBackground
//when
feedbackType = ContentOverlayStepperFeedbackType(spyStepperLayout)
//then
verify(mockOverlayView).setBackgroundResource(CUSTOM_BACKGROUND_RESOURCE_ID)
}
@Test
fun `Should show overlay with alpha set to 0 once feedback type is created`() {
//when
createFeedbackType()
//then
assertStepperLayout()
.hasContentOverlayHidden()
}
@Test
fun `Should fade overlay in when showing progress`() {
//given
createFeedbackType()
//when
feedbackType.showProgress(PROGRESS_MESSAGE)
//then
assertStepperLayout()
.hasContentOverlayShown()
}
@Test
fun `Should fade overlay out when hiding progress`() {
//given
createFeedbackType()
feedbackType.showProgress(PROGRESS_MESSAGE)
//when
feedbackType.hideProgress()
//then
assertStepperLayout()
.hasContentOverlayHidden()
}
private fun createFeedbackType() {
feedbackType = ContentOverlayStepperFeedbackType(stepperLayout)
}
fun assertStepperLayout(): StepperLayoutAssert {
return StepperLayoutAssert.assertThat(stepperLayout)
}
} | apache-2.0 | 919f941baa364aac03557e047c0bc271 | 28.429752 | 99 | 0.701124 | 4.930748 | false | true | false | false |
apollostack/apollo-android | composite/samples/multiplatform/kmp-lib-sample/src/commonMain/kotlin/com/apollographql/apollo3/kmpsample/data/ApolloCoroutinesRepository.kt | 1 | 2885 | package com.apollographql.apollo3.kmpsample.data
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.ApolloRequest
import com.apollographql.apollo3.kmpsample.GithubRepositoriesQuery
import com.apollographql.apollo3.kmpsample.GithubRepositoryCommitsQuery
import com.apollographql.apollo3.kmpsample.GithubRepositoryCommitsQuery.Data.Viewer.Repository.Ref.Target.Companion.asCommit
import com.apollographql.apollo3.kmpsample.GithubRepositoryDetailQuery
import com.apollographql.apollo3.kmpsample.GithubRepositoryDetailQuery.Data.Viewer.Repository.Companion.repositoryDetail
import com.apollographql.apollo3.kmpsample.fragment.RepositoryDetail
import com.apollographql.apollo3.kmpsample.fragment.RepositoryFragment
import com.apollographql.apollo3.kmpsample.type.OrderDirection
import com.apollographql.apollo3.kmpsample.type.PullRequestState
import com.apollographql.apollo3.kmpsample.type.RepositoryOrderField
import com.apollographql.apollo3.network.http.HttpResponseInfo
import com.apollographql.apollo3.network.http.ApolloHttpNetworkTransport
import kotlinx.coroutines.flow.single
/**
* An implementation of a [GitHubDataSource] that shows how we can use coroutines to make our apollo requests.
*/
class ApolloCoroutinesRepository {
private val apolloClient = ApolloClient(ApolloHttpNetworkTransport(
serverUrl = "https://api.github.com/graphql",
headers = mapOf(
"Accept" to "application/json",
"Content-Type" to "application/json",
"Authorization" to "bearer $GITHUB_KEY"
)
)
)
suspend fun fetchRepositories(): List<RepositoryFragment> {
val repositoriesQuery = GithubRepositoriesQuery(
repositoriesCount = 50,
orderBy = RepositoryOrderField.UPDATED_AT,
orderDirection = OrderDirection.DESC
)
val response = apolloClient.query(ApolloRequest(repositoriesQuery))
println("Http response: " + response.executionContext[HttpResponseInfo])
return response.data?.viewer?.repositories?.nodes?.mapNotNull { it }.orEmpty()
}
suspend fun fetchRepositoryDetail(repositoryName: String): RepositoryDetail? {
val repositoryDetailQuery = GithubRepositoryDetailQuery(
name = repositoryName,
pullRequestStates = listOf(PullRequestState.OPEN)
)
val response = apolloClient.query(ApolloRequest(repositoryDetailQuery))
return response.data?.viewer?.repository?.repositoryDetail()
}
suspend fun fetchCommits(repositoryName: String): List<GithubRepositoryCommitsQuery.Data.Viewer.Repository.Ref.CommitTarget.History.Edge?> {
val response = apolloClient.query(ApolloRequest(GithubRepositoryCommitsQuery(repositoryName)))
val headCommit = response.data?.viewer?.repository?.ref?.target?.asCommit()
return headCommit?.history?.edges.orEmpty()
}
companion object {
private const val GITHUB_KEY = "change me"
}
}
| mit | f87897760d90025735d1be687d739c46 | 45.532258 | 142 | 0.794454 | 4.507813 | false | false | false | false |
exponentjs/exponent | packages/expo-constants/android/src/main/java/expo/modules/constants/ExponentInstallationId.kt | 2 | 3616 | package expo.modules.constants
import android.util.Log
import android.content.Context
import android.content.SharedPreferences
import java.util.UUID
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException
import java.io.BufferedReader
import kotlin.IllegalArgumentException
private val TAG = ExponentInstallationId::class.java.simpleName
private const val PREFERENCES_FILE_NAME = "host.exp.exponent.SharedPreferences"
/**
* An installation ID provider - it solves two purposes:
* - in installations that have a legacy UUID persisted
* in shared-across-expo-modules SharedPreferences,
* migrates the UUID from there to a non-backed-up file,
* - provides/creates a UUID unique per an installation.
*
* Similar class exists in expoview and expo-notifications.
*/
class ExponentInstallationId internal constructor(private val context: Context) {
private var uuid: String? = null
private val mSharedPreferences: SharedPreferences = context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE)
fun getUUID(): String? {
// If it has already been cached, return the value.
if (uuid != null) {
return uuid
}
// Read from non-backed-up storage
val uuidFile = nonBackedUpUuidFile
try {
FileReader(uuidFile).use { fileReader ->
BufferedReader(fileReader).use { bufferedReader ->
// Cache for future calls
uuid = UUID.fromString(bufferedReader.readLine()).toString()
}
}
} catch (e: Exception) {
when (e) {
is IOException, is IllegalArgumentException -> { /* do nothing, try other sources */ }
else -> throw e
}
}
// We could have returned inside try clause,
// but putting it like this here makes it immediately
// visible.
if (uuid != null) {
return uuid
}
// In November 2020 we decided to move installationID (backed by LEGACY_UUID_KEY value) from
// backed-up SharedPreferences to a non-backed-up text file to fix issues where devices restored
// from backups have the same installation IDs as the devices where the backup was created.
val legacyUuid = mSharedPreferences.getString(LEGACY_UUID_KEY, null)
if (legacyUuid != null) {
uuid = legacyUuid
val uuidHasBeenSuccessfullyMigrated = try {
FileWriter(uuidFile).use { writer -> writer.write(legacyUuid) }
true
} catch (e: IOException) {
Log.e(TAG, "Error while migrating UUID from legacy storage. $e")
false
}
// We only remove the value from old storage once it's set and saved in the new storage.
if (uuidHasBeenSuccessfullyMigrated) {
mSharedPreferences.edit().remove(LEGACY_UUID_KEY).apply()
}
}
// Return either value from legacy storage or null
return uuid
}
fun getOrCreateUUID(): String {
val uuid = getUUID()
if (uuid != null) {
return uuid
}
// We persist the new UUID in "session storage"
// so that if writing to persistent storage
// fails subsequent calls to get(orCreate)UUID
// return the same value.
this.uuid = UUID.randomUUID().toString()
try {
FileWriter(nonBackedUpUuidFile).use { writer -> writer.write(this.uuid) }
} catch (e: IOException) {
Log.e(TAG, "Error while writing new UUID. $e")
}
return this.uuid!!
}
private val nonBackedUpUuidFile: File
get() = File(context.noBackupFilesDir, UUID_FILE_NAME)
companion object {
const val LEGACY_UUID_KEY = "uuid"
const val UUID_FILE_NAME = "expo_installation_uuid.txt"
}
}
| bsd-3-clause | 56f52b4d4849d56cd79c1b636660724f | 31.285714 | 127 | 0.687223 | 4.254118 | false | false | false | false |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/request/internal/BaseRequest.kt | 1 | 6131 | package com.auth0.android.request.internal
import androidx.annotation.VisibleForTesting
import com.auth0.android.Auth0Exception
import com.auth0.android.callback.Callback
import com.auth0.android.request.*
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
/**
* Base class for every request on this library.
* @param method the HTTP method to use on this request.
* @param url the destination URL to open the connection against.
* @param client the client that will execute this request.
* @param resultAdapter the adapter that will convert a successful response into the expected type.
* @param errorAdapter the adapter that will convert a failed response into the expected type.
*/
internal open class BaseRequest<T, U : Auth0Exception>(
method: HttpMethod,
private val url: String,
private val client: NetworkingClient,
private val resultAdapter: JsonAdapter<T>,
private val errorAdapter: ErrorAdapter<U>,
private val threadSwitcher: ThreadSwitcher = CommonThreadSwitcher.getInstance()
) : Request<T, U> {
private val options: RequestOptions = RequestOptions(method)
override fun addHeader(name: String, value: String): Request<T, U> {
options.headers[name] = value
return this
}
override fun addParameters(parameters: Map<String, String>): Request<T, U> {
val mapCopy = parameters.toMutableMap()
if (parameters.containsKey(OidcUtils.KEY_SCOPE)) {
val updatedScope =
OidcUtils.includeRequiredScope(parameters.getValue(OidcUtils.KEY_SCOPE))
mapCopy[OidcUtils.KEY_SCOPE] = updatedScope
}
options.parameters.putAll(mapCopy)
return this
}
override fun addParameter(name: String, value: String): Request<T, U> {
val anyValue: Any = if (name == OidcUtils.KEY_SCOPE) {
OidcUtils.includeRequiredScope(value)
} else {
value
}
return addParameter(name, anyValue)
}
internal fun addParameter(name: String, value: Any): Request<T, U> {
options.parameters[name] = value
return this
}
/**
* Runs asynchronously and executes the network request, without blocking the current thread.
* The result is parsed into a <T> value and posted in the callback's onSuccess method or a <U>
* exception is raised and posted in the callback's onFailure method if something went wrong.
* @param callback the callback to post the results in. Uses the Main thread.
*/
override fun start(callback: Callback<T, U>) {
threadSwitcher.backgroundThread {
try {
val result: T = execute()
threadSwitcher.mainThread {
callback.onSuccess(result)
}
} catch (error: Auth0Exception) {
@Suppress("UNCHECKED_CAST") // https://youtrack.jetbrains.com/issue/KT-11774
val uError: U = error as? U ?: errorAdapter.fromException(error)
threadSwitcher.mainThread {
callback.onFailure(uError)
}
}
}
}
/**
* Runs an asynchronous network request on a thread from [Dispatchers.IO]
* The result is parsed into a <T> value or a <U> exception is thrown if something went wrong.
* This is a Coroutine that is exposed only for Kotlin.
*/
@JvmSynthetic
@kotlin.jvm.Throws(Auth0Exception::class)
override suspend fun await(): T {
return switchRequestContext(Dispatchers.IO) {
execute()
}
}
/**
* Used to switch to the provided [CoroutineDispatcher].
* This extra method is used to mock and verify during testing. It is not exposed to public.
*/
@VisibleForTesting
internal suspend fun switchRequestContext(
dispatcher: CoroutineDispatcher,
runnable: () -> T
): T {
return withContext(dispatcher) {
return@withContext runnable.invoke()
}
}
/**
* Blocks the thread and executes the network request.
* The result is parsed into a <T> value or a <U> exception is thrown if something went wrong.
*/
@kotlin.jvm.Throws(Auth0Exception::class)
override fun execute(): T {
val response: ServerResponse
try {
response = client.load(url, options)
} catch (exception: IOException) {
//1. Network exceptions, timeouts, etc
val error: U = errorAdapter.fromException(exception)
throw error
}
InputStreamReader(response.body, StandardCharsets.UTF_8).use { reader ->
if (response.isSuccess()) {
//2. Successful scenario. Response of type T
return try {
resultAdapter.fromJson(reader)
} catch (exception: Exception) {
//multi catch IOException and JsonParseException (including JsonIOException)
//3. Network exceptions, timeouts, etc reading response body
val error: U = errorAdapter.fromException(exception)
throw error
}
}
//4. Error scenario. Response of type U
val error: U = try {
if (response.isJson()) {
errorAdapter.fromJsonResponse(response.statusCode, reader)
} else {
errorAdapter.fromRawResponse(
response.statusCode,
reader.readText(),
response.headers
)
}
} catch (exception: Exception) {
//multi catch IOException and JsonParseException (including JsonIOException)
//5. Network exceptions, timeouts, etc reading response body
errorAdapter.fromException(exception)
}
throw error
}
}
}
| mit | 31c76e9adae40a50395ca51dbd7d0c15 | 37.080745 | 99 | 0.621432 | 4.9048 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/io/file/Path.kt | 1 | 2353 | /*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.io.file
class Path(v: String) : Comparable<Path> {
constructor(baseDir: String, child: String) : this("${baseDir.trimEnd('/')}/${child.trim('/')}")
val value: String = v.replace('\\', '/').trimEnd('/')
val name: String
get() = value.substringAfterLast('/')
val nameNoExtension: String
get() = name.substringBeforeLast('.')
val extension: String
get() = value.substringAfterLast('.')
fun hasExtension(extension: String): Boolean {
return this.extension.equals(extension, ignoreCase = true)
}
/**
* Returns the number of parts in the path.
* e.g.
* `Path("one/two/three").depth == 3`
* `Path("one/two").depth == 2`
* `Path("one").depth == 1`
* `Path("").depth == 0`
*/
val depth: Int
get() = if (value.isEmpty()) 0 else value.count { it == '/' } + 1
fun resolve(child: String): Path = Path("$value/$child")
fun sibling(sibling: String): Path {
return parent.resolve(sibling)
}
fun stripComponents(count: Int): Path {
return Path(value.split("/").drop(count).joinToString("/"))
}
val parent: Path
get() = Path(value.substringBeforeLast("/"))
/**
* Note, files are sorted case-sensitively. This is to ensure consistent order when two files have names
* that differ only in case.
*/
override fun compareTo(other: Path): Int {
return if (depth == other.depth) {
value.compareTo(other.value)
} else {
depth.compareTo(other.depth)
}
}
override fun toString(): String = value
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as Path
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
return value.hashCode()
}
} | apache-2.0 | 46c1013fe6f26777ce9323e3cfaca7ce | 25.449438 | 105 | 0.669358 | 3.592366 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/repository/faviorites/FavoritesRepository.kt | 1 | 5991 | package forpdateam.ru.forpda.model.repository.faviorites
import android.util.Log
import forpdateam.ru.forpda.entity.app.TabNotification
import forpdateam.ru.forpda.entity.remote.events.NotificationEvent
import forpdateam.ru.forpda.entity.remote.favorites.FavData
import forpdateam.ru.forpda.entity.remote.favorites.FavItem
import forpdateam.ru.forpda.model.AuthHolder
import forpdateam.ru.forpda.model.CountersHolder
import forpdateam.ru.forpda.model.SchedulersProvider
import forpdateam.ru.forpda.model.data.cache.favorites.FavoritesCache
import forpdateam.ru.forpda.model.data.remote.api.favorites.FavoritesApi
import forpdateam.ru.forpda.model.data.remote.api.favorites.Sorting
import forpdateam.ru.forpda.model.preferences.ListsPreferencesHolder
import forpdateam.ru.forpda.model.preferences.NotificationPreferencesHolder
import forpdateam.ru.forpda.model.repository.BaseRepository
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
/**
* Created by radiationx on 01.01.18.
*/
class FavoritesRepository(
private val schedulers: SchedulersProvider,
private val favoritesApi: FavoritesApi,
private val favoritesCache: FavoritesCache,
private val authHolder: AuthHolder,
private val countersHolder: CountersHolder,
private val listsPreferencesHolder: ListsPreferencesHolder,
private val notificationPreferencesHolder: NotificationPreferencesHolder
) : BaseRepository(schedulers) {
fun observeItems(): Observable<List<FavItem>> = favoritesCache
.observeItems()
.runInIoToUi()
fun loadCache(): Single<List<FavItem>> = Single
.fromCallable { favoritesCache.getItems() }
.runInIoToUi()
fun loadFavorites(st: Int, all: Boolean, sorting: Sorting): Single<FavData> = Single
.fromCallable { favoritesApi.getFavorites(st, all, sorting) }
.doOnSuccess { favData -> favoritesCache.saveFavorites(favData.items) }
.runInIoToUi()
fun editFavorites(act: Int, favId: Int, id: Int, type: String?): Single<Boolean> = Single
.fromCallable {
when (act) {
FavoritesApi.ACTION_EDIT_SUB_TYPE -> favoritesApi.editSubscribeType(type, favId)
FavoritesApi.ACTION_EDIT_PIN_STATE -> favoritesApi.editPinState(type, favId)
FavoritesApi.ACTION_DELETE -> favoritesApi.delete(favId)
FavoritesApi.ACTION_ADD, FavoritesApi.ACTION_ADD_FORUM -> favoritesApi.add(id, act, type)
else -> false
}
}
.runInIoToUi()
fun markRead(topicId: Int): Completable = Completable
.fromRunnable {
val favItem = favoritesCache.getItemByTopicId(topicId)
if (favItem != null) {
favItem.isNew = false
favoritesCache.updateItem(favItem)
}
}
.runInIoToUi()
fun handleEvent(event: TabNotification): Single<Int> = Single
.fromCallable {
val favItems = favoritesCache.getItems()
val sorting = Sorting(
listsPreferencesHolder.getSortingKey(),
listsPreferencesHolder.getSortingOrder()
)
val count = countersHolder.get().favorites
handleEventTransaction(favItems, event, sorting, count).also {
countersHolder.set(countersHolder.get().apply {
favorites = it
})
}
}
.runInIoToUi()
private fun handleEventTransaction(favItems: List<FavItem>, event: TabNotification, sorting: Sorting, count: Int): Int {
if (!NotificationEvent.fromTheme(event.source)) return count
if (!notificationPreferencesHolder.getFavLiveTab()) return count
if (event.isWebSocket && event.event.isNew) return count
var newCount = count
val newFavItems = favItems.toMutableList()
val loadedEvent = event.event
val topicId = loadedEvent.sourceId
val isRead = loadedEvent.isRead
Log.e("testtabnotify", "handleEventTransaction $newCount, $topicId, $isRead, ${loadedEvent.userNick}")
if (isRead) {
newFavItems.find { it.topicId == topicId }?.also {
if (it.isNew) {
newCount--
it.isNew = false
}
Log.e("testtabnotify", "found item ${it.isNew}, $newCount")
}
} else {
newCount = event.loadedEvents.size
Log.e("testtabnotify", "lalala $newCount")
newFavItems.find { it.topicId == topicId }?.also {
if (it.lastUserId != authHolder.get().userId) {
it.isNew = true
}
it.lastUserNick = loadedEvent.userNick
it.lastUserId = loadedEvent.userId
it.isPin = loadedEvent.isImportant
}
if (sorting.key == Sorting.Key.TITLE) {
if (sorting.order == Sorting.Order.ASC) {
newFavItems.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.topicTitle.orEmpty() })
} else {
newFavItems.sortWith(compareByDescending(String.CASE_INSENSITIVE_ORDER) { it.topicTitle.orEmpty() })
}
}
if (sorting.key == Sorting.Key.LAST_POST) {
newFavItems.find { it.topicId == topicId }?.also {
newFavItems.remove(it)
if (sorting.order == Sorting.Order.ASC) {
newFavItems.add(newFavItems.size, it)
} else {
newFavItems.add(0, it)
}
}
}
}
favoritesCache.saveFavorites(newFavItems)
return newCount
}
}
| gpl-3.0 | b02d781811c7a4f79aa366908a786a77 | 40.895105 | 124 | 0.609247 | 4.773705 | false | false | false | false |
akakim/akakim.github.io | Android/KotlinRepository/QSalesPrototypeKotilnVersion/main/java/tripath/com/samplekapp/MainActivity.kt | 1 | 2603 | package tripath.com.samplekapp
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.android.volley.Response
import com.android.volley.VolleyError
import tripath.com.samplekapp.data.User
import tripath.com.samplekapp.restclient.RestApiClient
class MainActivity : BaseActivity() , View.OnClickListener,Response.Listener<User>, Response.ErrorListener{
val TAG = javaClass.simpleName
lateinit var edId : EditText
lateinit var edPassword : EditText
override fun onResponse(response: User?) {
Log.d(TAG,"onResponse")
Log.d(TAG,response.toString())
if( response == null){
Toast.makeText(this , "response is null " , Toast.LENGTH_SHORT ).show()
}else if(response is User ){
Toast.makeText(this , response.toString(), Toast.LENGTH_SHORT ).show()
}else {
Toast.makeText(this , "another object is in... ", Toast.LENGTH_SHORT ).show()
}
}
override fun onErrorResponse(error: VolleyError?) {
Log.d(TAG,"onError occured")
error?.printStackTrace()
if( error != null){
Toast.makeText(this , "error occured " + error.message, Toast.LENGTH_SHORT ).show()
}else {
Toast.makeText(this , "error is null .. " , Toast.LENGTH_SHORT ).show()
}
// val stackTrace = error?.stackTrace
//
// error.message
// if(stackTrace != null) {
// for (stack in stackTrace) {
//
// }
//
//
// }else {
// Toast.makeText(this , "stackTrace is null ", Toast.LENGTH_SHORT ).show()
// }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
resapiService
setTitle(localClassName);
edId = findViewById(R.id.edId) as EditText
edPassword = findViewById( R.id.edPwd) as EditText
findViewById( R.id.btnLogin).setOnClickListener( this )
edId.setText("[email protected]")
edPassword.setText("1q2w3e4r5t")
}
override fun onClick(p0: View?) {
when (p0?.id){
R.id.btnLogin -> {
val user = User(edId.text.toString(),edPassword.text.toString(),"","" )
resApiClient.loginCheck(user,this,this)
}
else -> {
Toast.makeText(this,"hello error",Toast.LENGTH_SHORT).show()
}
}
}
}
| gpl-3.0 | 58008e1602f6841621d25d0914dd2161 | 26.989247 | 107 | 0.613523 | 4.067188 | false | false | false | false |
benjamin-bader/thrifty | thrifty-runtime/src/commonMain/kotlin/com/microsoft/thrifty/util/ObfuscationUtil.kt | 1 | 1663 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.util
import kotlin.jvm.JvmStatic
/**
* Utility methods for printing obfuscated versions of sensitive data.
*/
object ObfuscationUtil {
@JvmStatic
fun summarizeCollection(collection: Collection<*>?, collectionType: String, elementType: String): String {
return when (collection) {
null -> "null"
else -> "$collectionType<$elementType>(size=${collection.size})"
}
}
@JvmStatic
fun summarizeMap(map: Map<*, *>?, keyType: String, valueType: String): String {
return when (map) {
null -> "null"
else -> "map<$keyType, $valueType>(size=${map.size})"
}
}
@JvmStatic
fun hash(value: Any?): String {
if (value == null) {
return "null"
}
val hashcode = value.hashCode()
return hashcode.toString(radix = 16).uppercase().padStart(length = 8, padChar = '0')
}
}
| apache-2.0 | f69e10245703ebeacc5635ed2dd579e5 | 29.796296 | 116 | 0.653037 | 4.30829 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/ScratchFileModuleInfoProvider.kt | 4 | 1983 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.scratch
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.ModuleManager
import org.jetbrains.kotlin.idea.core.script.ScriptDependenciesModificationTracker
import org.jetbrains.kotlin.idea.core.script.ScriptRelatedModuleNameFile
import org.jetbrains.kotlin.idea.util.projectStructure.getModule
import org.jetbrains.kotlin.parsing.KotlinParserDefinition.Companion.STD_SCRIPT_SUFFIX
class ScratchFileModuleInfoProvider() : ScratchFileListener {
companion object {
private val LOG = logger<ScratchFileModuleInfoProvider>()
}
override fun fileCreated(file: ScratchFile) {
val ktFile = file.ktScratchFile ?: return
val virtualFile = ktFile.virtualFile ?: return
val project = ktFile.project
if (virtualFile.extension != STD_SCRIPT_SUFFIX) {
LOG.error("Kotlin Scratch file should have .kts extension. Cannot add scratch panel for ${virtualFile.path}")
return
}
file.addModuleListener { psiFile, module ->
ScriptRelatedModuleNameFile[project, psiFile.virtualFile] = module?.name
// Drop caches for old module
ScriptDependenciesModificationTracker.getInstance(project).incModificationCount()
// Force re-highlighting
DaemonCodeAnalyzer.getInstance(project).restart(psiFile)
}
if (virtualFile.isKotlinWorksheet) {
val module = virtualFile.getModule(project) ?: return
file.setModule(module)
} else {
val module = ScriptRelatedModuleNameFile[project, virtualFile]?.let { ModuleManager.getInstance(project).findModuleByName(it) } ?: return
file.setModule(module)
}
}
}
| apache-2.0 | 5dd4e04f8f5bbce40d50dbc5225f5358 | 43.066667 | 158 | 0.72113 | 5.032995 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveDefaultParameterValueFix.kt | 1 | 1537 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtParameter
class RemoveDefaultParameterValueFix(parameter: KtParameter) : KotlinQuickFixAction<KtParameter>(parameter) {
override fun getText() = KotlinBundle.message("remove.default.parameter.value")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val parameter = element ?: return
val typeReference = parameter.typeReference ?: return
val defaultValue = parameter.defaultValue ?: return
val commentSaver = CommentSaver(parameter)
parameter.deleteChildRange(typeReference.nextSibling, defaultValue)
commentSaver.restore(parameter)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtParameter>? =
(diagnostic.psiElement as? KtParameter)?.let { RemoveDefaultParameterValueFix(it) }
}
} | apache-2.0 | fc16b4c0e59074f6eb8bc665f96d9e77 | 45.606061 | 158 | 0.776187 | 4.910543 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/opus/OpusSubscription.kt | 1 | 2665 | /*
* OpusSubscription.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.opus
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.transit.en1545.*
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
internal data class OpusSubscription(override val parsed: En1545Parsed,
val ctr: Int?) : En1545Subscription() {
override val lookup: En1545Lookup
get() = OpusLookup
override val remainingTripCount: Int?
get() = if (parsed.getIntOrZero(En1545FixedInteger.dateName(En1545Subscription.CONTRACT_END)) == 0)
ctr else null
constructor(data: ImmutableByteArray, ctr: Int?) : this(En1545Parser.parse(data, FIELDS), ctr)
companion object {
private val FIELDS = En1545Container(
En1545FixedInteger(En1545Subscription.CONTRACT_UNKNOWN_A, 3),
En1545Bitmap(
En1545FixedInteger(En1545Subscription.CONTRACT_PROVIDER, 8),
En1545FixedInteger(En1545Subscription.CONTRACT_TARIFF, 16),
En1545Bitmap(
En1545FixedInteger.date(En1545Subscription.CONTRACT_START),
En1545FixedInteger.date(En1545Subscription.CONTRACT_END)
),
En1545Container(
En1545FixedInteger(En1545Subscription.CONTRACT_UNKNOWN_B, 17),
En1545FixedInteger.date(En1545Subscription.CONTRACT_SALE),
En1545FixedInteger.timeLocal(En1545Subscription.CONTRACT_SALE),
En1545FixedHex(En1545Subscription.CONTRACT_UNKNOWN_C, 36),
En1545FixedInteger(En1545Subscription.CONTRACT_STATUS, 8),
En1545FixedHex(En1545Subscription.CONTRACT_UNKNOWN_D, 36)
)
)
)
}
}
| gpl-3.0 | 94d00e8f956b1fae157be288c5b9c59e | 44.169492 | 107 | 0.634897 | 4.675439 | false | false | false | false |
phicdy/toto-anticipation | android/feature_game_list/src/main/java/com/phicdy/totoanticipation/feature/gamelist/GameListFragment.kt | 1 | 11318 | package com.phicdy.totoanticipation.feature.gamelist
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.TextView
import androidx.annotation.IntDef
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.phicdy.totoanticipation.advertisement.AdProvider
import com.phicdy.totoanticipation.advertisement.AdViewHolder
import com.phicdy.totoanticipation.di_common.FragmentScope
import com.phicdy.totoanticipation.domain.Game
import com.phicdy.totoanticipation.intentprovider.IntentProvider
import com.phicdy.totoanticipation.scheduler.DeadlineAlarm
import dagger.Provides
import dagger.android.support.DaggerFragment
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
class GameListFragment : GameListView, DaggerFragment(), CoroutineScope {
private var mTwoPane: Boolean = false
private lateinit var recyclerView: RecyclerView
private val adapter by lazy { SimpleItemRecyclerViewAdapter() }
private lateinit var progressBar: SmoothProgressBar
private lateinit var fab: FloatingActionButton
private lateinit var content: View
private lateinit var empty: ConstraintLayout
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
@Inject
lateinit var presenter: GameListPresenter
@Inject
lateinit var adProvider: AdProvider
@Inject
lateinit var intentProvider: IntentProvider
private var isAnticipationMenuVisible = true
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_game_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)
toolbar.title = activity?.title
recyclerView = view.findViewById(R.id.game_list)
progressBar = view.findViewById(R.id.progress)
content = view.findViewById(R.id.content)
empty = view.findViewById(R.id.empty)
fab = view.findViewById(R.id.fab)
fab.setOnClickListener { presenter.onFabClicked() }
if (view.findViewById<View>(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true
}
launch {
presenter.onCreate()
}
setHasOptionsMenu(true)
}
override fun onDestroy() {
job.cancel()
super.onDestroy()
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.menu_auto_anticipation)?.isVisible = isAnticipationMenuVisible
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.game_list, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_auto_anticipation -> presenter.onOptionsAutoAnticipationSelected()
R.id.menu_setting -> presenter.onOptionsSettingSelected()
}
return false
}
override fun initList() {
recyclerView.visibility = View.VISIBLE
recyclerView.adapter = adapter
}
override fun setTitleFrom(xxTh: String, deadline: String) {
activity?.title = getString(R.string.top_title, xxTh, deadline)
}
override fun startProgress() {
progressBar.visibility = View.VISIBLE
}
override fun stopProgress() {
progressBar.progressiveStop()
val handler = Handler()
handler.postDelayed({ progressBar.visibility = View.GONE }, 3000)
}
override fun startTotoAnticipationActivity(totoNum: String) {
val intent: Intent
if (BuildConfig.FLAVOR == "googlePlay") {
// Google Play forbids to upload gambling app for Japan, open external browser
val totoTopUrl = "https://sp.toto-dream.com/dcs/subos/screen/si01/ssin026/PGSSIN02601InittotoSP.form?holdCntId=$totoNum"
intent = Intent(Intent.ACTION_VIEW, Uri.parse(totoTopUrl))
} else {
intent = intentProvider.totoAnticipation(requireContext(), totoNum)
}
startActivity(intent)
}
override fun goToSetting() {
intentProvider.setting(this)
}
override fun showAnticipationStart() {
showSnackbar(R.string.start_auto_anticipation, Snackbar.LENGTH_SHORT)
}
override fun showAnticipationFinish() {
showSnackbar(R.string.finish_auto_anticipation, Snackbar.LENGTH_SHORT)
}
override fun notifyDataSetChanged() {
adapter.notifyDataSetChanged()
}
override fun showAnticipationNotSupport() {
showSnackbar(R.string.anticipation_not_support, Snackbar.LENGTH_SHORT)
}
private fun showSnackbar(@StringRes res: Int, @SnackbarLength length: Int) {
Snackbar.make(content, res, length).show()
}
override fun showPrivacyPolicyDialog() {
val alert = AlertDialog.Builder(requireActivity())
.setMessage(Html.fromHtml(getString(R.string.privacy_policy_message)))
.setCancelable(false)
.setPositiveButton(R.string.accept) { _, _ ->
presenter.onPrivacyPolicyAccepted()
}
.setNegativeButton(R.string.not_accept) { _, _ ->
activity?.finish()
}
.create()
alert.show()
alert.findViewById<TextView>(android.R.id.message)?.movementMethod = LinkMovementMethod.getInstance()
}
override fun hideList() {
recyclerView.visibility = View.GONE
}
override fun hideFab() {
fab.hide()
}
override fun hideAnticipationMenu() {
isAnticipationMenuVisible = false
activity?.invalidateOptionsMenu()
}
override fun showEmptyView() {
empty.visibility = View.VISIBLE
}
@IntDef(Snackbar.LENGTH_SHORT, Snackbar.LENGTH_LONG)
internal annotation class SnackbarLength
internal inner class SimpleItemRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val VIEW_TYPE_CONTENT = 1
private val VIEW_TYPE_AD = 2
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_TYPE_CONTENT -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.game_list_content, parent, false)
ViewHolder(view)
}
VIEW_TYPE_AD -> adProvider.newViewHolderInstance(parent)
else -> throw IllegalStateException()
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is ViewHolder -> {
val game = presenter.gameAt(position)
holder.tvHome.text = when (game.homeRanking) {
Game.defaultRank -> getString(R.string.team_label, "- ", game.homeTeam)
else -> getString(R.string.team_label, game.homeRanking.toString(), game.homeTeam)
}
holder.tvAway.text = when (game.awayRanking) {
Game.defaultRank -> getString(R.string.team_label, "- ", game.awayTeam)
else -> getString(R.string.team_label, game.awayRanking.toString(), game.awayTeam)
}
holder.mView.setOnClickListener { view ->
if (game.homeRanking == Game.defaultRank || game.awayRanking == Game.defaultRank) {
showSnackbar(R.string.not_support_foreign_league, Snackbar.LENGTH_SHORT)
return@setOnClickListener
}
intentProvider.teamInfo(this@GameListFragment, game)
}
when (game.anticipation) {
Game.Anticipation.HOME -> holder.rbHome.isChecked = true
Game.Anticipation.AWAY -> holder.rbAway.isChecked = true
Game.Anticipation.DRAW -> holder.rbDraw.isChecked = true
}
holder.rbHome.setOnCheckedChangeListener { _, isChecked -> presenter.onHomeRadioButtonClicked(holder.adapterPosition, isChecked) }
holder.rbAway.setOnCheckedChangeListener { _, isChecked -> presenter.onAwayRadioButtonClicked(holder.adapterPosition, isChecked) }
holder.rbDraw.setOnCheckedChangeListener { _, isChecked -> presenter.onDrawRadioButtonClicked(holder.adapterPosition, isChecked) }
}
is AdViewHolder -> holder.bind()
}
}
override fun getItemCount(): Int {
return presenter.gameSize() + 1 // 1 for Ad
}
override fun getItemViewType(position: Int) = if (position == presenter.gameSize()) VIEW_TYPE_AD else VIEW_TYPE_CONTENT
}
internal inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
val tvHome: TextView = mView.findViewById(R.id.tv_home)
val tvAway: TextView = mView.findViewById(R.id.tv_away)
val rbHome: RadioButton = mView.findViewById(R.id.rb_home)
val rbAway: RadioButton = mView.findViewById(R.id.rb_away)
val rbDraw: RadioButton = mView.findViewById(R.id.rb_draw)
override fun toString(): String {
return super.toString() + " '" + tvAway.text + "'"
}
}
@dagger.Module
object Module {
@Provides
@JvmStatic
@FragmentScope
fun provideGameListView(fragment: GameListFragment): GameListView = fragment
@Provides
@JvmStatic
@FragmentScope
fun provideDeadlineAlarm(fragment: GameListFragment): DeadlineAlarm = DeadlineAlarm(fragment.requireContext())
}
}
| apache-2.0 | 380c9f6fda22ff629e33fee8f780bddc | 37.496599 | 150 | 0.660541 | 4.743504 | false | false | false | false |
fuzz-productions/Salvage | salvage-processor/src/main/java/com/fuzz/android/salvage/ElementUtility.kt | 1 | 2572 | package com.fuzz.android.salvage
import com.fuzz.android.salvage.core.PersistIgnore
import com.squareup.javapoet.ClassName
import java.util.ArrayList
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeMirror
/**
* Description:
*/
object ElementUtility {
/**
* @return real full-set of elements, including ones from super-class.
*/
fun getAllElements(element: TypeElement, manager: ProcessorManager): List<Element> {
val elements = ArrayList(manager.elements.getAllMembers(element))
var superMirror: TypeMirror? = null
var typeElement: TypeElement? = element
while (typeElement?.superclass.let { superMirror = it; it != null }) {
typeElement = manager.typeUtils.asElement(superMirror) as TypeElement?
typeElement?.let {
val superElements = manager.elements.getAllMembers(typeElement)
superElements.forEach { if (!elements.contains(it)) elements += it }
}
}
return elements
}
fun isInSamePackage(manager: ProcessorManager, elementToCheck: Element, original: Element): Boolean {
return manager.elements.getPackageOf(elementToCheck).toString() == manager.elements.getPackageOf(original).toString()
}
fun isPackagePrivate(element: Element): Boolean {
return !element.modifiers.contains(Modifier.PUBLIC) && !element.modifiers.contains(Modifier.PRIVATE)
&& !element.modifiers.contains(Modifier.STATIC)
}
fun isValidAllFields(allFields: Boolean, element: Element): Boolean {
return allFields && element.kind.isField &&
!element.modifiers.contains(Modifier.TRANSIENT) &&
!element.modifiers.contains(Modifier.STATIC) &&
element.getAnnotation(PersistIgnore::class.java) == null
}
fun getClassName(elementClassname: String, manager: ProcessorManager): ClassName? {
val typeElement: TypeElement? = manager.elements.getTypeElement(elementClassname)
return if (typeElement != null) {
ClassName.get(typeElement)
} else {
val names = elementClassname.split(".")
if (names.size > 0) {
// attempt to take last part as class name
val className = names[names.size - 1]
ClassName.get(elementClassname.replace("." + className, ""), className)
} else {
null
}
}
}
}
| apache-2.0 | 0b0c0e61c5dfdfc32e04ad463675ab0d | 39.1875 | 125 | 0.65591 | 4.702011 | false | false | false | false |
AsamK/TextSecure | donations/lib/src/main/java/org/signal/donations/StripeApi.kt | 1 | 9491 | package org.signal.donations
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.ByteString
import org.json.JSONObject
import org.signal.core.util.logging.Log
import org.signal.core.util.money.FiatMoney
import java.math.BigDecimal
import java.util.Locale
class StripeApi(
private val configuration: Configuration,
private val paymentIntentFetcher: PaymentIntentFetcher,
private val setupIntentHelper: SetupIntentHelper,
private val okHttpClient: OkHttpClient
) {
companion object {
private val TAG = Log.tag(StripeApi::class.java)
}
sealed class CreatePaymentIntentResult {
data class AmountIsTooSmall(val amount: FiatMoney) : CreatePaymentIntentResult()
data class AmountIsTooLarge(val amount: FiatMoney) : CreatePaymentIntentResult()
data class CurrencyIsNotSupported(val currencyCode: String) : CreatePaymentIntentResult()
data class Success(val paymentIntent: PaymentIntent) : CreatePaymentIntentResult()
}
data class CreateSetupIntentResult(val setupIntent: SetupIntent)
fun createSetupIntent(): Single<CreateSetupIntentResult> {
return setupIntentHelper
.fetchSetupIntent()
.map { CreateSetupIntentResult(it) }
.subscribeOn(Schedulers.io())
}
fun confirmSetupIntent(paymentSource: PaymentSource, setupIntent: SetupIntent): Completable = Single.fromCallable {
val paymentMethodId = createPaymentMethodAndParseId(paymentSource)
val parameters = mapOf(
"client_secret" to setupIntent.clientSecret,
"payment_method" to paymentMethodId
)
postForm("setup_intents/${setupIntent.id}/confirm", parameters)
paymentMethodId
}.flatMapCompletable {
setupIntentHelper.setDefaultPaymentMethod(it)
}
fun createPaymentIntent(price: FiatMoney, level: Long): Single<CreatePaymentIntentResult> {
@Suppress("CascadeIf")
return if (Validation.isAmountTooSmall(price)) {
Single.just(CreatePaymentIntentResult.AmountIsTooSmall(price))
} else if (Validation.isAmountTooLarge(price)) {
Single.just(CreatePaymentIntentResult.AmountIsTooLarge(price))
} else if (!Validation.supportedCurrencyCodes.contains(price.currency.currencyCode.uppercase(Locale.ROOT))) {
Single.just<CreatePaymentIntentResult>(CreatePaymentIntentResult.CurrencyIsNotSupported(price.currency.currencyCode))
} else {
paymentIntentFetcher
.fetchPaymentIntent(price, level)
.map<CreatePaymentIntentResult> { CreatePaymentIntentResult.Success(it) }
}.subscribeOn(Schedulers.io())
}
fun confirmPaymentIntent(paymentSource: PaymentSource, paymentIntent: PaymentIntent): Completable = Completable.fromAction {
val paymentMethodId = createPaymentMethodAndParseId(paymentSource)
val parameters = mutableMapOf(
"client_secret" to paymentIntent.clientSecret,
"payment_method" to paymentMethodId
)
postForm("payment_intents/${paymentIntent.id}/confirm", parameters)
}.subscribeOn(Schedulers.io())
private fun createPaymentMethodAndParseId(paymentSource: PaymentSource): String {
return createPaymentMethod(paymentSource).use { response ->
val body = response.body()
if (body != null) {
val paymentMethodObject = body.string().replace("\n", "").let { JSONObject(it) }
paymentMethodObject.getString("id")
} else {
throw StripeError.FailedToParsePaymentMethodResponseError
}
}
}
private fun createPaymentMethod(paymentSource: PaymentSource): Response {
val tokenizationData = paymentSource.parameterize()
val parameters = mutableMapOf(
"card[token]" to JSONObject((tokenizationData.get("token") as String).replace("\n", "")).getString("id"),
"type" to "card",
)
return postForm("payment_methods", parameters)
}
private fun postForm(endpoint: String, parameters: Map<String, String>): Response {
val formBodyBuilder = FormBody.Builder()
parameters.forEach { (k, v) ->
formBodyBuilder.add(k, v)
}
val request = Request.Builder()
.url("${configuration.baseUrl}/$endpoint")
.addHeader("Authorization", "Basic ${ByteString.encodeUtf8("${configuration.publishableKey}:").base64()}")
.post(formBodyBuilder.build())
.build()
val response = okHttpClient.newCall(request).execute()
if (response.isSuccessful) {
return response
} else {
val body = response.body()?.string()
throw StripeError.PostError(
response.code(),
parseErrorCode(body),
parseDeclineCode(body)
)
}
}
private fun parseErrorCode(body: String?): String? {
if (body == null) {
Log.d(TAG, "parseErrorCode: No body.", true)
return null
}
return try {
JSONObject(body).getJSONObject("error").getString("code")
} catch (e: Exception) {
Log.d(TAG, "parseErrorCode: Failed to parse error.", e, true)
null
}
}
private fun parseDeclineCode(body: String?): StripeDeclineCode? {
if (body == null) {
Log.d(TAG, "parseDeclineCode: No body.", true)
return null
}
return try {
StripeDeclineCode.getFromCode(JSONObject(body).getJSONObject("error").getString("decline_code"))
} catch (e: Exception) {
Log.d(TAG, "parseDeclineCode: Failed to parse decline code.", e, true)
null
}
}
object Validation {
private val MAX_AMOUNT = BigDecimal(99_999_999)
fun isAmountTooLarge(fiatMoney: FiatMoney): Boolean {
return fiatMoney.minimumUnitPrecisionString.toBigDecimal() > MAX_AMOUNT
}
fun isAmountTooSmall(fiatMoney: FiatMoney): Boolean {
return fiatMoney.minimumUnitPrecisionString.toBigDecimal() < BigDecimal(minimumIntegralChargePerCurrencyCode[fiatMoney.currency.currencyCode] ?: 50)
}
private val minimumIntegralChargePerCurrencyCode: Map<String, Int> = mapOf(
"USD" to 50,
"AED" to 200,
"AUD" to 50,
"BGN" to 100,
"BRL" to 50,
"CAD" to 50,
"CHF" to 50,
"CZK" to 1500,
"DKK" to 250,
"EUR" to 50,
"GBP" to 30,
"HKD" to 400,
"HUF" to 17500,
"INR" to 50,
"JPY" to 50,
"MXN" to 10,
"MYR" to 2,
"NOK" to 300,
"NZD" to 50,
"PLN" to 200,
"RON" to 200,
"SEK" to 300,
"SGD" to 50
)
val supportedCurrencyCodes: List<String> = listOf(
"USD",
"AED",
"AFN",
"ALL",
"AMD",
"ANG",
"AOA",
"ARS",
"AUD",
"AWG",
"AZN",
"BAM",
"BBD",
"BDT",
"BGN",
"BIF",
"BMD",
"BND",
"BOB",
"BRL",
"BSD",
"BWP",
"BZD",
"CAD",
"CDF",
"CHF",
"CLP",
"CNY",
"COP",
"CRC",
"CVE",
"CZK",
"DJF",
"DKK",
"DOP",
"DZD",
"EGP",
"ETB",
"EUR",
"FJD",
"FKP",
"GBP",
"GEL",
"GIP",
"GMD",
"GNF",
"GTQ",
"GYD",
"HKD",
"HNL",
"HRK",
"HTG",
"HUF",
"IDR",
"ILS",
"INR",
"ISK",
"JMD",
"JPY",
"KES",
"KGS",
"KHR",
"KMF",
"KRW",
"KYD",
"KZT",
"LAK",
"LBP",
"LKR",
"LRD",
"LSL",
"MAD",
"MDL",
"MGA",
"MKD",
"MMK",
"MNT",
"MOP",
"MRO",
"MUR",
"MVR",
"MWK",
"MXN",
"MYR",
"MZN",
"NAD",
"NGN",
"NIO",
"NOK",
"NPR",
"NZD",
"PAB",
"PEN",
"PGK",
"PHP",
"PKR",
"PLN",
"PYG",
"QAR",
"RON",
"RSD",
"RUB",
"RWF",
"SAR",
"SBD",
"SCR",
"SEK",
"SGD",
"SHP",
"SLL",
"SOS",
"SRD",
"STD",
"SZL",
"THB",
"TJS",
"TOP",
"TRY",
"TTD",
"TWD",
"TZS",
"UAH",
"UGX",
"UYU",
"UZS",
"VND",
"VUV",
"WST",
"XAF",
"XCD",
"XOF",
"XPF",
"YER",
"ZAR",
"ZMW"
)
}
class Gateway(private val configuration: Configuration) : GooglePayApi.Gateway {
override fun getTokenizationSpecificationParameters(): Map<String, String> {
return mapOf(
"gateway" to "stripe",
"stripe:version" to configuration.version,
"stripe:publishableKey" to configuration.publishableKey
)
}
override val allowedCardNetworks: List<String> = listOf(
"AMEX",
"DISCOVER",
"JCB",
"MASTERCARD",
"VISA"
)
}
data class Configuration(
val publishableKey: String,
val baseUrl: String = "https://api.stripe.com/v1",
val version: String = "2018-10-31"
)
interface PaymentIntentFetcher {
fun fetchPaymentIntent(
price: FiatMoney,
level: Long
): Single<PaymentIntent>
}
interface SetupIntentHelper {
fun fetchSetupIntent(): Single<SetupIntent>
fun setDefaultPaymentMethod(paymentMethodId: String): Completable
}
data class PaymentIntent(
val id: String,
val clientSecret: String
)
data class SetupIntent(
val id: String,
val clientSecret: String
)
interface PaymentSource {
fun parameterize(): JSONObject
fun email(): String?
}
} | gpl-3.0 | e9462d7b139959d4be6d507d788e7314 | 23.590674 | 154 | 0.607944 | 3.847183 | false | false | false | false |
emanuelpalm/palm-compute | core/src/main/java/se/ltu/emapal/compute/util/media/schema/MediaSchemaException.kt | 1 | 1181 | package se.ltu.emapal.compute.util.media.schema
import se.ltu.emapal.compute.util.media.MediaEncodableException
import se.ltu.emapal.compute.util.media.MediaEncoder
/**
* Signifies that some media decoder fails to comply to some [MediaSchema].
*
* @param violations A list of violated [MediaRequirement]s.
*/
class MediaSchemaException(
val violations: List<MediaViolation>
) : MediaEncodableException("Media schema violated.") {
/** Constructs new media schema error from given violations. */
constructor(vararg violations: MediaViolation) : this (listOf(*violations))
override val encodable: (MediaEncoder) -> Unit
get() = {
it.encodeMap {
it.addList("violations", violations)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other?.javaClass != javaClass) {
return false
}
other as MediaSchemaException
return violations == other.violations
}
override fun hashCode() = violations.hashCode()
override fun toString() = "MediaSchemaException(violations=$violations)"
} | mit | 6433a665b4c07f5cdb4888ff5aa66be3 | 30.105263 | 79 | 0.65707 | 4.613281 | false | false | false | false |
cmzy/okhttp | okhttp/src/main/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt | 1 | 11783 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.publicsuffix
import java.io.IOException
import java.io.InterruptedIOException
import java.net.IDN
import java.nio.charset.StandardCharsets.UTF_8
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicBoolean
import okhttp3.internal.and
import okhttp3.internal.platform.Platform
import okio.GzipSource
import okio.buffer
import okio.source
/**
* A database of public suffixes provided by [publicsuffix.org][publicsuffix_org].
*
* [publicsuffix_org]: https://publicsuffix.org/
*/
class PublicSuffixDatabase {
/** True after we've attempted to read the list for the first time. */
private val listRead = AtomicBoolean(false)
/** Used for concurrent threads reading the list for the first time. */
private val readCompleteLatch = CountDownLatch(1)
// The lists are held as a large array of UTF-8 bytes. This is to avoid allocating lots of strings
// that will likely never be used. Each rule is separated by '\n'. Please see the
// PublicSuffixListGenerator class for how these lists are generated.
// Guarded by this.
private lateinit var publicSuffixListBytes: ByteArray
private lateinit var publicSuffixExceptionListBytes: ByteArray
/**
* Returns the effective top-level domain plus one (eTLD+1) by referencing the public suffix list.
* Returns null if the domain is a public suffix or a private address.
*
* Here are some examples:
*
* ```java
* assertEquals("google.com", getEffectiveTldPlusOne("google.com"));
* assertEquals("google.com", getEffectiveTldPlusOne("www.google.com"));
* assertNull(getEffectiveTldPlusOne("com"));
* assertNull(getEffectiveTldPlusOne("localhost"));
* assertNull(getEffectiveTldPlusOne("mymacbook"));
* ```
*
* @param domain A canonicalized domain. An International Domain Name (IDN) should be punycode
* encoded.
*/
fun getEffectiveTldPlusOne(domain: String): String? {
// We use UTF-8 in the list so we need to convert to Unicode.
val unicodeDomain = IDN.toUnicode(domain)
val domainLabels = splitDomain(unicodeDomain)
val rule = findMatchingRule(domainLabels)
if (domainLabels.size == rule.size && rule[0][0] != EXCEPTION_MARKER) {
return null // The domain is a public suffix.
}
val firstLabelOffset = if (rule[0][0] == EXCEPTION_MARKER) {
// Exception rules hold the effective TLD plus one.
domainLabels.size - rule.size
} else {
// Otherwise the rule is for a public suffix, so we must take one more label.
domainLabels.size - (rule.size + 1)
}
return splitDomain(domain).asSequence().drop(firstLabelOffset).joinToString(".")
}
private fun splitDomain(domain: String): List<String> {
val domainLabels = domain.split('.')
if (domainLabels.last() == "") {
// allow for domain name trailing dot
return domainLabels.dropLast(1)
}
return domainLabels
}
private fun findMatchingRule(domainLabels: List<String>): List<String> {
if (!listRead.get() && listRead.compareAndSet(false, true)) {
readTheListUninterruptibly()
} else {
try {
readCompleteLatch.await()
} catch (_: InterruptedException) {
Thread.currentThread().interrupt() // Retain interrupted status.
}
}
check(::publicSuffixListBytes.isInitialized) {
"Unable to load $PUBLIC_SUFFIX_RESOURCE resource from the classpath."
}
// Break apart the domain into UTF-8 labels, i.e. foo.bar.com turns into [foo, bar, com].
val domainLabelsUtf8Bytes = Array(domainLabels.size) { i -> domainLabels[i].toByteArray(UTF_8) }
// Start by looking for exact matches. We start at the leftmost label. For example, foo.bar.com
// will look like: [foo, bar, com], [bar, com], [com]. The longest matching rule wins.
var exactMatch: String? = null
for (i in domainLabelsUtf8Bytes.indices) {
val rule = publicSuffixListBytes.binarySearch(domainLabelsUtf8Bytes, i)
if (rule != null) {
exactMatch = rule
break
}
}
// In theory, wildcard rules are not restricted to having the wildcard in the leftmost position.
// In practice, wildcards are always in the leftmost position. For now, this implementation
// cheats and does not attempt every possible permutation. Instead, it only considers wildcards
// in the leftmost position. We assert this fact when we generate the public suffix file. If
// this assertion ever fails we'll need to refactor this implementation.
var wildcardMatch: String? = null
if (domainLabelsUtf8Bytes.size > 1) {
val labelsWithWildcard = domainLabelsUtf8Bytes.clone()
for (labelIndex in 0 until labelsWithWildcard.size - 1) {
labelsWithWildcard[labelIndex] = WILDCARD_LABEL
val rule = publicSuffixListBytes.binarySearch(labelsWithWildcard, labelIndex)
if (rule != null) {
wildcardMatch = rule
break
}
}
}
// Exception rules only apply to wildcard rules, so only try it if we matched a wildcard.
var exception: String? = null
if (wildcardMatch != null) {
for (labelIndex in 0 until domainLabelsUtf8Bytes.size - 1) {
val rule = publicSuffixExceptionListBytes.binarySearch(
domainLabelsUtf8Bytes, labelIndex)
if (rule != null) {
exception = rule
break
}
}
}
if (exception != null) {
// Signal we've identified an exception rule.
exception = "!$exception"
return exception.split('.')
} else if (exactMatch == null && wildcardMatch == null) {
return PREVAILING_RULE
}
val exactRuleLabels = exactMatch?.split('.') ?: listOf()
val wildcardRuleLabels = wildcardMatch?.split('.') ?: listOf()
return if (exactRuleLabels.size > wildcardRuleLabels.size) {
exactRuleLabels
} else {
wildcardRuleLabels
}
}
/**
* Reads the public suffix list treating the operation as uninterruptible. We always want to read
* the list otherwise we'll be left in a bad state. If the thread was interrupted prior to this
* operation, it will be re-interrupted after the list is read.
*/
private fun readTheListUninterruptibly() {
var interrupted = false
try {
while (true) {
try {
readTheList()
return
} catch (_: InterruptedIOException) {
Thread.interrupted() // Temporarily clear the interrupted state.
interrupted = true
} catch (e: IOException) {
Platform.get().log("Failed to read public suffix list", Platform.WARN, e)
return
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt() // Retain interrupted status.
}
}
}
@Throws(IOException::class)
private fun readTheList() {
var publicSuffixListBytes: ByteArray?
var publicSuffixExceptionListBytes: ByteArray?
val resource =
PublicSuffixDatabase::class.java.getResourceAsStream(PUBLIC_SUFFIX_RESOURCE) ?: return
GzipSource(resource.source()).buffer().use { bufferedSource ->
val totalBytes = bufferedSource.readInt()
publicSuffixListBytes = bufferedSource.readByteArray(totalBytes.toLong())
val totalExceptionBytes = bufferedSource.readInt()
publicSuffixExceptionListBytes = bufferedSource.readByteArray(totalExceptionBytes.toLong())
}
synchronized(this) {
this.publicSuffixListBytes = publicSuffixListBytes!!
this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes!!
}
readCompleteLatch.countDown()
}
/** Visible for testing. */
fun setListBytes(
publicSuffixListBytes: ByteArray,
publicSuffixExceptionListBytes: ByteArray
) {
this.publicSuffixListBytes = publicSuffixListBytes
this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes
listRead.set(true)
readCompleteLatch.countDown()
}
companion object {
const val PUBLIC_SUFFIX_RESOURCE = "publicsuffixes.gz"
private val WILDCARD_LABEL = byteArrayOf('*'.code.toByte())
private val PREVAILING_RULE = listOf("*")
private const val EXCEPTION_MARKER = '!'
private val instance = PublicSuffixDatabase()
fun get(): PublicSuffixDatabase {
return instance
}
private fun ByteArray.binarySearch(
labels: Array<ByteArray>,
labelIndex: Int
): String? {
var low = 0
var high = size
var match: String? = null
while (low < high) {
var mid = (low + high) / 2
// Search for a '\n' that marks the start of a value. Don't go back past the start of the
// array.
while (mid > -1 && this[mid] != '\n'.code.toByte()) {
mid--
}
mid++
// Now look for the ending '\n'.
var end = 1
while (this[mid + end] != '\n'.code.toByte()) {
end++
}
val publicSuffixLength = mid + end - mid
// Compare the bytes. Note that the file stores UTF-8 encoded bytes, so we must compare the
// unsigned bytes.
var compareResult: Int
var currentLabelIndex = labelIndex
var currentLabelByteIndex = 0
var publicSuffixByteIndex = 0
var expectDot = false
while (true) {
val byte0: Int
if (expectDot) {
byte0 = '.'.code
expectDot = false
} else {
byte0 = labels[currentLabelIndex][currentLabelByteIndex] and 0xff
}
val byte1 = this[mid + publicSuffixByteIndex] and 0xff
compareResult = byte0 - byte1
if (compareResult != 0) break
publicSuffixByteIndex++
currentLabelByteIndex++
if (publicSuffixByteIndex == publicSuffixLength) break
if (labels[currentLabelIndex].size == currentLabelByteIndex) {
// We've exhausted our current label. Either there are more labels to compare, in which
// case we expect a dot as the next character. Otherwise, we've checked all our labels.
if (currentLabelIndex == labels.size - 1) {
break
} else {
currentLabelIndex++
currentLabelByteIndex = -1
expectDot = true
}
}
}
if (compareResult < 0) {
high = mid - 1
} else if (compareResult > 0) {
low = mid + end + 1
} else {
// We found a match, but are the lengths equal?
val publicSuffixBytesLeft = publicSuffixLength - publicSuffixByteIndex
var labelBytesLeft = labels[currentLabelIndex].size - currentLabelByteIndex
for (i in currentLabelIndex + 1 until labels.size) {
labelBytesLeft += labels[i].size
}
if (labelBytesLeft < publicSuffixBytesLeft) {
high = mid - 1
} else if (labelBytesLeft > publicSuffixBytesLeft) {
low = mid + end + 1
} else {
// Found a match.
match = String(this, mid, publicSuffixLength, UTF_8)
break
}
}
}
return match
}
}
}
| apache-2.0 | 990919b1b97b47402e828e9bfe964e52 | 33.554252 | 100 | 0.653144 | 4.690685 | false | false | false | false |
nlgcoin/guldencoin-official | src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/SendCoinsFragment.kt | 2 | 22505 | // Copyright (c) 2018 The Gulden developers
// Authored by: Malcolm MacLeod ([email protected]), Willem de Jonge ([email protected])
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
package com.gulden.unity_wallet
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.gulden.jniunifiedbackend.AddressRecord
import com.gulden.jniunifiedbackend.ILibraryController
import com.gulden.jniunifiedbackend.UriRecipient
import com.gulden.unity_wallet.Config.Companion.PRECISION_SHORT
import com.gulden.unity_wallet.R.layout.text_input_address_label
import com.gulden.unity_wallet.ui.getDisplayDimensions
import com.gulden.unity_wallet.util.invokeNowOrOnSuccessfulCompletion
import kotlinx.android.synthetic.main.fragment_send_coins.view.*
import kotlinx.android.synthetic.main.text_input_address_label.view.*
import kotlinx.coroutines.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.appcompat.v7.Appcompat
import org.jetbrains.anko.dimen
import kotlin.coroutines.CoroutineContext
class SendCoinsFragment : BottomSheetDialogFragment(), CoroutineScope
{
override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob()
private var localRate: Double = 0.0
private lateinit var recipient: UriRecipient
private var foreignCurrency = localCurrency
private enum class EntryMode {
Native,
Local
}
private var entryMode = EntryMode.Native
set(value)
{
field = value
when (entryMode)
{
EntryMode.Local -> mMainlayout.findViewById<Button>(R.id.button_currency).text = "G"
EntryMode.Native -> mMainlayout.findViewById<Button>(R.id.button_currency).text = foreignCurrency.short
}
}
private var amountEditStr: String = "0"
set(value) {
field = value
updateDisplayAmount()
}
private val amount: Double
get() = amountEditStr.toDoubleOrZero()
private val foreignAmount: Double
get() {
return when (entryMode) {
EntryMode.Local -> amountEditStr.toDoubleOrZero()
EntryMode.Native -> amountEditStr.toDoubleOrZero() * localRate
}
}
private val recipientDisplayAddress: String
get () {
return if (recipient.label.isEmpty()) recipient.address else "${recipient.label} (${recipient.address})"
}
companion object {
const val EXTRA_RECIPIENT = "recipient"
const val EXTRA_FINISH_ACTIVITY_ON_CLOSE = "finish_on_close"
fun newInstance(recipient: UriRecipient, finishActivityOnClose : Boolean) = SendCoinsFragment().apply {
arguments = Bundle().apply {
putParcelable(EXTRA_RECIPIENT, recipient)
putBoolean(EXTRA_FINISH_ACTIVITY_ON_CLOSE, finishActivityOnClose)
}
}
}
private lateinit var fragmentActivity : Activity
private var mBehavior: BottomSheetBehavior<*>? = null
private lateinit var mSendCoinsReceivingStaticAddress : TextView
private lateinit var mSendCoinsReceivingStaticLabel : TextView
private lateinit var mLabelRemoveFromAddressBook : TextView
private lateinit var mLabelAddToAddressBook : TextView
private lateinit var mMainlayout : View
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog
{
val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
mMainlayout = View.inflate(context, R.layout.fragment_send_coins, null)
// test layout using display dimens
val outSize = getDisplayDimensions(context!!)
mMainlayout.measure(outSize.x, outSize.y)
// height that the entire bottom sheet wants to be
val preferredHeight = mMainlayout.measuredHeight
// maximum height that we allow it to be, to be sure that the balance shows through (if not hidden)
val allowedHeight = outSize.y - context!!.dimen(R.dimen.top_space_send_coins)
// programmatically adjust layout, only if needed
if (preferredHeight > allowedHeight) {
// for the preferredHeight numeric_keypad is square due to the ratio constraint, squeeze it to fit allowed height
val newHeight = outSize.x - (preferredHeight - allowedHeight)
// setup new layout params, stripping ratio constaint and adding newly calculatied height
val params = mMainlayout.numeric_keypad_holder.layoutParams as ConstraintLayout.LayoutParams
params.dimensionRatio = null
params.height = newHeight
params.matchConstraintMaxHeight = newHeight
// apply new layout
mMainlayout.numeric_keypad_holder.layoutParams = params
}
mSendCoinsReceivingStaticAddress = mMainlayout.findViewById(R.id.send_coins_receiving_static_address)
mSendCoinsReceivingStaticLabel = mMainlayout.findViewById(R.id.send_coins_receiving_static_label)
mLabelRemoveFromAddressBook = mMainlayout.findViewById(R.id.labelRemoveFromAddressBook)
mLabelAddToAddressBook = mMainlayout.findViewById(R.id.labelAddToAddressBook)
mSendCoinsReceivingStaticAddress = mMainlayout.findViewById(R.id.send_coins_receiving_static_address)
mMainlayout.findViewById<View>(R.id.button_0).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_1).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_2).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_3).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_4).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_5).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_6).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_7).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_8).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_9).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_send).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_currency).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_decimal).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_backspace).setOnClickListener { view -> handleKeypadButtonClick(view) }
mMainlayout.findViewById<View>(R.id.button_backspace).setOnLongClickListener { view -> handleKeypadButtonLongClick(view) }
mMainlayout.findViewById<View>(R.id.labelAddToAddressBook).setOnClickListener { view -> handleAddToAddressBookClick(view) }
mMainlayout.findViewById<View>(R.id.labelRemoveFromAddressBook).setOnClickListener { view -> handleRemoveFromAddressBookClick(view) }
dialog.setContentView(mMainlayout)
mBehavior = BottomSheetBehavior.from(mMainlayout.parent as View)
return dialog
}
override fun onStart()
{
super.onStart()
mBehavior!!.skipCollapsed = true
mBehavior!!.state = BottomSheetBehavior.STATE_EXPANDED
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val view = super.onCreateView(inflater, container, savedInstanceState)
fragmentActivity = super.getActivity()!!
arguments?.getParcelable<UriRecipient>(EXTRA_RECIPIENT)?.let {
recipient = it
}
if (recipient.amount != 0L)
amountEditStr = formatNativeSimple(recipient.amount)
updateDisplayAmount()
mSendCoinsReceivingStaticAddress.text = recipient.address
setAddressLabel(recipient.label)
foreignCurrency = localCurrency
setupRate()
return view
}
private fun updateDisplayAmount() {
var primaryStr = ""
var secondaryStr = ""
val amount = amountEditStr.toDoubleOrZero()
when (entryMode) {
EntryMode.Native -> {
primaryStr = "G %s".format(amountEditStr)
if (localRate > 0.0) {
secondaryStr = String.format("(%s %.${foreignCurrency.precision}f)", foreignCurrency.short, localRate * amount)
}
}
EntryMode.Local -> {
primaryStr = "%s %s".format(foreignCurrency.short, amountEditStr)
if (localRate > 0.0) {
secondaryStr = String.format("(G %.${PRECISION_SHORT}f)", amount / localRate)
}
}
}
(mMainlayout.findViewById<View>(R.id.send_coins_amount_primary) as TextView?)?.text = primaryStr
(mMainlayout.findViewById<View>(R.id.send_coins_amount_secondary) as TextView?)?.text = secondaryStr
}
private fun performAuthenticatedPayment(d : Dialog, request : UriRecipient, msg: String?, subtractFee: Boolean = false)
{
val amountStr = String.format("%.${PRECISION_SHORT}f", request.amount.toDouble() / 100000000)
val message = msg ?: getString(R.string.send_coins_confirm_template, amountStr, recipientDisplayAddress)
Authentication.instance.authenticate([email protected]!!,
null, msg = message) {
try {
ILibraryController.performPaymentToRecipient(request, subtractFee)
d.dismiss()
}
catch (exception: RuntimeException) {
errorMessage(exception.message!!)
}
}
}
private fun confirmAndCommitGuldenPayment()
{
val amountNativeStr = when (entryMode) {
EntryMode.Local -> (amountEditStr.toDoubleOrZero() / localRate).toString()
EntryMode.Native -> amountEditStr
}.toDoubleOrZero()
val amountNative = amountNativeStr.toNative()
try {
val paymentRequest = UriRecipient(true, recipient.address, recipient.label, recipient.desc, amountNative)
val fee = ILibraryController.feeForRecipient(paymentRequest)
val balance = ILibraryController.GetBalance()
if (fee > balance) {
errorMessage(getString(R.string.send_insufficient_balance))
return
}
if (fee + amountNative > balance) {
// alert dialog for confirmation of payment and reduction of amount since amount + fee exceeds balance
fragmentActivity.alert(Appcompat, getString(R.string.send_all_instead_msg), getString(R.string.send_all_instead_title)) {
// on confirmation compose recipient with reduced amount and execute payment with subtractFee fee from amount
positiveButton(getString(R.string.send_all_btn)) {
val sendAllRequest = UriRecipient(true, recipient.address, recipient.label, recipient.desc, balance)
performAuthenticatedPayment(dialog!!, sendAllRequest, null,true)
}
negativeButton(getString(R.string.cancel_btn)) {}
}.show()
} else {
// create styled message from resource template and arguments bundle
val amountStr = String.format("%.${PRECISION_SHORT}f", amountNativeStr)
val message = getString(R.string.send_coins_confirm_template, amountStr, recipientDisplayAddress)
// alert dialog for confirmation
fragmentActivity.alert(Appcompat, message, getString(R.string.send_gulden_title)) {
// on confirmation compose recipient and execute payment
positiveButton(getString(R.string.send_btn)) {
performAuthenticatedPayment(dialog!!, paymentRequest, null,false)
}
negativeButton(getString(R.string.cancel_btn)) {}
}.show()
}
} catch (exception: RuntimeException) {
errorMessage(exception.message!!)
}
}
private fun errorMessage(msg: String) {
fragmentActivity.alert(Appcompat, msg, "") {
positiveButton(getString(R.string.send_coins_error_acknowledge)) {}
}.show()
}
override fun onDestroy() {
super.onDestroy()
coroutineContext[Job]!!.cancel()
// Let the invisible URI activity know to close itself
arguments?.getBoolean(EXTRA_FINISH_ACTIVITY_ON_CLOSE)?.let {
if (it) {
activity?.moveTaskToBack(true)
activity?.finish()
}
}
}
private fun setupRate()
{
entryMode = EntryMode.Native
this.launch( Dispatchers.Main) {
try {
localRate = fetchCurrencyRate(foreignCurrency.code)
}
catch (e: Throwable) {
entryMode = EntryMode.Native
}
updateDisplayAmount()
}
}
private fun setAddressLabel(label : String)
{
mSendCoinsReceivingStaticLabel.text = label
if (label.isNotEmpty()) {
mSendCoinsReceivingStaticLabel.visibility = View.VISIBLE
mLabelRemoveFromAddressBook.visibility = View.INVISIBLE // use for layout already, when wallet is ready will become visible (or will be switched to add to address book)
mLabelAddToAddressBook.visibility = View.GONE
}
else {
mSendCoinsReceivingStaticLabel.visibility = View.GONE
mLabelRemoveFromAddressBook.visibility = View.GONE
mLabelAddToAddressBook.visibility = View.INVISIBLE // use for layout already, will become visible when wallet is ready
}
UnityCore.instance.walletReady.invokeNowOrOnSuccessfulCompletion(this) {
if (label.isNotEmpty())
{
val isInAddressBook = ILibraryController.getAddressBookRecords().count { it.name.equals(other = label, ignoreCase = true) } > 0
if (isInAddressBook) {
mLabelRemoveFromAddressBook.visibility = View.VISIBLE
mLabelAddToAddressBook.visibility = View.GONE
}
else {
mLabelRemoveFromAddressBook.visibility = View.GONE
mLabelAddToAddressBook.visibility = View.VISIBLE
}
}
else
{
mLabelRemoveFromAddressBook.visibility = View.GONE
mLabelAddToAddressBook.visibility = View.VISIBLE
}
}
}
private fun allowedDecimals(): Int {
return when(entryMode) {
EntryMode.Native -> PRECISION_SHORT
EntryMode.Local -> foreignCurrency.precision
}
}
private fun numFractionalDigits(amount:String): Int {
val pos = amount.indexOfLast { it == '.' }
return if (pos > 0) amount.length - pos - 1 else 0
}
private fun numWholeDigits(amount:String): Int {
val pos = amount.indexOfFirst { it == '.' }
return if (pos > 0) pos else amount.length
}
private fun chopExcessDecimals() {
if (numFractionalDigits(amountEditStr) > allowedDecimals()) {
amountEditStr = amountEditStr.substring(0, amountEditStr.length - (numFractionalDigits(amountEditStr) - allowedDecimals()))
}
}
private fun appendNumberToAmount(number : String) {
if (amountEditStr == "0")
{
amountEditStr = number
}
else
{
if (!amountEditStr.contains("."))
{
if (numWholeDigits(amountEditStr) < 8)
{
amountEditStr += number
}
}
else if (numFractionalDigits(amountEditStr) < allowedDecimals())
{
amountEditStr += number
}
else
{
if (numFractionalDigits(amountEditStr) < allowedDecimals())
{
amountEditStr += number
}
else
{
if (numWholeDigits(amountEditStr) < 8)
{
amountEditStr = buildString {
append(amountEditStr)
deleteCharAt(lastIndexOf("."))
append(number)
insert(length - allowedDecimals(), ".")
}.trimStart('0')
}
}
}
}
}
private fun handleKeypadButtonLongClick(view : View) : Boolean
{
when (view.id)
{
R.id.button_backspace ->
{
amountEditStr = "0"
}
}
return true
}
private fun handleSendButton()
{
if (!UnityCore.instance.walletReady.isCompleted) {
errorMessage(getString(R.string.core_not_ready_yet))
return
}
run {
if ((amountEditStr.isEmpty()) || (foreignAmount<=0 && amount<=0))
{
errorMessage("Enter an amount to pay")
return@run
}
confirmAndCommitGuldenPayment()
}
}
private fun handleKeypadButtonClick(view : View)
{
when (view.id)
{
R.id.button_1 -> appendNumberToAmount("1")
R.id.button_2 -> appendNumberToAmount("2")
R.id.button_3 -> appendNumberToAmount("3")
R.id.button_4 -> appendNumberToAmount("4")
R.id.button_5 -> appendNumberToAmount("5")
R.id.button_6 -> appendNumberToAmount("6")
R.id.button_7 -> appendNumberToAmount("7")
R.id.button_8 -> appendNumberToAmount("8")
R.id.button_9 -> appendNumberToAmount("9")
R.id.button_0 ->
{
if (amountEditStr.isEmpty()) amountEditStr += "0."
else if (amountEditStr != "0" && amountEditStr != "0.00") appendNumberToAmount("0")
}
R.id.button_backspace ->
{
amountEditStr = if (amountEditStr.length > 1)
amountEditStr.dropLast(1)
else
"0"
}
R.id.button_decimal ->
{
if (!amountEditStr.contains("."))
{
if (amountEditStr.isEmpty()) amountEditStr = "0."
else amountEditStr = "$amountEditStr."
}
}
R.id.button_currency ->
{
entryMode = when (entryMode) {
EntryMode.Local -> EntryMode.Native
EntryMode.Native -> EntryMode.Local
}
chopExcessDecimals()
updateDisplayAmount()
}
R.id.button_send ->
{
handleSendButton()
}
}
}
private fun handleAddToAddressBookClick(view : View)
{
if (!UnityCore.instance.walletReady.isCompleted) {
errorMessage(getString(R.string.core_not_ready_yet))
return
}
val builder = AlertDialog.Builder(fragmentActivity)
builder.setTitle(getString(R.string.dialog_title_add_address))
val layoutInflater : LayoutInflater = fragmentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val viewInflated : View = layoutInflater.inflate(text_input_address_label, view.rootView as ViewGroup, false)
viewInflated.labelAddAddressAddress.text = mSendCoinsReceivingStaticAddress.text
val input = viewInflated.findViewById(R.id.addAddressInput) as EditText
if (recipient.label.isNotEmpty()) {
input.setText(recipient.label)
}
builder.setView(viewInflated)
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
dialog.dismiss()
val label = input.text.toString()
val record = AddressRecord(mSendCoinsReceivingStaticAddress.text.toString(), label, "", "Send")
UnityCore.instance.addAddressBookRecord(record)
setAddressLabel(label)
}
builder.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.cancel() }
val dialog = builder.create()
dialog.setOnShowListener {
viewInflated.addAddressInput.requestFocus()
viewInflated.addAddressInput.post {
val imm = fragmentActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(viewInflated.addAddressInput, InputMethodManager.SHOW_IMPLICIT)
}
}
dialog.show()
}
@Suppress("UNUSED_PARAMETER")
fun handleRemoveFromAddressBookClick(view : View)
{
if (!UnityCore.instance.walletReady.isCompleted) {
errorMessage(getString(R.string.core_not_ready_yet))
return
}
val record = AddressRecord(mSendCoinsReceivingStaticAddress.text.toString(), mSendCoinsReceivingStaticLabel.text.toString(), "", "Send")
UnityCore.instance.deleteAddressBookRecord(record)
setAddressLabel("")
}
}
| mit | bb94caf0a0f472cd543ce9c299213286 | 39.54955 | 180 | 0.627461 | 4.779146 | false | false | false | false |
sys1yagi/DroiDon | app/src/main/java/com/sys1yagi/mastodon/android/view/TimelineAdapter.kt | 1 | 3931 | package com.sys1yagi.mastodon.android.view
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import android.widget.LinearLayout
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
import com.sys1yagi.mastodon.android.R
import com.sys1yagi.mastodon.android.data.model.TimelineStatus
import com.sys1yagi.mastodon.android.databinding.ListItemStatusBinding
import com.sys1yagi.mastodon.android.extensions.getDimensionPixelSize
import com.sys1yagi.mastodon.android.extensions.gone
import com.sys1yagi.mastodon.android.extensions.layoutInflator
import com.sys1yagi.mastodon.android.extensions.visible
import com.sys1yagi.mastodon4j.api.entity.Attachment
import io.reactivex.Observable
typealias OnReplayClick = (TimelineStatus) -> Unit
typealias OnReTweetClick = (TimelineStatus) -> Unit
typealias OnFavClick = (TimelineStatus) -> Unit
typealias OnOtherClick = (TimelineStatus) -> Unit
typealias OnAttachmentClick = (Int, List<Attachment>) -> Unit
class TimelineAdapter : RecyclerView.Adapter<TimelineAdapter.Holder>() {
class Holder(val binding: ListItemStatusBinding) : RecyclerView.ViewHolder(binding.root)
private val statues = arrayListOf<TimelineStatus>()
var onReplayClick: OnReplayClick = {}
var onReblogClick: OnReTweetClick = {}
var onFavClick: OnFavClick = {}
var onOtherClick: OnOtherClick = {}
var onAttachmentClick: OnAttachmentClick = { _, _ -> }
override fun onBindViewHolder(holder: Holder, position: Int) {
val timelineStatus = statues[position]
val status = timelineStatus.reblog?.let { it } ?: timelineStatus
val rebloggedBy = timelineStatus.reblog?.let { timelineStatus.entity.account }
status.entity.account?.let {
holder.binding.icon.setImageURI(it.avatar)
} ?: holder.binding.icon.setImageURI(null as String?)
showMedia(holder.binding.mediaContainer, status)
holder.apply {
binding.status = status
binding.rebloggedBy = rebloggedBy
binding.replay.setOnClickListener {
onReplayClick(status)
}
binding.retweet.setOnClickListener {
onReblogClick(status)
}
binding.fav.setOnClickListener {
onFavClick(status)
}
binding.other.setOnClickListener {
onOtherClick(status)
}
}
}
fun showMedia(mediaContainer: LinearLayout, status: TimelineStatus) {
val context = mediaContainer.context
mediaContainer.removeAllViews()
if (status.entity.mediaAttachments.isEmpty()) {
mediaContainer.gone()
} else {
mediaContainer.visible()
val attachments = status.entity.mediaAttachments
attachments.forEachIndexed { i, attachment ->
val image = SimpleDraweeView(context)
val roundingParams = RoundingParams.fromCornersRadius(8f)
image.hierarchy.roundingParams = roundingParams
image.setImageURI(attachment.previewUrl)
val params = LinearLayout.LayoutParams(0, context.getDimensionPixelSize(R.dimen.toot_media_preview_height))
params.weight = 1f
params.leftMargin = 2
mediaContainer.addView(image, params)
image.setOnClickListener {
onAttachmentClick(i, attachments)
}
}
}
}
override fun getItemCount() = statues.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
Holder(ListItemStatusBinding.inflate(parent.layoutInflator(), parent, false))
fun clear() {
this.statues.clear()
}
fun addAll(statues: List<TimelineStatus>) {
this.statues.addAll(0, statues)
notifyDataSetChanged()
}
}
| mit | d384eb7ffe3c9e5214ec88ba4fe9193b | 36.084906 | 123 | 0.678962 | 4.624706 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/history/HistoryDbHelper.kt | 1 | 3966 | package org.wikipedia.history
import android.text.TextUtils
import org.wikipedia.WikipediaApp
import org.wikipedia.database.contract.PageHistoryContract
import org.wikipedia.history.HistoryFragment.IndexedHistoryEntry
import org.wikipedia.page.PageTitle
import org.wikipedia.search.SearchResult
import org.wikipedia.search.SearchResult.SearchResultType
import org.wikipedia.search.SearchResults
import java.text.DateFormat
import java.util.*
import kotlin.collections.ArrayList
object HistoryDbHelper {
fun findHistoryItem(searchQuery: String): SearchResults {
val db = WikipediaApp.getInstance().database.readableDatabase
val titleCol = PageHistoryContract.PageWithImage.DISPLAY_TITLE.qualifiedName()
var selection: String? = null
var selectionArgs: Array<String>? = null
var searchStr = searchQuery
if (!TextUtils.isEmpty(searchStr)) {
searchStr = searchStr.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
selection = "UPPER($titleCol) LIKE UPPER(?) ESCAPE '\\'"
selectionArgs = arrayOf("%$searchStr%")
}
db.query(PageHistoryContract.PageWithImage.TABLES, PageHistoryContract.PageWithImage.PROJECTION,
selection,
selectionArgs,
null, null, PageHistoryContract.PageWithImage.ORDER_MRU).use { cursor ->
if (cursor.moveToFirst()) {
val indexedEntry = IndexedHistoryEntry(cursor)
val pageTitle: PageTitle = indexedEntry.entry.title
pageTitle.thumbUrl = indexedEntry.imageUrl
return SearchResults(Collections.singletonList(SearchResult(pageTitle, SearchResultType.HISTORY)))
}
}
return SearchResults()
}
fun filterHistoryItems(searchQuery: String): List<Any> {
val db = WikipediaApp.getInstance().database.readableDatabase
val titleCol = PageHistoryContract.PageWithImage.DISPLAY_TITLE.qualifiedName()
var selection: String? = null
var selectionArgs: Array<String>? = null
var searchStr = searchQuery
if (!TextUtils.isEmpty(searchStr)) {
searchStr = searchStr.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
selection = "UPPER($titleCol) LIKE UPPER(?) ESCAPE '\\'"
selectionArgs = arrayOf("%$searchStr%")
}
val list = ArrayList<Any>()
db.query(PageHistoryContract.PageWithImage.TABLES, PageHistoryContract.PageWithImage.PROJECTION,
selection,
selectionArgs,
null, null, PageHistoryContract.PageWithImage.ORDER_MRU).use { cursor ->
while (cursor.moveToNext()) {
val indexedEntry = IndexedHistoryEntry(cursor)
// Check the previous item, see if the times differ enough
// If they do, display the section header.
// Always do it if this is the first item.
// Check the previous item, see if the times differ enough
// If they do, display the section header.
// Always do it if this is the first item.
val curTime: String = getDateString(indexedEntry.entry.timestamp)
val prevTime: String
if (cursor.position != 0) {
cursor.moveToPrevious()
val prevEntry = HistoryEntry.DATABASE_TABLE.fromCursor(cursor)
prevTime = getDateString(prevEntry.timestamp)
if (curTime != prevTime) {
list.add(curTime)
}
cursor.moveToNext()
} else {
list.add(curTime)
}
list.add(indexedEntry)
}
}
return list
}
private fun getDateString(date: Date): String {
return DateFormat.getDateInstance().format(date)
}
}
| apache-2.0 | 579955f601748b3ac1dd9b677aa04c1f | 44.068182 | 114 | 0.613212 | 5.177546 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRListPersistentSearchHistory.kt | 1 | 1033 | // 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.ui.toolwindow
import com.intellij.openapi.components.*
import com.intellij.openapi.util.SimpleModificationTracker
import kotlinx.serialization.Serializable
@Service(Service.Level.PROJECT)
@State(name = "GitHubPullRequestSearchHistory", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)], reportStatistic = false)
internal class GHPRListPersistentSearchHistory :
SerializablePersistentStateComponent<GHPRListPersistentSearchHistory.HistoryState>(HistoryState()) {
@Serializable
data class HistoryState(var history: List<GHPRListSearchValue> = listOf())
private val tracker = SimpleModificationTracker()
var history: List<GHPRListSearchValue>
get() = state.history.toList()
set(value) {
state.history = value
tracker.incModificationCount()
}
override fun getStateModificationCount(): Long = tracker.modificationCount
}
| apache-2.0 | dc8fb6f8a3b2a664d91304c3cb8b51a3 | 38.730769 | 128 | 0.795741 | 4.827103 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateService.kt | 1 | 16960 | package eu.kanade.tachiyomi.data.library
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.IBinder
import android.os.PowerManager
import android.support.v4.app.NotificationCompat
import eu.kanade.tachiyomi.Constants
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.library.LibraryUpdateService.Companion.start
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.source.SourceManager
import eu.kanade.tachiyomi.data.source.online.OnlineSource
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.util.AndroidComponentUtil
import eu.kanade.tachiyomi.util.notification
import eu.kanade.tachiyomi.util.notificationManager
import eu.kanade.tachiyomi.util.syncChaptersWithSource
import rx.Observable
import rx.Subscription
import rx.schedulers.Schedulers
import uy.kohesive.injekt.injectLazy
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
/**
* This class will take care of updating the chapters of the manga from the library. It can be
* started calling the [start] method. If it's already running, it won't do anything.
* While the library is updating, a [PowerManager.WakeLock] will be held until the update is
* completed, preventing the device from going to sleep mode. A notification will display the
* progress of the update, and if case of an unexpected error, this service will be silently
* destroyed.
*/
class LibraryUpdateService : Service() {
/**
* Database helper.
*/
val db: DatabaseHelper by injectLazy()
/**
* Source manager.
*/
val sourceManager: SourceManager by injectLazy()
/**
* Preferences.
*/
val preferences: PreferencesHelper by injectLazy()
/**
* Wake lock that will be held until the service is destroyed.
*/
private lateinit var wakeLock: PowerManager.WakeLock
/**
* Subscription where the update is done.
*/
private var subscription: Subscription? = null
/**
* Id of the library update notification.
*/
private val notificationId: Int
get() = Constants.NOTIFICATION_LIBRARY_ID
private var notificationBitmap: Bitmap? = null
companion object {
/**
* Key for category to update.
*/
const val UPDATE_CATEGORY = "category"
/**
* Key for updating the details instead of the chapters.
*/
const val UPDATE_DETAILS = "details"
/**
* Returns the status of the service.
*
* @param context the application context.
* @return true if the service is running, false otherwise.
*/
fun isRunning(context: Context): Boolean {
return AndroidComponentUtil.isServiceRunning(context, LibraryUpdateService::class.java)
}
/**
* Starts the service. It will be started only if there isn't another instance already
* running.
*
* @param context the application context.
* @param category a specific category to update, or null for global update.
* @param details whether to update the details instead of the list of chapters.
*/
fun start(context: Context, category: Category? = null, details: Boolean = false) {
if (!isRunning(context)) {
val intent = Intent(context, LibraryUpdateService::class.java).apply {
putExtra(UPDATE_DETAILS, details)
category?.let { putExtra(UPDATE_CATEGORY, it.id) }
}
context.startService(intent)
}
}
/**
* Stops the service.
*
* @param context the application context.
*/
fun stop(context: Context) {
context.stopService(Intent(context, LibraryUpdateService::class.java))
}
}
/**
* Method called when the service is created. It injects dagger dependencies and acquire
* the wake lock.
*/
override fun onCreate() {
super.onCreate()
createAndAcquireWakeLock()
}
/**
* Method called when the service is destroyed. It destroys the running subscription, resets
* the alarm and release the wake lock.
*/
override fun onDestroy() {
subscription?.unsubscribe()
notificationBitmap?.recycle()
notificationBitmap = null
destroyWakeLock()
super.onDestroy()
}
/**
* This method needs to be implemented, but it's not used/needed.
*/
override fun onBind(intent: Intent): IBinder? {
return null
}
/**
* Method called when the service receives an intent.
*
* @param intent the start intent from.
* @param flags the flags of the command.
* @param startId the start id of this command.
* @return the start value of the command.
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) return Service.START_NOT_STICKY
// Unsubscribe from any previous subscription if needed.
subscription?.unsubscribe()
// Update favorite manga. Destroy service when completed or in case of an error.
subscription = Observable
.defer {
if (notificationBitmap == null) {
notificationBitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
}
val mangaList = getMangaToUpdate(intent)
// Update either chapter list or manga details.
if (!intent.getBooleanExtra(UPDATE_DETAILS, false))
updateChapterList(mangaList)
else
updateDetails(mangaList)
}
.subscribeOn(Schedulers.io())
.subscribe({
}, {
showNotification(getString(R.string.notification_update_error), "")
stopSelf(startId)
}, {
stopSelf(startId)
})
return Service.START_REDELIVER_INTENT
}
/**
* Returns the list of manga to be updated.
*
* @param intent the update intent.
* @return a list of manga to update
*/
fun getMangaToUpdate(intent: Intent): List<Manga> {
val categoryId = intent.getIntExtra(UPDATE_CATEGORY, -1)
var listToUpdate = if (categoryId != -1)
db.getLibraryMangas().executeAsBlocking().filter { it.category == categoryId }
else {
val categoriesToUpdate = preferences.libraryUpdateCategories().getOrDefault().map { it.toInt() }
if (categoriesToUpdate.isNotEmpty())
db.getLibraryMangas().executeAsBlocking()
.filter { it.category in categoriesToUpdate }
.distinctBy { it.id }
else
db.getFavoriteMangas().executeAsBlocking().distinctBy { it.id }
}
if (!intent.getBooleanExtra(UPDATE_DETAILS, false) && preferences.updateOnlyNonCompleted()) {
listToUpdate = listToUpdate.filter { it.status != Manga.COMPLETED }
}
return listToUpdate
}
/**
* Method that updates the given list of manga. It's called in a background thread, so it's safe
* to do heavy operations or network calls here.
* For each manga it calls [updateManga] and updates the notification showing the current
* progress.
*
* @param mangaToUpdate the list to update
* @return an observable delivering the progress of each update.
*/
fun updateChapterList(mangaToUpdate: List<Manga>): Observable<Manga> {
// Initialize the variables holding the progress of the updates.
val count = AtomicInteger(0)
val newUpdates = ArrayList<Manga>()
val failedUpdates = ArrayList<Manga>()
val cancelIntent = PendingIntent.getBroadcast(this, 0,
Intent(this, CancelUpdateReceiver::class.java), 0)
// Emit each manga and update it sequentially.
return Observable.from(mangaToUpdate)
// Notify manga that will update.
.doOnNext { showProgressNotification(it, count.andIncrement, mangaToUpdate.size, cancelIntent) }
// Update the chapters of the manga.
.concatMap { manga ->
updateManga(manga)
// If there's any error, return empty update and continue.
.onErrorReturn {
failedUpdates.add(manga)
Pair(0, 0)
}
// Filter out mangas without new chapters (or failed).
.filter { pair -> pair.first > 0 }
// Convert to the manga that contains new chapters.
.map { manga }
}
// Add manga with new chapters to the list.
.doOnNext { newUpdates.add(it) }
// Notify result of the overall update.
.doOnCompleted {
if (newUpdates.isEmpty()) {
cancelNotification()
} else {
showResultNotification(newUpdates, failedUpdates)
}
LibraryUpdateJob.setupTask()
}
}
/**
* Updates the chapters for the given manga and adds them to the database.
*
* @param manga the manga to update.
* @return a pair of the inserted and removed chapters.
*/
fun updateManga(manga: Manga): Observable<Pair<Int, Int>> {
val source = sourceManager.get(manga.source) as? OnlineSource ?: return Observable.empty()
return source.fetchChapterList(manga)
.map { syncChaptersWithSource(db, it, manga, source) }
}
/**
* Method that updates the details of the given list of manga. It's called in a background
* thread, so it's safe to do heavy operations or network calls here.
* For each manga it calls [updateManga] and updates the notification showing the current
* progress.
*
* @param mangaToUpdate the list to update
* @return an observable delivering the progress of each update.
*/
fun updateDetails(mangaToUpdate: List<Manga>): Observable<Manga> {
// Initialize the variables holding the progress of the updates.
val count = AtomicInteger(0)
val cancelIntent = PendingIntent.getBroadcast(this, 0,
Intent(this, CancelUpdateReceiver::class.java), 0)
// Emit each manga and update it sequentially.
return Observable.from(mangaToUpdate)
// Notify manga that will update.
.doOnNext { showProgressNotification(it, count.andIncrement, mangaToUpdate.size, cancelIntent) }
// Update the details of the manga.
.concatMap { manga ->
val source = sourceManager.get(manga.source) as? OnlineSource
?: return@concatMap Observable.empty<Manga>()
source.fetchMangaDetails(manga)
.doOnNext { networkManga ->
manga.copyFrom(networkManga)
db.insertManga(manga).executeAsBlocking()
}
.onErrorReturn { manga }
}
.doOnCompleted {
cancelNotification()
}
}
/**
* Returns the text that will be displayed in the notification when there are new chapters.
*
* @param updates a list of manga that contains new chapters.
* @param failedUpdates a list of manga that failed to update.
* @return the body of the notification to display.
*/
private fun getUpdatedMangasBody(updates: List<Manga>, failedUpdates: List<Manga>): String {
return with(StringBuilder()) {
if (updates.isEmpty()) {
append(getString(R.string.notification_no_new_chapters))
append("\n")
} else {
append(getString(R.string.notification_new_chapters))
for (manga in updates) {
append("\n")
append(manga.title)
}
}
if (!failedUpdates.isEmpty()) {
append("\n\n")
append(getString(R.string.notification_manga_update_failed))
for (manga in failedUpdates) {
append("\n")
append(manga.title)
}
}
toString()
}
}
/**
* Creates and acquires a wake lock until the library is updated.
*/
private fun createAndAcquireWakeLock() {
wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "LibraryUpdateService:WakeLock")
wakeLock.acquire()
}
/**
* Releases the wake lock if it's held.
*/
private fun destroyWakeLock() {
if (wakeLock.isHeld) {
wakeLock.release()
}
}
/**
* Shows the notification with the given title and body.
*
* @param title the title of the notification.
* @param body the body of the notification.
*/
private fun showNotification(title: String, body: String) {
notificationManager.notify(notificationId, notification() {
setSmallIcon(R.drawable.ic_refresh_white_24dp_img)
setLargeIcon(notificationBitmap)
setContentTitle(title)
setContentText(body)
})
}
/**
* Shows the notification containing the currently updating manga and the progress.
*
* @param manga the manga that's being updated.
* @param current the current progress.
* @param total the total progress.
*/
private fun showProgressNotification(manga: Manga, current: Int, total: Int, cancelIntent: PendingIntent) {
notificationManager.notify(notificationId, notification() {
setSmallIcon(R.drawable.ic_refresh_white_24dp_img)
setLargeIcon(notificationBitmap)
setContentTitle(manga.title)
setProgress(total, current, false)
setOngoing(true)
addAction(R.drawable.ic_clear_grey_24dp_img, getString(android.R.string.cancel), cancelIntent)
})
}
/**
* Shows the notification containing the result of the update done by the service.
*
* @param updates a list of manga with new updates.
* @param failed a list of manga that failed to update.
*/
private fun showResultNotification(updates: List<Manga>, failed: List<Manga>) {
val title = getString(R.string.notification_update_completed)
val body = getUpdatedMangasBody(updates, failed)
notificationManager.notify(notificationId, notification() {
setSmallIcon(R.drawable.ic_refresh_white_24dp_img)
setLargeIcon(notificationBitmap)
setContentTitle(title)
setStyle(NotificationCompat.BigTextStyle().bigText(body))
setContentIntent(notificationIntent)
setAutoCancel(true)
})
}
/**
* Cancels the notification.
*/
private fun cancelNotification() {
notificationManager.cancel(notificationId)
}
/**
* Property that returns an intent to open the main activity.
*/
private val notificationIntent: PendingIntent
get() {
val intent = Intent(this, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Class that stops updating the library.
*/
class CancelUpdateReceiver : BroadcastReceiver() {
/**
* Method called when user wants a library update.
* @param context the application context.
* @param intent the intent received.
*/
override fun onReceive(context: Context, intent: Intent) {
LibraryUpdateService.stop(context)
context.notificationManager.cancel(Constants.NOTIFICATION_LIBRARY_ID)
}
}
}
| apache-2.0 | fdff598810cf5e3b04af25915d0ec3a9 | 36.111597 | 112 | 0.607252 | 5.103822 | false | false | false | false |
Killian-LeClainche/Java-Base-Application-Engine | src/polaris/okapi/gui/Gui.kt | 1 | 897 | package polaris.okapi.gui
import polaris.okapi.App
import polaris.okapi.options.Settings
import polaris.okapi.render.*
import polaris.okapi.world.World
/**
* Created by Killian Le Clainche on 12/10/2017.
*/
abstract class Gui @JvmOverloads constructor(protected val application: App, val parent: Gui? = null, protected var ticksExisted: Double = 0.0) {
val settings: Settings = application.settings
var world: World? = application.currentWorld
val renderer: RenderManager = application.renderManager
val textures: TextureManager = application.textureManager
val fonts: FontManager = application.fontManager
val models: ModelManager = application.modelManager
open fun init() {}
open fun render(delta: Double) {
application.updateView()
ticksExisted += delta
}
open fun reinit() {}
open fun reload() {}
open fun close() {}
} | gpl-2.0 | db435de075cb749e1548cabb64dbd7e3 | 27.0625 | 145 | 0.719064 | 4.3125 | false | false | false | false |
flesire/ontrack | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/model/GitChangeLog.kt | 2 | 1388 | package net.nemerosa.ontrack.extension.git.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import net.nemerosa.ontrack.extension.scm.model.SCMBuildView
import net.nemerosa.ontrack.extension.scm.model.SCMChangeLog
import net.nemerosa.ontrack.model.structure.Project
@JsonPropertyOrder(alphabetic = true)
class GitChangeLog(
uuid: String,
project: Project,
scmBuildFrom: SCMBuildView<GitBuildInfo>,
scmBuildTo: SCMBuildView<GitBuildInfo>,
val syncError: Boolean
) : SCMChangeLog<GitBuildInfo>(uuid, project, scmBuildFrom, scmBuildTo) {
@JsonIgnore // Not sent to the client
var commits: GitChangeLogCommits? = null
@JsonIgnore // Not sent to the client
var issues: GitChangeLogIssues? = null
@JsonIgnore // Not sent to the client
var files: GitChangeLogFiles? = null
fun loadCommits(loader: (GitChangeLog) -> GitChangeLogCommits): GitChangeLogCommits {
return commits ?: run {
val loadedCommits = loader(this)
this.commits = loadedCommits
loadedCommits
}
}
fun withIssues(issues: GitChangeLogIssues): GitChangeLog {
this.issues = issues
return this
}
fun withFiles(files: GitChangeLogFiles): GitChangeLog {
this.files = files
return this
}
}
| mit | 10329221f010cb031a9ca0a96c4c4bfb | 29.844444 | 89 | 0.705331 | 4.521173 | false | false | false | false |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationSchemeManager.kt | 2 | 6095 | // 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.execution.impl
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeContentChangedHandler
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.execution.RunConfigurationConverter
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.configurations.UnknownConfigurationType
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.JDOMUtil
import gnu.trove.THashMap
import org.jdom.Element
import java.util.function.Function
private val LOG = logger<RunConfigurationSchemeManager>()
internal class RunConfigurationSchemeManager(private val manager: RunManagerImpl, private val templateDifferenceHelper: TemplateDifferenceHelper, private val isShared: Boolean, private val isWrapSchemeIntoComponentElement: Boolean) :
LazySchemeProcessor<RunnerAndConfigurationSettingsImpl, RunnerAndConfigurationSettingsImpl>(), SchemeContentChangedHandler<RunnerAndConfigurationSettingsImpl> {
private val converters by lazy {
ConfigurationType.CONFIGURATION_TYPE_EP.extensionList.filterIsInstance(RunConfigurationConverter::class.java)
}
override fun getSchemeKey(scheme: RunnerAndConfigurationSettingsImpl): String {
// here only isShared, because for workspace `workspaceSchemeManagerProvider.load` is used (see RunManagerImpl.loadState)
return when {
isShared -> {
if (scheme.type.isManaged) {
scheme.name
}
else {
// do not use name as scheme key for Unknown RC or for Rider (some Rider RC types can use RC with not unique names)
// using isManaged not strictly correct but separate API will be overkill for now
scheme.uniqueID
}
}
else -> "${scheme.type.id}-${scheme.name}"
}
}
override fun createScheme(dataHolder: SchemeDataHolder<RunnerAndConfigurationSettingsImpl>, name: String, attributeProvider: Function<in String, String?>, isBundled: Boolean): RunnerAndConfigurationSettingsImpl {
val settings = RunnerAndConfigurationSettingsImpl(manager)
val element = readData(settings, dataHolder)
manager.addConfiguration(element, settings, isCheckRecentsLimit = false)
return settings
}
private fun readData(settings: RunnerAndConfigurationSettingsImpl, dataHolder: SchemeDataHolder<RunnerAndConfigurationSettingsImpl>): Element {
var element = dataHolder.read()
if (isShared && element.name == "component") {
element = element.getChild("configuration") ?: throw RuntimeException("Unexpected element: " + JDOMUtil.write(element))
}
converters.any {
LOG.runAndLogException { it.convertRunConfigurationOnDemand(element) } ?: false
}
try {
settings.readExternal(element, isShared)
}
catch (e: InvalidDataException) {
LOG.error(e)
}
var elementAfterStateLoaded: Element? = element
if (!settings.needsToBeMigrated()) {
try {
elementAfterStateLoaded = writeScheme(settings)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot compute digest for RC using state after load", e)
}
}
// very important to not write file with only changed line separators
dataHolder.updateDigest(elementAfterStateLoaded)
return element
}
override fun getSchemeKey(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String): String? {
var name = attributeProvider.apply("name")
if (name == "<template>" || name == null) {
attributeProvider.apply("type")?.let {
if (name == null) {
name = "<template>"
}
name += " of type ${it}"
}
}
else if (name != null && !isShared) {
val typeId = attributeProvider.apply("type")
LOG.assertTrue(typeId != null)
return "$typeId-${name}"
}
return name
}
override fun isExternalizable(scheme: RunnerAndConfigurationSettingsImpl) = true
override fun schemeContentChanged(scheme: RunnerAndConfigurationSettingsImpl, name: String, dataHolder: SchemeDataHolder<RunnerAndConfigurationSettingsImpl>) {
readData(scheme, dataHolder)
manager.eventPublisher.runConfigurationChanged(scheme)
}
override fun onSchemeAdded(scheme: RunnerAndConfigurationSettingsImpl) {
// createScheme automatically call addConfiguration
}
override fun onSchemeDeleted(scheme: RunnerAndConfigurationSettingsImpl) {
manager.removeConfiguration(scheme)
}
override fun writeScheme(scheme: RunnerAndConfigurationSettingsImpl): Element? {
val result = super.writeScheme(scheme) ?: return null
if (isShared && isWrapSchemeIntoComponentElement) {
return Element("component")
.setAttribute("name", "ProjectRunConfigurationManager")
.addContent(result)
}
else if (scheme.isTemplate) {
val factory = scheme.factory
if (factory != UnknownConfigurationType.getInstance() && !templateDifferenceHelper.isTemplateModified(result, factory)) {
return null
}
}
return result
}
}
internal class TemplateDifferenceHelper(private val manager: RunManagerImpl) {
private val cachedSerializedTemplateIdToData = THashMap<ConfigurationFactory, Element>()
fun isTemplateModified(serialized: Element, factory: ConfigurationFactory): Boolean {
val originalTemplate = cachedSerializedTemplateIdToData.getOrPut(factory) {
JDOMUtil.internElement(manager.createTemplateSettings(factory).writeScheme())
}
return !JDOMUtil.areElementsEqual(serialized, originalTemplate)
}
fun clearCache() {
cachedSerializedTemplateIdToData.clear()
}
} | apache-2.0 | 9fb30f5e11d70c7d6f21647852eaceed | 38.329032 | 233 | 0.747662 | 5.28621 | false | true | false | false |
google/intellij-community | platform/configuration-store-impl/src/XmlElementStorage.kt | 5 | 16881 | // 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.configurationStore
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.PathMacroSubstitutor
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.vfs.LargeFileWriteRequestor
import com.intellij.openapi.vfs.SafeWriteRequestor
import com.intellij.util.LineSeparator
import com.intellij.util.SmartList
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.io.delete
import com.intellij.util.io.outputStream
import com.intellij.util.io.safeOutputStream
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet
import org.jdom.Attribute
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.io.FileNotFoundException
import java.io.OutputStream
import java.io.Writer
import java.nio.file.Path
import kotlin.math.min
abstract class XmlElementStorage protected constructor(val fileSpec: String,
protected val rootElementName: String?,
private val pathMacroSubstitutor: PathMacroSubstitutor? = null,
roamingType: RoamingType? = RoamingType.DEFAULT,
private val provider: StreamProvider? = null) : StorageBaseEx<StateMap>() {
val roamingType = roamingType ?: RoamingType.DEFAULT
protected abstract fun loadLocalData(): Element?
final override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean) = storageData.getState(componentName, archive)
final override fun archiveState(storageData: StateMap, componentName: String, serializedState: Element?) {
storageData.archive(componentName, serializedState)
}
final override fun hasState(storageData: StateMap, componentName: String) = storageData.hasState(componentName)
final override fun loadData() = loadElement()?.let { loadState(it) } ?: StateMap.EMPTY
private fun loadElement(useStreamProvider: Boolean = true): Element? {
var element: Element? = null
try {
val isLoadLocalData: Boolean
if (useStreamProvider && provider != null) {
isLoadLocalData = !provider.read(fileSpec, roamingType) { inputStream ->
inputStream?.let {
element = JDOMUtil.load(inputStream)
providerDataStateChanged(createDataWriterForElement(element!!, toString()), DataStateChanged.LOADED)
}
}
}
else {
isLoadLocalData = true
}
if (isLoadLocalData) {
element = loadLocalData()
}
}
catch (e: FileNotFoundException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot load data for $fileSpec", e)
}
return element
}
protected open fun providerDataStateChanged(writer: DataWriter?, type: DataStateChanged) {
}
private fun loadState(element: Element): StateMap {
beforeElementLoaded(element)
return StateMap.fromMap(FileStorageCoreUtil.load(element, pathMacroSubstitutor))
}
final override fun createSaveSessionProducer(): SaveSessionProducer? {
return if (checkIsSavingDisabled()) null else createSaveSession(getStorageData())
}
protected abstract fun createSaveSession(states: StateMap): SaveSessionProducer
override fun analyzeExternalChangesAndUpdateIfNeeded(componentNames: MutableSet<in String>) {
val oldData = storageDataRef.get()
val newData = getStorageData(true)
if (oldData == null) {
LOG.debug { "analyzeExternalChangesAndUpdateIfNeeded: old data null, load new for ${toString()}" }
componentNames.addAll(newData.keys())
}
else {
val changedComponentNames = getChangedComponentNames(oldData, newData)
if (changedComponentNames.isNotEmpty()) {
LOG.debug { "analyzeExternalChangesAndUpdateIfNeeded: changedComponentNames $changedComponentNames for ${toString()}" }
componentNames.addAll(changedComponentNames)
}
}
}
private fun setStates(oldStorageData: StateMap, newStorageData: StateMap?) {
if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) {
LOG.warn("Old storage data is not equal to current, new storage data was set anyway")
}
}
abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() {
private var copiedStates: MutableMap<String, Any>? = null
private var newLiveStates: MutableMap<String, Element>? = HashMap()
protected open fun isSaveAllowed() = !storage.checkIsSavingDisabled()
final override fun createSaveSession(): SaveSession? {
if (copiedStates == null || !isSaveAllowed()) {
return null
}
val stateMap = StateMap.fromMap(copiedStates!!)
val elements = save(stateMap, newLiveStates ?: throw IllegalStateException("createSaveSession was already called"))
newLiveStates = null
val writer: DataWriter?
if (elements == null) {
writer = null
}
else {
val rootAttributes = LinkedHashMap<String, String>()
storage.beforeElementSaved(elements, rootAttributes)
val macroManager = if (storage.pathMacroSubstitutor == null) null else (storage.pathMacroSubstitutor as TrackingPathMacroSubstitutorImpl).macroManager
writer = XmlDataWriter(storage.rootElementName, elements, rootAttributes, macroManager, storage.toString())
}
// during beforeElementSaved() elements can be modified and so, even if our save() never returns empty list, at this point, elements can be an empty list
return SaveExecutor(elements, writer, stateMap)
}
private inner class SaveExecutor(private val elements: MutableList<Element>?,
private val writer: DataWriter?,
private val stateMap: StateMap) : SaveSession, SafeWriteRequestor, LargeFileWriteRequestor {
override fun save() {
var isSavedLocally = false
val provider = storage.provider
if (elements == null) {
if (provider == null || !provider.delete(storage.fileSpec, storage.roamingType)) {
isSavedLocally = true
saveLocally(writer)
}
}
else if (provider != null && provider.isApplicable(storage.fileSpec, storage.roamingType)) {
// we should use standard line-separator (\n) - stream provider can share file content on any OS
provider.write(storage.fileSpec, writer!!.toBufferExposingByteArray(), storage.roamingType)
}
else {
isSavedLocally = true
saveLocally(writer)
}
if (!isSavedLocally) {
storage.providerDataStateChanged(writer, DataStateChanged.SAVED)
}
storage.setStates(originalStates, stateMap)
}
}
override fun setSerializedState(componentName: String, element: Element?) {
val newLiveStates = newLiveStates ?: throw IllegalStateException("createSaveSession was already called")
val normalized = element?.normalizeRootName()
if (copiedStates == null) {
copiedStates = setStateAndCloneIfNeeded(componentName, normalized, originalStates, newLiveStates)
}
else {
updateState(copiedStates!!, componentName, normalized, newLiveStates)
}
}
protected abstract fun saveLocally(dataWriter: DataWriter?)
}
protected open fun beforeElementLoaded(element: Element) {
}
protected open fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) {
}
fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) {
updatedFrom(changedComponentNames, deleted, true)
}
fun updatedFrom(changedComponentNames: MutableSet<String>, deleted: Boolean, useStreamProvider: Boolean) {
if (roamingType == RoamingType.DISABLED) {
// storage roaming was changed to DISABLED, but settings repository has old state
return
}
LOG.runAndLogException {
val newElement = if (deleted) null else loadElement(useStreamProvider)
val states = storageDataRef.get()
if (newElement == null) {
// if data was loaded, mark as changed all loaded components
if (states != null) {
changedComponentNames.addAll(states.keys())
setStates(states, null)
}
}
else if (states != null) {
val newStates = loadState(newElement)
changedComponentNames.addAll(getChangedComponentNames(states, newStates))
setStates(states, newStates)
}
}
}
}
internal class XmlDataWriter(private val rootElementName: String?,
private val elements: List<Element>,
private val rootAttributes: Map<String, String>,
private val macroManager: PathMacroManager?,
private val storageFilePathForDebugPurposes: String) : StringDataWriter() {
override fun hasData(filter: DataWriterFilter): Boolean {
return elements.any { filter.hasData(it) }
}
override fun write(writer: Writer, lineSeparator: String, filter: DataWriterFilter?) {
var lineSeparatorWithIndent = lineSeparator
val hasRootElement = rootElementName != null
val replacePathMap = macroManager?.replacePathMap
val macroFilter = macroManager?.macroFilter
if (hasRootElement) {
lineSeparatorWithIndent += " "
writer.append('<').append(rootElementName)
for (entry in rootAttributes) {
writer.append(' ')
writer.append(entry.key)
writer.append('=')
writer.append('"')
var value = entry.value
if (replacePathMap != null) {
value = replacePathMap.substitute(JDOMUtil.escapeText(value, false, true), SystemInfo.isFileSystemCaseSensitive)
}
writer.append(JDOMUtil.escapeText(value, false, true))
writer.append('"')
}
if (elements.isEmpty()) {
// see note in the save() why elements here can be an empty list
writer.append(" />")
return
}
writer.append('>')
}
val xmlOutputter = JbXmlOutputter(lineSeparatorWithIndent, filter?.toElementFilter(), replacePathMap, macroFilter, storageFilePathForDebugPurposes = storageFilePathForDebugPurposes)
for (element in elements) {
if (hasRootElement) {
writer.append(lineSeparatorWithIndent)
}
xmlOutputter.printElement(writer, element, 0)
}
if (rootElementName != null) {
writer.append(lineSeparator)
writer.append("</").append(rootElementName).append('>')
}
}
}
private fun save(states: StateMap, newLiveStates: Map<String, Element>): MutableList<Element>? {
if (states.isEmpty()) {
return null
}
var result: MutableList<Element>? = null
for (componentName in states.keys()) {
val element: Element
try {
element = states.getElement(componentName, newLiveStates)?.clone() ?: continue
}
catch (e: Exception) {
LOG.error("Cannot save \"$componentName\" data", e)
continue
}
// name attribute should be first
val elementAttributes = element.attributes
var nameAttribute = element.getAttribute(FileStorageCoreUtil.NAME)
if (nameAttribute != null && nameAttribute === elementAttributes[0] && componentName == nameAttribute.value) {
// all is OK
}
else {
if (nameAttribute == null) {
nameAttribute = Attribute(FileStorageCoreUtil.NAME, componentName)
elementAttributes.add(0, nameAttribute)
}
else {
nameAttribute.value = componentName
if (elementAttributes[0] != nameAttribute) {
elementAttributes.remove(nameAttribute)
elementAttributes.add(0, nameAttribute)
}
}
}
if (result == null) {
result = SmartList()
}
result.add(element)
}
return result
}
internal fun Element.normalizeRootName(): Element {
if (org.jdom.JDOMInterner.isInterned(this)) {
if (name == FileStorageCoreUtil.COMPONENT) {
return this
}
else {
val clone = clone()
clone.name = FileStorageCoreUtil.COMPONENT
return clone
}
}
else {
if (parent != null) {
LOG.warn("State element must not have a parent: ${JDOMUtil.writeElement(this)}")
detach()
}
name = FileStorageCoreUtil.COMPONENT
return this
}
}
// newStorageData - myStates contains only live (unarchived) states
private fun getChangedComponentNames(oldStateMap: StateMap, newStateMap: StateMap): Set<String> {
val newKeys = newStateMap.keys()
val existingKeys = oldStateMap.keys()
val bothStates = ArrayList<String>(min(newKeys.size, existingKeys.size))
@Suppress("SSBasedInspection")
val existingKeysSet = if (existingKeys.size < 3) existingKeys.asList() else ObjectOpenHashSet(existingKeys)
for (newKey in newKeys) {
if (existingKeysSet.contains(newKey)) {
bothStates.add(newKey)
}
}
val diffs = CollectionFactory.createSmallMemoryFootprintSet<String>(newKeys.size + existingKeys.size)
diffs.addAll(newKeys)
diffs.addAll(existingKeys)
for (state in bothStates) {
diffs.remove(state)
}
for (componentName in bothStates) {
oldStateMap.compare(componentName, newStateMap, diffs)
}
return diffs
}
enum class DataStateChanged {
LOADED, SAVED
}
interface DataWriterFilter {
enum class ElementLevel {
ZERO, FIRST
}
companion object {
fun requireAttribute(name: String, onLevel: ElementLevel): DataWriterFilter {
return object: DataWriterFilter {
override fun toElementFilter(): JDOMUtil.ElementOutputFilter {
return JDOMUtil.ElementOutputFilter { childElement, level -> level != onLevel.ordinal || childElement.getAttribute(name) != null }
}
override fun hasData(element: Element): Boolean {
val elementFilter = toElementFilter()
if (onLevel == ElementLevel.ZERO && elementFilter.accept(element, 0)) {
return true
}
return element.children.any { elementFilter.accept(it, 1) }
}
}
}
}
fun toElementFilter(): JDOMUtil.ElementOutputFilter
fun hasData(element: Element): Boolean
}
interface DataWriter {
// LineSeparator cannot be used because custom (with an indent) line separator can be used
fun write(output: OutputStream, lineSeparator: String = LineSeparator.LF.separatorString, filter: DataWriterFilter? = null)
fun hasData(filter: DataWriterFilter): Boolean
}
internal fun DataWriter?.writeTo(file: Path, requestor: Any?, lineSeparator: String = LineSeparator.LF.separatorString) {
if (this == null) {
file.delete()
}
else {
val safe = SafeWriteRequestor.shouldUseSafeWrite(requestor)
(if (safe) file.safeOutputStream() else file.outputStream()).use {
write(it, lineSeparator)
}
}
}
internal abstract class StringDataWriter : DataWriter {
final override fun write(output: OutputStream, lineSeparator: String, filter: DataWriterFilter?) {
output.bufferedWriter().use {
write(it, lineSeparator, filter)
}
}
internal abstract fun write(writer: Writer, lineSeparator: String, filter: DataWriterFilter?)
}
internal fun DataWriter.toBufferExposingByteArray(lineSeparator: LineSeparator = LineSeparator.LF): BufferExposingByteArrayOutputStream {
val out = BufferExposingByteArrayOutputStream(1024)
out.use { write(out, lineSeparator.separatorString) }
return out
}
// use ONLY for non-ordinal usages (default project, deprecated directoryBased storage)
internal fun createDataWriterForElement(element: Element, storageFilePathForDebugPurposes: String): DataWriter {
return object: DataWriter {
override fun hasData(filter: DataWriterFilter) = filter.hasData(element)
override fun write(output: OutputStream, lineSeparator: String, filter: DataWriterFilter?) {
output.bufferedWriter().use {
JbXmlOutputter(lineSeparator, elementFilter = filter?.toElementFilter(), storageFilePathForDebugPurposes = storageFilePathForDebugPurposes).output(element, it)
}
}
}
}
@ApiStatus.Internal
interface ExternalStorageWithInternalPart {
val internalStorage: StateStorage
} | apache-2.0 | b9fb451ef1117d6e93c1d7446ebbfd88 | 35.7 | 185 | 0.6967 | 5.069369 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/WithAssertConsistency.kt | 2 | 1842 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
// ------------------- Entity with consistency assertion --------------------------------
interface AssertConsistencyEntity : WorkspaceEntity {
val passCheck: Boolean
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : AssertConsistencyEntity, ModifiableWorkspaceEntity<AssertConsistencyEntity>, ObjBuilder<AssertConsistencyEntity> {
override var entitySource: EntitySource
override var passCheck: Boolean
}
companion object : Type<AssertConsistencyEntity, Builder>() {
operator fun invoke(passCheck: Boolean, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): AssertConsistencyEntity {
val builder = builder()
builder.passCheck = passCheck
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: AssertConsistencyEntity,
modification: AssertConsistencyEntity.Builder.() -> Unit) = modifyEntity(
AssertConsistencyEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addAssertConsistencyEntity(passCheck: Boolean, source: EntitySource = MySource): AssertConsistencyEntity {
val assertConsistencyEntity = AssertConsistencyEntity(passCheck, source)
this.addEntity(assertConsistencyEntity)
return assertConsistencyEntity
}
| apache-2.0 | 7c40c76cdf8942e264868b1b129b29ed | 36.591837 | 136 | 0.767101 | 5.323699 | false | false | false | false |
google/intellij-community | java/debugger/memory-agent/src/com/intellij/debugger/memory/agent/extractor/AgentExtractor.kt | 3 | 1568 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.memory.agent.extractor
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import java.io.File
import java.io.FileNotFoundException
import java.nio.file.Files
import java.nio.file.Path
object AgentExtractor {
private lateinit var extractedFile: File
private var lastModified = -1L
@Synchronized
fun extract(agentType: AgentLibraryType, directory: Path): Path {
if (!::extractedFile.isInitialized || !extractedFile.exists() || extractedFile.lastModified() != lastModified) {
val agentFileName = "${agentType.prefix}memory_agent${agentType.suffix}"
val file = FileUtilRt.createTempFile(directory.toFile(), "${agentType.prefix}memory_agent", agentType.suffix, true)
val inputStream = AgentExtractor::class.java.classLoader.getResourceAsStream("bin/$agentFileName") ?: throw FileNotFoundException(agentFileName)
inputStream.use { input ->
Files.newOutputStream(file.toPath()).use { output ->
FileUtil.copy(input, output)
}
}
extractedFile = file
lastModified = file.lastModified()
}
return extractedFile.toPath()
}
enum class AgentLibraryType(val prefix: String, val suffix: String) {
WINDOWS32("", "32.dll"),
WINDOWS64("", ".dll"),
LINUX_X64("lib", ".so"),
LINUX_AARCH64("lib", "_aarch64.so"),
MACOS("lib", ".dylib")
}
}
| apache-2.0 | 4dfe8f1d9d54c3b228d3497036d03841 | 38.2 | 152 | 0.703444 | 4.26087 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/CliArgumentStringBuilder.kt | 3 | 3266 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.codeInsight
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
object CliArgumentStringBuilder {
private const val LANGUAGE_FEATURE_FLAG_PREFIX = "-XXLanguage:"
private const val LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX = "-X"
private val LanguageFeature.dedicatedFlagInfo
get() = when (this) {
LanguageFeature.InlineClasses -> Pair("inline-classes", KotlinVersion(1, 3, 50))
else -> null
}
private val LanguageFeature.State.sign: String
get() = when (this) {
LanguageFeature.State.ENABLED -> "+"
LanguageFeature.State.DISABLED -> "-"
LanguageFeature.State.ENABLED_WITH_WARNING -> "+" // not supported normally
LanguageFeature.State.ENABLED_WITH_ERROR -> "-" // not supported normally
}
private fun LanguageFeature.getFeatureMentionInCompilerArgsRegex(): Regex {
val basePattern = "$LANGUAGE_FEATURE_FLAG_PREFIX(?:-|\\+)$name"
val fullPattern =
if (dedicatedFlagInfo != null) "(?:$basePattern)|$LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX${dedicatedFlagInfo!!.first}" else basePattern
return Regex(fullPattern)
}
fun LanguageFeature.buildArgumentString(state: LanguageFeature.State, kotlinVersion: IdeKotlinVersion?): String {
val shouldBeFeatureEnabled = state == LanguageFeature.State.ENABLED || state == LanguageFeature.State.ENABLED_WITH_WARNING
val dedicatedFlag = dedicatedFlagInfo?.run {
val (xFlag, xFlagSinceVersion) = this
if (kotlinVersion == null || kotlinVersion.kotlinVersion >= xFlagSinceVersion) xFlag else null
}
return if (shouldBeFeatureEnabled && dedicatedFlag != null) {
LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX + dedicatedFlag
} else {
"$LANGUAGE_FEATURE_FLAG_PREFIX${state.sign}$name"
}
}
fun String.replaceLanguageFeature(
feature: LanguageFeature,
state: LanguageFeature.State,
kotlinVersion: IdeKotlinVersion?,
prefix: String = "",
postfix: String = "",
separator: String = ", ",
quoted: Boolean = true
): String {
val quote = if (quoted) "\"" else ""
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val existingFeatureMatchResult = feature.getFeatureMentionInCompilerArgsRegex().find(this)
return if (existingFeatureMatchResult != null) {
replace(existingFeatureMatchResult.value, featureArgumentString)
} else {
val splitText = if (postfix.isNotEmpty()) split(postfix) else listOf(this, "")
if (splitText.size != 2) {
"$prefix$quote$featureArgumentString$quote$postfix"
} else {
val (mainPart, commentPart) = splitText
// In Groovy / Kotlin DSL, we can have comment after [...] or listOf(...)
mainPart + "$separator$quote$featureArgumentString$quote$postfix" + commentPart
}
}
}
} | apache-2.0 | 2e14ec9761d40862f84747f1f0389dd8 | 43.753425 | 146 | 0.657073 | 4.933535 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/config/DebuggerConfigurable.kt | 1 | 5269 | package org.jetbrains.haskell.debugger.config
import com.intellij.openapi.options.Configurable
import javax.swing.JComponent
import com.intellij.openapi.ui.ComboBox
import javax.swing.DefaultComboBoxModel
import com.intellij.ui.DocumentAdapter
import javax.swing.event.DocumentEvent
import java.awt.event.ItemListener
import java.awt.event.ItemEvent
import javax.swing.JPanel
import java.awt.GridBagLayout
import org.jetbrains.haskell.util.gridBagConstraints
import java.awt.Insets
import javax.swing.JLabel
import org.jetbrains.haskell.util.setConstraints
import java.awt.GridBagConstraints
import javax.swing.Box
import javax.swing.JCheckBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import org.jetbrains.haskell.debugger.utils.UIUtils
import javax.swing.JButton
import javax.swing.AbstractAction
import java.awt.event.ActionEvent
/**
* Manages debugger settings. Creates additional section in IDEA Settings and tracks changes appeared there to obtain
* debugger settings. The settings are as follows:
* 1) user can select what debugger he would like to use
* 2) user can switch ':trace' command off
*
* @author Habibullin Marat
*/
class DebuggerConfigurable : Configurable {
companion object {
private val ITEM_GHCI = "GHCi"
private val ITEM_REMOTE = "Remote"
private val TRACE_CHECKBOX_LABEL = "Switch off ':trace' command"
private val PRINT_DEBUG_OUTPUT_LABEL = "Print debugger output to stdout"
}
private val selectDebuggerComboBox: ComboBox<*> = ComboBox(DefaultComboBoxModel(arrayOf(ITEM_GHCI, ITEM_REMOTE)))
private val remoteDebuggerPathField: TextFieldWithBrowseButton = TextFieldWithBrowseButton()
private val traceSwitchOffCheckBox: JCheckBox = JCheckBox(TRACE_CHECKBOX_LABEL, false)
private val printDebugOutputCheckBox: JCheckBox = JCheckBox(PRINT_DEBUG_OUTPUT_LABEL, false)
private var isModified = false
override fun getDisplayName(): String? = "Haskell debugger"
override fun getHelpTopic(): String? = null
/**
* Creates UI for settings page
*/
override fun createComponent(): JComponent? {
remoteDebuggerPathField.addBrowseFolderListener(
"Select remote debugger executable",
null,
null,
FileChooserDescriptorFactory.createSingleLocalFileDescriptor())
val itemListener = object : ItemListener {
override fun itemStateChanged(e: ItemEvent) {
isModified = true
}
}
val docListener : DocumentAdapter = object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent?) {
isModified = true
}
}
selectDebuggerComboBox.addItemListener(itemListener)
remoteDebuggerPathField.textField!!.document!!.addDocumentListener(docListener)
traceSwitchOffCheckBox.addItemListener(itemListener)
printDebugOutputCheckBox.addItemListener(itemListener)
val result = JPanel(GridBagLayout())
UIUtils.addLabeledControl(result, 0, "Prefered debugger:", selectDebuggerComboBox, false)
UIUtils.addLabeledControl(result, 1, "Remote debugger path:", remoteDebuggerPathField)
result.add(traceSwitchOffCheckBox, gridBagConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0
gridwidth = 2
gridy = 2
})
result.add(printDebugOutputCheckBox, gridBagConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0
gridwidth = 2
gridy = 3
})
result.add(JPanel(), gridBagConstraints { gridx = 0; gridy = 4; weighty = 10.0 })
return result
}
override fun isModified(): Boolean = isModified
/**
* Actions performed when user press "Apply" button. Here we obtain settings and need to set them in some global
* debug settings object
*/
override fun apply() {
val ghciSelected = selectDebuggerComboBox.selectedIndex == 0
val remotePath = remoteDebuggerPathField.textField!!.text
val traceSwitchedOff = traceSwitchOffCheckBox.isSelected
val printDebugOutput = printDebugOutputCheckBox.isSelected
val state = HaskellDebugSettings.getInstance().state
state.debuggerType = if (ghciSelected) DebuggerType.GHCI else DebuggerType.REMOTE
state.remoteDebuggerPath = remotePath
state.traceOff = traceSwitchedOff
state.printDebugOutput = printDebugOutput
isModified = false
}
/**
* Actions performed when user press "Reset" button. Here we need to reset appropriate properties in global
* debug settings object
*/
override fun reset() {
val state = HaskellDebugSettings.getInstance().state
selectDebuggerComboBox.selectedIndex = if (state.debuggerType == DebuggerType.GHCI) 0 else 1
traceSwitchOffCheckBox.isSelected = state.traceOff
remoteDebuggerPathField.textField!!.text = state.remoteDebuggerPath
printDebugOutputCheckBox.isSelected = state.printDebugOutput
isModified = false
}
override fun disposeUIResources() {}
} | apache-2.0 | ea72bb59a382d0d4fd00863b05aec7b1 | 38.62406 | 117 | 0.713418 | 5.316852 | false | false | false | false |
mikepenz/Android-Iconics | material-design-dx-typeface-library/src/main/java/com/mikepenz/iconics/typeface/library/materialdesigndx/MaterialDesignDx.kt | 1 | 47490 | /*
* Copyright 2020 Mike Penz
*
* 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.mikepenz.iconics.typeface.library.materialdesigndx
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.typeface.ITypeface
import java.util.LinkedList
@Suppress("EnumEntryName")
object MaterialDesignDx : ITypeface {
override val fontRes: Int
get() = R.font.material_design_dx_font_v5_0_1
override val characters: Map<String, Char> by lazy {
Icon.values().associate { it.name to it.character }
}
override val mappingPrefix: String
get() = "gmf"
override val fontName: String
get() = "Material Design DX"
override val version: String
get() = "5.0.1"
override val iconCount: Int
get() = characters.size
override val icons: List<String>
get() = characters.keys.toCollection(LinkedList())
override val author: String
get() = "Jossef Harush"
override val url: String
get() = "https://github.com/jossef/material-design-icons-iconfont"
override val description: String
get() = "MDIDX - Same Material Design icons, Better DX"
override val license: String
get() = "Apache 2.0"
override val licenseUrl: String
get() = "https://www.apache.org/licenses/LICENSE-2.0"
override fun getIcon(key: String): IIcon = Icon.valueOf(key)
enum class Icon constructor(override val character: Char) : IIcon {
gmf_10k('\ue951'),
gmf_10mp('\ue952'),
gmf_11mp('\ue953'),
gmf_12mp('\ue954'),
gmf_13mp('\ue955'),
gmf_14mp('\ue956'),
gmf_15mp('\ue957'),
gmf_16mp('\ue958'),
gmf_17mp('\ue959'),
gmf_18mp('\ue95a'),
gmf_19mp('\ue95b'),
gmf_1k('\ue95c'),
gmf_1k_plus('\ue95d'),
gmf_20mp('\ue95e'),
gmf_21mp('\ue95f'),
gmf_22mp('\ue960'),
gmf_23mp('\ue961'),
gmf_24mp('\ue962'),
gmf_2k('\ue963'),
gmf_2k_plus('\ue964'),
gmf_2mp('\ue965'),
gmf_360('\ue577'),
gmf_3d_rotation('\ue84d'),
gmf_3k('\ue966'),
gmf_3k_plus('\ue967'),
gmf_3mp('\ue968'),
gmf_4k('\ue072'),
gmf_4k_plus('\ue969'),
gmf_4mp('\ue96a'),
gmf_5k('\ue96b'),
gmf_5k_plus('\ue96c'),
gmf_5mp('\ue96d'),
gmf_6k('\ue96e'),
gmf_6k_plus('\ue96f'),
gmf_6mp('\ue970'),
gmf_7k('\ue971'),
gmf_7k_plus('\ue972'),
gmf_7mp('\ue973'),
gmf_8k('\ue974'),
gmf_8k_plus('\ue975'),
gmf_8mp('\ue976'),
gmf_9k('\ue977'),
gmf_9k_plus('\ue978'),
gmf_9mp('\ue979'),
gmf_ac_unit('\ueb3b'),
gmf_access_alarm('\ue190'),
gmf_access_alarms('\ue191'),
gmf_access_time('\ue192'),
gmf_accessibility('\ue84e'),
gmf_accessibility_new('\ue92c'),
gmf_accessible('\ue914'),
gmf_accessible_forward('\ue934'),
gmf_account_balance('\ue84f'),
gmf_account_balance_wallet('\ue850'),
gmf_account_box('\ue851'),
gmf_account_circle('\ue853'),
gmf_account_tree('\ue97a'),
gmf_adb('\ue60e'),
gmf_add('\ue145'),
gmf_add_a_photo('\ue439'),
gmf_add_alarm('\ue193'),
gmf_add_alert('\ue003'),
gmf_add_box('\ue146'),
gmf_add_call('\ue0e8'),
gmf_add_chart('\ue97b'),
gmf_add_circle('\ue147'),
gmf_add_circle_outline('\ue148'),
gmf_add_comment('\ue266'),
gmf_add_ic_call('\ue97c'),
gmf_add_link('\ue178'),
gmf_add_location('\ue567'),
gmf_add_moderator('\ue97d'),
gmf_add_photo_alternate('\ue43e'),
gmf_add_shopping_cart('\ue854'),
gmf_add_to_home_screen('\ue1fe'),
gmf_add_to_photos('\ue39d'),
gmf_add_to_queue('\ue05c'),
gmf_adjust('\ue39e'),
gmf_airline_seat_flat('\ue630'),
gmf_airline_seat_flat_angled('\ue631'),
gmf_airline_seat_individual_suite('\ue632'),
gmf_airline_seat_legroom_extra('\ue633'),
gmf_airline_seat_legroom_normal('\ue634'),
gmf_airline_seat_legroom_reduced('\ue635'),
gmf_airline_seat_recline_extra('\ue636'),
gmf_airline_seat_recline_normal('\ue637'),
gmf_airplanemode_active('\ue195'),
gmf_airplanemode_inactive('\ue194'),
gmf_airplanemode_off('\ue194'),
gmf_airplanemode_on('\ue195'),
gmf_airplay('\ue055'),
gmf_airport_shuttle('\ueb3c'),
gmf_alarm('\ue855'),
gmf_alarm_add('\ue856'),
gmf_alarm_off('\ue857'),
gmf_alarm_on('\ue858'),
gmf_album('\ue019'),
gmf_all_inbox('\ue97f'),
gmf_all_inclusive('\ueb3d'),
gmf_all_out('\ue90b'),
gmf_alternate_email('\ue0e6'),
gmf_amp_stories('\uea13'),
gmf_android('\ue859'),
gmf_announcement('\ue85a'),
gmf_apartment('\uea40'),
gmf_approval('\ue982'),
gmf_apps('\ue5c3'),
gmf_archive('\ue149'),
gmf_arrow_back('\ue5c4'),
gmf_arrow_back_ios('\ue5e0'),
gmf_arrow_downward('\ue5db'),
gmf_arrow_drop_down('\ue5c5'),
gmf_arrow_drop_down_circle('\ue5c6'),
gmf_arrow_drop_up('\ue5c7'),
gmf_arrow_forward('\ue5c8'),
gmf_arrow_forward_ios('\ue5e1'),
gmf_arrow_left('\ue5de'),
gmf_arrow_right('\ue5df'),
gmf_arrow_right_alt('\ue941'),
gmf_arrow_upward('\ue5d8'),
gmf_art_track('\ue060'),
gmf_aspect_ratio('\ue85b'),
gmf_assessment('\ue85c'),
gmf_assignment('\ue85d'),
gmf_assignment_ind('\ue85e'),
gmf_assignment_late('\ue85f'),
gmf_assignment_return('\ue860'),
gmf_assignment_returned('\ue861'),
gmf_assignment_turned_in('\ue862'),
gmf_assistant('\ue39f'),
gmf_assistant_direction('\ue988'),
gmf_assistant_navigation('\ue989'),
gmf_assistant_photo('\ue3a0'),
gmf_atm('\ue573'),
gmf_attach_file('\ue226'),
gmf_attach_money('\ue227'),
gmf_attachment('\ue2bc'),
gmf_attractions('\uea52'),
gmf_audiotrack('\ue3a1'),
gmf_autorenew('\ue863'),
gmf_av_timer('\ue01b'),
gmf_backspace('\ue14a'),
gmf_backup('\ue864'),
gmf_badge('\uea67'),
gmf_bakery_dining('\uea53'),
gmf_ballot('\ue172'),
gmf_bar_chart('\ue26b'),
gmf_bathtub('\uea41'),
gmf_battery_alert('\ue19c'),
gmf_battery_charging_full('\ue1a3'),
gmf_battery_full('\ue1a4'),
gmf_battery_std('\ue1a5'),
gmf_battery_unknown('\ue1a6'),
gmf_beach_access('\ueb3e'),
gmf_beenhere('\ue52d'),
gmf_block('\ue14b'),
gmf_bluetooth('\ue1a7'),
gmf_bluetooth_audio('\ue60f'),
gmf_bluetooth_connected('\ue1a8'),
gmf_bluetooth_disabled('\ue1a9'),
gmf_bluetooth_searching('\ue1aa'),
gmf_blur_circular('\ue3a2'),
gmf_blur_linear('\ue3a3'),
gmf_blur_off('\ue3a4'),
gmf_blur_on('\ue3a5'),
gmf_bolt('\uea0b'),
gmf_book('\ue865'),
gmf_bookmark('\ue866'),
gmf_bookmark_border('\ue867'),
gmf_bookmark_outline('\ue867'),
gmf_bookmarks('\ue98b'),
gmf_border_all('\ue228'),
gmf_border_bottom('\ue229'),
gmf_border_clear('\ue22a'),
gmf_border_color('\ue22b'),
gmf_border_horizontal('\ue22c'),
gmf_border_inner('\ue22d'),
gmf_border_left('\ue22e'),
gmf_border_outer('\ue22f'),
gmf_border_right('\ue230'),
gmf_border_style('\ue231'),
gmf_border_top('\ue232'),
gmf_border_vertical('\ue233'),
gmf_branding_watermark('\ue06b'),
gmf_breakfast_dining('\uea54'),
gmf_brightness_1('\ue3a6'),
gmf_brightness_2('\ue3a7'),
gmf_brightness_3('\ue3a8'),
gmf_brightness_4('\ue3a9'),
gmf_brightness_5('\ue3aa'),
gmf_brightness_6('\ue3ab'),
gmf_brightness_7('\ue3ac'),
gmf_brightness_auto('\ue1ab'),
gmf_brightness_high('\ue1ac'),
gmf_brightness_low('\ue1ad'),
gmf_brightness_medium('\ue1ae'),
gmf_broken_image('\ue3ad'),
gmf_brunch_dining('\uea73'),
gmf_brush('\ue3ae'),
gmf_bubble_chart('\ue6dd'),
gmf_bug_report('\ue868'),
gmf_build('\ue869'),
gmf_burst_mode('\ue43c'),
gmf_bus_alert('\ue98f'),
gmf_business('\ue0af'),
gmf_business_center('\ueb3f'),
gmf_cached('\ue86a'),
gmf_cake('\ue7e9'),
gmf_calendar_today('\ue935'),
gmf_calendar_view_day('\ue936'),
gmf_call('\ue0b0'),
gmf_call_end('\ue0b1'),
gmf_call_made('\ue0b2'),
gmf_call_merge('\ue0b3'),
gmf_call_missed('\ue0b4'),
gmf_call_missed_outgoing('\ue0e4'),
gmf_call_received('\ue0b5'),
gmf_call_split('\ue0b6'),
gmf_call_to_action('\ue06c'),
gmf_camera('\ue3af'),
gmf_camera_alt('\ue3b0'),
gmf_camera_enhance('\ue8fc'),
gmf_camera_front('\ue3b1'),
gmf_camera_rear('\ue3b2'),
gmf_camera_roll('\ue3b3'),
gmf_cancel('\ue5c9'),
gmf_cancel_presentation('\ue0e9'),
gmf_cancel_schedule_send('\uea39'),
gmf_car_rental('\uea55'),
gmf_car_repair('\uea56'),
gmf_card_giftcard('\ue8f6'),
gmf_card_membership('\ue8f7'),
gmf_card_travel('\ue8f8'),
gmf_cases('\ue992'),
gmf_casino('\ueb40'),
gmf_cast('\ue307'),
gmf_cast_connected('\ue308'),
gmf_category('\ue574'),
gmf_celebration('\uea65'),
gmf_cell_wifi('\ue0ec'),
gmf_center_focus_strong('\ue3b4'),
gmf_center_focus_weak('\ue3b5'),
gmf_change_history('\ue86b'),
gmf_chat('\ue0b7'),
gmf_chat_bubble('\ue0ca'),
gmf_chat_bubble_outline('\ue0cb'),
gmf_check('\ue5ca'),
gmf_check_box('\ue834'),
gmf_check_box_outline_blank('\ue835'),
gmf_check_circle('\ue86c'),
gmf_check_circle_outline('\ue92d'),
gmf_chevron_left('\ue5cb'),
gmf_chevron_right('\ue5cc'),
gmf_child_care('\ueb41'),
gmf_child_friendly('\ueb42'),
gmf_chrome_reader_mode('\ue86d'),
gmf_circle_notifications('\ue994'),
gmf_class('\ue86e'),
gmf_clear('\ue14c'),
gmf_clear_all('\ue0b8'),
gmf_close('\ue5cd'),
gmf_closed_caption('\ue01c'),
gmf_closed_caption_off('\ue996'),
gmf_cloud('\ue2bd'),
gmf_cloud_circle('\ue2be'),
gmf_cloud_done('\ue2bf'),
gmf_cloud_download('\ue2c0'),
gmf_cloud_off('\ue2c1'),
gmf_cloud_queue('\ue2c2'),
gmf_cloud_upload('\ue2c3'),
gmf_code('\ue86f'),
gmf_collections('\ue3b6'),
gmf_collections_bookmark('\ue431'),
gmf_color_lens('\ue3b7'),
gmf_colorize('\ue3b8'),
gmf_comment('\ue0b9'),
gmf_commute('\ue940'),
gmf_compare('\ue3b9'),
gmf_compare_arrows('\ue915'),
gmf_compass_calibration('\ue57c'),
gmf_compress('\ue94d'),
gmf_computer('\ue30a'),
gmf_confirmation_num('\ue638'),
gmf_confirmation_number('\ue638'),
gmf_connected_tv('\ue998'),
gmf_contact_mail('\ue0d0'),
gmf_contact_phone('\ue0cf'),
gmf_contact_support('\ue94c'),
gmf_contactless('\uea71'),
gmf_contacts('\ue0ba'),
gmf_content_copy('\ue14d'),
gmf_content_cut('\ue14e'),
gmf_content_paste('\ue14f'),
gmf_control_camera('\ue074'),
gmf_control_point('\ue3ba'),
gmf_control_point_duplicate('\ue3bb'),
gmf_copyright('\ue90c'),
gmf_create('\ue150'),
gmf_create_new_folder('\ue2cc'),
gmf_credit_card('\ue870'),
gmf_crop('\ue3be'),
gmf_crop_16_9('\ue3bc'),
gmf_crop_3_2('\ue3bd'),
gmf_crop_5_4('\ue3bf'),
gmf_crop_7_5('\ue3c0'),
gmf_crop_din('\ue3c1'),
gmf_crop_free('\ue3c2'),
gmf_crop_landscape('\ue3c3'),
gmf_crop_original('\ue3c4'),
gmf_crop_portrait('\ue3c5'),
gmf_crop_rotate('\ue437'),
gmf_crop_square('\ue3c6'),
gmf_dangerous('\ue99a'),
gmf_dashboard('\ue871'),
gmf_dashboard_customize('\ue99b'),
gmf_data_usage('\ue1af'),
gmf_date_range('\ue916'),
gmf_deck('\uea42'),
gmf_dehaze('\ue3c7'),
gmf_delete('\ue872'),
gmf_delete_forever('\ue92b'),
gmf_delete_outline('\ue92e'),
gmf_delete_sweep('\ue16c'),
gmf_delivery_dining('\uea72'),
gmf_departure_board('\ue576'),
gmf_description('\ue873'),
gmf_desktop_access_disabled('\ue99d'),
gmf_desktop_mac('\ue30b'),
gmf_desktop_windows('\ue30c'),
gmf_details('\ue3c8'),
gmf_developer_board('\ue30d'),
gmf_developer_mode('\ue1b0'),
gmf_device_hub('\ue335'),
gmf_device_thermostat('\ue1ff'),
gmf_device_unknown('\ue339'),
gmf_devices('\ue1b1'),
gmf_devices_other('\ue337'),
gmf_dialer_sip('\ue0bb'),
gmf_dialpad('\ue0bc'),
gmf_dinner_dining('\uea57'),
gmf_directions('\ue52e'),
gmf_directions_bike('\ue52f'),
gmf_directions_boat('\ue532'),
gmf_directions_bus('\ue530'),
gmf_directions_car('\ue531'),
gmf_directions_ferry('\ue532'),
gmf_directions_railway('\ue534'),
gmf_directions_run('\ue566'),
gmf_directions_subway('\ue533'),
gmf_directions_train('\ue534'),
gmf_directions_transit('\ue535'),
gmf_directions_walk('\ue536'),
gmf_disc_full('\ue610'),
gmf_dnd_forwardslash('\ue611'),
gmf_dns('\ue875'),
gmf_do_not_disturb('\ue612'),
gmf_do_not_disturb_alt('\ue611'),
gmf_do_not_disturb_off('\ue643'),
gmf_do_not_disturb_on('\ue644'),
gmf_dock('\ue30e'),
gmf_domain('\ue7ee'),
gmf_domain_disabled('\ue0ef'),
gmf_done('\ue876'),
gmf_done_all('\ue877'),
gmf_done_outline('\ue92f'),
gmf_donut_large('\ue917'),
gmf_donut_small('\ue918'),
gmf_double_arrow('\uea50'),
gmf_drafts('\ue151'),
gmf_drag_handle('\ue25d'),
gmf_drag_indicator('\ue945'),
gmf_drive_eta('\ue613'),
gmf_drive_file_move_outline('\ue9a1'),
gmf_drive_file_rename_outline('\ue9a2'),
gmf_drive_folder_upload('\ue9a3'),
gmf_dry_cleaning('\uea58'),
gmf_duo('\ue9a5'),
gmf_dvr('\ue1b2'),
gmf_dynamic_feed('\uea14'),
gmf_eco('\uea35'),
gmf_edit('\ue3c9'),
gmf_edit_attributes('\ue578'),
gmf_edit_location('\ue568'),
gmf_edit_off('\ue950'),
gmf_eject('\ue8fb'),
gmf_email('\ue0be'),
gmf_emoji_emotions('\uea22'),
gmf_emoji_events('\uea23'),
gmf_emoji_flags('\uea1a'),
gmf_emoji_food_beverage('\uea1b'),
gmf_emoji_nature('\uea1c'),
gmf_emoji_objects('\uea24'),
gmf_emoji_people('\uea1d'),
gmf_emoji_symbols('\uea1e'),
gmf_emoji_transportation('\uea1f'),
gmf_enhance_photo_translate('\ue8fc'),
gmf_enhanced_encryption('\ue63f'),
gmf_equalizer('\ue01d'),
gmf_error('\ue000'),
gmf_error_outline('\ue001'),
gmf_euro('\uea15'),
gmf_euro_symbol('\ue926'),
gmf_ev_station('\ue56d'),
gmf_event('\ue878'),
gmf_event_available('\ue614'),
gmf_event_busy('\ue615'),
gmf_event_note('\ue616'),
gmf_event_seat('\ue903'),
gmf_exit_to_app('\ue879'),
gmf_expand('\ue94f'),
gmf_expand_less('\ue5ce'),
gmf_expand_more('\ue5cf'),
gmf_explicit('\ue01e'),
gmf_explore('\ue87a'),
gmf_explore_off('\ue9a8'),
gmf_exposure('\ue3ca'),
gmf_exposure_minus_1('\ue3cb'),
gmf_exposure_minus_2('\ue3cc'),
gmf_exposure_neg_1('\ue3cb'),
gmf_exposure_neg_2('\ue3cc'),
gmf_exposure_plus_1('\ue3cd'),
gmf_exposure_plus_2('\ue3ce'),
gmf_exposure_zero('\ue3cf'),
gmf_extension('\ue87b'),
gmf_face('\ue87c'),
gmf_fast_forward('\ue01f'),
gmf_fast_rewind('\ue020'),
gmf_fastfood('\ue57a'),
gmf_favorite('\ue87d'),
gmf_favorite_border('\ue87e'),
gmf_favorite_outline('\ue87e'),
gmf_featured_play_list('\ue06d'),
gmf_featured_video('\ue06e'),
gmf_feedback('\ue87f'),
gmf_festival('\uea68'),
gmf_fiber_dvr('\ue05d'),
gmf_fiber_manual_record('\ue061'),
gmf_fiber_new('\ue05e'),
gmf_fiber_pin('\ue06a'),
gmf_fiber_smart_record('\ue062'),
gmf_file_copy('\ue173'),
gmf_file_download('\ue2c4'),
gmf_file_download_done('\ue9aa'),
gmf_file_present('\uea0e'),
gmf_file_upload('\ue2c6'),
gmf_filter('\ue3d3'),
gmf_filter_1('\ue3d0'),
gmf_filter_2('\ue3d1'),
gmf_filter_3('\ue3d2'),
gmf_filter_4('\ue3d4'),
gmf_filter_5('\ue3d5'),
gmf_filter_6('\ue3d6'),
gmf_filter_7('\ue3d7'),
gmf_filter_8('\ue3d8'),
gmf_filter_9('\ue3d9'),
gmf_filter_9_plus('\ue3da'),
gmf_filter_b_and_w('\ue3db'),
gmf_filter_center_focus('\ue3dc'),
gmf_filter_drama('\ue3dd'),
gmf_filter_frames('\ue3de'),
gmf_filter_hdr('\ue3df'),
gmf_filter_list('\ue152'),
gmf_filter_list_alt('\ue94e'),
gmf_filter_none('\ue3e0'),
gmf_filter_tilt_shift('\ue3e2'),
gmf_filter_vintage('\ue3e3'),
gmf_find_in_page('\ue880'),
gmf_find_replace('\ue881'),
gmf_fingerprint('\ue90d'),
gmf_fireplace('\uea43'),
gmf_first_page('\ue5dc'),
gmf_fit_screen('\uea10'),
gmf_fitness_center('\ueb43'),
gmf_flag('\ue153'),
gmf_flare('\ue3e4'),
gmf_flash_auto('\ue3e5'),
gmf_flash_off('\ue3e6'),
gmf_flash_on('\ue3e7'),
gmf_flight('\ue539'),
gmf_flight_land('\ue904'),
gmf_flight_takeoff('\ue905'),
gmf_flip('\ue3e8'),
gmf_flip_camera_android('\uea37'),
gmf_flip_camera_ios('\uea38'),
gmf_flip_to_back('\ue882'),
gmf_flip_to_front('\ue883'),
gmf_folder('\ue2c7'),
gmf_folder_open('\ue2c8'),
gmf_folder_shared('\ue2c9'),
gmf_folder_special('\ue617'),
gmf_font_download('\ue167'),
gmf_format_align_center('\ue234'),
gmf_format_align_justify('\ue235'),
gmf_format_align_left('\ue236'),
gmf_format_align_right('\ue237'),
gmf_format_bold('\ue238'),
gmf_format_clear('\ue239'),
gmf_format_color_fill('\ue23a'),
gmf_format_color_reset('\ue23b'),
gmf_format_color_text('\ue23c'),
gmf_format_indent_decrease('\ue23d'),
gmf_format_indent_increase('\ue23e'),
gmf_format_italic('\ue23f'),
gmf_format_line_spacing('\ue240'),
gmf_format_list_bulleted('\ue241'),
gmf_format_list_numbered('\ue242'),
gmf_format_list_numbered_rtl('\ue267'),
gmf_format_paint('\ue243'),
gmf_format_quote('\ue244'),
gmf_format_shapes('\ue25e'),
gmf_format_size('\ue245'),
gmf_format_strikethrough('\ue246'),
gmf_format_textdirection_l_to_r('\ue247'),
gmf_format_textdirection_r_to_l('\ue248'),
gmf_format_underline('\ue249'),
gmf_format_underlined('\ue249'),
gmf_forum('\ue0bf'),
gmf_forward('\ue154'),
gmf_forward_10('\ue056'),
gmf_forward_30('\ue057'),
gmf_forward_5('\ue058'),
gmf_free_breakfast('\ueb44'),
gmf_fullscreen('\ue5d0'),
gmf_fullscreen_exit('\ue5d1'),
gmf_functions('\ue24a'),
gmf_g_translate('\ue927'),
gmf_gamepad('\ue30f'),
gmf_games('\ue021'),
gmf_gavel('\ue90e'),
gmf_gesture('\ue155'),
gmf_get_app('\ue884'),
gmf_gif('\ue908'),
gmf_goat('\udbff'),
gmf_golf_course('\ueb45'),
gmf_gps_fixed('\ue1b3'),
gmf_gps_not_fixed('\ue1b4'),
gmf_gps_off('\ue1b5'),
gmf_grade('\ue885'),
gmf_gradient('\ue3e9'),
gmf_grain('\ue3ea'),
gmf_graphic_eq('\ue1b8'),
gmf_grid_off('\ue3eb'),
gmf_grid_on('\ue3ec'),
gmf_grid_view('\ue9b0'),
gmf_group('\ue7ef'),
gmf_group_add('\ue7f0'),
gmf_group_work('\ue886'),
gmf_hail('\ue9b1'),
gmf_hardware('\uea59'),
gmf_hd('\ue052'),
gmf_hdr_off('\ue3ed'),
gmf_hdr_on('\ue3ee'),
gmf_hdr_strong('\ue3f1'),
gmf_hdr_weak('\ue3f2'),
gmf_headset('\ue310'),
gmf_headset_mic('\ue311'),
gmf_headset_off('\ue33a'),
gmf_healing('\ue3f3'),
gmf_hearing('\ue023'),
gmf_height('\uea16'),
gmf_help('\ue887'),
gmf_help_outline('\ue8fd'),
gmf_high_quality('\ue024'),
gmf_highlight('\ue25f'),
gmf_highlight_off('\ue888'),
gmf_highlight_remove('\ue888'),
gmf_history('\ue889'),
gmf_home('\ue88a'),
gmf_home_filled('\ue9b2'),
gmf_home_work('\uea09'),
gmf_horizontal_split('\ue947'),
gmf_hot_tub('\ueb46'),
gmf_hotel('\ue53a'),
gmf_hourglass_empty('\ue88b'),
gmf_hourglass_full('\ue88c'),
gmf_house('\uea44'),
gmf_how_to_reg('\ue174'),
gmf_how_to_vote('\ue175'),
gmf_http('\ue902'),
gmf_https('\ue88d'),
gmf_icecream('\uea69'),
gmf_image('\ue3f4'),
gmf_image_aspect_ratio('\ue3f5'),
gmf_image_search('\ue43f'),
gmf_imagesearch_roller('\ue9b4'),
gmf_import_contacts('\ue0e0'),
gmf_import_export('\ue0c3'),
gmf_important_devices('\ue912'),
gmf_inbox('\ue156'),
gmf_indeterminate_check_box('\ue909'),
gmf_info('\ue88e'),
gmf_info_outline('\ue88f'),
gmf_input('\ue890'),
gmf_insert_chart('\ue24b'),
gmf_insert_chart_outlined('\ue26a'),
gmf_insert_comment('\ue24c'),
gmf_insert_drive_file('\ue24d'),
gmf_insert_emoticon('\ue24e'),
gmf_insert_invitation('\ue24f'),
gmf_insert_link('\ue250'),
gmf_insert_photo('\ue251'),
gmf_inventory('\ue179'),
gmf_invert_colors('\ue891'),
gmf_invert_colors_off('\ue0c4'),
gmf_invert_colors_on('\ue891'),
gmf_iso('\ue3f6'),
gmf_keyboard('\ue312'),
gmf_keyboard_arrow_down('\ue313'),
gmf_keyboard_arrow_left('\ue314'),
gmf_keyboard_arrow_right('\ue315'),
gmf_keyboard_arrow_up('\ue316'),
gmf_keyboard_backspace('\ue317'),
gmf_keyboard_capslock('\ue318'),
gmf_keyboard_control('\ue5d3'),
gmf_keyboard_hide('\ue31a'),
gmf_keyboard_return('\ue31b'),
gmf_keyboard_tab('\ue31c'),
gmf_keyboard_voice('\ue31d'),
gmf_king_bed('\uea45'),
gmf_kitchen('\ueb47'),
gmf_label('\ue892'),
gmf_label_important('\ue937'),
gmf_label_important_outline('\ue948'),
gmf_label_off('\ue9b6'),
gmf_label_outline('\ue893'),
gmf_landscape('\ue3f7'),
gmf_language('\ue894'),
gmf_laptop('\ue31e'),
gmf_laptop_chromebook('\ue31f'),
gmf_laptop_mac('\ue320'),
gmf_laptop_windows('\ue321'),
gmf_last_page('\ue5dd'),
gmf_launch('\ue895'),
gmf_layers('\ue53b'),
gmf_layers_clear('\ue53c'),
gmf_leak_add('\ue3f8'),
gmf_leak_remove('\ue3f9'),
gmf_lens('\ue3fa'),
gmf_library_add('\ue02e'),
gmf_library_add_check('\ue9b7'),
gmf_library_books('\ue02f'),
gmf_library_music('\ue030'),
gmf_lightbulb('\ue0f0'),
gmf_lightbulb_outline('\ue90f'),
gmf_line_style('\ue919'),
gmf_line_weight('\ue91a'),
gmf_linear_scale('\ue260'),
gmf_link('\ue157'),
gmf_link_off('\ue16f'),
gmf_linked_camera('\ue438'),
gmf_liquor('\uea60'),
gmf_list('\ue896'),
gmf_list_alt('\ue0ee'),
gmf_live_help('\ue0c6'),
gmf_live_tv('\ue639'),
gmf_local_activity('\ue53f'),
gmf_local_airport('\ue53d'),
gmf_local_atm('\ue53e'),
gmf_local_attraction('\ue53f'),
gmf_local_bar('\ue540'),
gmf_local_cafe('\ue541'),
gmf_local_car_wash('\ue542'),
gmf_local_convenience_store('\ue543'),
gmf_local_dining('\ue556'),
gmf_local_drink('\ue544'),
gmf_local_florist('\ue545'),
gmf_local_gas_station('\ue546'),
gmf_local_grocery_store('\ue547'),
gmf_local_hospital('\ue548'),
gmf_local_hotel('\ue549'),
gmf_local_laundry_service('\ue54a'),
gmf_local_library('\ue54b'),
gmf_local_mall('\ue54c'),
gmf_local_movies('\ue54d'),
gmf_local_offer('\ue54e'),
gmf_local_parking('\ue54f'),
gmf_local_pharmacy('\ue550'),
gmf_local_phone('\ue551'),
gmf_local_pizza('\ue552'),
gmf_local_play('\ue553'),
gmf_local_post_office('\ue554'),
gmf_local_print_shop('\ue555'),
gmf_local_printshop('\ue555'),
gmf_local_restaurant('\ue556'),
gmf_local_see('\ue557'),
gmf_local_shipping('\ue558'),
gmf_local_taxi('\ue559'),
gmf_location_city('\ue7f1'),
gmf_location_disabled('\ue1b6'),
gmf_location_history('\ue55a'),
gmf_location_off('\ue0c7'),
gmf_location_on('\ue0c8'),
gmf_location_searching('\ue1b7'),
gmf_lock('\ue897'),
gmf_lock_open('\ue898'),
gmf_lock_outline('\ue899'),
gmf_logout('\ue9ba'),
gmf_looks('\ue3fc'),
gmf_looks_3('\ue3fb'),
gmf_looks_4('\ue3fd'),
gmf_looks_5('\ue3fe'),
gmf_looks_6('\ue3ff'),
gmf_looks_one('\ue400'),
gmf_looks_two('\ue401'),
gmf_loop('\ue028'),
gmf_loupe('\ue402'),
gmf_low_priority('\ue16d'),
gmf_loyalty('\ue89a'),
gmf_lunch_dining('\uea61'),
gmf_mail('\ue158'),
gmf_mail_outline('\ue0e1'),
gmf_map('\ue55b'),
gmf_margin('\ue9bb'),
gmf_mark_as_unread('\ue9bc'),
gmf_markunread('\ue159'),
gmf_markunread_mailbox('\ue89b'),
gmf_maximize('\ue930'),
gmf_meeting_room('\ueb4f'),
gmf_memory('\ue322'),
gmf_menu('\ue5d2'),
gmf_menu_book('\uea19'),
gmf_menu_open('\ue9bd'),
gmf_merge_type('\ue252'),
gmf_message('\ue0c9'),
gmf_messenger('\ue0ca'),
gmf_messenger_outline('\ue0cb'),
gmf_mic('\ue029'),
gmf_mic_none('\ue02a'),
gmf_mic_off('\ue02b'),
gmf_minimize('\ue931'),
gmf_missed_video_call('\ue073'),
gmf_mms('\ue618'),
gmf_mobile_friendly('\ue200'),
gmf_mobile_off('\ue201'),
gmf_mobile_screen_share('\ue0e7'),
gmf_mode_comment('\ue253'),
gmf_mode_edit('\ue254'),
gmf_monetization_on('\ue263'),
gmf_money('\ue57d'),
gmf_money_off('\ue25c'),
gmf_monochrome_photos('\ue403'),
gmf_mood('\ue7f2'),
gmf_mood_bad('\ue7f3'),
gmf_more('\ue619'),
gmf_more_horiz('\ue5d3'),
gmf_more_vert('\ue5d4'),
gmf_motorcycle('\ue91b'),
gmf_mouse('\ue323'),
gmf_move_to_inbox('\ue168'),
gmf_movie('\ue02c'),
gmf_movie_creation('\ue404'),
gmf_movie_filter('\ue43a'),
gmf_mp('\ue9c3'),
gmf_multiline_chart('\ue6df'),
gmf_multitrack_audio('\ue1b8'),
gmf_museum('\uea36'),
gmf_music_note('\ue405'),
gmf_music_off('\ue440'),
gmf_music_video('\ue063'),
gmf_my_library_add('\ue02e'),
gmf_my_library_books('\ue02f'),
gmf_my_library_music('\ue030'),
gmf_my_location('\ue55c'),
gmf_nature('\ue406'),
gmf_nature_people('\ue407'),
gmf_navigate_before('\ue408'),
gmf_navigate_next('\ue409'),
gmf_navigation('\ue55d'),
gmf_near_me('\ue569'),
gmf_network_cell('\ue1b9'),
gmf_network_check('\ue640'),
gmf_network_locked('\ue61a'),
gmf_network_wifi('\ue1ba'),
gmf_new_releases('\ue031'),
gmf_next_week('\ue16a'),
gmf_nfc('\ue1bb'),
gmf_nightlife('\uea62'),
gmf_nights_stay('\uea46'),
gmf_no_encryption('\ue641'),
gmf_no_meeting_room('\ueb4e'),
gmf_no_sim('\ue0cc'),
gmf_not_interested('\ue033'),
gmf_not_listed_location('\ue575'),
gmf_note('\ue06f'),
gmf_note_add('\ue89c'),
gmf_notes('\ue26c'),
gmf_notification_important('\ue004'),
gmf_notifications('\ue7f4'),
gmf_notifications_active('\ue7f7'),
gmf_notifications_none('\ue7f5'),
gmf_notifications_off('\ue7f6'),
gmf_notifications_on('\ue7f7'),
gmf_notifications_paused('\ue7f8'),
gmf_now_wallpaper('\ue1bc'),
gmf_now_widgets('\ue1bd'),
gmf_offline_bolt('\ue932'),
gmf_offline_pin('\ue90a'),
gmf_offline_share('\ue9c5'),
gmf_ondemand_video('\ue63a'),
gmf_opacity('\ue91c'),
gmf_open_in_browser('\ue89d'),
gmf_open_in_new('\ue89e'),
gmf_open_with('\ue89f'),
gmf_outdoor_grill('\uea47'),
gmf_outlined_flag('\ue16e'),
gmf_padding('\ue9c8'),
gmf_pages('\ue7f9'),
gmf_pageview('\ue8a0'),
gmf_palette('\ue40a'),
gmf_pan_tool('\ue925'),
gmf_panorama('\ue40b'),
gmf_panorama_fish_eye('\ue40c'),
gmf_panorama_fisheye('\ue40c'),
gmf_panorama_horizontal('\ue40d'),
gmf_panorama_photosphere('\ue9c9'),
gmf_panorama_photosphere_select('\ue9ca'),
gmf_panorama_vertical('\ue40e'),
gmf_panorama_wide_angle('\ue40f'),
gmf_park('\uea63'),
gmf_party_mode('\ue7fa'),
gmf_pause('\ue034'),
gmf_pause_circle_filled('\ue035'),
gmf_pause_circle_outline('\ue036'),
gmf_pause_presentation('\ue0ea'),
gmf_payment('\ue8a1'),
gmf_people('\ue7fb'),
gmf_people_alt('\uea21'),
gmf_people_outline('\ue7fc'),
gmf_perm_camera_mic('\ue8a2'),
gmf_perm_contact_cal('\ue8a3'),
gmf_perm_contact_calendar('\ue8a3'),
gmf_perm_data_setting('\ue8a4'),
gmf_perm_device_info('\ue8a5'),
gmf_perm_device_information('\ue8a5'),
gmf_perm_identity('\ue8a6'),
gmf_perm_media('\ue8a7'),
gmf_perm_phone_msg('\ue8a8'),
gmf_perm_scan_wifi('\ue8a9'),
gmf_person('\ue7fd'),
gmf_person_add('\ue7fe'),
gmf_person_add_disabled('\ue9cb'),
gmf_person_outline('\ue7ff'),
gmf_person_pin('\ue55a'),
gmf_person_pin_circle('\ue56a'),
gmf_personal_video('\ue63b'),
gmf_pets('\ue91d'),
gmf_phone('\ue0cd'),
gmf_phone_android('\ue324'),
gmf_phone_bluetooth_speaker('\ue61b'),
gmf_phone_callback('\ue649'),
gmf_phone_disabled('\ue9cc'),
gmf_phone_enabled('\ue9cd'),
gmf_phone_forwarded('\ue61c'),
gmf_phone_in_talk('\ue61d'),
gmf_phone_iphone('\ue325'),
gmf_phone_locked('\ue61e'),
gmf_phone_missed('\ue61f'),
gmf_phone_paused('\ue620'),
gmf_phonelink('\ue326'),
gmf_phonelink_erase('\ue0db'),
gmf_phonelink_lock('\ue0dc'),
gmf_phonelink_off('\ue327'),
gmf_phonelink_ring('\ue0dd'),
gmf_phonelink_setup('\ue0de'),
gmf_photo('\ue410'),
gmf_photo_album('\ue411'),
gmf_photo_camera('\ue412'),
gmf_photo_filter('\ue43b'),
gmf_photo_library('\ue413'),
gmf_photo_size_select_actual('\ue432'),
gmf_photo_size_select_large('\ue433'),
gmf_photo_size_select_small('\ue434'),
gmf_picture_as_pdf('\ue415'),
gmf_picture_in_picture('\ue8aa'),
gmf_picture_in_picture_alt('\ue911'),
gmf_pie_chart('\ue6c4'),
gmf_pie_chart_outlined('\ue6c5'),
gmf_pin_drop('\ue55e'),
gmf_pivot_table_chart('\ue9ce'),
gmf_place('\ue55f'),
gmf_play_arrow('\ue037'),
gmf_play_circle_fill('\ue038'),
gmf_play_circle_filled('\ue038'),
gmf_play_circle_outline('\ue039'),
gmf_play_for_work('\ue906'),
gmf_playlist_add('\ue03b'),
gmf_playlist_add_check('\ue065'),
gmf_playlist_play('\ue05f'),
gmf_plus_one('\ue800'),
gmf_policy('\uea17'),
gmf_poll('\ue801'),
gmf_polymer('\ue8ab'),
gmf_pool('\ueb48'),
gmf_portable_wifi_off('\ue0ce'),
gmf_portrait('\ue416'),
gmf_post_add('\uea20'),
gmf_power('\ue63c'),
gmf_power_input('\ue336'),
gmf_power_off('\ue646'),
gmf_power_settings_new('\ue8ac'),
gmf_pregnant_woman('\ue91e'),
gmf_present_to_all('\ue0df'),
gmf_print('\ue8ad'),
gmf_print_disabled('\ue9cf'),
gmf_priority_high('\ue645'),
gmf_public('\ue80b'),
gmf_publish('\ue255'),
gmf_query_builder('\ue8ae'),
gmf_question_answer('\ue8af'),
gmf_queue('\ue03c'),
gmf_queue_music('\ue03d'),
gmf_queue_play_next('\ue066'),
gmf_quick_contacts_dialer('\ue0cf'),
gmf_quick_contacts_mail('\ue0d0'),
gmf_radio('\ue03e'),
gmf_radio_button_checked('\ue837'),
gmf_radio_button_off('\ue836'),
gmf_radio_button_on('\ue837'),
gmf_radio_button_unchecked('\ue836'),
gmf_railway_alert('\ue9d1'),
gmf_ramen_dining('\uea64'),
gmf_rate_review('\ue560'),
gmf_receipt('\ue8b0'),
gmf_recent_actors('\ue03f'),
gmf_recommend('\ue9d2'),
gmf_record_voice_over('\ue91f'),
gmf_redeem('\ue8b1'),
gmf_redo('\ue15a'),
gmf_refresh('\ue5d5'),
gmf_remove('\ue15b'),
gmf_remove_circle('\ue15c'),
gmf_remove_circle_outline('\ue15d'),
gmf_remove_done('\ue9d3'),
gmf_remove_from_queue('\ue067'),
gmf_remove_moderator('\ue9d4'),
gmf_remove_red_eye('\ue417'),
gmf_remove_shopping_cart('\ue928'),
gmf_reorder('\ue8fe'),
gmf_repeat('\ue040'),
gmf_repeat_on('\ue9d6'),
gmf_repeat_one('\ue041'),
gmf_repeat_one_on('\ue9d7'),
gmf_replay('\ue042'),
gmf_replay_10('\ue059'),
gmf_replay_30('\ue05a'),
gmf_replay_5('\ue05b'),
gmf_replay_circle_filled('\ue9d8'),
gmf_reply('\ue15e'),
gmf_reply_all('\ue15f'),
gmf_report('\ue160'),
gmf_report_off('\ue170'),
gmf_report_problem('\ue8b2'),
gmf_reset_tv('\ue9d9'),
gmf_restaurant('\ue56c'),
gmf_restaurant_menu('\ue561'),
gmf_restore('\ue8b3'),
gmf_restore_from_trash('\ue938'),
gmf_restore_page('\ue929'),
gmf_ring_volume('\ue0d1'),
gmf_room('\ue8b4'),
gmf_room_service('\ueb49'),
gmf_rotate_90_degrees_ccw('\ue418'),
gmf_rotate_left('\ue419'),
gmf_rotate_right('\ue41a'),
gmf_rounded_corner('\ue920'),
gmf_router('\ue328'),
gmf_rowing('\ue921'),
gmf_rss_feed('\ue0e5'),
gmf_rtt('\ue9ad'),
gmf_rv_hookup('\ue642'),
gmf_satellite('\ue562'),
gmf_save('\ue161'),
gmf_save_alt('\ue171'),
gmf_saved_search('\uea11'),
gmf_scanner('\ue329'),
gmf_scatter_plot('\ue268'),
gmf_schedule('\ue8b5'),
gmf_schedule_send('\uea0a'),
gmf_school('\ue80c'),
gmf_score('\ue269'),
gmf_screen_lock_landscape('\ue1be'),
gmf_screen_lock_portrait('\ue1bf'),
gmf_screen_lock_rotation('\ue1c0'),
gmf_screen_rotation('\ue1c1'),
gmf_screen_share('\ue0e2'),
gmf_sd('\ue9dd'),
gmf_sd_card('\ue623'),
gmf_sd_storage('\ue1c2'),
gmf_search('\ue8b6'),
gmf_security('\ue32a'),
gmf_segment('\ue94b'),
gmf_select_all('\ue162'),
gmf_send('\ue163'),
gmf_send_and_archive('\uea0c'),
gmf_sentiment_dissatisfied('\ue811'),
gmf_sentiment_neutral('\ue812'),
gmf_sentiment_satisfied('\ue813'),
gmf_sentiment_satisfied_alt('\ue0ed'),
gmf_sentiment_very_dissatisfied('\ue814'),
gmf_sentiment_very_satisfied('\ue815'),
gmf_settings('\ue8b8'),
gmf_settings_applications('\ue8b9'),
gmf_settings_backup_restore('\ue8ba'),
gmf_settings_bluetooth('\ue8bb'),
gmf_settings_brightness('\ue8bd'),
gmf_settings_cell('\ue8bc'),
gmf_settings_display('\ue8bd'),
gmf_settings_ethernet('\ue8be'),
gmf_settings_input_antenna('\ue8bf'),
gmf_settings_input_component('\ue8c0'),
gmf_settings_input_composite('\ue8c1'),
gmf_settings_input_hdmi('\ue8c2'),
gmf_settings_input_svideo('\ue8c3'),
gmf_settings_overscan('\ue8c4'),
gmf_settings_phone('\ue8c5'),
gmf_settings_power('\ue8c6'),
gmf_settings_remote('\ue8c7'),
gmf_settings_system_daydream('\ue1c3'),
gmf_settings_voice('\ue8c8'),
gmf_share('\ue80d'),
gmf_shield('\ue9e0'),
gmf_shop('\ue8c9'),
gmf_shop_two('\ue8ca'),
gmf_shopping_basket('\ue8cb'),
gmf_shopping_cart('\ue8cc'),
gmf_short_text('\ue261'),
gmf_show_chart('\ue6e1'),
gmf_shuffle('\ue043'),
gmf_shuffle_on('\ue9e1'),
gmf_shutter_speed('\ue43d'),
gmf_signal_cellular_4_bar('\ue1c8'),
gmf_signal_cellular_alt('\ue202'),
gmf_signal_cellular_connected_no_internet_4_bar('\ue1cd'),
gmf_signal_cellular_no_sim('\ue1ce'),
gmf_signal_cellular_null('\ue1cf'),
gmf_signal_cellular_off('\ue1d0'),
gmf_signal_wifi_4_bar('\ue1d8'),
gmf_signal_wifi_4_bar_lock('\ue1d9'),
gmf_signal_wifi_off('\ue1da'),
gmf_sim_card('\ue32b'),
gmf_sim_card_alert('\ue624'),
gmf_single_bed('\uea48'),
gmf_skip_next('\ue044'),
gmf_skip_previous('\ue045'),
gmf_slideshow('\ue41b'),
gmf_slow_motion_video('\ue068'),
gmf_smartphone('\ue32c'),
gmf_smoke_free('\ueb4a'),
gmf_smoking_rooms('\ueb4b'),
gmf_sms('\ue625'),
gmf_sms_failed('\ue626'),
gmf_snooze('\ue046'),
gmf_sort('\ue164'),
gmf_sort_by_alpha('\ue053'),
gmf_spa('\ueb4c'),
gmf_space_bar('\ue256'),
gmf_speaker('\ue32d'),
gmf_speaker_group('\ue32e'),
gmf_speaker_notes('\ue8cd'),
gmf_speaker_notes_off('\ue92a'),
gmf_speaker_phone('\ue0d2'),
gmf_speed('\ue9e4'),
gmf_spellcheck('\ue8ce'),
gmf_sports('\uea30'),
gmf_sports_baseball('\uea51'),
gmf_sports_basketball('\uea26'),
gmf_sports_cricket('\uea27'),
gmf_sports_esports('\uea28'),
gmf_sports_football('\uea29'),
gmf_sports_golf('\uea2a'),
gmf_sports_handball('\uea33'),
gmf_sports_hockey('\uea2b'),
gmf_sports_kabaddi('\uea34'),
gmf_sports_mma('\uea2c'),
gmf_sports_motorsports('\uea2d'),
gmf_sports_rugby('\uea2e'),
gmf_sports_soccer('\uea2f'),
gmf_sports_tennis('\uea32'),
gmf_sports_volleyball('\uea31'),
gmf_square_foot('\uea49'),
gmf_stacked_bar_chart('\ue9e6'),
gmf_star('\ue838'),
gmf_star_border('\ue83a'),
gmf_star_half('\ue839'),
gmf_star_outline('\ue83a'),
gmf_stars('\ue8d0'),
gmf_stay_current_landscape('\ue0d3'),
gmf_stay_current_portrait('\ue0d4'),
gmf_stay_primary_landscape('\ue0d5'),
gmf_stay_primary_portrait('\ue0d6'),
gmf_stop('\ue047'),
gmf_stop_screen_share('\ue0e3'),
gmf_storage('\ue1db'),
gmf_store('\ue8d1'),
gmf_store_mall_directory('\ue563'),
gmf_storefront('\uea12'),
gmf_straighten('\ue41c'),
gmf_stream('\ue9e9'),
gmf_streetview('\ue56e'),
gmf_strikethrough_s('\ue257'),
gmf_style('\ue41d'),
gmf_subdirectory_arrow_left('\ue5d9'),
gmf_subdirectory_arrow_right('\ue5da'),
gmf_subject('\ue8d2'),
gmf_subscriptions('\ue064'),
gmf_subtitles('\ue048'),
gmf_subway('\ue56f'),
gmf_supervised_user_circle('\ue939'),
gmf_supervisor_account('\ue8d3'),
gmf_surround_sound('\ue049'),
gmf_swap_calls('\ue0d7'),
gmf_swap_horiz('\ue8d4'),
gmf_swap_horizontal_circle('\ue933'),
gmf_swap_vert('\ue8d5'),
gmf_swap_vert_circle('\ue8d6'),
gmf_swap_vertical_circle('\ue8d6'),
gmf_swipe('\ue9ec'),
gmf_switch_account('\ue9ed'),
gmf_switch_camera('\ue41e'),
gmf_switch_video('\ue41f'),
gmf_sync('\ue627'),
gmf_sync_alt('\uea18'),
gmf_sync_disabled('\ue628'),
gmf_sync_problem('\ue629'),
gmf_system_update('\ue62a'),
gmf_system_update_alt('\ue8d7'),
gmf_system_update_tv('\ue8d7'),
gmf_tab('\ue8d8'),
gmf_tab_unselected('\ue8d9'),
gmf_table_chart('\ue265'),
gmf_tablet('\ue32f'),
gmf_tablet_android('\ue330'),
gmf_tablet_mac('\ue331'),
gmf_tag('\ue9ef'),
gmf_tag_faces('\ue420'),
gmf_takeout_dining('\uea74'),
gmf_tap_and_play('\ue62b'),
gmf_terrain('\ue564'),
gmf_text_fields('\ue262'),
gmf_text_format('\ue165'),
gmf_text_rotate_up('\ue93a'),
gmf_text_rotate_vertical('\ue93b'),
gmf_text_rotation_angledown('\ue93c'),
gmf_text_rotation_angleup('\ue93d'),
gmf_text_rotation_down('\ue93e'),
gmf_text_rotation_none('\ue93f'),
gmf_textsms('\ue0d8'),
gmf_texture('\ue421'),
gmf_theater_comedy('\uea66'),
gmf_theaters('\ue8da'),
gmf_thumb_down('\ue8db'),
gmf_thumb_down_alt('\ue816'),
gmf_thumb_down_off_alt('\ue9f2'),
gmf_thumb_up('\ue8dc'),
gmf_thumb_up_alt('\ue817'),
gmf_thumb_up_off_alt('\ue9f3'),
gmf_thumbs_up_down('\ue8dd'),
gmf_time_to_leave('\ue62c'),
gmf_timelapse('\ue422'),
gmf_timeline('\ue922'),
gmf_timer('\ue425'),
gmf_timer_10('\ue423'),
gmf_timer_3('\ue424'),
gmf_timer_off('\ue426'),
gmf_title('\ue264'),
gmf_toc('\ue8de'),
gmf_today('\ue8df'),
gmf_toggle_off('\ue9f5'),
gmf_toggle_on('\ue9f6'),
gmf_toll('\ue8e0'),
gmf_tonality('\ue427'),
gmf_touch_app('\ue913'),
gmf_toys('\ue332'),
gmf_track_changes('\ue8e1'),
gmf_traffic('\ue565'),
gmf_train('\ue570'),
gmf_tram('\ue571'),
gmf_transfer_within_a_station('\ue572'),
gmf_transform('\ue428'),
gmf_transit_enterexit('\ue579'),
gmf_translate('\ue8e2'),
gmf_trending_down('\ue8e3'),
gmf_trending_flat('\ue8e4'),
gmf_trending_neutral('\ue8e4'),
gmf_trending_up('\ue8e5'),
gmf_trip_origin('\ue57b'),
gmf_tune('\ue429'),
gmf_turned_in('\ue8e6'),
gmf_turned_in_not('\ue8e7'),
gmf_tv('\ue333'),
gmf_tv_off('\ue647'),
gmf_two_wheeler('\ue9f9'),
gmf_unarchive('\ue169'),
gmf_undo('\ue166'),
gmf_unfold_less('\ue5d6'),
gmf_unfold_more('\ue5d7'),
gmf_unsubscribe('\ue0eb'),
gmf_update('\ue923'),
gmf_upload_file('\ue9fc'),
gmf_usb('\ue1e0'),
gmf_verified_user('\ue8e8'),
gmf_vertical_align_bottom('\ue258'),
gmf_vertical_align_center('\ue259'),
gmf_vertical_align_top('\ue25a'),
gmf_vertical_split('\ue949'),
gmf_vibration('\ue62d'),
gmf_video_call('\ue070'),
gmf_video_collection('\ue04a'),
gmf_video_label('\ue071'),
gmf_video_library('\ue04a'),
gmf_videocam('\ue04b'),
gmf_videocam_off('\ue04c'),
gmf_videogame_asset('\ue338'),
gmf_view_agenda('\ue8e9'),
gmf_view_array('\ue8ea'),
gmf_view_carousel('\ue8eb'),
gmf_view_column('\ue8ec'),
gmf_view_comfortable('\ue42a'),
gmf_view_comfy('\ue42a'),
gmf_view_compact('\ue42b'),
gmf_view_day('\ue8ed'),
gmf_view_headline('\ue8ee'),
gmf_view_in_ar('\ue9fe'),
gmf_view_list('\ue8ef'),
gmf_view_module('\ue8f0'),
gmf_view_quilt('\ue8f1'),
gmf_view_stream('\ue8f2'),
gmf_view_week('\ue8f3'),
gmf_vignette('\ue435'),
gmf_visibility('\ue8f4'),
gmf_visibility_off('\ue8f5'),
gmf_voice_chat('\ue62e'),
gmf_voice_over_off('\ue94a'),
gmf_voicemail('\ue0d9'),
gmf_volume_down('\ue04d'),
gmf_volume_mute('\ue04e'),
gmf_volume_off('\ue04f'),
gmf_volume_up('\ue050'),
gmf_volunteer_activism('\uea70'),
gmf_vpn_key('\ue0da'),
gmf_vpn_lock('\ue62f'),
gmf_wallet_giftcard('\ue8f6'),
gmf_wallet_membership('\ue8f7'),
gmf_wallet_travel('\ue8f8'),
gmf_wallpaper('\ue1bc'),
gmf_warning('\ue002'),
gmf_watch('\ue334'),
gmf_watch_later('\ue924'),
gmf_waterfall_chart('\uea00'),
gmf_waves('\ue176'),
gmf_wb_auto('\ue42c'),
gmf_wb_cloudy('\ue42d'),
gmf_wb_incandescent('\ue42e'),
gmf_wb_iridescent('\ue436'),
gmf_wb_shade('\uea01'),
gmf_wb_sunny('\ue430'),
gmf_wb_twighlight('\uea02'),
gmf_wc('\ue63d'),
gmf_web('\ue051'),
gmf_web_asset('\ue069'),
gmf_weekend('\ue16b'),
gmf_whatshot('\ue80e'),
gmf_where_to_vote('\ue177'),
gmf_widgets('\ue1bd'),
gmf_wifi('\ue63e'),
gmf_wifi_lock('\ue1e1'),
gmf_wifi_off('\ue648'),
gmf_wifi_tethering('\ue1e2'),
gmf_work('\ue8f9'),
gmf_work_off('\ue942'),
gmf_work_outline('\ue943'),
gmf_workspaces_filled('\uea0d'),
gmf_workspaces_outline('\uea0f'),
gmf_wrap_text('\ue25b'),
gmf_youtube_searched_for('\ue8fa'),
gmf_zoom_in('\ue8ff'),
gmf_zoom_out('\ue900'),
gmf_zoom_out_map('\ue56b');
override val typeface: ITypeface by lazy { MaterialDesignDx }
}
} | apache-2.0 | 9b0124f47c5998a0bf3163ab6aee2272 | 34.283061 | 75 | 0.530764 | 2.995081 | false | false | false | false |
mikepenz/Android-Iconics | weather-icons-typeface-library/src/main/java/com/mikepenz/iconics/typeface/library/weathericons/WeatherIcons.kt | 1 | 23285 | /*
* Copyright 2020 Mike Penz
*
* 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.mikepenz.iconics.typeface.library.weathericons
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.typeface.ITypeface
import java.util.LinkedList
@Suppress("EnumEntryName")
object WeatherIcons : ITypeface {
override val fontRes: Int
get() = R.font.weather_icons_v2_0_10
override val characters: Map<String, Char> by lazy {
Icon.values().associate { it.name to it.character }
}
override val mappingPrefix: String
get() = "wic"
override val fontName: String
get() = "Weather Icons"
override val version: String
get() = "2.0.10"
override val iconCount: Int
get() = characters.size
override val icons: List<String>
get() = characters.keys.toCollection(LinkedList())
override val author: String
get() = "Erik Flowers"
override val url: String
get() = "http://weathericons.io/"
override val description: String
get() = "Weather Icons is the only icon font and CSS with 222 weather themed icons, " +
"ready to be dropped right into Bootstrap, or any project that needs high " +
"quality weather, maritime, and meteorological based icons!"
override val license: String
get() = "SIL OFL 1.1"
override val licenseUrl: String
get() = "http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL"
override fun getIcon(key: String): IIcon = Icon.valueOf(key)
enum class Icon constructor(override val character: Char) : IIcon {
wic_day_sunny('\uf00d'),
wic_day_cloudy('\uf002'),
wic_day_cloudy_gusts('\uf000'),
wic_day_cloudy_windy('\uf001'),
wic_day_fog('\uf003'),
wic_day_hail('\uf004'),
wic_day_haze('\uf0b6'),
wic_day_lightning('\uf005'),
wic_day_rain('\uf008'),
wic_day_rain_mix('\uf006'),
wic_day_rain_wind('\uf007'),
wic_day_showers('\uf009'),
wic_day_sleet('\uf0b2'),
wic_day_sleet_storm('\uf068'),
wic_day_snow('\uf00a'),
wic_day_snow_thunderstorm('\uf06b'),
wic_day_snow_wind('\uf065'),
wic_day_sprinkle('\uf00b'),
wic_day_storm_showers('\uf00e'),
wic_day_sunny_overcast('\uf00c'),
wic_day_thunderstorm('\uf010'),
wic_day_windy('\uf085'),
wic_solar_eclipse('\uf06e'),
wic_hot('\uf072'),
wic_day_cloudy_high('\uf07d'),
wic_day_light_wind('\uf0c4'),
wic_night_clear('\uf02e'),
wic_night_alt_cloudy('\uf086'),
wic_night_alt_cloudy_gusts('\uf022'),
wic_night_alt_cloudy_windy('\uf023'),
wic_night_alt_hail('\uf024'),
wic_night_alt_lightning('\uf025'),
wic_night_alt_rain('\uf028'),
wic_night_alt_rain_mix('\uf026'),
wic_night_alt_rain_wind('\uf027'),
wic_night_alt_showers('\uf029'),
wic_night_alt_sleet('\uf0b4'),
wic_night_alt_sleet_storm('\uf06a'),
wic_night_alt_snow('\uf02a'),
wic_night_alt_snow_thunderstorm('\uf06d'),
wic_night_alt_snow_wind('\uf067'),
wic_night_alt_sprinkle('\uf02b'),
wic_night_alt_storm_showers('\uf02c'),
wic_night_alt_thunderstorm('\uf02d'),
wic_night_cloudy('\uf031'),
wic_night_cloudy_gusts('\uf02f'),
wic_night_cloudy_windy('\uf030'),
wic_night_fog('\uf04a'),
wic_night_hail('\uf032'),
wic_night_lightning('\uf033'),
wic_night_partly_cloudy('\uf083'),
wic_night_rain('\uf036'),
wic_night_rain_mix('\uf034'),
wic_night_rain_wind('\uf035'),
wic_night_showers('\uf037'),
wic_night_sleet('\uf0b3'),
wic_night_sleet_storm('\uf069'),
wic_night_snow('\uf038'),
wic_night_snow_thunderstorm('\uf06c'),
wic_night_snow_wind('\uf066'),
wic_night_sprinkle('\uf039'),
wic_night_storm_showers('\uf03a'),
wic_night_thunderstorm('\uf03b'),
wic_lunar_eclipse('\uf070'),
wic_stars('\uf077'),
wic_night_alt_cloudy_high('\uf07e'),
wic_night_cloudy_high('\uf080'),
wic_night_alt_partly_cloudy('\uf081'),
wic_cloud('\uf041'),
wic_cloudy('\uf013'),
wic_cloudy_gusts('\uf011'),
wic_cloudy_windy('\uf012'),
wic_fog('\uf014'),
wic_hail('\uf015'),
wic_rain('\uf019'),
wic_rain_mix('\uf017'),
wic_rain_wind('\uf018'),
wic_showers('\uf01a'),
wic_sleet('\uf0b5'),
wic_sprinkle('\uf01c'),
wic_storm_showers('\uf01d'),
wic_thunderstorm('\uf01e'),
wic_snow_wind('\uf064'),
wic_snow('\uf01b'),
wic_smog('\uf074'),
wic_smoke('\uf062'),
wic_lightning('\uf016'),
wic_raindrops('\uf04e'),
wic_raindrop('\uf078'),
wic_dust('\uf063'),
wic_snowflake_cold('\uf076'),
wic_windy('\uf021'),
wic_strong_wind('\uf050'),
wic_sandstorm('\uf082'),
wic_earthquake('\uf0c6'),
wic_fire('\uf0c7'),
wic_flood('\uf07c'),
wic_meteor('\uf071'),
wic_tsunami('\uf0c5'),
wic_volcano('\uf0c8'),
wic_hurricane('\uf073'),
wic_tornado('\uf056'),
wic_small_craft_advisory('\uf0cc'),
wic_gale_warning('\uf0cd'),
wic_storm_warning('\uf0ce'),
wic_hurricane_warning('\uf0cf'),
wic_wind_direction('\uf0b1'),
wic_alien('\uf075'),
wic_celsius('\uf03c'),
wic_fahrenheit('\uf045'),
wic_degrees('\uf042'),
wic_thermometer('\uf055'),
wic_thermometer_exterior('\uf053'),
wic_thermometer_internal('\uf054'),
wic_cloud_down('\uf03d'),
wic_cloud_up('\uf040'),
wic_cloud_refresh('\uf03e'),
wic_horizon('\uf047'),
wic_horizon_alt('\uf046'),
wic_sunrise('\uf051'),
wic_sunset('\uf052'),
wic_moonrise('\uf0c9'),
wic_moonset('\uf0ca'),
wic_refresh('\uf04c'),
wic_refresh_alt('\uf04b'),
wic_umbrella('\uf084'),
wic_barometer('\uf079'),
wic_humidity('\uf07a'),
wic_na('\uf07b'),
wic_train('\uf0cb'),
wic_moon_new('\uf095'),
wic_moon_waxing_crescent_1('\uf096'),
wic_moon_waxing_crescent_2('\uf097'),
wic_moon_waxing_crescent_3('\uf098'),
wic_moon_waxing_crescent_4('\uf099'),
wic_moon_waxing_crescent_5('\uf09a'),
wic_moon_waxing_crescent_6('\uf09b'),
wic_moon_first_quarter('\uf09c'),
wic_moon_waxing_gibbous_1('\uf09d'),
wic_moon_waxing_gibbous_2('\uf09e'),
wic_moon_waxing_gibbous_3('\uf09f'),
wic_moon_waxing_gibbous_4('\uf0a0'),
wic_moon_waxing_gibbous_5('\uf0a1'),
wic_moon_waxing_gibbous_6('\uf0a2'),
wic_moon_full('\uf0a3'),
wic_moon_waning_gibbous_1('\uf0a4'),
wic_moon_waning_gibbous_2('\uf0a5'),
wic_moon_waning_gibbous_3('\uf0a6'),
wic_moon_waning_gibbous_4('\uf0a7'),
wic_moon_waning_gibbous_5('\uf0a8'),
wic_moon_waning_gibbous_6('\uf0a9'),
wic_moon_third_quarter('\uf0aa'),
wic_moon_waning_crescent_1('\uf0ab'),
wic_moon_waning_crescent_2('\uf0ac'),
wic_moon_waning_crescent_3('\uf0ad'),
wic_moon_waning_crescent_4('\uf0ae'),
wic_moon_waning_crescent_5('\uf0af'),
wic_moon_waning_crescent_6('\uf0b0'),
wic_moon_alt_new('\uf0eb'),
wic_moon_alt_waxing_crescent_1('\uf0d0'),
wic_moon_alt_waxing_crescent_2('\uf0d1'),
wic_moon_alt_waxing_crescent_3('\uf0d2'),
wic_moon_alt_waxing_crescent_4('\uf0d3'),
wic_moon_alt_waxing_crescent_5('\uf0d4'),
wic_moon_alt_waxing_crescent_6('\uf0d5'),
wic_moon_alt_first_quarter('\uf0d6'),
wic_moon_alt_waxing_gibbous_1('\uf0d7'),
wic_moon_alt_waxing_gibbous_2('\uf0d8'),
wic_moon_alt_waxing_gibbous_3('\uf0d9'),
wic_moon_alt_waxing_gibbous_4('\uf0da'),
wic_moon_alt_waxing_gibbous_5('\uf0db'),
wic_moon_alt_waxing_gibbous_6('\uf0dc'),
wic_moon_alt_full('\uf0dd'),
wic_moon_alt_waning_gibbous_1('\uf0de'),
wic_moon_alt_waning_gibbous_2('\uf0df'),
wic_moon_alt_waning_gibbous_3('\uf0e0'),
wic_moon_alt_waning_gibbous_4('\uf0e1'),
wic_moon_alt_waning_gibbous_5('\uf0e2'),
wic_moon_alt_waning_gibbous_6('\uf0e3'),
wic_moon_alt_third_quarter('\uf0e4'),
wic_moon_alt_waning_crescent_1('\uf0e5'),
wic_moon_alt_waning_crescent_2('\uf0e6'),
wic_moon_alt_waning_crescent_3('\uf0e7'),
wic_moon_alt_waning_crescent_4('\uf0e8'),
wic_moon_alt_waning_crescent_5('\uf0e9'),
wic_moon_alt_waning_crescent_6('\uf0ea'),
wic_moon_0('\uf095'),
wic_moon_1('\uf096'),
wic_moon_2('\uf097'),
wic_moon_3('\uf098'),
wic_moon_4('\uf099'),
wic_moon_5('\uf09a'),
wic_moon_6('\uf09b'),
wic_moon_7('\uf09c'),
wic_moon_8('\uf09d'),
wic_moon_9('\uf09e'),
wic_moon_10('\uf09f'),
wic_moon_11('\uf0a0'),
wic_moon_12('\uf0a1'),
wic_moon_13('\uf0a2'),
wic_moon_14('\uf0a3'),
wic_moon_15('\uf0a4'),
wic_moon_16('\uf0a5'),
wic_moon_17('\uf0a6'),
wic_moon_18('\uf0a7'),
wic_moon_19('\uf0a8'),
wic_moon_20('\uf0a9'),
wic_moon_21('\uf0aa'),
wic_moon_22('\uf0ab'),
wic_moon_23('\uf0ac'),
wic_moon_24('\uf0ad'),
wic_moon_25('\uf0ae'),
wic_moon_26('\uf0af'),
wic_moon_27('\uf0b0'),
wic_time_1('\uf08a'),
wic_time_2('\uf08b'),
wic_time_3('\uf08c'),
wic_time_4('\uf08d'),
wic_time_5('\uf08e'),
wic_time_6('\uf08f'),
wic_time_7('\uf090'),
wic_time_8('\uf091'),
wic_time_9('\uf092'),
wic_time_10('\uf093'),
wic_time_11('\uf094'),
wic_time_12('\uf089'),
wic_direction_up('\uf058'),
wic_direction_up_right('\uf057'),
wic_direction_right('\uf04d'),
wic_direction_down_right('\uf088'),
wic_direction_down('\uf044'),
wic_direction_down_left('\uf043'),
wic_direction_left('\uf048'),
wic_direction_up_left('\uf087'),
wic_wind_beaufort_0('\uf0b7'),
wic_wind_beaufort_1('\uf0b8'),
wic_wind_beaufort_2('\uf0b9'),
wic_wind_beaufort_3('\uf0ba'),
wic_wind_beaufort_4('\uf0bb'),
wic_wind_beaufort_5('\uf0bc'),
wic_wind_beaufort_6('\uf0bd'),
wic_wind_beaufort_7('\uf0be'),
wic_wind_beaufort_8('\uf0bf'),
wic_wind_beaufort_9('\uf0c0'),
wic_wind_beaufort_10('\uf0c1'),
wic_wind_beaufort_11('\uf0c2'),
wic_wind_beaufort_12('\uf0c3'),
wic_yahoo_0('\uf056'),
wic_yahoo_1('\uf00e'),
wic_yahoo_2('\uf073'),
wic_yahoo_3('\uf01e'),
wic_yahoo_4('\uf01e'),
wic_yahoo_5('\uf017'),
wic_yahoo_6('\uf017'),
wic_yahoo_7('\uf017'),
wic_yahoo_8('\uf015'),
wic_yahoo_9('\uf01a'),
wic_yahoo_10('\uf015'),
wic_yahoo_11('\uf01a'),
wic_yahoo_12('\uf01a'),
wic_yahoo_13('\uf01b'),
wic_yahoo_14('\uf00a'),
wic_yahoo_15('\uf064'),
wic_yahoo_16('\uf01b'),
wic_yahoo_17('\uf015'),
wic_yahoo_18('\uf017'),
wic_yahoo_19('\uf063'),
wic_yahoo_20('\uf014'),
wic_yahoo_21('\uf021'),
wic_yahoo_22('\uf062'),
wic_yahoo_23('\uf050'),
wic_yahoo_24('\uf050'),
wic_yahoo_25('\uf076'),
wic_yahoo_26('\uf013'),
wic_yahoo_27('\uf031'),
wic_yahoo_28('\uf002'),
wic_yahoo_29('\uf031'),
wic_yahoo_30('\uf002'),
wic_yahoo_31('\uf02e'),
wic_yahoo_32('\uf00d'),
wic_yahoo_33('\uf083'),
wic_yahoo_34('\uf00c'),
wic_yahoo_35('\uf017'),
wic_yahoo_36('\uf072'),
wic_yahoo_37('\uf00e'),
wic_yahoo_38('\uf00e'),
wic_yahoo_39('\uf00e'),
wic_yahoo_40('\uf01a'),
wic_yahoo_41('\uf064'),
wic_yahoo_42('\uf01b'),
wic_yahoo_43('\uf064'),
wic_yahoo_44('\uf00c'),
wic_yahoo_45('\uf00e'),
wic_yahoo_46('\uf01b'),
wic_yahoo_47('\uf00e'),
wic_yahoo_3200('\uf077'),
wic_forecast_io_clear_day('\uf00d'),
wic_forecast_io_clear_night('\uf02e'),
wic_forecast_io_rain('\uf019'),
wic_forecast_io_snow('\uf01b'),
wic_forecast_io_sleet('\uf0b5'),
wic_forecast_io_wind('\uf050'),
wic_forecast_io_fog('\uf014'),
wic_forecast_io_cloudy('\uf013'),
wic_forecast_io_partly_cloudy_day('\uf002'),
wic_forecast_io_partly_cloudy_night('\uf031'),
wic_forecast_io_hail('\uf015'),
wic_forecast_io_thunderstorm('\uf01e'),
wic_forecast_io_tornado('\uf056'),
wic_wmo4680_0('\uf055'),
wic_wmo4680_00('\uf055'),
wic_wmo4680_1('\uf013'),
wic_wmo4680_01('\uf013'),
wic_wmo4680_2('\uf055'),
wic_wmo4680_02('\uf055'),
wic_wmo4680_3('\uf013'),
wic_wmo4680_03('\uf013'),
wic_wmo4680_4('\uf014'),
wic_wmo4680_04('\uf014'),
wic_wmo4680_5('\uf014'),
wic_wmo4680_05('\uf014'),
wic_wmo4680_10('\uf014'),
wic_wmo4680_11('\uf014'),
wic_wmo4680_12('\uf016'),
wic_wmo4680_18('\uf050'),
wic_wmo4680_20('\uf014'),
wic_wmo4680_21('\uf017'),
wic_wmo4680_22('\uf017'),
wic_wmo4680_23('\uf019'),
wic_wmo4680_24('\uf01b'),
wic_wmo4680_25('\uf015'),
wic_wmo4680_26('\uf01e'),
wic_wmo4680_27('\uf063'),
wic_wmo4680_28('\uf063'),
wic_wmo4680_29('\uf063'),
wic_wmo4680_30('\uf014'),
wic_wmo4680_31('\uf014'),
wic_wmo4680_32('\uf014'),
wic_wmo4680_33('\uf014'),
wic_wmo4680_34('\uf014'),
wic_wmo4680_35('\uf014'),
wic_wmo4680_40('\uf017'),
wic_wmo4680_41('\uf01c'),
wic_wmo4680_42('\uf019'),
wic_wmo4680_43('\uf01c'),
wic_wmo4680_44('\uf019'),
wic_wmo4680_45('\uf015'),
wic_wmo4680_46('\uf015'),
wic_wmo4680_47('\uf01b'),
wic_wmo4680_48('\uf01b'),
wic_wmo4680_50('\uf01c'),
wic_wmo4680_51('\uf01c'),
wic_wmo4680_52('\uf019'),
wic_wmo4680_53('\uf019'),
wic_wmo4680_54('\uf076'),
wic_wmo4680_55('\uf076'),
wic_wmo4680_56('\uf076'),
wic_wmo4680_57('\uf01c'),
wic_wmo4680_58('\uf019'),
wic_wmo4680_60('\uf01c'),
wic_wmo4680_61('\uf01c'),
wic_wmo4680_62('\uf019'),
wic_wmo4680_63('\uf019'),
wic_wmo4680_64('\uf015'),
wic_wmo4680_65('\uf015'),
wic_wmo4680_66('\uf015'),
wic_wmo4680_67('\uf017'),
wic_wmo4680_68('\uf017'),
wic_wmo4680_70('\uf01b'),
wic_wmo4680_71('\uf01b'),
wic_wmo4680_72('\uf01b'),
wic_wmo4680_73('\uf01b'),
wic_wmo4680_74('\uf076'),
wic_wmo4680_75('\uf076'),
wic_wmo4680_76('\uf076'),
wic_wmo4680_77('\uf01b'),
wic_wmo4680_78('\uf076'),
wic_wmo4680_80('\uf019'),
wic_wmo4680_81('\uf01c'),
wic_wmo4680_82('\uf019'),
wic_wmo4680_83('\uf019'),
wic_wmo4680_84('\uf01d'),
wic_wmo4680_85('\uf017'),
wic_wmo4680_86('\uf017'),
wic_wmo4680_87('\uf017'),
wic_wmo4680_89('\uf015'),
wic_wmo4680_90('\uf016'),
wic_wmo4680_91('\uf01d'),
wic_wmo4680_92('\uf01e'),
wic_wmo4680_93('\uf01e'),
wic_wmo4680_94('\uf016'),
wic_wmo4680_95('\uf01e'),
wic_wmo4680_96('\uf01e'),
wic_wmo4680_99('\uf056'),
wic_owm_200('\uf01e'),
wic_owm_201('\uf01e'),
wic_owm_202('\uf01e'),
wic_owm_210('\uf016'),
wic_owm_211('\uf016'),
wic_owm_212('\uf016'),
wic_owm_221('\uf016'),
wic_owm_230('\uf01e'),
wic_owm_231('\uf01e'),
wic_owm_232('\uf01e'),
wic_owm_300('\uf01c'),
wic_owm_301('\uf01c'),
wic_owm_302('\uf019'),
wic_owm_310('\uf017'),
wic_owm_311('\uf019'),
wic_owm_312('\uf019'),
wic_owm_313('\uf01a'),
wic_owm_314('\uf019'),
wic_owm_321('\uf01c'),
wic_owm_500('\uf01c'),
wic_owm_501('\uf019'),
wic_owm_502('\uf019'),
wic_owm_503('\uf019'),
wic_owm_504('\uf019'),
wic_owm_511('\uf017'),
wic_owm_520('\uf01a'),
wic_owm_521('\uf01a'),
wic_owm_522('\uf01a'),
wic_owm_531('\uf01d'),
wic_owm_600('\uf01b'),
wic_owm_601('\uf01b'),
wic_owm_602('\uf0b5'),
wic_owm_611('\uf017'),
wic_owm_612('\uf017'),
wic_owm_615('\uf017'),
wic_owm_616('\uf017'),
wic_owm_620('\uf017'),
wic_owm_621('\uf01b'),
wic_owm_622('\uf01b'),
wic_owm_701('\uf01a'),
wic_owm_711('\uf062'),
wic_owm_721('\uf0b6'),
wic_owm_731('\uf063'),
wic_owm_741('\uf014'),
wic_owm_761('\uf063'),
wic_owm_762('\uf063'),
wic_owm_771('\uf011'),
wic_owm_781('\uf056'),
wic_owm_800('\uf00d'),
wic_owm_801('\uf011'),
wic_owm_802('\uf011'),
wic_owm_803('\uf012'),
wic_owm_804('\uf013'),
wic_owm_900('\uf056'),
wic_owm_901('\uf01d'),
wic_owm_902('\uf073'),
wic_owm_903('\uf076'),
wic_owm_904('\uf072'),
wic_owm_905('\uf021'),
wic_owm_906('\uf015'),
wic_owm_957('\uf050'),
wic_owm_day_200('\uf010'),
wic_owm_day_201('\uf010'),
wic_owm_day_202('\uf010'),
wic_owm_day_210('\uf005'),
wic_owm_day_211('\uf005'),
wic_owm_day_212('\uf005'),
wic_owm_day_221('\uf005'),
wic_owm_day_230('\uf010'),
wic_owm_day_231('\uf010'),
wic_owm_day_232('\uf010'),
wic_owm_day_300('\uf00b'),
wic_owm_day_301('\uf00b'),
wic_owm_day_302('\uf008'),
wic_owm_day_310('\uf008'),
wic_owm_day_311('\uf008'),
wic_owm_day_312('\uf008'),
wic_owm_day_313('\uf008'),
wic_owm_day_314('\uf008'),
wic_owm_day_321('\uf00b'),
wic_owm_day_500('\uf00b'),
wic_owm_day_501('\uf008'),
wic_owm_day_502('\uf008'),
wic_owm_day_503('\uf008'),
wic_owm_day_504('\uf008'),
wic_owm_day_511('\uf006'),
wic_owm_day_520('\uf009'),
wic_owm_day_521('\uf009'),
wic_owm_day_522('\uf009'),
wic_owm_day_531('\uf00e'),
wic_owm_day_600('\uf00a'),
wic_owm_day_601('\uf0b2'),
wic_owm_day_602('\uf00a'),
wic_owm_day_611('\uf006'),
wic_owm_day_612('\uf006'),
wic_owm_day_615('\uf006'),
wic_owm_day_616('\uf006'),
wic_owm_day_620('\uf006'),
wic_owm_day_621('\uf00a'),
wic_owm_day_622('\uf00a'),
wic_owm_day_701('\uf009'),
wic_owm_day_711('\uf062'),
wic_owm_day_721('\uf0b6'),
wic_owm_day_731('\uf063'),
wic_owm_day_741('\uf003'),
wic_owm_day_761('\uf063'),
wic_owm_day_762('\uf063'),
wic_owm_day_781('\uf056'),
wic_owm_day_800('\uf00d'),
wic_owm_day_801('\uf000'),
wic_owm_day_802('\uf000'),
wic_owm_day_803('\uf000'),
wic_owm_day_804('\uf00c'),
wic_owm_day_900('\uf056'),
wic_owm_day_902('\uf073'),
wic_owm_day_903('\uf076'),
wic_owm_day_904('\uf072'),
wic_owm_day_906('\uf004'),
wic_owm_day_957('\uf050'),
wic_owm_night_200('\uf02d'),
wic_owm_night_201('\uf02d'),
wic_owm_night_202('\uf02d'),
wic_owm_night_210('\uf025'),
wic_owm_night_211('\uf025'),
wic_owm_night_212('\uf025'),
wic_owm_night_221('\uf025'),
wic_owm_night_230('\uf02d'),
wic_owm_night_231('\uf02d'),
wic_owm_night_232('\uf02d'),
wic_owm_night_300('\uf02b'),
wic_owm_night_301('\uf02b'),
wic_owm_night_302('\uf028'),
wic_owm_night_310('\uf028'),
wic_owm_night_311('\uf028'),
wic_owm_night_312('\uf028'),
wic_owm_night_313('\uf028'),
wic_owm_night_314('\uf028'),
wic_owm_night_321('\uf02b'),
wic_owm_night_500('\uf02b'),
wic_owm_night_501('\uf028'),
wic_owm_night_502('\uf028'),
wic_owm_night_503('\uf028'),
wic_owm_night_504('\uf028'),
wic_owm_night_511('\uf026'),
wic_owm_night_520('\uf029'),
wic_owm_night_521('\uf029'),
wic_owm_night_522('\uf029'),
wic_owm_night_531('\uf02c'),
wic_owm_night_600('\uf02a'),
wic_owm_night_601('\uf0b4'),
wic_owm_night_602('\uf02a'),
wic_owm_night_611('\uf026'),
wic_owm_night_612('\uf026'),
wic_owm_night_615('\uf026'),
wic_owm_night_616('\uf026'),
wic_owm_night_620('\uf026'),
wic_owm_night_621('\uf02a'),
wic_owm_night_622('\uf02a'),
wic_owm_night_701('\uf029'),
wic_owm_night_711('\uf062'),
wic_owm_night_721('\uf0b6'),
wic_owm_night_731('\uf063'),
wic_owm_night_741('\uf04a'),
wic_owm_night_761('\uf063'),
wic_owm_night_762('\uf063'),
wic_owm_night_781('\uf056'),
wic_owm_night_800('\uf02e'),
wic_owm_night_801('\uf022'),
wic_owm_night_802('\uf022'),
wic_owm_night_803('\uf022'),
wic_owm_night_804('\uf086'),
wic_owm_night_900('\uf056'),
wic_owm_night_902('\uf073'),
wic_owm_night_903('\uf076'),
wic_owm_night_904('\uf072'),
wic_owm_night_906('\uf024'),
wic_owm_night_957('\uf050'),
wic_wu_chanceflurries('\uf064'),
wic_wu_chancerain('\uf019'),
wic_wu_chancesleat('\uf0b5'),
wic_wu_chancesnow('\uf01b'),
wic_wu_chancetstorms('\uf01e'),
wic_wu_clear('\uf00d'),
wic_wu_cloudy('\uf002'),
wic_wu_flurries('\uf064'),
wic_wu_hazy('\uf0b6'),
wic_wu_mostlycloudy('\uf002'),
wic_wu_mostlysunny('\uf00d'),
wic_wu_partlycloudy('\uf002'),
wic_wu_partlysunny('\uf00d'),
wic_wu_rain('\uf01a'),
wic_wu_sleat('\uf0b5'),
wic_wu_snow('\uf01b'),
wic_wu_sunny('\uf00d'),
wic_wu_tstorms('\uf01e'),
wic_wu_unknown('\uf00d');
override val typeface: ITypeface by lazy { WeatherIcons }
}
}
| apache-2.0 | b0d6ca0a91fe66b59107c47d59f68fb0 | 34.280303 | 95 | 0.52639 | 2.67275 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/stage/bg/SpaceDanceBackground.kt | 2 | 3574 | package io.github.chrislo27.rhre3.stage.bg
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.MathUtils
import io.github.chrislo27.rhre3.RHRE3
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.util.gdxutils.fillRect
class SpaceDanceBackground(id: String, val color: Color = Color.valueOf("0029D6"))
: Background(id) {
val starfield1: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_starfield"), 1, 2, 510, 374) }
val starfield2: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_starfield"), 513, 2, 510, 374) }
// val smallTwinkle: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_stars"), 2, 74, 78, 78) }
// val bigTwinkle: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_stars"), 82, 74, 78, 78) }
// val bigDiamond: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_stars"), 162, 74, 78, 78) }
// val smallDiamond: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_stars"), 242, 74, 78, 78) }
// val starburst: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_stars"), 114, 2, 70, 70) }
// val dentedStar: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_stars"), 186, 2, 70, 70) }
// val starCross: TextureRegion by lazy { TextureRegion(AssetRegistry.get<Texture>("bg_sd_stars"), 258, 2, 70, 70) }
var veloX: Float = 0f
var veloY: Float = 0f
var x: Float = 0f
var y: Float = 0f
val timeBetweenDirChanges: Float = 10f
var timeToChangeDir: Float = 0f
private var first = true
fun changeDirection() {
veloX = MathUtils.random(75f) * MathUtils.randomSign()
veloY = MathUtils.random(75f) * MathUtils.randomSign()
}
override fun render(camera: OrthographicCamera, batch: SpriteBatch, shapeRenderer: ShapeRenderer, delta: Float) {
if (first) {
first = false
starfield1.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
starfield2.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
changeDirection()
}
val width = camera.viewportWidth
val height = camera.viewportHeight
val ratioX = width / RHRE3.WIDTH
val ratioY = height / RHRE3.HEIGHT
batch.color = color
batch.fillRect(0f, 0f, width, height)
batch.setColor(1f, 1f, 1f, 1f)
run {
for (a in -1..1) {
for (b in -1..1) {
batch.draw(starfield2, (x * 0.6f - width * 0.05f) + width * a, (y * 0.6f - height * 0.05f) + height * b, width, height)
batch.draw(starfield2, (x * 0.75f - width * 0.1f) + width * a, (y * 0.75f + height * 0.1f) + height * b, width, height)
batch.draw(starfield1, (x) + width * a, (y) + height * b, width, height)
}
}
}
x += delta * veloX
y += delta * veloY
x %= width
y %= height
timeToChangeDir += delta
if (timeToChangeDir >= timeBetweenDirChanges) {
timeToChangeDir %= timeBetweenDirChanges
changeDirection()
}
}
} | gpl-3.0 | d47058f8f20c5d904ebcee3caef51d39 | 42.597561 | 139 | 0.653609 | 3.650664 | false | false | false | false |
tiarebalbi/okhttp | okhttp/src/main/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt | 2 | 7018 | /*
* Copyright (C) 2012 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 okhttp3.internal.http2
import java.io.IOException
import java.net.ProtocolException
import java.util.ArrayList
import java.util.Locale
import java.util.concurrent.TimeUnit
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.connection.RealConnection
import okhttp3.internal.headersContentLength
import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.http.RealInterceptorChain
import okhttp3.internal.http.RequestLine
import okhttp3.internal.http.StatusLine
import okhttp3.internal.http.StatusLine.Companion.HTTP_CONTINUE
import okhttp3.internal.http.promisesBody
import okhttp3.internal.http2.Header.Companion.RESPONSE_STATUS_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_AUTHORITY
import okhttp3.internal.http2.Header.Companion.TARGET_AUTHORITY_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_METHOD
import okhttp3.internal.http2.Header.Companion.TARGET_METHOD_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_PATH
import okhttp3.internal.http2.Header.Companion.TARGET_PATH_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_SCHEME
import okhttp3.internal.http2.Header.Companion.TARGET_SCHEME_UTF8
import okhttp3.internal.immutableListOf
import okio.Sink
import okio.Source
/** Encode requests and responses using HTTP/2 frames. */
class Http2ExchangeCodec(
client: OkHttpClient,
override val connection: RealConnection,
private val chain: RealInterceptorChain,
private val http2Connection: Http2Connection
) : ExchangeCodec {
@Volatile private var stream: Http2Stream? = null
private val protocol: Protocol = if (Protocol.H2_PRIOR_KNOWLEDGE in client.protocols) {
Protocol.H2_PRIOR_KNOWLEDGE
} else {
Protocol.HTTP_2
}
@Volatile
private var canceled = false
override fun createRequestBody(request: Request, contentLength: Long): Sink {
return stream!!.getSink()
}
override fun writeRequestHeaders(request: Request) {
if (stream != null) return
val hasRequestBody = request.body != null
val requestHeaders = http2HeadersList(request)
stream = http2Connection.newStream(requestHeaders, hasRequestBody)
// We may have been asked to cancel while creating the new stream and sending the request
// headers, but there was still no stream to close.
if (canceled) {
stream!!.closeLater(ErrorCode.CANCEL)
throw IOException("Canceled")
}
stream!!.readTimeout().timeout(chain.readTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)
stream!!.writeTimeout().timeout(chain.writeTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)
}
override fun flushRequest() {
http2Connection.flush()
}
override fun finishRequest() {
stream!!.getSink().close()
}
override fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {
val stream = stream ?: throw IOException("stream wasn't created")
val headers = stream.takeHeaders()
val responseBuilder = readHttp2HeadersList(headers, protocol)
return if (expectContinue && responseBuilder.code == HTTP_CONTINUE) {
null
} else {
responseBuilder
}
}
override fun reportedContentLength(response: Response): Long {
return when {
!response.promisesBody() -> 0L
else -> response.headersContentLength()
}
}
override fun openResponseBodySource(response: Response): Source {
return stream!!.source
}
override fun trailers(): Headers {
return stream!!.trailers()
}
override fun cancel() {
canceled = true
stream?.closeLater(ErrorCode.CANCEL)
}
companion object {
private const val CONNECTION = "connection"
private const val HOST = "host"
private const val KEEP_ALIVE = "keep-alive"
private const val PROXY_CONNECTION = "proxy-connection"
private const val TRANSFER_ENCODING = "transfer-encoding"
private const val TE = "te"
private const val ENCODING = "encoding"
private const val UPGRADE = "upgrade"
/** See http://tools.ietf.org/html/draft-ietf-httpbis-http2-09#section-8.1.3. */
private val HTTP_2_SKIPPED_REQUEST_HEADERS = immutableListOf(
CONNECTION,
HOST,
KEEP_ALIVE,
PROXY_CONNECTION,
TE,
TRANSFER_ENCODING,
ENCODING,
UPGRADE,
TARGET_METHOD_UTF8,
TARGET_PATH_UTF8,
TARGET_SCHEME_UTF8,
TARGET_AUTHORITY_UTF8)
private val HTTP_2_SKIPPED_RESPONSE_HEADERS = immutableListOf(
CONNECTION,
HOST,
KEEP_ALIVE,
PROXY_CONNECTION,
TE,
TRANSFER_ENCODING,
ENCODING,
UPGRADE)
fun http2HeadersList(request: Request): List<Header> {
val headers = request.headers
val result = ArrayList<Header>(headers.size + 4)
result.add(Header(TARGET_METHOD, request.method))
result.add(Header(TARGET_PATH, RequestLine.requestPath(request.url)))
val host = request.header("Host")
if (host != null) {
result.add(Header(TARGET_AUTHORITY, host)) // Optional.
}
result.add(Header(TARGET_SCHEME, request.url.scheme))
for (i in 0 until headers.size) {
// header names must be lowercase.
val name = headers.name(i).toLowerCase(Locale.US)
if (name !in HTTP_2_SKIPPED_REQUEST_HEADERS ||
name == TE && headers.value(i) == "trailers") {
result.add(Header(name, headers.value(i)))
}
}
return result
}
/** Returns headers for a name value block containing an HTTP/2 response. */
fun readHttp2HeadersList(headerBlock: Headers, protocol: Protocol): Response.Builder {
var statusLine: StatusLine? = null
val headersBuilder = Headers.Builder()
for (i in 0 until headerBlock.size) {
val name = headerBlock.name(i)
val value = headerBlock.value(i)
if (name == RESPONSE_STATUS_UTF8) {
statusLine = StatusLine.parse("HTTP/1.1 $value")
} else if (name !in HTTP_2_SKIPPED_RESPONSE_HEADERS) {
headersBuilder.addLenient(name, value)
}
}
if (statusLine == null) throw ProtocolException("Expected ':status' header not present")
return Response.Builder()
.protocol(protocol)
.code(statusLine.code)
.message(statusLine.message)
.headers(headersBuilder.build())
}
}
}
| apache-2.0 | 6b0a4db7f7aa0959f3b80815c3292b5c | 33.401961 | 94 | 0.708321 | 4.174896 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/io/Uri.kt | 1 | 4138 | package slatekit.common.io
import java.io.File
/**
* Represents a File or Directory using a simple form of a Uniform Resource Identifier ( URI ) approach
* 1. user dir: usr://{path} or ~/{path}
* 2. curr dir: cur://{path} or ./{path}
* 3. path dir: abs://{path} or /{path}
* 4. temp dir: tmp://{path} or $TMPDIR/{path}
* 5. conf dir: cfg://{path} or ./conf/{path}
* 6. jars dir: jar://{path} or app.jar/resources/{path}
* @param raw : Raw path e.g. "~/app1/conf/env.conf"
* @param root : Root Alias e.g. "abs | usr | cur | tmp | cfg"
* @param path : Path to file e.g. "app1/conf/env.conf"
* @param full : Full path to file e.g. "/Users/batman/app1/conf/env.conf"
*/
data class Uri internal constructor(val raw: String,
val root: Alias,
val path: String?,
val full: String) {
internal constructor(raw:String, root: Alias, path:String?): this(raw, root, path, resolve(root, path))
fun isEmpty(): Boolean = path.isNullOrEmpty()
fun combine(otherPath: String): Uri {
return when {
path.isNullOrEmpty() -> {
this.copy(
raw = otherPath,
path = otherPath,
full = File(full, otherPath).toString()
)
}
else -> {
this.copy(
raw = File(path, otherPath).toString(),
path = File(path, otherPath).toString(),
full = File(full, otherPath).toString()
)
}
}
}
fun toFile(): java.io.File {
return when (root) {
is Alias.Abs -> java.io.File(full)
is Alias.Cur -> java.io.File(full)
is Alias.Rel -> java.io.File(full)
is Alias.Cfg -> java.io.File(full)
is Alias.Usr -> java.io.File(full)
is Alias.Ref -> java.io.File(System.getProperty("java.io.tmpdir"), path)
is Alias.Jar -> java.io.File(this.javaClass.getResource("/$path").file)
else -> java.io.File(path)
}
}
companion object {
fun abs(path: String, lookup: Map<String, String>? = null): Uri = of(Alias.Abs, path, lookup)
fun cur(path: String, lookup: Map<String, String>? = null): Uri = of(Alias.Cur, path, lookup)
fun rel(path: String, lookup: Map<String, String>? = null): Uri = of(Alias.Rel, path, lookup)
fun cfg(path: String, lookup: Map<String, String>? = null): Uri = of(Alias.Cfg, path, lookup)
fun usr(path: String, lookup: Map<String, String>? = null): Uri = of(Alias.Usr, path, lookup)
fun tmp(path: String, lookup: Map<String, String>? = null): Uri = of(Alias.Ref, path, lookup)
fun jar(path: String, lookup: Map<String, String>? = null): Uri = of(Alias.Jar, path, lookup)
fun of(alias: Alias, raw: String, lookup: Map<String, String>? = null): Uri {
val clean = clean(raw)
val trim = trim(clean)
return Uris.build(alias, raw, trim, lookup)
}
fun clean(path:String):String {
return when {
File.separator == "/" -> { path.replace("\\", File.separator).replace("\\\\", File.separator) }
File.separator == "\\" -> { path.replace("/", File.separator).replace("//", File.separator) }
else -> path
}
}
fun trim(path:String):String {
val trimmed = path.trim()
return when {
trimmed.startsWith("/") -> trimmed.substring(1)
trimmed.startsWith("\\") -> trimmed.substring(1)
trimmed.startsWith(File.separator) -> trimmed.substring(1)
else -> trimmed
}
}
private fun resolve(root:Alias, path:String?):String {
return when(path) {
null -> File(Alias.resolve(root)).toString()
else -> File(Alias.resolve(root), path).toString()
}
}
}
} | apache-2.0 | f19217f2b26af7ef7bf809d50a3998b2 | 39.184466 | 111 | 0.518366 | 3.911153 | false | false | false | false |
zdary/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootWebServerRootsProvider.kt | 12 | 1900 | /*
* 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.openapi.vcs.impl
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.builtInWebServer.FileResolver
import org.jetbrains.builtInWebServer.PathInfo
import org.jetbrains.builtInWebServer.PathQuery
import org.jetbrains.builtInWebServer.PrefixlessWebServerRootsProvider
internal class VcsRootWebServerRootsProvider : PrefixlessWebServerRootsProvider() {
override fun resolve(path: String, project: Project, resolver: FileResolver, pathQuery: PathQuery): PathInfo? {
for (vcsRoot in ProjectLevelVcsManager.getInstance(project).allVcsRoots) {
val root = if (vcsRoot.vcs != null) vcsRoot.path else continue
val virtualFile = resolver.resolve(path, root, pathQuery = pathQuery)
if (virtualFile != null) return virtualFile
}
return null
}
override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? {
for (vcsRoot in ProjectLevelVcsManager.getInstance(project).allVcsRoots) {
val root = if (vcsRoot.vcs != null) vcsRoot.path else continue
if (VfsUtilCore.isAncestor(root, file, true)) {
return PathInfo(null, file, root)
}
}
return null
}
} | apache-2.0 | 3427ea1e952f509fb80789179285675e | 40.326087 | 113 | 0.761053 | 4.481132 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/util/PanScaleProxyView.kt | 1 | 17915 | /*
* Copyright 2014 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.google.android.apps.muzei.util
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Point
import android.graphics.PointF
import android.graphics.RectF
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import android.widget.OverScroller
import androidx.core.view.GestureDetectorCompat
import kotlin.math.max
import kotlin.math.min
class PanScaleProxyView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0)
: View(context, attrs, defStyle) {
/**
* The current viewport. This rectangle represents the currently visible chart domain
* and range. The currently visible chart X values are from this rectangle's left to its right.
* The currently visible chart Y values are from this rectangle's top to its bottom.
*/
var currentViewport = RectF(0f, 0f, 1f, 1f)
private set
var relativeAspectRatio = 1f
set(value) {
field = value
constrainViewport()
triggerViewportChangedListener()
}
var panScaleEnabled = true
private val surfaceSizeBuffer = Point()
private var currentWidth = 1
private var currentHeight = 1
private var minViewportWidthOrHeight = 0.01f
// State objects and values related to gesture tracking.
private var scaleGestureDetector: ScaleGestureDetector
private val gestureDetector: GestureDetectorCompat
private val scroller = OverScroller(context)
private val zoomer = Zoomer(context)
private val zoomFocalPoint = PointF()
private val scrollerStartViewport = RectF() // Used only for zooms and flings.
private var dragZoomed = false
private var motionEventDown = false
var onViewportChanged: () -> Unit = {}
var onSingleTapUp: () -> Unit = {}
var onLongPress: () -> Unit = {}
/**
* The scale listener, used for handling multi-finger scale gestures.
*/
private val scaleGestureListener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
/**
* This is the active focal point in terms of the viewport. Could be a local
* variable but kept here to minimize per-frame allocations.
*/
private val viewportFocus = PointF()
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
if (!panScaleEnabled) {
return false
}
dragZoomed = true
return true
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
if (!panScaleEnabled) {
return false
}
val newWidth = 1 / detector.scaleFactor * currentViewport.width()
val newHeight = 1 / detector.scaleFactor * currentViewport.height()
val focusX = detector.focusX
val focusY = detector.focusY
hitTest(focusX, focusY, viewportFocus)
currentViewport.set(
viewportFocus.x - newWidth * focusX / currentWidth,
viewportFocus.y - newHeight * focusY / currentHeight,
0f,
0f)
currentViewport.right = currentViewport.left + newWidth
currentViewport.bottom = currentViewport.top + newHeight
constrainViewport()
triggerViewportChangedListener()
return true
}
}
/**
* The gesture listener, used for handling simple gestures such as double touches, scrolls,
* and flings.
*/
private val gestureListener = object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
if (!panScaleEnabled) {
return false
}
dragZoomed = false
scrollerStartViewport.set(currentViewport)
scroller.forceFinished(true)
return true
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
onSingleTapUp.invoke()
return true
}
override fun onLongPress(e: MotionEvent) {
onLongPress.invoke()
}
override fun onDoubleTapEvent(e: MotionEvent): Boolean {
if (!panScaleEnabled || dragZoomed || e.actionMasked != MotionEvent.ACTION_UP) {
return false
}
zoomer.forceFinished(true)
hitTest(e.x, e.y, zoomFocalPoint)
val startZoom = if (relativeAspectRatio > 1) {
1 / currentViewport.height()
} else {
1 / currentViewport.width()
}
val zoomIn = startZoom < 1.5f
zoomer.startZoom(startZoom, if (zoomIn) 2f else 1f)
triggerViewportChangedListener()
postAnimateTick()
// Workaround for 11952668; blow away the entire scale gesture detector after
// a double tap
scaleGestureDetector = ScaleGestureDetector(getContext(), scaleGestureListener).apply {
isQuickScaleEnabled = true
}
return true
}
override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
if (!panScaleEnabled) {
return false
}
// Scrolling uses math based on the viewport (as opposed to math using pixels).
/*
Pixel offset is the offset in screen pixels, while viewport offset is the
offset within the current viewport. For additional information on surface sizes
and pixel offsets, see the docs for {@link computeScrollSurfaceSize()}. For
additional information about the viewport, see the comments for
{@link currentViewport}.
*/
val viewportOffsetX = distanceX * currentViewport.width() / currentWidth
val viewportOffsetY = distanceY * currentViewport.height() / currentHeight
computeScrollSurfaceSize(surfaceSizeBuffer)
setViewportTopLeft(
currentViewport.left + viewportOffsetX,
currentViewport.top + viewportOffsetY)
return true
}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
if (!panScaleEnabled) {
return false
}
fling((-velocityX).toInt(), (-velocityY).toInt())
return true
}
}
private val animateTickRunnable = Runnable {
var needsInvalidate = false
if (scroller.computeScrollOffset()) {
// The scroller isn't finished, meaning a fling or programmatic pan operation is
// currently active.
computeScrollSurfaceSize(surfaceSizeBuffer)
val currX = scroller.currX
val currY = scroller.currY
val currXRange = currX * 1f / surfaceSizeBuffer.x
val currYRange = currY * 1f / surfaceSizeBuffer.y
setViewportTopLeft(currXRange, currYRange)
needsInvalidate = true
}
if (zoomer.computeZoom()) {
// Performs the zoom since a zoom is in progress.
val newWidth: Float
val newHeight: Float
if (relativeAspectRatio > 1) {
newHeight = 1 / zoomer.currZoom
newWidth = newHeight / relativeAspectRatio
} else {
newWidth = 1 / zoomer.currZoom
newHeight = newWidth * relativeAspectRatio
}
// focalPointOnScreen... 0 = left/top edge of screen, 1 = right/bottom edge of sreen
val focalPointOnScreenX = (zoomFocalPoint.x - scrollerStartViewport.left) / scrollerStartViewport.width()
val focalPointOnScreenY = (zoomFocalPoint.y - scrollerStartViewport.top) / scrollerStartViewport.height()
currentViewport.set(
zoomFocalPoint.x - newWidth * focalPointOnScreenX,
zoomFocalPoint.y - newHeight * focalPointOnScreenY,
zoomFocalPoint.x + newWidth * (1 - focalPointOnScreenX),
zoomFocalPoint.y + newHeight * (1 - focalPointOnScreenY))
constrainViewport()
needsInvalidate = true
}
if (needsInvalidate) {
triggerViewportChangedListener()
postAnimateTick()
}
}
init {
setWillNotDraw(true)
// Sets up interactions
scaleGestureDetector = ScaleGestureDetector(context, scaleGestureListener).apply {
isQuickScaleEnabled = true
}
gestureDetector = GestureDetectorCompat(context, gestureListener)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
currentWidth = max(1, w)
currentHeight = max(1, h)
}
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Methods and objects related to gesture handling
//
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finds the chart point (i.e. within the chart's domain and range) represented by the
* given pixel coordinates. The "dest" argument is set to the point and
* this function returns true.
*/
private fun hitTest(x: Float, y: Float, dest: PointF) {
dest.set(currentViewport.left + currentViewport.width() * x / currentWidth,
currentViewport.top + currentViewport.height() * y / currentHeight)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
motionEventDown = true
}
var retVal = scaleGestureDetector.onTouchEvent(event)
retVal = gestureDetector.onTouchEvent(event) || retVal
if (motionEventDown && event.actionMasked == MotionEvent.ACTION_UP) {
motionEventDown = false
}
return retVal || super.onTouchEvent(event)
}
/**
* Ensures that current viewport is inside the viewport extremes and original
* aspect ratio is kept.
*/
private fun constrainViewport() {
currentViewport.run {
if (relativeAspectRatio > 1) {
if (top < 0) {
offset(0f, -top)
}
if (bottom > 1) {
val requestedHeight = height()
bottom = 1f
top = max(0f, bottom - requestedHeight)
}
if (height() < minViewportWidthOrHeight) {
bottom = (bottom + top) / 2 + minViewportWidthOrHeight / 2
top = bottom - minViewportWidthOrHeight
}
val halfWidth = height() / relativeAspectRatio / 2f
val centerX = ((right + left) / 2).constrain(halfWidth, 1 - halfWidth)
left = centerX - halfWidth
right = centerX + halfWidth
} else {
if (left < 0) {
offset(-left, 0f)
}
if (right > 1) {
val requestedWidth = width()
right = 1f
left = max(0f, right - requestedWidth)
}
if (width() < minViewportWidthOrHeight) {
right = (right + left) / 2 + minViewportWidthOrHeight / 2
left = right - minViewportWidthOrHeight
}
val halfHeight = width() * relativeAspectRatio / 2
val centerY = ((bottom + top) / 2).constrain(halfHeight, 1 - halfHeight)
top = centerY - halfHeight
bottom = centerY + halfHeight
}
}
}
private fun fling(velocityX: Int, velocityY: Int) {
// Flings use math in pixels (as opposed to math based on the viewport).
computeScrollSurfaceSize(surfaceSizeBuffer)
scrollerStartViewport.set(currentViewport)
val startX = (surfaceSizeBuffer.x * scrollerStartViewport.left).toInt()
val startY = (surfaceSizeBuffer.y * scrollerStartViewport.top).toInt()
scroller.forceFinished(true)
scroller.fling(
startX,
startY,
velocityX,
velocityY,
0, surfaceSizeBuffer.x - currentWidth,
0, surfaceSizeBuffer.y - currentHeight,
currentWidth / 2,
currentHeight / 2)
postAnimateTick()
triggerViewportChangedListener()
}
private fun postAnimateTick() {
handler?.run {
removeCallbacks(animateTickRunnable)
post(animateTickRunnable)
}
}
override fun onDetachedFromWindow() {
handler?.run {
removeCallbacks(animateTickRunnable)
}
super.onDetachedFromWindow()
}
/**
* Computes the current scrollable surface size, in pixels. For example, if the entire chart
* area is visible, this is simply the current view width and height. If the chart
* is zoomed in 200% in both directions, the returned size will be twice as large horizontally
* and vertically.
*/
private fun computeScrollSurfaceSize(out: Point) {
out.set(
(currentWidth / currentViewport.width()).toInt(),
(currentHeight / currentViewport.height()).toInt())
}
/**
* Sets the current viewport (defined by [currentViewport]) to the given
* X and Y positions. Note that the Y value represents the topmost pixel position, and thus
* the bottom of the [currentViewport] rectangle. For more details on why top and
* bottom are flipped, see [currentViewport].
*/
private fun setViewportTopLeft(newX: Float, newY: Float) {
var x = newX
var y = newY
/*
Constrains within the scroll range. The scroll range is simply the viewport extremes
(AXIS_X_MAX, etc.) minus the viewport size. For example, if the extrema were 0 and 10,
and the viewport size was 2, the scroll range would be 0 to 8.
*/
val curWidth = currentViewport.width()
val curHeight = currentViewport.height()
x = max(0f, min(x, 1 - curWidth))
y = max(0f, min(y, 1 - curHeight))
currentViewport.set(x, y, x + curWidth, y + curHeight)
triggerViewportChangedListener()
}
private fun triggerViewportChangedListener() {
onViewportChanged.invoke()
}
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Methods and classes related to view state persistence.
//
////////////////////////////////////////////////////////////////////////////////////////////////
public override fun onSaveInstanceState(): Parcelable {
val superState = super.onSaveInstanceState()
return SavedState(superState).apply { viewport = currentViewport }
}
public override fun onRestoreInstanceState(state: Parcelable) {
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
super.onRestoreInstanceState(state.superState)
currentViewport = state.viewport
}
fun setViewport(viewport: RectF) {
currentViewport.set(viewport)
triggerViewportChangedListener()
}
fun setMaxZoom(maxZoom: Int) {
minViewportWidthOrHeight = 1f / maxZoom
}
/**
* Persistent state that is saved by PanScaleProxyView.
*/
internal class SavedState : BaseSavedState {
companion object {
@Suppress("unused")
@JvmField
val CREATOR = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
internal lateinit var viewport: RectF
constructor(superState: Parcelable?) : super(superState)
internal constructor(source: Parcel) : super(source) {
viewport = RectF(source.readFloat(), source.readFloat(), source.readFloat(), source.readFloat())
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeFloat(viewport.left)
out.writeFloat(viewport.top)
out.writeFloat(viewport.right)
out.writeFloat(viewport.bottom)
}
override fun toString(): String {
return ("PanScaleProxyView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " viewport=" + viewport.toString() + "}")
}
}
} | apache-2.0 | 6aeda2c0f81f6ca7ab5eab447e915fa5 | 36.402923 | 117 | 0.589618 | 5.20029 | false | false | false | false |
zdary/intellij-community | python/python-features-trainer/src/com/jetbrains/python/ift/lesson/essensial/PythonOnboardingTour.kt | 1 | 22390 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.ift.lesson.essensial
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.RunManager
import com.intellij.execution.ui.layout.impl.JBRunnerTabs
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.ide.util.gotoByName.GotoActionItemProvider
import com.intellij.ide.util.gotoByName.GotoActionModel
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.impl.FocusManagerImpl
import com.intellij.openapi.wm.impl.StripeButton
import com.intellij.ui.UIBundle
import com.intellij.ui.tree.TreeVisitor
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.xdebugger.XDebuggerBundle
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.ift.PythonLessonsBundle
import com.jetbrains.python.ift.PythonLessonsUtil
import icons.FeaturesTrainerIcons
import org.intellij.lang.annotations.Language
import org.jetbrains.annotations.Nls
import training.dsl.*
import training.dsl.LessonUtil.checkExpectedStateOfEditor
import training.dsl.LessonUtil.restoreIfModified
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.course.Lesson
import training.learn.course.LessonProperties
import training.learn.lesson.LessonListener
import training.learn.lesson.LessonManager
import training.learn.lesson.general.run.clearBreakpoints
import training.learn.lesson.general.run.toggleBreakpointTask
import training.ui.LearningUiHighlightingManager
import training.ui.LearningUiManager
import training.util.invokeActionForFocusContext
import java.awt.Component
import java.awt.Rectangle
import java.awt.event.KeyEvent
import java.util.concurrent.CompletableFuture
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JTree
import javax.swing.tree.TreePath
class PythonOnboardingTour :
KLesson("python.onboarding", PythonLessonsBundle.message("python.onboarding.lesson.name")) {
private val demoConfigurationName: String = "welcome"
private val demoFileName: String = "$demoConfigurationName.py"
override val properties = LessonProperties(
canStartInDumbMode = true,
openFileAtStart = false
)
override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true)
val sample: LessonSample = parseLessonSample("""
def find_average(values)<caret id=3/>:
result = 0
for v in values:
result += v
<caret>return result<caret id=2/>
print("AVERAGE", find_average([5,6, 7, 8]))
""".trimIndent())
override val lessonContent: LessonContext.() -> Unit = {
prepareRuntimeTask {
addEndLessonListener()
configurations().forEach { runManager().removeConfiguration(it) }
val root = ProjectRootManager.getInstance(project).contentRoots[0]
if (root.findChild(demoFileName) == null) invokeLater {
runWriteAction {
root.createChildData(this, demoFileName)
}
}
}
clearBreakpoints()
projectTasks()
prepareSample(sample)
openLearnToolwindow()
runTasks()
debugTasks()
completionSteps()
contextActions()
waitBeforeContinue(500)
searchEverywhereTasks()
task {
text(PythonLessonsBundle.message("python.onboarding.epilog",
getCallBackActionId("CloseProject"),
returnToWelcomeScreenRemark(),
LearningUiManager.addCallback { LearningUiManager.resetModulesView() }))
}
}
private fun returnToWelcomeScreenRemark(): String {
val isSingleProject = ProjectManager.getInstance().openProjects.size == 1
return if (isSingleProject) PythonLessonsBundle.message("python.onboarding.return.to.welcome") else ""
}
private fun TaskRuntimeContext.addEndLessonListener() {
val listener = object : LessonListener {
override fun lessonPassed(lesson: Lesson) {
invokeLater {
val result = MessageDialogBuilder.yesNoCancel(PythonLessonsBundle.message("python.onboarding.finish.title"),
PythonLessonsBundle.message("python.onboarding.finish.text", returnToWelcomeScreenRemark()))
.yesText(PythonLessonsBundle.message("python.onboarding.finish.exit"))
.noText(PythonLessonsBundle.message("python.onboarding.finish.modules"))
.icon(FeaturesTrainerIcons.Img.PluginIcon)
.show(project)
when (result) {
Messages.YES -> invokeLater {
LessonManager.instance.stopLesson()
val closeAction = ActionManager.getInstance().getAction("CloseProject") ?: error("No close project action found")
invokeActionForFocusContext(closeAction)
}
Messages.NO -> invokeLater {
LearningUiManager.resetModulesView()
}
}
}
}
override fun lessonStopped(lesson: Lesson) {
invokeLater {
removeLessonListener(this)
}
}
}
addLessonListener(listener)
}
private fun getCallBackActionId(@Suppress("SameParameterValue") actionId: String): Int {
val action = ActionManager.getInstance().getAction(actionId) ?: error("No action with Id $actionId")
return LearningUiManager.addCallback { invokeActionForFocusContext(action) }
}
private fun LessonContext.debugTasks() {
var logicalPosition = LogicalPosition(0, 0)
prepareRuntimeTask {
logicalPosition = editor.offsetToLogicalPosition(sample.startOffset)
}
caret(sample.startOffset)
toggleBreakpointTask(sample, { logicalPosition }, checkLine = false) {
text(PythonLessonsBundle.message("python.onboarding.balloon.click.here"),
LearningBalloonConfig(Balloon.Position.below, width = 0, duplicateMessage = false))
text(PythonLessonsBundle.message("python.onboarding.toggle.breakpoint.1",
code("6.5"), code("find_average"), code("26")))
text(PythonLessonsBundle.message("python.onboarding.toggle.breakpoint.2"))
}
highlightButtonByIdTask("Debug")
actionTask("Debug") {
buttonBalloon(PythonLessonsBundle.message("python.onboarding.balloon.start.debugging"))
restoreIfModified(sample)
PythonLessonsBundle.message("python.onboarding.start.debugging", icon(AllIcons.Actions.StartDebugger))
}
task {
// Need to wait until Debugger tab will be selected
stateCheck {
val f = UIUtil.getParentOfType(JBRunnerTabs::class.java, focusOwner)
f?.selectedInfo?.text == XDebuggerBundle.message("xdebugger.debugger.tab.title")
}
}
task {
val needFirstAction = ActionManager.getInstance().getAction("ShowExecutionPoint")
triggerByUiComponentAndHighlight(highlightInside = true, usePulsation = true) { ui: ActionToolbarImpl ->
ui.size.let { it.width > 0 && it.height > 0 } && ui.place == "DebuggerToolbar" && checkFirstButton(ui, needFirstAction)
}
}
highlightAllFoundUi(clearPreviousHighlights = false, highlightInside = true, usePulsation = true) { ui: ActionToolbarImpl ->
ui.size.let { it.width > 0 && it.height > 0 } && ui.place == "DebuggerToolbar" &&
checkFirstButton(ui, ActionManager.getInstance().getAction("Rerun"))
}
task {
text(PythonLessonsBundle.message("python.onboarding.balloon.about.debug.panel",
strong(UIBundle.message("tool.window.name.debug")),
strong(LessonsBundle.message("debug.workflow.lesson.name"))))
proceedLink()
restoreIfModified(sample)
}
highlightButtonByIdTask("Stop")
actionTask("Stop") {
buttonBalloon(
PythonLessonsBundle.message("python.onboarding.balloon.stop.debugging")) { list -> list.minByOrNull { it.locationOnScreen.y } }
restoreIfModified(sample)
PythonLessonsBundle.message("python.onboarding.stop.debugging", icon(AllIcons.Actions.Suspend))
}
prepareRuntimeTask {
LearningUiHighlightingManager.clearHighlights()
}
}
private fun LessonContext.highlightButtonByIdTask(actionId: String) {
val highlighted = highlightButtonById(actionId)
task {
addStep(highlighted)
}
}
private fun TaskContext.buttonBalloon(@Language("HTML") @Nls message: String,
chooser: (List<JComponent>) -> JComponent? = { it.firstOrNull() }) {
val highlightingComponent = chooser(LearningUiHighlightingManager.highlightingComponents.filterIsInstance<JComponent>())
val useBalloon = LearningBalloonConfig(Balloon.Position.below,
width = 0,
highlightingComponent = highlightingComponent,
duplicateMessage = false)
text(message, useBalloon)
}
private fun checkFirstButton(ui: ActionToolbarImpl,
needFirstAction: AnAction?): Boolean {
return ui.components.let {
it.isNotEmpty<Component?>() && (it[0] as? ActionButton)?.let { first ->
first.action == needFirstAction
} == true
}
}
private fun LessonContext.runTasks() {
val runItem = ExecutionBundle.message("default.runner.start.action.text").dropMnemonic() + " '$demoConfigurationName'"
task {
text(PythonLessonsBundle.message("python.onboarding.context.menu"))
triggerByUiComponentAndHighlight(usePulsation = true) { ui: ActionMenuItem ->
ui.text?.contains(runItem) ?: false
}
restoreIfModified(sample)
}
task {
text(PythonLessonsBundle.message("python.onboarding.run.sample", strong(runItem), action("RunClass")))
checkToolWindowState("Run", true)
stateCheck {
configurations().isNotEmpty()
}
restoreIfModified(sample)
}
task {
triggerByPartOfComponent(highlightInside = true, usePulsation = true) { ui: ActionToolbarImpl ->
ui.takeIf { (ui.place == "NavBarToolbar" || ui.place == "MainToolbar") }?.let { toolbar ->
val configurations = ui.components.find { it is JPanel && it.components.any { b -> b is ComboBoxAction.ComboBoxButton } }
val stop = ui.components.find { it is ActionButton && it.action == ActionManager.getInstance().getAction("Stop") }
if (configurations != null && stop != null) {
val x = configurations.x
val y = configurations.y
val width = stop.x + stop.width - x
val height = stop.y + stop.height - y
Rectangle(x, y, width, height)
} else null
}
}
}
task {
text(PythonLessonsBundle.message("python.onboarding.temporary.configuration.description",
icon(AllIcons.Actions.Execute),
icon(AllIcons.Actions.StartDebugger),
icon(AllIcons.Actions.Profile),
icon(AllIcons.General.RunWithCoverage)))
proceedLink()
restoreIfModified(sample)
}
}
private fun TaskContext.proceedLink() {
val gotIt = CompletableFuture<Boolean>()
runtimeText {
removeAfterDone = true
PythonLessonsBundle.message("python.onboarding.proceed.to.the.next.step", LearningUiManager.addCallback { gotIt.complete(true) })
}
addStep(gotIt)
}
private fun LessonContext.openLearnToolwindow() {
task {
triggerByUiComponentAndHighlight(usePulsation = true) { stripe: StripeButton ->
stripe.windowInfo.id == "Learn"
}
}
task {
text(
PythonLessonsBundle.message("python.onboarding.balloon.open.learn.toolbar", strong(LearnBundle.message("toolwindow.stripe.Learn"))),
LearningBalloonConfig(Balloon.Position.atRight, width = 300))
stateCheck {
ToolWindowManager.getInstance(project).getToolWindow("Learn")?.isVisible == true
}
restoreIfModified(sample)
}
prepareRuntimeTask {
LearningUiHighlightingManager.clearHighlights()
}
}
private fun LessonContext.projectTasks() {
prepareRuntimeTask {
LessonUtil.hideStandardToolwindows(project)
}
task {
triggerByUiComponentAndHighlight(usePulsation = true) { stripe: StripeButton ->
stripe.windowInfo.id == "Project"
}
}
task {
var collapsed = false
text(PythonLessonsBundle.message("python.onboarding.project.view.description",
action("ActivateProjectToolWindow")))
text(PythonLessonsBundle.message("python.onboarding.balloon.project.view"),
LearningBalloonConfig(Balloon.Position.atRight, width = 0))
triggerByFoundPathAndHighlight { tree: JTree, path: TreePath ->
val result = path.pathCount >= 1 && path.getPathComponent(0).toString().contains("PyCharmLearningProject")
if (result) {
if (!collapsed) {
invokeLater {
tree.collapsePath(path)
}
}
collapsed = true
}
result
}
}
fun isDemoFilePath(path: TreePath) =
path.pathCount >= 3 && path.getPathComponent(2).toString().contains(demoFileName)
task {
text(PythonLessonsBundle.message("python.onboarding.balloon.project.directory"),
LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 400))
triggerByFoundPathAndHighlight { _: JTree, path: TreePath ->
isDemoFilePath(path)
}
restoreByUi()
}
task {
text(PythonLessonsBundle.message("python.onboarding.balloon.open.file", code(demoFileName)),
LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0))
stateCheck l@{
if (FileEditorManager.getInstance(project).selectedTextEditor == null) return@l false
virtualFile.name == demoFileName
}
restoreState {
(previous.ui as? JTree)?.takeIf { tree ->
TreeUtil.visitVisibleRows(tree, TreeVisitor { path ->
if (isDemoFilePath(path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE
}) != null
}?.isShowing?.not() ?: true
}
}
}
private fun LessonContext.completionSteps() {
val completionPosition = sample.getPosition(2)
caret(completionPosition)
prepareRuntimeTask {
FocusManagerImpl.getInstance(project).requestFocusInProject(editor.contentComponent, project)
}
task {
text(PythonLessonsBundle.message("python.onboarding.type.division", code(" / l")))
var wasEmpty = false
proposeRestore {
checkExpectedStateOfEditor(previous.sample) {
if (it.isEmpty()) wasEmpty = true
wasEmpty && "/len".contains(it.replace(" ", ""))
}
}
triggerByListItemAndHighlight(highlightBorder = true, highlightInside = false) { // no highlighting
it.toString().contains("string=len;")
}
}
task {
text(PythonLessonsBundle.message("python.onboarding.choose.len.item",
code("len(__obj)"), action("EditorChooseLookupItem")))
stateCheck {
checkEditorModification(completionPosition, "/len()")
}
restoreByUi()
}
task("CodeCompletion") {
text(PythonLessonsBundle.message("python.onboarding.invoke.completion",
code("values"),
code("()"),
action(it)))
trigger(it)
triggerByListItemAndHighlight(highlightBorder = true, highlightInside = false) { item ->
item.toString().contains("values")
}
restoreIfModifiedOrMoved()
}
task {
text(PythonLessonsBundle.message("python.onboarding.choose.values.item",
strong("val"), code("values"), action("EditorChooseLookupItem")))
stateCheck {
checkEditorModification(completionPosition, "/len(values)")
}
restoreByUi()
}
}
private fun TaskRuntimeContext.checkEditorModification(completionPosition: LessonSamplePosition, needChange: String): Boolean {
val startOfChange = completionPosition.startOffset
val sampleText = sample.text
val prefix = sampleText.substring(0, startOfChange)
val suffix = sampleText.substring(startOfChange, sampleText.length)
val current = editor.document.text
if (!current.startsWith(prefix)) return false
if (!current.endsWith(suffix)) return false
val indexOfSuffix = current.indexOf(suffix)
if (indexOfSuffix < startOfChange) return false
val change = current.substring(startOfChange, indexOfSuffix)
return change.replace(" ", "") == needChange
}
private fun LessonContext.contextActions() {
val reformatMessage = PyBundle.message("QFIX.reformat.file")
caret(",6")
task("ShowIntentionActions") {
text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.warning.1"))
text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.warning.2", action(it)))
triggerByListItemAndHighlight(highlightBorder = true, highlightInside = false) { item ->
item.toString().contains(reformatMessage)
}
restoreIfModifiedOrMoved()
}
task {
text(PythonLessonsBundle.message("python.onboarding.select.fix", strong(reformatMessage)))
stateCheck {
// TODO: make normal check
previous.sample.text != editor.document.text
}
restoreByUi(delayMillis = defaultRestoreDelay)
}
fun returnTypeMessage(project: Project)=
if (PythonLessonsUtil.isPython3Installed(project)) PyPsiBundle.message("INTN.specify.return.type.in.annotation")
else PyPsiBundle.message("INTN.specify.return.type.in.docstring")
caret("find_average")
task("ShowIntentionActions") {
text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.code",
code("find_average"), action(it)))
triggerByListItemAndHighlight(highlightBorder = true, highlightInside = false) { item ->
item.toString().contains(returnTypeMessage(project))
}
restoreIfModifiedOrMoved()
}
task {
text(PythonLessonsBundle.message("python.onboarding.apply.intention", strong(returnTypeMessage(project)), LessonUtil.rawEnter()))
stateCheck {
val text = editor.document.text
previous.sample.text != text && text.contains("object")
}
restoreByUi(delayMillis = defaultRestoreDelay)
}
task {
lateinit var forRestore: LessonSample
before {
val text = previous.sample.text
val toReplace = "object"
forRestore = LessonSample(text.replace(toReplace, ""), text.indexOf(toReplace).takeIf { it != -1 } ?: 0)
}
text(PythonLessonsBundle.message("python.onboarding.complete.template", code("float"), LessonUtil.rawEnter()))
stateCheck {
// TODO: make normal check
val activeTemplate = TemplateManagerImpl.getInstance(project).getActiveTemplate(editor)
editor.document.text.contains("float") && activeTemplate == null
}
proposeRestore {
checkExpectedStateOfEditor(forRestore) {
"object".contains(it) || "float".contains(it)
}
}
}
}
private fun LessonContext.searchEverywhereTasks() {
val toggleCase = ActionsBundle.message("action.EditorToggleCase.text")
caret("AVERAGE", select = true)
task("SearchEverywhere") {
text(PythonLessonsBundle.message("python.onboarding.invoke.search.everywhere.1",
strong(toggleCase), code("AVERAGE")))
text(PythonLessonsBundle.message("python.onboarding.invoke.search.everywhere.2",
LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT), LessonUtil.actionName(it)))
trigger(it)
restoreIfModifiedOrMoved()
}
task {
text(PythonLessonsBundle.message("python.onboarding.search.everywhere.description", strong("AVERAGE")))
triggerByListItemAndHighlight { item ->
(item as? GotoActionModel.MatchedValue)?.value?.let { GotoActionItemProvider.getActionText(it) } == toggleCase
}
restoreIfModifiedOrMoved()
restoreState(delayMillis = defaultRestoreDelay) {
UIUtil.getParentOfType(SearchEverywhereUI::class.java, focusOwner) == null
}
}
actionTask("EditorToggleCase") {
restoreByUi(delayMillis = defaultRestoreDelay)
PythonLessonsBundle.message("python.onboarding.apply.action", strong(toggleCase), LessonUtil.rawEnter())
}
text(PythonLessonsBundle.message("python.onboarding.case.changed"))
}
private fun TaskRuntimeContext.runManager() = RunManager.getInstance(project)
private fun TaskRuntimeContext.configurations() =
runManager().allSettings.filter { it.name.contains(demoConfigurationName) }
}
| apache-2.0 | 7896dcc57eed2d9a5c541b4c11cdab83 | 38.143357 | 148 | 0.68151 | 5.034855 | false | false | false | false |
Triple-T/gradle-play-publisher | play/android-publisher/src/main/kotlin/com/github/triplet/gradle/androidpublisher/Responses.kt | 1 | 4358 | package com.github.triplet.gradle.androidpublisher
import com.github.triplet.gradle.androidpublisher.internal.has
import com.google.api.client.googleapis.json.GoogleJsonResponseException
/** Response for an app details request. */
data class GppAppDetails internal constructor(
/** The default language. */
val defaultLocale: String?,
/** Developer contact email. */
val contactEmail: String?,
/** Developer contact phone. */
val contactPhone: String?,
/** Developer contact website. */
val contactWebsite: String?,
)
/** Response for an app listing request. */
data class GppListing internal constructor(
/** The listing's language. */
val locale: String,
/** The app description. */
val fullDescription: String?,
/** The app tagline. */
val shortDescription: String?,
/** The app title. */
val title: String?,
/** The app promo url. */
val video: String?,
)
/** Response for an app graphic request. */
data class GppImage internal constructor(
/** The image's download URL. */
val url: String,
/** The image's SHA256 hash. */
val sha256: String,
)
/** Response for a track release note request. */
data class ReleaseNote internal constructor(
/** The release note's track. */
val track: String,
/** The release note's language. */
val locale: String,
/** The release note. */
val contents: String,
)
/** Response for an edit request. */
sealed class EditResponse {
/** Response for a successful edit request. */
data class Success internal constructor(
/** The id of the edit in question. */
val id: String,
) : EditResponse()
/** Response for an unsuccessful edit request. */
data class Failure internal constructor(
private val e: GoogleJsonResponseException,
) : EditResponse() {
/** @return true if the app wasn't found in the Play Console, false otherwise */
fun isNewApp(): Boolean = e has "applicationNotFound"
/** @return true if the provided edit is invalid for any reason, false otherwise */
fun isInvalidEdit(): Boolean =
e has "editAlreadyCommitted" || e has "editNotFound" || e has "editExpired"
/** @return true if the user doesn't have permission to access this app, false otherwise */
fun isUnauthorized(): Boolean = e.statusCode == 401
/** Cleanly rethrows the error. */
fun rethrow(): Nothing = throw e
/** Wraps the error in a new exception with the provided [newMessage]. */
fun rethrow(newMessage: String): Nothing = throw IllegalStateException(newMessage, e)
}
}
/** Response for an commit request. */
sealed class CommitResponse {
/** Response for a successful commit request. */
object Success : CommitResponse()
/** Response for an unsuccessful commit request. */
data class Failure internal constructor(
private val e: GoogleJsonResponseException,
) : CommitResponse() {
/** @return true if the changes cannot be sent for review, false otherwise */
fun failedToSendForReview(): Boolean =
e has "badRequest" && e.details.message.orEmpty().contains("changesNotSentForReview")
/** Cleanly rethrows the error. */
fun rethrow(suppressed: Failure? = null): Nothing {
if (suppressed != null) {
e.addSuppressed(suppressed.e)
}
throw e
}
}
}
/** Response for an internal sharing artifact upload. */
data class UploadInternalSharingArtifactResponse internal constructor(
/** The response's full JSON payload. */
val json: String,
/** The download URL of the uploaded artifact. */
val downloadUrl: String,
)
/** Response for a product request. */
data class GppProduct internal constructor(
/** The product ID. */
val sku: String,
/** The response's full JSON payload. */
val json: String,
)
/** Response for a product update request. */
data class UpdateProductResponse internal constructor(
/** @return true if the product doesn't exist and needs to be created, false otherwise. */
val needsCreating: Boolean,
)
| mit | 4903bbc2b3f453f7594ec43abbd3e772 | 33.864 | 101 | 0.630335 | 4.88565 | false | false | false | false |
smmribeiro/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/build/DelegateBuildRunner.kt | 10 | 2626 | // 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 org.jetbrains.idea.maven.execution.build
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.impl.DefaultJavaProgramRunner
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ProgramRunner
import com.intellij.execution.runners.RunContentBuilder
import com.intellij.execution.target.TargetEnvironmentAwareRunProfileState
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import org.jetbrains.concurrency.Promise
import java.util.concurrent.atomic.AtomicReference
internal class DelegateBuildRunner : DefaultJavaProgramRunner() {
override fun getRunnerId() = ID
@Throws(ExecutionException::class)
override fun doExecute(state: RunProfileState, environment: ExecutionEnvironment): RunContentDescriptor? {
val executionResult = state.execute(environment.executor, this) ?: return null
val result = AtomicReference<RunContentDescriptor?>()
ApplicationManager.getApplication().invokeAndWait {
val runContentBuilder = RunContentBuilder(executionResult, environment)
val runContentDescriptor = runContentBuilder.showRunContent(environment.contentToReuse) ?: return@invokeAndWait
val descriptor = object : RunContentDescriptor(runContentDescriptor.executionConsole, runContentDescriptor.processHandler,
runContentDescriptor.component, runContentDescriptor.displayName,
runContentDescriptor.icon, null,
runContentDescriptor.restartActions) {
override fun isHiddenContent() = true
}
descriptor.runnerLayoutUi = runContentDescriptor.runnerLayoutUi
result.set(descriptor)
}
return result.get()
}
override fun doExecuteAsync(state: TargetEnvironmentAwareRunProfileState, env: ExecutionEnvironment): Promise<RunContentDescriptor?> {
return state.prepareTargetToCommandExecution(env, LOG, "Failed to execute delegate run configuration async") { doExecute(state, env) }
}
companion object {
private const val ID = "MAVEN_DELEGATE_BUILD_RUNNER"
private val LOG = logger<DelegateBuildRunner>()
@JvmStatic
fun getDelegateRunner(): ProgramRunner<*>? = ProgramRunner.findRunnerById(ID)
}
}
| apache-2.0 | 6ee0761ec6abae9d8086b9fa1d80e2ba | 49.5 | 140 | 0.761615 | 5.647312 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyNegatedBinaryExpressionInspection.kt | 4 | 4128 | // 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.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
class SimplifyNegatedBinaryExpressionInspection : AbstractApplicabilityBasedInspection<KtPrefixExpression>(KtPrefixExpression::class.java) {
override fun inspectionHighlightRangeInElement(element: KtPrefixExpression) = element.operationReference.textRangeIn(element)
override fun inspectionText(element: KtPrefixExpression) = KotlinBundle.message("negated.operation.should.be.simplified")
override val defaultFixText get() = KotlinBundle.message("simplify.negated.operation")
override fun fixText(element: KtPrefixExpression): String {
val expression = KtPsiUtil.deparenthesize(element.baseExpression) as? KtOperationExpression ?: return defaultFixText
val operation = expression.operationReference.getReferencedNameElementType() as? KtSingleValueToken ?: return defaultFixText
val negatedOperation = operation.negate() ?: return defaultFixText
return KotlinBundle.message("replace.negated.0.operation.with.1", operation.value, negatedOperation.value)
}
override fun isApplicable(element: KtPrefixExpression): Boolean {
return element.canBeSimplified()
}
override fun applyTo(element: KtPrefixExpression, project: Project, editor: Editor?) {
element.simplify()
}
companion object {
fun simplifyNegatedBinaryExpressionIfNeeded(expression: KtPrefixExpression) {
if (expression.canBeSimplified()) expression.simplify()
}
private fun KtPrefixExpression.canBeSimplified(): Boolean {
if (operationToken != KtTokens.EXCL) return false
val expression = KtPsiUtil.deparenthesize(baseExpression) as? KtOperationExpression ?: return false
when (expression) {
is KtIsExpression -> if (expression.typeReference == null) return false
is KtBinaryExpression -> if (expression.left == null || expression.right == null) return false
else -> return false
}
return (expression.operationReference.getReferencedNameElementType() as? KtSingleValueToken)?.negate() != null
}
private fun KtPrefixExpression.simplify() {
val expression = KtPsiUtil.deparenthesize(baseExpression) ?: return
val operation =
(expression as KtOperationExpression).operationReference.getReferencedNameElementType().negate()?.value ?: return
val psiFactory = KtPsiFactory(expression)
val newExpression = when (expression) {
is KtIsExpression ->
psiFactory.createExpressionByPattern("$0 $1 $2", expression.leftHandSide, operation, expression.typeReference!!)
is KtBinaryExpression ->
psiFactory.createExpressionByPattern("$0 $1 $2", expression.left ?: return, operation, expression.right ?: return)
else ->
throw IllegalArgumentException()
}
replace(newExpression)
}
private fun IElementType.negate(): KtSingleValueToken? = when (this) {
KtTokens.IN_KEYWORD -> KtTokens.NOT_IN
KtTokens.NOT_IN -> KtTokens.IN_KEYWORD
KtTokens.IS_KEYWORD -> KtTokens.NOT_IS
KtTokens.NOT_IS -> KtTokens.IS_KEYWORD
KtTokens.EQEQ -> KtTokens.EXCLEQ
KtTokens.EXCLEQ -> KtTokens.EQEQ
KtTokens.LT -> KtTokens.GTEQ
KtTokens.GTEQ -> KtTokens.LT
KtTokens.GT -> KtTokens.LTEQ
KtTokens.LTEQ -> KtTokens.GT
else -> null
}
}
} | apache-2.0 | 9c52f17aefa6931afa78330b71dabaaf | 44.373626 | 158 | 0.691134 | 5.68595 | false | false | false | false |
MarcinMoskala/ActivityStarter | sample/kotlinapp/src/main/java/com/marcinmoskala/kotlinapp/StudentDataActivity.kt | 1 | 1083 | package com.marcinmoskala.kotlinapp
import activitystarter.Arg
import activitystarter.MakeActivityStarter
import android.annotation.SuppressLint
import android.os.Bundle
import com.marcinmoskala.activitystarter.argExtra
import kotlinx.android.synthetic.main.activity_data.*
@MakeActivityStarter
class StudentDataActivity : BaseActivity() {
@get:Arg(optional = true) var name: String by argExtra(defaultName)
@get:Arg(optional = true) var id: Int by argExtra(defaultId)
@get:Arg var grade: Char by argExtra()
@get:Arg var passing: Boolean by argExtra()
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_data)
nameView.text = "Name: $name"
idView.text = "Id: $id"
gradeView.text = "Grade: $grade"
isPassingView.text = "Passing status: $passing"
}
companion object {
private const val NO_ID = -1
const val defaultName = "No name provided"
const val defaultId = NO_ID
}
}
| apache-2.0 | a07de8bb8f34334c05d3cf2f86535ac2 | 31.818182 | 71 | 0.709141 | 3.981618 | false | false | false | false |
lucasgomes-eti/KotlinAndroidProjects | CameraDemo/app/src/main/java/com/example/lucas/camerademo/MainActivity.kt | 1 | 2416 | package com.example.lucas.camerademo
import android.Manifest
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.frosquivel.magicalcamera.MagicalPermissions
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import android.R.attr.keySet
import android.app.Fragment
import android.content.Intent
import android.util.Log
import com.frosquivel.magicalcamera.MagicalCamera
import android.os.AsyncTask
import android.app.Activity
import android.R.attr.data
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var magicalPermissions: MagicalPermissions
private lateinit var magicalCamera: MagicalCamera
private val RESIZE_PHOTO_PIXELS_PERCENTAGE = 100
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val permissions = arrayOf<String>(Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
magicalPermissions = MagicalPermissions(this, permissions)
magicalCamera = MagicalCamera(this, RESIZE_PHOTO_PIXELS_PERCENTAGE, magicalPermissions)
buttonTakePhoto.setOnClickListener {
magicalCamera.takePhoto()
}
buttonPickPhoto.setOnClickListener{
magicalCamera.selectedPicture("Selecione imagem com")
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
val map = magicalPermissions.permissionResult(requestCode, permissions, grantResults)
for (permission in map.keys) {
Log.d("PERMISSIONS", permission + " was: " + map[permission])
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
//you should to call the method ever, for obtain the bitmap photo (= magicalCamera.getPhoto())
magicalCamera.resultPhoto(requestCode, resultCode, data)
imageViewPhoto.setImageBitmap(magicalCamera.photo)
magicalCamera.savePhotoInMemoryDevice(magicalCamera.getPhoto(),"IMG_${Random().nextInt()}","Camera Demo", MagicalCamera.JPEG, true)
}
}
}
| cc0-1.0 | 8fd21fd0079157dc9ed51650025dcfa7 | 38.606557 | 143 | 0.730546 | 4.549906 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/draw/base_api/Practice4PointView.kt | 1 | 1226 | package com.zeke.demo.draw.base_api
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import com.zeke.demo.base.BasePracticeView
import com.zeke.demo.model.CardItemConst
class Practice4PointView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BasePracticeView(context, attrs, defStyleAttr) {
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// 练习内容:使用 canvas.drawPoint() 方法画点
// 一个圆点,一个方点
// 圆点和方点的切换使用 paint.setStrokeCap(cap):`ROUND` 是圆点,`BUTT` 或 `SQUARE` 是方点
paint.color = Color.BLACK
paint.strokeCap = Paint.Cap.ROUND
paint.strokeWidth = 40f
canvas.drawPoint(330f, 50f, paint)
paint.strokeCap = Paint.Cap.BUTT
canvas.drawPoint(550f, 50f, paint)
paint.color = Color.RED
paint.strokeCap = Paint.Cap.SQUARE
canvas.drawPoint(750f, 50f, paint)
}
override fun getViewHeight(): Int {
return CardItemConst.SMALL_HEIGHT
}
}
| gpl-2.0 | 6391111fcb1e026b5871d14fa6e19c8a | 30.888889 | 86 | 0.679443 | 3.656051 | false | false | false | false |
nonylene/PhotoLinkViewer-Core | photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/fragment/ShowFragment.kt | 1 | 17488 | package net.nonylene.photolinkviewer.core.fragment
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Matrix
import android.graphics.Point
import android.os.Build
import android.os.Bundle
import android.preference.PreferenceManager
import android.app.DialogFragment
import android.content.res.Configuration
import android.support.v4.app.LoaderManager
import android.support.v4.content.Loader
import android.support.v7.app.AlertDialog
import android.text.TextUtils
import android.view.*
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.Toast
import butterknife.bindView
import net.nonylene.photolinkviewer.core.PLVMaxSizePreferenceActivity
import net.nonylene.photolinkviewer.core.R
import net.nonylene.photolinkviewer.core.async.AsyncHttpBitmap
import net.nonylene.photolinkviewer.core.event.DownloadButtonEvent
import net.nonylene.photolinkviewer.core.event.RotateEvent
import net.nonylene.photolinkviewer.core.event.BaseShowFragmentEvent
import net.nonylene.photolinkviewer.core.event.SnackbarEvent
import net.nonylene.photolinkviewer.core.tool.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
class ShowFragment : BaseShowFragment() {
private val imageView: ImageView by bindView(R.id.imgview)
private val showFrameLayout: FrameLayout by bindView(R.id.showframe)
private val progressBar: ProgressBar by bindView(R.id.showprogress)
private val preferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(activity) }
private var firstScale = 1f
private var quickScale: MyQuickScale? = null
private var applicationContext : Context? = null
companion object {
private val IS_SINGLE_FRAGMENT_KEY = "is_single"
private val PLV_URL_KEY = "plvurl"
/**
* @param isSingleFragment if true, background color and progressbar become transparent in this fragment.
*/
fun createArguments(plvUrl: PLVUrl, isSingleFragment: Boolean): Bundle {
return Bundle().apply {
putParcelable(PLV_URL_KEY, plvUrl)
putBoolean(IS_SINGLE_FRAGMENT_KEY, isSingleFragment)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
applicationContext = activity.applicationContext
return inflater.inflate(R.layout.plv_core_show_fragment, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val scaleGestureDetector = ScaleGestureDetector(activity, simpleOnScaleGestureListener())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
scaleGestureDetector.isQuickScaleEnabled = false
}
val gestureDetector = GestureDetector(activity, simpleOnGestureListener())
imageView.setOnTouchListener { view, event ->
scaleGestureDetector.onTouchEvent(event)
if (!scaleGestureDetector.isInProgress) {
gestureDetector.onTouchEvent(event)
}
when (event.action) {
// image_view double_tap quick scale
MotionEvent.ACTION_MOVE -> quickScale?.onMove(event)
MotionEvent.ACTION_UP -> quickScale = null
}
true
}
if (!preferences.getBoolean("initialized39", false)) {
Initialize.initialize39(activity)
}
if (!preferences.isInitialized47()) {
Initialize.initialize47(activity)
}
if (arguments.getBoolean(IS_SINGLE_FRAGMENT_KEY)) {
showFrameLayout.setBackgroundResource(R.color.plv_core_transparent)
progressBar.visibility = View.GONE
}
EventBus.getDefault().postSticky(DownloadButtonEvent(listOf(arguments.getParcelable(PLV_URL_KEY)), false))
AsyncExecute(arguments.getParcelable(PLV_URL_KEY)).Start()
}
override fun onResume() {
super.onResume()
EventBus.getDefault().register(this)
}
override fun onPause() {
EventBus.getDefault().unregister(this)
super.onPause()
}
internal inner class simpleOnGestureListener : GestureDetector.SimpleOnGestureListener() {
var isDoubleZoomDisabled: Boolean = false
override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
// drag photo
val matrix = Matrix()
matrix.set(imageView.imageMatrix)
val values = FloatArray(9)
matrix.getValues(values)
// move photo
values[Matrix.MTRANS_X] = values[Matrix.MTRANS_X] - distanceX
values[Matrix.MTRANS_Y] = values[Matrix.MTRANS_Y] - distanceY
matrix.setValues(values)
imageView.imageMatrix = matrix
return super.onScroll(e1, e2, distanceX, distanceY)
}
override fun onDoubleTap(e: MotionEvent): Boolean {
isDoubleZoomDisabled = preferences.isDoubleZoomDisabled()
quickScale = MyQuickScale(e, !isDoubleZoomDisabled)
if (!isDoubleZoomDisabled) doubleZoom(e)
return super.onDoubleTap(e)
}
override fun onDoubleTapEvent(e: MotionEvent): Boolean {
if (e.action == MotionEvent.ACTION_UP) {
quickScale?.let {
if (isDoubleZoomDisabled && !it.moved) doubleZoom(e)
quickScale = null
}
}
return false
}
private fun doubleZoom(e: MotionEvent) {
val touchX = e.x
val touchY = e.y
imageView.startAnimation(ScaleAnimation(1f, 2f, 1f, 2f, touchX, touchY).apply {
duration = 200
isFillEnabled = true
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
val matrix = Matrix()
matrix.set(imageView.imageMatrix)
matrix.postScale(2f, 2f, touchX, touchY)
imageView.imageMatrix = matrix
}
override fun onAnimationRepeat(animation: Animation) {
}
})
})
}
}
private inner class MyQuickScale(e: MotionEvent, double_frag: Boolean) {
// quick scale zoom
private val initialY: Float
private val initialX: Float
private var basezoom: Float = 0f
private var old_zoom: Float = 0f
var moved = false
init {
initialY = e.y
initialX = e.x
//get current status
val values = FloatArray(9)
val matrix = Matrix()
matrix.set(imageView.imageMatrix)
matrix.getValues(values)
//set base zoom param
basezoom = values[Matrix.MSCALE_X]
if (basezoom == 0f) basezoom = Math.abs(values[Matrix.MSKEW_X])
// double tap
if (double_frag) basezoom *= 2
old_zoom = 1f
}
fun onMove(e: MotionEvent) {
moved = true
val touchY = e.y
val matrix = Matrix()
matrix.set(imageView.imageMatrix)
// adjust zoom speed
// If using preference_fragment, value is saved to DefaultSharedPref.
val zoomSpeed = preferences.getZoomSpeed()
val new_zoom = Math.pow((touchY / initialY).toDouble(), (zoomSpeed * 2).toDouble()).toFloat()
// photo's zoom scale (is relative to old zoom value.)
val scale = new_zoom / old_zoom
if (new_zoom > firstScale / basezoom * 0.8) {
old_zoom = new_zoom
matrix.postScale(scale, scale, initialX, initialY)
imageView.imageMatrix = matrix
}
}
}
internal inner class simpleOnScaleGestureListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
private var touchX: Float = 0f
private var touchY: Float = 0f
private var basezoom: Float = 0f
private var old_zoom: Float = 0f
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
//define zoom-base point
touchX = detector.focusX
touchY = detector.focusY
//get current status
val values = FloatArray(9)
val matrix = Matrix()
matrix.set(imageView.imageMatrix)
matrix.getValues(values)
//set base zoom param
basezoom = values[Matrix.MSCALE_X]
if (basezoom == 0f) basezoom = Math.abs(values[Matrix.MSKEW_X])
old_zoom = 1f
return super.onScaleBegin(detector)
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
val matrix = Matrix()
matrix.set(imageView.imageMatrix)
// adjust zoom speed
// If using preference_fragment, value is saved to DefaultSharedPref.
val zoomSpeed = preferences.getZoomSpeed()
val new_zoom = Math.pow(detector.scaleFactor.toDouble(), zoomSpeed.toDouble()).toFloat()
// photo's zoom scale (is relative to old zoom value.)
val scale = new_zoom / old_zoom
if (new_zoom > firstScale / basezoom * 0.8) {
old_zoom = new_zoom
matrix.postScale(scale, scale, touchX, touchY)
imageView.imageMatrix = matrix
}
return super.onScale(detector)
}
}
inner class AsyncExecute(private val plvUrl: PLVUrl) : LoaderManager.LoaderCallbacks<AsyncHttpBitmap.Result> {
fun Start() {
//there are some loaders, so restart(all has finished)
val bundle = Bundle().apply {
putParcelable("plvurl", plvUrl)
}
loaderManager.restartLoader(0, bundle, this)
}
override fun onCreateLoader(id: Int, bundle: Bundle): Loader<AsyncHttpBitmap.Result> {
val max_size = preferences.getImageViewMaxSize() * 1024
return AsyncHttpBitmap(activity.applicationContext, bundle.getParcelable<PLVUrl>("plvurl"), max_size)
}
override fun onLoadFinished(loader: Loader<AsyncHttpBitmap.Result>, result: AsyncHttpBitmap.Result) {
plvUrl.type = result.type
plvUrl.height = result.originalHeight
plvUrl.width = result.originalWidth
val bitmap = result.bitmap
if (bitmap == null) {
Toast.makeText(applicationContext, getString(R.string.plv_core_show_bitamap_error) +
result.errorMessage?.let { "\n" + it }, Toast.LENGTH_LONG).show()
return
}
EventBus.getDefault().postSticky(DownloadButtonEvent(listOf(plvUrl), false))
if ("gif" == result.type) {
addWebView(plvUrl)
return
} else {
removeProgressBar()
}
val display = activity.windowManager.defaultDisplay
val displaySize = Point()
display.getSize(displaySize)
// get picture scale
val widthScale = displaySize.x / bitmap.width.toFloat()
val heightScale = displaySize.y / bitmap.height.toFloat()
val minScale = Math.min(widthScale, heightScale)
if (preferences.isAdjustZoom() || minScale < 1) {
imageView.scaleType = ImageView.ScaleType.FIT_CENTER
}
firstScale = Math.min(minScale, 1f)
if (result.isResized) {
// avoid crash after fragment closed
activity.let { activity ->
EventBus.getDefault().post(
SnackbarEvent(getString(R.string.plv_core_resize_message) + result.originalWidth + "x" + result.originalHeight,
getString(R.string.plv_core_resize_action_message), {
MaxSizeDialogFragment().show(activity.fragmentManager, "about")
}))
}
}
removeProgressBar()
// change scale to MATRIX
imageView.setImageBitmap(bitmap)
imageView.scaleType = ImageView.ScaleType.MATRIX
EventBus.getDefault().post(BaseShowFragmentEvent(this@ShowFragment, true))
}
override fun onLoaderReset(loader: Loader<AsyncHttpBitmap.Result>) {
}
}
@Suppress("unused")
@Subscribe
fun onEvent(rotateEvent: RotateEvent) {
rotateImg(rotateEvent.isRightRotate)
}
private fun rotateImg(right: Boolean) {
//get display size
val size = Point()
activity.windowManager.defaultDisplay.getSize(size)
imageView.imageMatrix = Matrix().apply {
set(imageView.imageMatrix)
postRotate(if (right) 90f else -90f, (size.x / 2).toFloat(), (size.y / 2).toFloat())
}
}
override fun onDestroyView() {
super.onDestroyView()
imageView.setImageBitmap(null)
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().post(BaseShowFragmentEvent(this, false))
}
private fun addWebView(plvUrl: PLVUrl) {
val videoWidth = plvUrl.width
val videoHeight = plvUrl.height
val display = activity.windowManager.defaultDisplay
val size = Point()
display.getSize(size)
val dispWidth = size.x
val dispHeight = size.y
// gif view by web view
val webView = WebView(activity).apply {
settings.useWideViewPort = true
settings.loadWithOverviewMode = true
}
val layoutParams: FrameLayout.LayoutParams
val escaped = TextUtils.htmlEncode(plvUrl.displayUrl)
val html: String
if ((videoHeight > dispHeight * 0.9 && videoWidth * dispHeight / dispHeight < dispWidth) || dispWidth * videoHeight / videoWidth > dispHeight) {
// if height of video > disp_height * 0.9, check whether calculated width > disp_width . if this is true,
// give priority to width. and, if check whether calculated height > disp_height, give priority to height.
val width = (dispWidth * 0.9).toInt()
val height = (dispHeight * 0.9).toInt()
layoutParams = FrameLayout.LayoutParams(width, height)
html = "<html><body><img style='display: block; margin: 0 auto' height='100%'src='$escaped'></body></html>"
} else {
val width = (dispWidth * 0.9).toInt()
layoutParams = FrameLayout.LayoutParams(width, width * videoHeight / videoWidth)
html = "<html><body><img style='display: block; margin: 0 auto' width='100%'src='$escaped'></body></html>"
}
layoutParams.gravity = Gravity.CENTER
webView.apply {
setLayoutParams(layoutParams)
// html to centering
loadData(html, "text/html", "utf-8")
setBackgroundColor(0)
settings.builtInZoomControls = true
}
removeProgressBar()
showFrameLayout.addView(webView)
}
private fun removeProgressBar() {
showFrameLayout.removeView(progressBar)
(activity as? ProgressBarListener)?.hideProgressBar()
}
class MaxSizeDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog? {
return AlertDialog.Builder(activity)
.setTitle(getString(R.string.plv_core_image_resized_dialog_title))
.setMessage(getString(R.string.plv_core_image_resized_dialog_text))
.setPositiveButton(getString(android.R.string.ok), null)
.setNeutralButton(getString(R.string.plv_core_image_resized_dialog_neutral), { dialogInterface, i ->
startActivity(Intent(activity, PLVMaxSizePreferenceActivity::class.java))
})
.create()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
when (newConfig.orientation) {
Configuration.ORIENTATION_LANDSCAPE, Configuration.ORIENTATION_PORTRAIT -> {
val matrix = Matrix().apply {
set(imageView.imageMatrix)
}
val values = FloatArray(9)
matrix.getValues(values)
// swap XY
values[Matrix.MTRANS_X].let {
values[Matrix.MTRANS_X] = values[Matrix.MTRANS_Y]
values[Matrix.MTRANS_Y] = it
}
matrix.setValues(values)
imageView.imageMatrix = matrix
}
}
}
} | gpl-2.0 | 5c301b0670353e7db817a51672ab4bd7 | 37.778271 | 152 | 0.611105 | 4.853733 | false | false | false | false |
Avarel/Kaiper | Kaiper-Interpreter/src/test/kotlin/xyz/avarel/kaiper/ExprTest.kt | 2 | 2033 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package xyz.avarel.kaiper
import org.junit.Test
class ExprTest {
@Test
fun `check compile`() {
eval("1")
eval("42")
eval("1+2^3")
eval("2*(3*4)")
eval("1.235")
eval("-2.0/17")
eval("3.0+2.5")
eval("3 >= 2")
eval("true && false")
eval("[1,2,3] == [1..3]")
eval("def(x) = { x + 2 }")
eval("{ x, y -> x ^ y }")
eval("def f(x) = x + 2; f(2) == 4")
eval("def isEven(x) { x % 2 == 0 }; [1..20] |> Array.filter(isEven)")
eval("let add = { x, y -> x + y }; [1..10] |> Array.fold(0, add) == 55")
eval("[1..10] |> Array.fold(1, { x, y -> x * y })")
eval("[[1, 2, 3], [1, 5, 8, 9, 10], [1..50]] |> Array.map(_.size)")
eval("Array.map([1..10], _ ^ 2) == [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]")
eval("[1,2,3][1]")
eval("let x = [50..60]; x[5]")
eval("let x = [100..200]; x[25:30]")
eval("[1..10] |> Array.map(_ ^ 2)")
eval("let add = { x, y -> x + y }; [1..10] |> Array.fold(0, add)")
eval("def isEven(x) { x % 2 == 0 }; [1..20] |> Array.filter(isEven)")
eval("[1..10] |> Array.fold(1, { x, y -> x * y })")
}
}
| apache-2.0 | 8c357a1c92c177df14d64145f61caa5a | 31.790323 | 83 | 0.533694 | 3.137346 | false | false | false | false |
chetdeva/recyclerview-bindings | app/src/main/java/com/fueled/recyclerviewbindings/util/ViewUtil.kt | 1 | 1191 | package com.fueled.recyclerviewbindings.util
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
/**
* Utility class pertaining to Views
* @author chetansachdeva on 25/07/17
*/
object ViewUtil {
/**
* converts drawable to bitmap
* @param drawable
* *
* @return bitmap
*/
fun getBitmap(drawable: Drawable): Bitmap {
val bitmap: Bitmap
if (drawable is BitmapDrawable) {
val bitmapDrawable = drawable
if (bitmapDrawable.bitmap != null) {
return bitmapDrawable.bitmap
}
}
if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
}
| mit | 597371d5c58323d2a67f2c0060c89859 | 26.697674 | 123 | 0.643997 | 4.44403 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentMultipleEntityImpl.kt | 2 | 9736 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ParentMultipleEntityImpl(val dataSource: ParentMultipleEntityData) : ParentMultipleEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentMultipleEntity::class.java,
ChildMultipleEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val parentData: String
get() = dataSource.parentData
override val children: List<ChildMultipleEntity>
get() = snapshot.extractOneToManyChildren<ChildMultipleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ParentMultipleEntityData?) : ModifiableWorkspaceEntityBase<ParentMultipleEntity, ParentMultipleEntityData>(
result), ParentMultipleEntity.Builder {
constructor() : this(ParentMultipleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentMultipleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isParentDataInitialized()) {
error("Field ParentMultipleEntity#parentData should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field ParentMultipleEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field ParentMultipleEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ParentMultipleEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.parentData != dataSource.parentData) this.parentData = dataSource.parentData
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var parentData: String
get() = getEntityData().parentData
set(value) {
checkModificationAllowed()
getEntityData(true).parentData = value
changedProperty.add("parentData")
}
// List of non-abstract referenced types
var _children: List<ChildMultipleEntity>? = emptyList()
override var children: List<ChildMultipleEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ChildMultipleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<ChildMultipleEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildMultipleEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityClass(): Class<ParentMultipleEntity> = ParentMultipleEntity::class.java
}
}
class ParentMultipleEntityData : WorkspaceEntityData<ParentMultipleEntity>() {
lateinit var parentData: String
fun isParentDataInitialized(): Boolean = ::parentData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ParentMultipleEntity> {
val modifiable = ParentMultipleEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ParentMultipleEntity {
return getCached(snapshot) {
val entity = ParentMultipleEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentMultipleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ParentMultipleEntity(parentData, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ParentMultipleEntityData
if (this.entitySource != other.entitySource) return false
if (this.parentData != other.parentData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ParentMultipleEntityData
if (this.parentData != other.parentData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 72e22e2940ed9bf3c7d646ba54bee0fb | 36.736434 | 188 | 0.682108 | 5.387936 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRDiffRequestChainProducer.kt | 7 | 7594 | // 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.plugins.github.pullrequest.ui.changes
import com.intellij.diff.chains.AsyncDiffRequestChain
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.tools.util.text.LineOffsetsUtil
import com.intellij.diff.util.DiffUserDataKeys
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.NonEmptyActionGroup
import com.intellij.openapi.ListSelection
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.diff.impl.GenericDataProvider
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer
import com.intellij.openapi.vcs.ex.isValidRanges
import com.intellij.openapi.vcs.history.VcsDiffUtil
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupport
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupportImpl
import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewResolvedThreadsToggleAction
import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsReloadAction
import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsToggleAction
import org.jetbrains.plugins.github.pullrequest.data.GHPRChangesProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDataProvider
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRRepositoryDataService
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.util.ChangeDiffRequestProducerFactory
import org.jetbrains.plugins.github.util.DiffRequestChainProducer
import org.jetbrains.plugins.github.util.GHToolbarLabelAction
import java.util.concurrent.CompletableFuture
open class GHPRDiffRequestChainProducer(
private val project: Project,
private val dataProvider: GHPRDataProvider,
private val avatarIconsProvider: GHAvatarIconsProvider,
private val repositoryDataService: GHPRRepositoryDataService,
private val currentUser: GHUser
) : DiffRequestChainProducer {
internal val changeProducerFactory = object : ChangeDiffRequestProducerFactory {
val changesData = dataProvider.changesData
val changesProviderFuture = changesData.loadChanges()
//TODO: check if revisions are already fetched or load via API (could be much quicker in some cases)
val fetchFuture = CompletableFuture.allOf(changesData.fetchBaseBranch(), changesData.fetchHeadBranch())
override fun create(project: Project?, change: Change): DiffRequestProducer? {
val indicator = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator()
val changeDataKeys = loadRequestDataKeys(indicator, change, changesProviderFuture, fetchFuture)
val customDataKeys = createCustomContext(change)
return ChangeDiffRequestProducer.create(project, change, changeDataKeys + customDataKeys)
}
}
override fun getRequestChain(changes: ListSelection<Change>): DiffRequestChain {
return object : AsyncDiffRequestChain() {
override fun loadRequestProducers(): ListSelection<out DiffRequestProducer> {
return changes.map { change -> changeProducerFactory.create(project, change) }
}
}
}
protected open fun createCustomContext(change: Change): Map<Key<*>, Any> = emptyMap()
private fun loadRequestDataKeys(indicator: ProgressIndicator,
change: Change,
changesProviderFuture: CompletableFuture<GHPRChangesProvider>,
fetchFuture: CompletableFuture<Void>): Map<Key<out Any>, Any?> {
val changesProvider = ProgressIndicatorUtils.awaitWithCheckCanceled(changesProviderFuture, indicator)
ProgressIndicatorUtils.awaitWithCheckCanceled(fetchFuture, indicator)
val requestDataKeys = mutableMapOf<Key<out Any>, Any?>()
VcsDiffUtil.putFilePathsIntoChangeContext(change, requestDataKeys)
val diffComputer = getDiffComputer(changesProvider, change)
if (diffComputer != null) {
requestDataKeys[DiffUserDataKeysEx.CUSTOM_DIFF_COMPUTER] = diffComputer
}
val reviewSupport = getReviewSupport(changesProvider, change)
if (reviewSupport != null) {
requestDataKeys[GHPRDiffReviewSupport.KEY] = reviewSupport
requestDataKeys[DiffUserDataKeys.DATA_PROVIDER] = GenericDataProvider().apply {
putData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER, dataProvider)
putData(GHPRDiffReviewSupport.DATA_KEY, reviewSupport)
}
val viewOptionsGroup = NonEmptyActionGroup().apply {
isPopup = true
templatePresentation.text = GithubBundle.message("pull.request.diff.view.options")
templatePresentation.icon = AllIcons.Actions.Show
add(GHPRDiffReviewThreadsToggleAction())
add(GHPRDiffReviewResolvedThreadsToggleAction())
}
requestDataKeys[DiffUserDataKeys.CONTEXT_ACTIONS] = listOf(
GHToolbarLabelAction(GithubBundle.message("pull.request.diff.review.label")),
viewOptionsGroup,
GHPRDiffReviewThreadsReloadAction(),
ActionManager.getInstance().getAction("Github.PullRequest.Review.Submit"))
}
return requestDataKeys
}
private fun getReviewSupport(changesProvider: GHPRChangesProvider, change: Change): GHPRDiffReviewSupport? {
val diffData = changesProvider.findChangeDiffData(change) ?: return null
return GHPRDiffReviewSupportImpl(project,
dataProvider.reviewData, dataProvider.detailsData, avatarIconsProvider,
repositoryDataService,
diffData,
currentUser)
}
private fun getDiffComputer(changesProvider: GHPRChangesProvider, change: Change): DiffUserDataKeysEx.DiffComputer? {
val diffRanges = changesProvider.findChangeDiffData(change)?.diffRangesWithoutContext ?: return null
return DiffUserDataKeysEx.DiffComputer { text1, text2, policy, innerChanges, indicator ->
val comparisonManager = ComparisonManagerImpl.getInstanceImpl()
val lineOffsets1 = LineOffsetsUtil.create(text1)
val lineOffsets2 = LineOffsetsUtil.create(text2)
if (!isValidRanges(text1, text2, lineOffsets1, lineOffsets2, diffRanges)) {
error("Invalid diff line ranges for change $change")
}
val iterable = DiffIterableUtil.create(diffRanges, lineOffsets1.lineCount, lineOffsets2.lineCount)
DiffIterableUtil.iterateAll(iterable).map {
comparisonManager.compareLinesInner(it.first, text1, text2, lineOffsets1, lineOffsets2, policy, innerChanges,
indicator)
}.flatten()
}
}
}
| apache-2.0 | 641ed36bc9d62661a6b117d30542c559 | 51.013699 | 158 | 0.775612 | 4.98294 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/rebase/interactive/dialog/GitInteractiveRebaseDialog.kt | 2 | 7631 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.rebase.interactive.dialog
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.AnActionButton
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.PopupHandler
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.ui.details.FullCommitDetailsListPanel
import git4idea.history.GitCommitRequirements
import git4idea.history.GitLogUtil
import git4idea.i18n.GitBundle
import git4idea.rebase.GitRebaseEntryWithDetails
import git4idea.rebase.interactive.GitRebaseTodoModel
import org.jetbrains.annotations.ApiStatus
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JSeparator
import javax.swing.SwingConstants
@ApiStatus.Internal
const val GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY = "Git.Interactive.Rebase.Dialog"
internal class GitInteractiveRebaseDialog<T : GitRebaseEntryWithDetails>(
private val project: Project,
root: VirtualFile,
entries: List<T>
) : DialogWrapper(project, true) {
companion object {
private const val DETAILS_PROPORTION = "Git.Interactive.Rebase.Details.Proportion"
internal const val PLACE = "Git.Interactive.Rebase.Dialog"
private const val DIALOG_HEIGHT = 550
private const val DIALOG_WIDTH = 1000
}
private val commitsTableModel = GitRebaseCommitsTableModel(entries)
private val resetEntriesLabel = LinkLabel<Any?>(GitBundle.message("rebase.interactive.dialog.reset.link.text"), null).apply {
isVisible = false
setListener(
LinkListener { _, _ ->
commitsTable.removeEditor()
commitsTableModel.resetEntries()
isVisible = false
},
null
)
}
private val commitsTable = object : GitRebaseCommitsTableView(project, commitsTableModel, disposable) {
override fun onEditorCreate() {
isOKActionEnabled = false
}
override fun onEditorRemove() {
isOKActionEnabled = true
}
}
private val modalityState = window?.let { ModalityState.stateForComponent(it) } ?: ModalityState.current()
private val fullCommitDetailsListPanel = object : FullCommitDetailsListPanel(project, disposable, modalityState) {
@RequiresBackgroundThread
@Throws(VcsException::class)
override fun loadChanges(commits: List<VcsCommitMetadata>): List<Change> {
val changes = mutableListOf<Change>()
GitLogUtil.readFullDetailsForHashes(project, root, commits.map { it.id.asString() }, GitCommitRequirements.DEFAULT) { gitCommit ->
changes.addAll(gitCommit.changes)
}
return CommittedChangesTreeBrowser.zipChanges(changes)
}
}
private val iconActions = listOf(
PickAction(commitsTable),
EditAction(commitsTable)
)
private val rewordAction = RewordAction(commitsTable)
private val fixupAction = FixupAction(commitsTable)
private val squashAction = SquashAction(commitsTable)
private val dropAction = DropAction(commitsTable)
private val contextMenuOnlyActions = listOf<AnAction>(ShowGitRebaseCommandsDialog(project, commitsTable))
private var modified = false
init {
commitsTable.selectionModel.addListSelectionListener { _ ->
fullCommitDetailsListPanel.commitsSelected(commitsTable.selectedRows.map { commitsTableModel.getEntry(it).commitDetails })
}
commitsTableModel.addTableModelListener { resetEntriesLabel.isVisible = true }
commitsTableModel.addTableModelListener { modified = true }
PopupHandler.installRowSelectionTablePopup(
commitsTable,
DefaultActionGroup().apply {
addAll(iconActions)
add(rewordAction)
add(squashAction)
add(fixupAction)
add(dropAction)
addSeparator()
addAll(contextMenuOnlyActions)
},
PLACE
)
title = GitBundle.message("rebase.interactive.dialog.title")
setOKButtonText(GitBundle.message("rebase.interactive.dialog.start.rebase"))
init()
}
override fun getDimensionServiceKey() = GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY
override fun createCenterPanel() = BorderLayoutPanel().apply {
val decorator = ToolbarDecorator.createDecorator(commitsTable)
.setToolbarPosition(ActionToolbarPosition.TOP)
.setPanelBorder(JBUI.Borders.empty())
.setScrollPaneBorder(JBUI.Borders.empty())
.disableAddAction()
.disableRemoveAction()
.addExtraActions(*iconActions.toTypedArray())
.addExtraAction(AnActionButtonSeparator())
.addExtraAction(rewordAction)
.addExtraAction(AnActionOptionButton(squashAction, listOf(fixupAction)))
.addExtraAction(dropAction)
val tablePanel = decorator.createPanel()
val resetEntriesLabelPanel = BorderLayoutPanel().addToCenter(resetEntriesLabel).apply {
border = JBUI.Borders.empty(0, 5, 0, 10)
}
decorator.actionsPanel.apply {
add(BorderLayout.EAST, resetEntriesLabelPanel)
}
val detailsSplitter = OnePixelSplitter(DETAILS_PROPORTION, 0.5f).apply {
firstComponent = tablePanel
secondComponent = fullCommitDetailsListPanel
}
addToCenter(detailsSplitter)
preferredSize = JBDimension(DIALOG_WIDTH, DIALOG_HEIGHT)
}
override fun getStyle() = DialogStyle.COMPACT
fun getModel(): GitRebaseTodoModel<T> = commitsTableModel.rebaseTodoModel
override fun getPreferredFocusedComponent(): JComponent = commitsTable
override fun doCancelAction() {
if (modified) {
val result = Messages.showDialog(
rootPane,
GitBundle.message("rebase.interactive.dialog.discard.modifications.message"),
GitBundle.message("rebase.interactive.dialog.discard.modifications.cancel"),
arrayOf(
GitBundle.message("rebase.interactive.dialog.discard.modifications.discard"),
GitBundle.message("rebase.interactive.dialog.discard.modifications.continue")
),
0,
Messages.getQuestionIcon()
)
if (result != Messages.YES) {
return
}
}
super.doCancelAction()
}
override fun getHelpId(): String {
return "reference.VersionControl.Git.RebaseCommits"
}
private class AnActionButtonSeparator : AnActionButton(), CustomComponentAction, DumbAware {
companion object {
private val SEPARATOR_HEIGHT = JBUI.scale(20)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun actionPerformed(e: AnActionEvent) {
throw UnsupportedOperationException()
}
override fun createCustomComponent(presentation: Presentation, place: String) = JSeparator(SwingConstants.VERTICAL).apply {
preferredSize = Dimension(preferredSize.width, SEPARATOR_HEIGHT)
}
}
} | apache-2.0 | e55f37fcfcf64e33eb1be773a5119697 | 36.596059 | 136 | 0.758092 | 4.728005 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameUnderscoreFix.kt | 4 | 2097 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.ide.DataManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.refactoring.rename.RenameHandlerRegistry
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
class RenameUnderscoreFix(declaration: KtDeclaration) : KotlinQuickFixAction<KtDeclaration>(declaration) {
override fun startInWriteAction(): Boolean = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (editor == null) return
val dataContext = DataManager.getInstance().getDataContext(editor.component)
val renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext)
renameHandler?.invoke(project, arrayOf(element), dataContext)
}
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
return editor != null
}
override fun getText(): String = KotlinBundle.message("rename.identifier.fix.text")
override fun getFamilyName(): String = text
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val declaration = diagnostic.psiElement.getNonStrictParentOfType<KtDeclaration>() ?: return null
if (diagnostic.psiElement == (declaration as? PsiNameIdentifierOwner)?.nameIdentifier) {
return RenameUnderscoreFix(declaration)
}
return null
}
}
} | apache-2.0 | f63ec22a408e2091dc6c39f51c0831b1 | 46.681818 | 158 | 0.764425 | 5.040865 | false | false | false | false |
smmribeiro/intellij-community | platform/execution-impl/src/com/intellij/execution/wsl/target/WslTargetEnvironment.kt | 1 | 7104 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.wsl.target
import com.intellij.execution.ExecutionException
import com.intellij.execution.Platform
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.PtyCommandLine
import com.intellij.execution.target.*
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.execution.wsl.WslProxy
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.impl.wsl.WslConstants
import com.intellij.util.io.sizeOrNull
import java.io.IOException
import java.nio.file.Path
import java.util.*
class WslTargetEnvironment constructor(override val request: WslTargetEnvironmentRequest,
private val distribution: WSLDistribution) : TargetEnvironment(request) {
private val myUploadVolumes: MutableMap<UploadRoot, UploadableVolume> = HashMap()
private val myDownloadVolumes: MutableMap<DownloadRoot, DownloadableVolume> = HashMap()
private val myTargetPortBindings: MutableMap<TargetPortBinding, Int> = HashMap()
private val myLocalPortBindings: MutableMap<LocalPortBinding, ResolvedPortBinding> = HashMap()
private val proxies = mutableMapOf<Int, WslProxy>() //port to proxy
override val uploadVolumes: Map<UploadRoot, UploadableVolume>
get() = Collections.unmodifiableMap(myUploadVolumes)
override val downloadVolumes: Map<DownloadRoot, DownloadableVolume>
get() = Collections.unmodifiableMap(myDownloadVolumes)
override val targetPortBindings: Map<TargetPortBinding, Int>
get() = Collections.unmodifiableMap(myTargetPortBindings)
override val localPortBindings: Map<LocalPortBinding, ResolvedPortBinding>
get() = Collections.unmodifiableMap(myLocalPortBindings)
override val targetPlatform: TargetPlatform
get() = TargetPlatform(Platform.UNIX)
init {
for (uploadRoot in request.uploadVolumes) {
val targetRoot: String? = toLinuxPath(uploadRoot.localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myUploadVolumes[uploadRoot] = Volume(uploadRoot.localRootPath, targetRoot)
}
else {
LOG.error("Cannot register upload volume: WSL path not found for local path: " + uploadRoot.localRootPath)
}
}
for (downloadRoot in request.downloadVolumes) {
val localRootPath = downloadRoot.localRootPath ?: FileUtil.createTempDirectory("intellij-target.", "").toPath()
val targetRoot: String? = toLinuxPath(localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myDownloadVolumes[downloadRoot] = Volume(localRootPath, targetRoot)
}
}
for (targetPortBinding in request.targetPortBindings) {
val theOnlyPort = targetPortBinding.target
if (targetPortBinding.local != null && targetPortBinding.local != theOnlyPort) {
throw UnsupportedOperationException("Local target's TCP port forwarder is not implemented")
}
myTargetPortBindings[targetPortBinding] = theOnlyPort
}
for (localPortBinding in request.localPortBindings) {
// Ports bound on localhost in Windows can be accessed by linux apps running in WSL1, but not in WSL2:
// https://docs.microsoft.com/en-US/windows/wsl/compare-versions#accessing-network-applications
val localPort = localPortBinding.local
val hostPort = HostPort("127.0.0.1", if (distribution.version > 1) getWslPort(localPort) else localPort)
myLocalPortBindings[localPortBinding] = ResolvedPortBinding(hostPort, hostPort)
}
}
private fun getWslPort(localPort: Int): Int {
proxies[localPort]?.wslIngressPort?.let {
return it
}
WslProxy(distribution, localPort).apply {
proxies[localPort] = this
return this.wslIngressPort
}
}
private fun toLinuxPath(localPath: String): String? {
val linuxPath = distribution.getWslPath(localPath)
if (linuxPath != null) {
return linuxPath
}
return convertUncPathToLinux(localPath)
}
private fun convertUncPathToLinux(localPath: String): String? {
val root: String = WslConstants.UNC_PREFIX + distribution.msId
val winLocalPath = FileUtil.toSystemDependentName(localPath)
if (winLocalPath.startsWith(root)) {
val linuxPath = winLocalPath.substring(root.length)
if (linuxPath.isEmpty()) {
return "/"
}
if (linuxPath.startsWith("\\")) {
return FileUtil.toSystemIndependentName(linuxPath)
}
}
return null
}
@Throws(ExecutionException::class)
override fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process {
val ptyOptions = request.ptyOptions
val generalCommandLine = if (ptyOptions != null) {
PtyCommandLine(commandLine.collectCommandsSynchronously()).withOptions(ptyOptions)
}
else {
GeneralCommandLine(commandLine.collectCommandsSynchronously())
}
generalCommandLine.environment.putAll(commandLine.environmentVariables)
request.wslOptions.remoteWorkingDirectory = commandLine.workingDirectory
generalCommandLine.withRedirectErrorStream(commandLine.isRedirectErrorStream)
distribution.patchCommandLine(generalCommandLine, null, request.wslOptions)
return generalCommandLine.createProcess().apply {
onExit().whenCompleteAsync { _, _ ->
proxies.forEach { Disposer.dispose(it.value) }
proxies.clear()
}
}
}
override fun shutdown() {}
private inner class Volume(override val localRoot: Path, override val targetRoot: String) : UploadableVolume, DownloadableVolume {
@Throws(IOException::class)
override fun resolveTargetPath(relativePath: String): String {
val localPath = FileUtil.toCanonicalPath(FileUtil.join(localRoot.toString(), relativePath))
return toLinuxPath(localPath) ?: throw RuntimeException("Cannot find Linux path for $localPath (${distribution.msId})")
}
@Throws(IOException::class)
override fun upload(relativePath: String, targetProgressIndicator: TargetProgressIndicator) {
}
@Throws(IOException::class)
override fun download(relativePath: String, progressIndicator: ProgressIndicator) {
// Synchronization may be slow -- let us wait until file size does not change
// in a reasonable amount of time
// (see https://github.com/microsoft/WSL/issues/4197)
val path = localRoot.resolve(relativePath)
var previousSize = -2L // sizeOrNull returns -1 if file does not exist
var newSize = path.sizeOrNull()
while (previousSize < newSize) {
Thread.sleep(100)
previousSize = newSize
newSize = path.sizeOrNull()
}
if (newSize == -1L) {
LOG.warn("Path $path was not found on local filesystem")
}
}
}
companion object {
val LOG = logger<WslTargetEnvironment>()
}
}
| apache-2.0 | 45fa7066ec16c89587a4af999ea00121 | 41.795181 | 140 | 0.736768 | 4.919668 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/SOTAAdventure.kt | 1 | 1772 | package pt.joaomneto.titancompanion.adventure.impl
import java.io.BufferedWriter
import java.io.IOException
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureEquipmentFragment
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureVitalStatsFragment
import pt.joaomneto.titancompanion.adventure.impl.fragments.sota.SOTAAdventureCombatFragment
import pt.joaomneto.titancompanion.adventure.impl.fragments.sota.SOTAAdventureTimeFragment
import pt.joaomneto.titancompanion.util.AdventureFragmentRunner
class SOTAAdventure : TFODAdventure(
arrayOf(
AdventureFragmentRunner(R.string.vitalStats, AdventureVitalStatsFragment::class),
AdventureFragmentRunner(R.string.time, SOTAAdventureTimeFragment::class),
AdventureFragmentRunner(R.string.fights, SOTAAdventureCombatFragment::class),
AdventureFragmentRunner(R.string.goldEquipment, AdventureEquipmentFragment::class),
AdventureFragmentRunner(R.string.notes, AdventureNotesFragment::class)
)
) {
var time = 0
override fun loadAdventureSpecificValuesFromFile() {
gold = Integer.valueOf(savedGame.getProperty("gold"))
provisions = Integer.valueOf(savedGame.getProperty("provisions"))
provisionsValue = Integer.valueOf(savedGame.getProperty("provisionsValue"))
time = Integer.valueOf(savedGame.getProperty("time"))
}
@Throws(IOException::class)
override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) {
bw.write("gold=$gold\n")
bw.write("time=$time\n")
bw.write("provisions=$provisions\n")
bw.write("provisionsValue=4\n")
}
}
| lgpl-3.0 | 2c9bcb6a52a88be7342df1f199f4f12c | 44.435897 | 92 | 0.781603 | 4.463476 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/library/LibraryUpdater.kt | 1 | 3811 | package xyz.nulldev.ts.library
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.util.syncChaptersWithSource
import mu.KotlinLogging
import rx.schedulers.Schedulers
import xyz.nulldev.ts.api.v3.util.await
import xyz.nulldev.ts.ext.kInstanceLazy
import java.util.*
/*
* Copyright 2016 Andy Bao
*
* 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.
*/
/**
* Project: TachiServer
* Author: nulldev
* Creation Date: 16/08/16
*/
class LibraryUpdater {
private val logger = KotlinLogging.logger {}
private val sourceManager: SourceManager by kInstanceLazy()
private val db: DatabaseHelper by kInstanceLazy()
@Deprecated("Use async variant instead")
fun _updateLibrary(updateAll: Boolean) {
if(updateAll) {
db.getMangas()
} else {
db.getFavoriteMangas()
}.executeAsBlocking().forEach {
_silentUpdateMangaInfo(it)
_silentUpdateChapters(it)
}
}
@Deprecated("Use async variant instead")
fun _silentUpdateMangaInfo(manga: Manga) {
val source = sourceManager.get(manga.source)
if(source == null) {
logger.warn { "Manga ${manga.id} is missing it's source!" }
return
}
try {
_updateMangaInfo(manga, source)
} catch (e: Exception) {
logger.error("Error updating manga!", e)
}
}
@Deprecated("Use async variant instead")
fun _updateMangaInfo(manga: Manga, source: Source) {
manga.copyFrom(source.fetchMangaDetails(manga).toBlocking().first())
db.insertManga(manga).executeAsBlocking()
}
@Deprecated("Use async variant instead")
fun _silentUpdateChapters(manga: Manga): Pair<List<Chapter>, List<Chapter>> {
val source = sourceManager.get(manga.source)
if(source == null) {
logger.warn { "Manga ${manga.id} is missing it's source!" }
return Pair(emptyList(), emptyList())
}
try {
return _updateChapters(manga, source).apply {
//If we find new chapters, update the "last update" field in the manga object
if(first.isNotEmpty() || second.isNotEmpty()) {
manga.last_update = Date().time
db.updateLastUpdated(manga).executeAsBlocking()
}
}
} catch (e: Exception) {
logger.error("Error updating chapters!", e)
return Pair(emptyList(), emptyList())
}
}
@Deprecated("Use async variant instead")
fun _updateChapters(manga: Manga, source: Source): Pair<List<Chapter>, List<Chapter>> {
return syncChaptersWithSource(db,
source.fetchChapterList(manga).toBlocking().first(),
manga,
source)
}
suspend fun updateMangaInfo(manga: Manga, source: Source) {
val networkManga = source.fetchMangaDetails(manga).toSingle().await(Schedulers.io())
manga.copyFrom(networkManga)
manga.initialized = true
db.insertManga(manga).await()
}
}
| apache-2.0 | aadd2bc4e8c7095edaf138fdf3dea414 | 33.645455 | 93 | 0.648386 | 4.365407 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/globalcode/GlobalScriptingActivity.kt | 1 | 6422 | package ch.rmy.android.http_shortcuts.activities.settings.globalcode
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import ch.rmy.android.framework.extensions.bindViewModel
import ch.rmy.android.framework.extensions.collectEventsWhileActive
import ch.rmy.android.framework.extensions.collectViewStateWhileActive
import ch.rmy.android.framework.extensions.color
import ch.rmy.android.framework.extensions.consume
import ch.rmy.android.framework.extensions.doOnTextChanged
import ch.rmy.android.framework.extensions.initialize
import ch.rmy.android.framework.extensions.insertAroundCursor
import ch.rmy.android.framework.extensions.setTextSafely
import ch.rmy.android.framework.ui.BaseIntentBuilder
import ch.rmy.android.framework.viewmodel.ViewModelEvent
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.BaseActivity
import ch.rmy.android.http_shortcuts.activities.editor.scripting.codesnippets.CodeSnippetPickerActivity
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.databinding.ActivityGlobalScriptingBinding
import ch.rmy.android.http_shortcuts.scripting.shortcuts.ShortcutPlaceholderProvider
import ch.rmy.android.http_shortcuts.scripting.shortcuts.ShortcutSpanManager
import ch.rmy.android.http_shortcuts.utils.InvalidSpanRemover
import ch.rmy.android.http_shortcuts.variables.VariablePlaceholderProvider
import ch.rmy.android.http_shortcuts.variables.Variables
import javax.inject.Inject
class GlobalScriptingActivity : BaseActivity() {
@Inject
lateinit var variablePlaceholderProvider: VariablePlaceholderProvider
@Inject
lateinit var shortcutPlaceholderProvider: ShortcutPlaceholderProvider
private val pickCodeSnippet = registerForActivityResult(CodeSnippetPickerActivity.PickCodeSnippet) { result ->
if (result != null) {
viewModel.onCodeSnippetPicked(result.textBeforeCursor, result.textAfterCursor)
}
}
private val viewModel: GlobalScriptingViewModel by bindViewModel()
private val variablePlaceholderColor by lazy(LazyThreadSafetyMode.NONE) {
color(context, R.color.variable)
}
private val shortcutPlaceholderColor by lazy(LazyThreadSafetyMode.NONE) {
color(context, R.color.shortcut)
}
private lateinit var binding: ActivityGlobalScriptingBinding
private var saveButton: MenuItem? = null
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override fun onCreated(savedState: Bundle?) {
viewModel.initialize()
initViews()
initUserInputBindings()
initViewModelBindings()
}
private fun initViews() {
binding = applyBinding(ActivityGlobalScriptingBinding.inflate(layoutInflater))
binding.inputCode.addTextChangedListener(InvalidSpanRemover())
binding.buttonAddCodeSnippet.setOnClickListener {
viewModel.onCodeSnippetButtonClicked()
}
}
private fun initUserInputBindings() {
bindTextChangeListener(binding.inputCode)
}
private fun initViewModelBindings() {
collectViewStateWhileActive(viewModel) { viewState ->
viewState.variables?.let(variablePlaceholderProvider::applyVariables)
viewState.shortcuts?.let(shortcutPlaceholderProvider::applyShortcuts)
binding.inputCode.setTextSafely(processTextForView(viewState.globalCode))
applyViewStateToMenuItems(viewState)
setDialogState(viewState.dialogState, viewModel)
}
collectEventsWhileActive(viewModel, ::handleEvent)
}
override fun handleEvent(event: ViewModelEvent) {
when (event) {
is GlobalScriptingEvent.ShowCodeSnippetPicker -> {
pickCodeSnippet.launch {
includeResponseOptions(false)
.includeNetworkErrorOption(false)
.includeFileOptions(true)
}
}
is GlobalScriptingEvent.InsertCodeSnippet -> {
insertCodeSnippet(event.textBeforeCursor, event.textAfterCursor)
}
else -> super.handleEvent(event)
}
}
private fun processTextForView(input: String): CharSequence {
val text = SpannableStringBuilder(input)
Variables.applyVariableFormattingToJS(
text,
variablePlaceholderProvider,
variablePlaceholderColor,
)
ShortcutSpanManager.applyShortcutFormattingToJS(
text,
shortcutPlaceholderProvider,
shortcutPlaceholderColor,
)
return text
}
private fun bindTextChangeListener(textView: EditText) {
textView.doOnTextChanged {
viewModel.onGlobalCodeChanged(it.toString())
}
}
private fun insertCodeSnippet(textBeforeCursor: String, textAfterCursor: String) {
binding.inputCode.insertAroundCursor(textBeforeCursor, textAfterCursor)
binding.inputCode.text?.let {
Variables.applyVariableFormattingToJS(it, variablePlaceholderProvider, variablePlaceholderColor)
ShortcutSpanManager.applyShortcutFormattingToJS(it, shortcutPlaceholderProvider, shortcutPlaceholderColor)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.global_scripting_activity_menu, menu)
saveButton = menu.findItem(R.id.action_save_changes)
viewModel.latestViewState?.let(::applyViewStateToMenuItems)
return super.onCreateOptionsMenu(menu)
}
private fun applyViewStateToMenuItems(viewState: GlobalScriptingViewState) {
saveButton?.isVisible = viewState.saveButtonVisible
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_show_help -> consume {
viewModel.onHelpButtonClicked()
}
R.id.action_save_changes -> consume {
viewModel.onSaveButtonClicked()
}
else -> super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
viewModel.onBackPressed()
}
override val navigateUpIcon = R.drawable.ic_clear
class IntentBuilder : BaseIntentBuilder(GlobalScriptingActivity::class)
}
| mit | 336280e556d99e458ed9ef35b8bfa741 | 38.158537 | 118 | 0.732638 | 5.060678 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/app/AppRepository.kt | 1 | 9232 | package ch.rmy.android.http_shortcuts.data.domains.app
import ch.rmy.android.framework.data.BaseRepository
import ch.rmy.android.framework.data.RealmFactory
import ch.rmy.android.framework.data.RealmTransactionContext
import ch.rmy.android.framework.extensions.deleteAllFromRealm
import ch.rmy.android.framework.extensions.runIfNotNull
import ch.rmy.android.http_shortcuts.data.domains.getAppLock
import ch.rmy.android.http_shortcuts.data.domains.getBase
import ch.rmy.android.http_shortcuts.data.domains.getTemporaryShortcut
import ch.rmy.android.http_shortcuts.data.domains.getTemporaryVariable
import ch.rmy.android.http_shortcuts.data.models.AppLockModel
import ch.rmy.android.http_shortcuts.data.models.BaseModel
import ch.rmy.android.http_shortcuts.data.models.CategoryModel
import ch.rmy.android.http_shortcuts.data.models.HeaderModel
import ch.rmy.android.http_shortcuts.data.models.OptionModel
import ch.rmy.android.http_shortcuts.data.models.ParameterModel
import ch.rmy.android.http_shortcuts.data.models.PendingExecutionModel
import ch.rmy.android.http_shortcuts.data.models.ResolvedVariableModel
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.import_export.Importer
import io.realm.kotlin.where
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class AppRepository
@Inject
constructor(
realmFactory: RealmFactory,
) : BaseRepository(realmFactory) {
suspend fun getBase(): BaseModel =
queryItem {
getBase()
}
suspend fun getGlobalCode(): String =
query {
getBase()
}
.firstOrNull()
?.globalCode
.orEmpty()
suspend fun getToolbarTitle(): String =
queryItem {
getBase()
}
.title
?.takeUnless { it.isBlank() }
.orEmpty()
fun getObservableToolbarTitle(): Flow<String> =
observeItem {
getBase()
}
.map { base ->
base.title
?.takeUnless { it.isBlank() }
.orEmpty()
}
suspend fun setToolbarTitle(title: String) {
commitTransaction {
getBase()
.findFirst()
?.title = title
}
}
suspend fun setGlobalCode(globalCode: String?) {
commitTransaction {
getBase()
.findFirst()
?.let { base ->
base.globalCode = globalCode
}
}
}
suspend fun getLock(): AppLockModel? =
query {
getAppLock()
}
.firstOrNull()
fun getObservableLock(): Flow<AppLockModel?> =
observeQuery {
getAppLock()
}
.map {
it.firstOrNull()
}
suspend fun setLock(passwordHash: String) {
commitTransaction {
copyOrUpdate(AppLockModel(passwordHash))
}
}
suspend fun removeLock() {
commitTransaction {
getAppLock()
.findAll()
.deleteAllFromRealm()
}
}
suspend fun importBase(base: BaseModel, importMode: Importer.ImportMode) {
commitTransaction {
val oldBase = getBase().findFirst()!!
when (importMode) {
Importer.ImportMode.MERGE -> {
if (base.title != null && oldBase.title.isNullOrEmpty()) {
oldBase.title = base.title
}
if (base.globalCode != null && oldBase.globalCode.isNullOrEmpty()) {
oldBase.globalCode = base.globalCode
}
if (oldBase.categories.singleOrNull()?.shortcuts?.isEmpty() == true) {
oldBase.categories.clear()
}
base.categories.forEach { category ->
importCategory(oldBase, category)
}
val persistedVariables = copyOrUpdate(base.variables)
oldBase.variables.removeAll(persistedVariables.toSet())
oldBase.variables.addAll(persistedVariables)
}
Importer.ImportMode.REPLACE -> {
if (base.title != null) {
oldBase.title = base.title
}
if (base.globalCode != null) {
oldBase.globalCode = base.globalCode
}
oldBase.categories.clear()
oldBase.categories.addAll(copyOrUpdate(base.categories))
oldBase.variables.clear()
oldBase.variables.addAll(copyOrUpdate(base.variables))
}
}
}
}
private fun RealmTransactionContext.importCategory(base: BaseModel, category: CategoryModel) {
val oldCategory = base.categories.find { it.id == category.id }
if (oldCategory == null) {
base.categories.add(copyOrUpdate(category))
} else {
oldCategory.name = category.name
oldCategory.categoryBackgroundType = category.categoryBackgroundType
oldCategory.hidden = category.hidden
oldCategory.categoryLayoutType = category.categoryLayoutType
category.shortcuts.forEach { shortcut ->
importShortcut(oldCategory, shortcut)
}
}
}
private fun RealmTransactionContext.importShortcut(category: CategoryModel, shortcut: ShortcutModel) {
val oldShortcut = category.shortcuts.find { it.id == shortcut.id }
if (oldShortcut == null) {
category.shortcuts.add(copyOrUpdate(shortcut))
} else {
copyOrUpdate(shortcut)
}
}
suspend fun deleteUnusedData() {
commitTransaction {
val base = getBase().findFirst() ?: return@commitTransaction
val temporaryShortcut = getTemporaryShortcut().findFirst()
val temporaryVariable = getTemporaryVariable().findFirst()
val categories = base.categories
val shortcuts = base.shortcuts
.runIfNotNull(temporaryShortcut) {
plus(it)
}
val variables = base.variables.toList()
.runIfNotNull(temporaryVariable) {
plus(it)
}
// Delete orphaned categories
val usedCategoryIds = categories.map { it.id }
realmInstance.where<CategoryModel>()
.findAll()
.filter {
it.id !in usedCategoryIds
}
.deleteAllFromRealm()
// Delete orphaned shortcuts
val usedShortcutIds = shortcuts.map { it.id }
realmInstance.where<ShortcutModel>()
.notEqualTo(ShortcutModel.FIELD_ID, ShortcutModel.TEMPORARY_ID)
.findAll()
.filter {
it.id !in usedShortcutIds
}
.deleteAllFromRealm()
// Delete orphaned headers
val usedHeaderIds = shortcuts
.flatMap { it.headers }
.map { header -> header.id }
realmInstance.where<HeaderModel>()
.findAll()
.filter {
it.id !in usedHeaderIds
}
.deleteAllFromRealm()
// Delete orphaned parameters
val usedParameterIds = shortcuts
.flatMap { it.parameters }
.map { parameter -> parameter.id }
realmInstance.where<ParameterModel>()
.findAll()
.filter {
it.id !in usedParameterIds
}
.deleteAllFromRealm()
// Delete orphaned variables
val usedVariableIds = variables.map { it.id }
realmInstance.where<VariableModel>()
.notEqualTo(VariableModel.FIELD_ID, VariableModel.TEMPORARY_ID)
.findAll()
.filter {
it.id !in usedVariableIds
}
.deleteAllFromRealm()
// Delete orphaned options
val usedOptionIds = variables.flatMap { it.options ?: emptyList() }.map { it.id }
realmInstance.where<OptionModel>()
.findAll()
.filter {
it.id !in usedOptionIds
}
.deleteAllFromRealm()
// Delete orphaned resolved variables
val usedResolvedVariableIds = realmInstance.where<PendingExecutionModel>()
.findAll()
.flatMap { it.resolvedVariables }
.map { it.id }
realmInstance.where<ResolvedVariableModel>()
.findAll()
.filter {
it.id !in usedResolvedVariableIds
}
.deleteAllFromRealm()
}
}
}
| mit | d0ce458aaa8895eeff6e4167765d519b | 33.837736 | 106 | 0.55351 | 5.2664 | false | false | false | false |
googlecodelabs/resizing-chromeos | complete/src/main/java/com/google/example/resizecodelab/view/MainViewModel.kt | 1 | 2960 | /*
* Copyright 2019 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.google.example.resizecodelab.view
import androidx.lifecycle.*
import com.google.example.resizecodelab.R
import com.google.example.resizecodelab.data.DataProvider
import com.google.example.resizecodelab.data.Review
internal const val KEY_ID = "KEY_ID"
private const val KEY_EXPANDED = "KEY_EXPANDED"
/**
* Facilitates fetching required data and exposes View related data back to view
* Survives config changes (e.g. rotation), good place to store data that takes time to recover
*/
class MainViewModel(private val state: SavedStateHandle) : ViewModel() {
private val appData = DataProvider.fetchData(getIdState())
val suggestions = DataProvider.fetchSuggestions(getIdState())
val showControls: LiveData<Boolean> = Transformations.map(appData) { it != null }
val productName: LiveData<String> = Transformations.map(appData) { it?.title }
val productCompany: LiveData<String> = Transformations.map(appData) { it?.developer }
private val isDescriptionExpanded: LiveData<Boolean> = state.getLiveData(KEY_EXPANDED)
private val _descriptionText = MediatorLiveData<String>().apply {
addSource(appData) { value = determineDescriptionText() }
addSource(isDescriptionExpanded) { value = determineDescriptionText() }
}
val descriptionText: LiveData<String>
get() = _descriptionText
val expandButtonTextResId: LiveData<Int> = Transformations.map(isDescriptionExpanded) {
if (it == true) {
R.string.button_collapse
} else {
R.string.button_expand
}
}
val reviews: LiveData<List<Review>> = Transformations.map(appData) { it?.reviews }
private fun determineDescriptionText(): String? {
return appData.value?.let { appData ->
if (isDescriptionExpanded.value == true) {
appData.description
} else {
appData.shortDescription
}
}
}
/**
* Handle toggle button presses
*/
fun toggleDescriptionExpanded() {
state.set(KEY_EXPANDED, !getExpandedState())
}
private fun getIdState(): Int {
return state.get(KEY_ID) ?: throw IllegalStateException("MainViewModel must be called with an Id to fetch data")
}
private fun getExpandedState(): Boolean {
return state.get(KEY_EXPANDED) ?: false
}
} | apache-2.0 | 94bb5d2871a97455ad84e70797742d17 | 35.109756 | 120 | 0.694595 | 4.41791 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/data/source/local/ZhihuDailyNewsLocalDataSource.kt | 1 | 3454 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data.source.local
import android.support.annotation.VisibleForTesting
import com.marktony.zhihudaily.data.ZhihuDailyNewsQuestion
import com.marktony.zhihudaily.data.source.LocalDataNotFoundException
import com.marktony.zhihudaily.data.source.Result
import com.marktony.zhihudaily.data.source.datasource.ZhihuDailyNewsDataSource
import com.marktony.zhihudaily.database.dao.ZhihuDailyNewsDao
import com.marktony.zhihudaily.util.AppExecutors
import kotlinx.coroutines.experimental.withContext
/**
* Created by lizhaotailang on 2017/5/21.
*
* Concrete implementation of a [ZhihuDailyNewsQuestion] data source as database.
*/
class ZhihuDailyNewsLocalDataSource private constructor(
val mAppExecutors: AppExecutors,
val mZhihuDailyNewsDao: ZhihuDailyNewsDao
) : ZhihuDailyNewsDataSource {
companion object {
private var INSTANCE: ZhihuDailyNewsLocalDataSource? = null
@JvmStatic
fun getInstance(appExecutors: AppExecutors, zhihuDailyNewsDao: ZhihuDailyNewsDao): ZhihuDailyNewsLocalDataSource {
if (INSTANCE == null) {
synchronized(ZhihuDailyNewsLocalDataSource::javaClass) {
INSTANCE = ZhihuDailyNewsLocalDataSource(appExecutors, zhihuDailyNewsDao)
}
}
return INSTANCE!!
}
@VisibleForTesting
fun clearInstance() {
INSTANCE = null
}
}
override suspend fun getZhihuDailyNews(forceUpdate: Boolean, clearCache: Boolean, date: Long): Result<List<ZhihuDailyNewsQuestion>> = withContext(mAppExecutors.ioContext) {
val news = mZhihuDailyNewsDao.queryAllByDate(date)
if (news.isNotEmpty()) Result.Success(news) else Result.Error(LocalDataNotFoundException())
}
override suspend fun getFavorites(): Result<List<ZhihuDailyNewsQuestion>> = withContext(mAppExecutors.ioContext) {
val favorites = mZhihuDailyNewsDao.queryAllFavorites()
if (favorites.isNotEmpty()) Result.Success(favorites) else Result.Error(LocalDataNotFoundException())
}
override suspend fun getItem(itemId: Int): Result<ZhihuDailyNewsQuestion> = withContext(mAppExecutors.ioContext) {
val item = mZhihuDailyNewsDao.queryItemById(itemId)
if (item != null) Result.Success(item) else Result.Error(LocalDataNotFoundException())
}
override suspend fun favoriteItem(itemId: Int, favorite: Boolean) {
withContext(mAppExecutors.ioContext) {
mZhihuDailyNewsDao.queryItemById(itemId)?.let {
it.isFavorite = favorite
mZhihuDailyNewsDao.update(it)
}
}
}
override suspend fun saveAll(list: List<ZhihuDailyNewsQuestion>) {
withContext(mAppExecutors.ioContext) {
mZhihuDailyNewsDao.insertAll(list)
}
}
}
| apache-2.0 | f4b1261d0627a3e614bfa4d7544a08c3 | 38.25 | 176 | 0.72264 | 4.718579 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/ui/fragment/AyahActionFragment.kt | 2 | 1837 | package com.quran.labs.androidquran.ui.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.quran.data.model.SuraAyah
import com.quran.data.model.selection.AyahSelection
import com.quran.data.model.selection.endSuraAyah
import com.quran.data.model.selection.startSuraAyah
import com.quran.reading.common.AudioEventPresenter
import com.quran.reading.common.ReadingEventPresenter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import javax.inject.Inject
abstract class AyahActionFragment : Fragment() {
private var scope: CoroutineScope = MainScope()
@Inject
lateinit var readingEventPresenter: ReadingEventPresenter
@Inject
lateinit var audioEventPresenter: AudioEventPresenter
protected var start: SuraAyah? = null
protected var end: SuraAyah? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
scope = MainScope()
readingEventPresenter.ayahSelectionFlow
.combine(audioEventPresenter.audioPlaybackAyahFlow) { selectedAyah, playbackAyah ->
if (selectedAyah !is AyahSelection.None) {
start = selectedAyah.startSuraAyah()
end = selectedAyah.endSuraAyah()
} else if (playbackAyah != null) {
start = playbackAyah
end = playbackAyah
}
refreshView()
}
.launchIn(scope)
readingEventPresenter.detailsPanelFlow
.map {
onToggleDetailsPanel(it)
}
.launchIn(scope)
}
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
open fun onToggleDetailsPanel(isVisible: Boolean) { }
protected abstract fun refreshView()
}
| gpl-3.0 | 0d449097d967d028df740aae5ae49429 | 28.15873 | 89 | 0.750136 | 4.5925 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/presenter/bookmark/BookmarksContextualModePresenter.kt | 2 | 2144 | package com.quran.labs.androidquran.presenter.bookmark
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode
import com.quran.labs.androidquran.R
import com.quran.labs.androidquran.presenter.Presenter
import com.quran.labs.androidquran.ui.fragment.BookmarksFragment
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BookmarksContextualModePresenter @Inject constructor() : Presenter<BookmarksFragment> {
private var actionMode: ActionMode? = null
private var fragment: BookmarksFragment? = null
private var activity: AppCompatActivity? = null
fun isInActionMode(): Boolean {
return actionMode != null
}
private fun startActionMode() {
activity?.let {
actionMode = it.startSupportActionMode(ModeCallback())
}
}
fun invalidateActionMode(startIfStopped: Boolean) {
if (actionMode != null) {
actionMode!!.invalidate()
} else if (startIfStopped) {
startActionMode()
}
}
fun finishActionMode() {
actionMode?.finish()
}
override fun bind(what: BookmarksFragment) {
fragment = what
activity = what.activity as AppCompatActivity
}
override fun unbind(what: BookmarksFragment) {
if (what == this.fragment) {
this.fragment = null
activity = null
}
}
private inner class ModeCallback : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
activity?.menuInflater?.inflate(R.menu.bookmark_contextual_menu, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
fragment?.prepareContextualMenu(menu)
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
val result = fragment?.onContextualActionClicked(item.itemId) ?: false
finishActionMode()
return result
}
override fun onDestroyActionMode(mode: ActionMode) {
fragment?.onCloseContextualActionMenu()
if (mode == actionMode) {
actionMode = null
}
}
}
}
| gpl-3.0 | 4b6139ff6c8f333bcfc3859052180de8 | 26.487179 | 93 | 0.717817 | 4.66087 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/widget/BookmarksWidget.kt | 2 | 3460 | package com.quran.labs.androidquran.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.RemoteViews
import com.quran.labs.androidquran.QuranApplication
import com.quran.labs.androidquran.QuranDataActivity
import com.quran.labs.androidquran.R
import com.quran.labs.androidquran.SearchActivity
import com.quran.labs.androidquran.ShortcutsActivity
import com.quran.labs.androidquran.ui.PagerActivity
import com.quran.labs.androidquran.ui.QuranActivity
import javax.inject.Inject
/**
* Widget that displays a list of bookmarks and some buttons for jumping into the app
*/
class BookmarksWidget : AppWidgetProvider() {
@Inject
lateinit var bookmarksWidgetSubscriber: BookmarksWidgetSubscriber
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
for (appWidgetId in appWidgetIds) {
val serviceIntent = Intent(context, BookmarksWidgetService::class.java).apply {
putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME))
}
val widget = RemoteViews(context.packageName, R.layout.bookmarks_widget)
var intent = Intent(context, QuranDataActivity::class.java)
var pendingIntent =
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
widget.setOnClickPendingIntent(R.id.widget_icon_button, pendingIntent)
intent = Intent(context, SearchActivity::class.java)
pendingIntent =
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
widget.setOnClickPendingIntent(R.id.widget_btn_search, pendingIntent)
intent = Intent(context, QuranActivity::class.java)
intent.action = ShortcutsActivity.ACTION_JUMP_TO_LATEST
pendingIntent =
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
widget.setOnClickPendingIntent(R.id.widget_btn_go_to_quran, pendingIntent)
intent = Intent(context, ShowJumpFragmentActivity::class.java)
pendingIntent =
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
widget.setOnClickPendingIntent(R.id.search_widget_btn_jump, pendingIntent)
widget.setRemoteAdapter(R.id.list_view_widget, serviceIntent)
val clickIntent = Intent(context, PagerActivity::class.java)
val clickPendingIntent = PendingIntent
.getActivity(
context, 0,
clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
widget.setPendingIntentTemplate(R.id.list_view_widget, clickPendingIntent)
widget.setEmptyView(R.id.list_view_widget, R.id.empty_view)
appWidgetManager.updateAppWidget(appWidgetId, widget)
}
super.onUpdate(context, appWidgetManager, appWidgetIds)
}
override fun onEnabled(context: Context) {
(context.applicationContext as QuranApplication).applicationComponent.inject(this)
bookmarksWidgetSubscriber.onEnabledBookmarksWidget()
super.onEnabled(context)
}
override fun onDisabled(context: Context) {
(context.applicationContext as QuranApplication).applicationComponent.inject(this)
bookmarksWidgetSubscriber.onDisabledBookmarksWidget()
super.onDisabled(context)
}
}
| gpl-3.0 | 17ce4a185e601b5e7b98b86cfaf47a8d | 38.318182 | 86 | 0.765607 | 4.650538 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/progress/MaterialProgressBar.kt | 1 | 20182 | /*
* Copyright (C) 2017-2021 Hazuki
*
* 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.
*/
/*
* Copyright (c) 2015 Zhang Hai <[email protected]>
* All Rights Reserved.
*/
package jp.hazuki.yuzubrowser.ui.widget.progress
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.util.AttributeSet
import android.util.Log
import android.widget.ProgressBar
import androidx.appcompat.widget.TintTypedArray
import androidx.core.graphics.drawable.TintAwareDrawable
import jp.hazuki.yuzubrowser.ui.R
/**
* A [ProgressBar] subclass that handles tasks related to backported progress drawable.
*/
class MaterialProgressBar : ProgressBar {
// This field remains false inside super class constructor.
private val mSuperInitialized = true
private val mProgressTintInfo = TintInfo()
/**
* Get the current drawable of this ProgressBar.
*
* @return The current drawable.
*/
val currentProgressDrawable: Drawable?
get() = if (isIndeterminate) indeterminateDrawable else progressDrawable
/**
* @see ProgressBar.getProgressTintList
*/
/**
* @see ProgressBar.setProgressTintList
*/
var supportProgressTintList: ColorStateList?
get() = mProgressTintInfo.mProgressTint
set(tint) {
mProgressTintInfo.mProgressTint = tint
mProgressTintInfo.mHasProgressTint = true
applyPrimaryProgressTint()
}
/**
* @see ProgressBar.getProgressTintMode
*/
/**
* @see ProgressBar.setProgressTintMode
*/
var supportProgressTintMode: PorterDuff.Mode?
get() = mProgressTintInfo.mProgressTintMode
set(tintMode) {
mProgressTintInfo.mProgressTintMode = tintMode
mProgressTintInfo.mHasProgressTintMode = true
applyPrimaryProgressTint()
}
/**
* @see ProgressBar.getSecondaryProgressTintList
*/
/**
* @see ProgressBar.setSecondaryProgressTintList
*/
var supportSecondaryProgressTintList: ColorStateList?
get() = mProgressTintInfo.mSecondaryProgressTint
set(tint) {
mProgressTintInfo.mSecondaryProgressTint = tint
mProgressTintInfo.mHasSecondaryProgressTint = true
applySecondaryProgressTint()
}
/**
* @see ProgressBar.getSecondaryProgressTintMode
*/
/**
* @see ProgressBar.setSecondaryProgressTintMode
*/
var supportSecondaryProgressTintMode: PorterDuff.Mode?
get() = mProgressTintInfo.mSecondaryProgressTintMode
set(tintMode) {
mProgressTintInfo.mSecondaryProgressTintMode = tintMode
mProgressTintInfo.mHasSecondaryProgressTintMode = true
applySecondaryProgressTint()
}
/**
* @see ProgressBar.getProgressBackgroundTintList
*/
/**
* @see ProgressBar.setProgressBackgroundTintList
*/
var supportProgressBackgroundTintList: ColorStateList?
get() = mProgressTintInfo.mProgressBackgroundTint
set(tint) {
mProgressTintInfo.mProgressBackgroundTint = tint
mProgressTintInfo.mHasProgressBackgroundTint = true
applyProgressBackgroundTint()
}
/**
* @see ProgressBar.getProgressBackgroundTintMode
*/
/**
* @see ProgressBar.setProgressBackgroundTintMode
*/
var supportProgressBackgroundTintMode: PorterDuff.Mode?
get() = mProgressTintInfo.mProgressBackgroundTintMode
set(tintMode) {
mProgressTintInfo.mProgressBackgroundTintMode = tintMode
mProgressTintInfo.mHasProgressBackgroundTintMode = true
applyProgressBackgroundTint()
}
/**
* @see ProgressBar.getIndeterminateTintList
*/
/**
* @see ProgressBar.setIndeterminateTintList
*/
var supportIndeterminateTintList: ColorStateList?
get() = mProgressTintInfo.mIndeterminateTint
set(tint) {
mProgressTintInfo.mIndeterminateTint = tint
mProgressTintInfo.mHasIndeterminateTint = true
applyIndeterminateTint()
}
/**
* @see ProgressBar.getIndeterminateTintMode
*/
/**
* @see ProgressBar.setIndeterminateTintMode
*/
var supportIndeterminateTintMode: PorterDuff.Mode?
get() = mProgressTintInfo.mIndeterminateTintMode
set(tintMode) {
mProgressTintInfo.mIndeterminateTintMode = tintMode
mProgressTintInfo.mHasIndeterminateTintMode = true
applyIndeterminateTint()
}
constructor(context: Context) : super(context) {
init(null, 0, 0)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(attrs, 0, 0)
}
constructor(context: Context, attrs: AttributeSet?,
defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs, defStyleAttr, 0)
}
constructor(context: Context, attrs: AttributeSet?,
defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
init(attrs, defStyleAttr, defStyleRes)
}
private fun init(attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) {
val context = context
val a = TintTypedArray.obtainStyledAttributes(context, attrs,
R.styleable.MaterialProgressBar, defStyleAttr, defStyleRes)
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_progressTint)) {
mProgressTintInfo.mProgressTint = a.getColorStateList(
R.styleable.MaterialProgressBar_mpb_progressTint)
mProgressTintInfo.mHasProgressTint = true
}
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_progressTintMode)) {
mProgressTintInfo.mProgressTintMode = parseTintMode(a.getInt(
R.styleable.MaterialProgressBar_mpb_progressTintMode, -1), null)
mProgressTintInfo.mHasProgressTintMode = true
}
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_secondaryProgressTint)) {
mProgressTintInfo.mSecondaryProgressTint = a.getColorStateList(
R.styleable.MaterialProgressBar_mpb_secondaryProgressTint)
mProgressTintInfo.mHasSecondaryProgressTint = true
}
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_secondaryProgressTintMode)) {
mProgressTintInfo.mSecondaryProgressTintMode = parseTintMode(a.getInt(
R.styleable.MaterialProgressBar_mpb_secondaryProgressTintMode, -1), null)
mProgressTintInfo.mHasSecondaryProgressTintMode = true
}
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_progressBackgroundTint)) {
mProgressTintInfo.mProgressBackgroundTint = a.getColorStateList(
R.styleable.MaterialProgressBar_mpb_progressBackgroundTint)
mProgressTintInfo.mHasProgressBackgroundTint = true
}
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_progressBackgroundTintMode)) {
mProgressTintInfo.mProgressBackgroundTintMode = parseTintMode(a.getInt(
R.styleable.MaterialProgressBar_mpb_progressBackgroundTintMode, -1), null)
mProgressTintInfo.mHasProgressBackgroundTintMode = true
}
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_indeterminateTint)) {
mProgressTintInfo.mIndeterminateTint = a.getColorStateList(
R.styleable.MaterialProgressBar_mpb_indeterminateTint)
mProgressTintInfo.mHasIndeterminateTint = true
}
if (a.hasValue(R.styleable.MaterialProgressBar_mpb_indeterminateTintMode)) {
mProgressTintInfo.mIndeterminateTintMode = parseTintMode(a.getInt(
R.styleable.MaterialProgressBar_mpb_indeterminateTintMode, -1), null)
mProgressTintInfo.mHasIndeterminateTintMode = true
}
a.recycle()
progressDrawable = HorizontalProgressDrawable(context)
indeterminateDrawable = IndeterminateHorizontalProgressDrawable(context)
applyIndeterminateTint()
}
@Synchronized
override fun setIndeterminate(indeterminate: Boolean) {
super.setIndeterminate(indeterminate)
if (mSuperInitialized && currentProgressDrawable !is MaterialProgressDrawable) {
Log.w(TAG, "Current drawable is not a MaterialProgressDrawable, you may want to set" + " app:mpb_setBothDrawables")
}
}
override fun setProgressDrawable(drawable: Drawable?) {
super.setProgressDrawable(drawable)
// mProgressTintInfo can be null during super class initialization.
if (mProgressTintInfo != null) {
applyProgressTints()
}
}
override fun setIndeterminateDrawable(drawable: Drawable?) {
super.setIndeterminateDrawable(drawable)
// mProgressTintInfo can be null during super class initialization.
if (mProgressTintInfo != null) {
applyIndeterminateTint()
}
}
@Deprecated("Use {@link #getSupportProgressTintList()} instead.")
override fun getProgressTintList(): ColorStateList? {
logProgressBarTintWarning()
return supportProgressTintList
}
@Deprecated("Use {@link #setSupportProgressTintList(ColorStateList)} instead.")
override fun setProgressTintList(tint: ColorStateList?) {
logProgressBarTintWarning()
supportProgressTintList = tint
}
@Deprecated("Use {@link #getSupportProgressTintMode()} instead.")
override fun getProgressTintMode(): PorterDuff.Mode? {
logProgressBarTintWarning()
return supportProgressTintMode
}
@Deprecated("Use {@link #setSupportProgressTintMode(PorterDuff.Mode)} instead.")
override fun setProgressTintMode(tintMode: PorterDuff.Mode?) {
logProgressBarTintWarning()
supportProgressTintMode = tintMode
}
@Deprecated("Use {@link #getSupportSecondaryProgressTintList()} instead.")
override fun getSecondaryProgressTintList(): ColorStateList? {
logProgressBarTintWarning()
return supportSecondaryProgressTintList
}
@Deprecated("Use {@link #setSupportSecondaryProgressTintList(ColorStateList)} instead.")
override fun setSecondaryProgressTintList(tint: ColorStateList?) {
logProgressBarTintWarning()
supportSecondaryProgressTintList = tint
}
@Deprecated("Use {@link #getSupportSecondaryProgressTintMode()} instead.")
override fun getSecondaryProgressTintMode(): PorterDuff.Mode? {
logProgressBarTintWarning()
return supportSecondaryProgressTintMode
}
@Deprecated("Use {@link #setSupportSecondaryProgressTintMode(PorterDuff.Mode)} instead.")
override fun setSecondaryProgressTintMode(tintMode: PorterDuff.Mode?) {
logProgressBarTintWarning()
supportSecondaryProgressTintMode = tintMode
}
@Deprecated("Use {@link #getSupportProgressBackgroundTintList()} instead.")
override fun getProgressBackgroundTintList(): ColorStateList? {
logProgressBarTintWarning()
return supportProgressBackgroundTintList
}
@Deprecated("Use {@link #setSupportProgressBackgroundTintList(ColorStateList)} instead.")
override fun setProgressBackgroundTintList(tint: ColorStateList?) {
logProgressBarTintWarning()
supportProgressBackgroundTintList = tint
}
@Deprecated("Use {@link #getSupportProgressBackgroundTintMode()} instead.")
override fun getProgressBackgroundTintMode(): PorterDuff.Mode? {
logProgressBarTintWarning()
return supportProgressBackgroundTintMode
}
@Deprecated("Use {@link #setSupportProgressBackgroundTintMode(PorterDuff.Mode)} instead.")
override fun setProgressBackgroundTintMode(tintMode: PorterDuff.Mode?) {
logProgressBarTintWarning()
supportProgressBackgroundTintMode = tintMode
}
@Deprecated("Use {@link #getSupportIndeterminateTintList()} instead.")
override fun getIndeterminateTintList(): ColorStateList? {
logProgressBarTintWarning()
return supportIndeterminateTintList
}
@Deprecated("Use {@link #setSupportIndeterminateTintList(ColorStateList)} instead.")
override fun setIndeterminateTintList(tint: ColorStateList?) {
logProgressBarTintWarning()
supportIndeterminateTintList = tint
}
@Deprecated("Use {@link #getSupportIndeterminateTintMode()} instead.")
override fun getIndeterminateTintMode(): PorterDuff.Mode? {
logProgressBarTintWarning()
return supportIndeterminateTintMode
}
@Deprecated("Use {@link #setSupportIndeterminateTintMode(PorterDuff.Mode)} instead.")
override fun setIndeterminateTintMode(tintMode: PorterDuff.Mode?) {
logProgressBarTintWarning()
supportIndeterminateTintMode = tintMode
}
private fun logProgressBarTintWarning() {
Log.w(TAG, "Non-support version of tint method called, this is error-prone and will crash" +
" below Lollipop if you are calling it as a method of ProgressBar instead of" +
" MaterialProgressBar")
}
private fun applyProgressTints() {
if (progressDrawable == null) {
return
}
applyPrimaryProgressTint()
applyProgressBackgroundTint()
applySecondaryProgressTint()
}
private fun applyPrimaryProgressTint() {
if (progressDrawable == null) {
return
}
if (mProgressTintInfo.mHasProgressTint || mProgressTintInfo.mHasProgressTintMode) {
val target = getTintTargetFromProgressDrawable(android.R.id.progress, true)
if (target != null) {
applyTintForDrawable(target, mProgressTintInfo.mProgressTint,
mProgressTintInfo.mHasProgressTint, mProgressTintInfo.mProgressTintMode,
mProgressTintInfo.mHasProgressTintMode)
}
}
}
private fun applySecondaryProgressTint() {
if (progressDrawable == null) {
return
}
if (mProgressTintInfo.mHasSecondaryProgressTint || mProgressTintInfo.mHasSecondaryProgressTintMode) {
val target = getTintTargetFromProgressDrawable(android.R.id.secondaryProgress,
false)
if (target != null) {
applyTintForDrawable(target, mProgressTintInfo.mSecondaryProgressTint,
mProgressTintInfo.mHasSecondaryProgressTint,
mProgressTintInfo.mSecondaryProgressTintMode,
mProgressTintInfo.mHasSecondaryProgressTintMode)
}
}
}
private fun applyProgressBackgroundTint() {
if (progressDrawable == null) {
return
}
if (mProgressTintInfo.mHasProgressBackgroundTint || mProgressTintInfo.mHasProgressBackgroundTintMode) {
val target = getTintTargetFromProgressDrawable(android.R.id.background, false)
if (target != null) {
applyTintForDrawable(target, mProgressTintInfo.mProgressBackgroundTint,
mProgressTintInfo.mHasProgressBackgroundTint,
mProgressTintInfo.mProgressBackgroundTintMode,
mProgressTintInfo.mHasProgressBackgroundTintMode)
}
}
}
private fun getTintTargetFromProgressDrawable(layerId: Int, shouldFallback: Boolean): Drawable? {
val progressDrawable = progressDrawable ?: return null
progressDrawable.mutate()
var layerDrawable: Drawable? = null
if (progressDrawable is LayerDrawable) {
layerDrawable = progressDrawable.findDrawableByLayerId(layerId)
}
if (layerDrawable == null && shouldFallback) {
layerDrawable = progressDrawable
}
return layerDrawable
}
private fun applyIndeterminateTint() {
val indeterminateDrawable = indeterminateDrawable ?: return
if (mProgressTintInfo.mHasIndeterminateTint || mProgressTintInfo.mHasIndeterminateTintMode) {
indeterminateDrawable.mutate()
applyTintForDrawable(indeterminateDrawable, mProgressTintInfo.mIndeterminateTint,
mProgressTintInfo.mHasIndeterminateTint,
mProgressTintInfo.mIndeterminateTintMode,
mProgressTintInfo.mHasIndeterminateTintMode)
}
}
// Progress drawables in this library has already rewritten tint related methods for
// compatibility.
@SuppressLint("NewApi")
private fun applyTintForDrawable(drawable: Drawable, tint: ColorStateList?,
hasTint: Boolean, tintMode: PorterDuff.Mode?,
hasTintMode: Boolean) {
if (hasTint || hasTintMode) {
if (hasTint) {
if (drawable is TintAwareDrawable) {
(drawable as TintAwareDrawable).setTintList(tint)
} else {
logDrawableTintWarning()
drawable.setTintList(tint)
}
}
if (hasTintMode && tintMode != null) {
if (drawable is TintAwareDrawable) {
(drawable as TintAwareDrawable).setTintMode(tintMode)
} else {
logDrawableTintWarning()
drawable.setTintMode(tintMode)
}
}
// The drawable (or one of its children) may not have been
// stateful before applying the tint, so let's try again.
if (drawable.isStateful) {
drawable.state = drawableState
}
}
}
private fun logDrawableTintWarning() {
Log.w(TAG, "Drawable did not implement TintableDrawable, it won't be tinted below" + " Lollipop")
}
private class TintInfo {
var mProgressTint: ColorStateList? = null
var mProgressTintMode: PorterDuff.Mode? = null
var mHasProgressTint: Boolean = false
var mHasProgressTintMode: Boolean = false
var mSecondaryProgressTint: ColorStateList? = null
var mSecondaryProgressTintMode: PorterDuff.Mode? = null
var mHasSecondaryProgressTint: Boolean = false
var mHasSecondaryProgressTintMode: Boolean = false
var mProgressBackgroundTint: ColorStateList? = null
var mProgressBackgroundTintMode: PorterDuff.Mode? = null
var mHasProgressBackgroundTint: Boolean = false
var mHasProgressBackgroundTintMode: Boolean = false
var mIndeterminateTint: ColorStateList? = null
var mIndeterminateTintMode: PorterDuff.Mode? = null
var mHasIndeterminateTint: Boolean = false
var mHasIndeterminateTintMode: Boolean = false
}
companion object {
private val TAG = MaterialProgressBar::class.java.simpleName
fun parseTintMode(value: Int,
defaultMode: PorterDuff.Mode?): PorterDuff.Mode? {
return when (value) {
3 -> PorterDuff.Mode.SRC_OVER
5 -> PorterDuff.Mode.SRC_IN
9 -> PorterDuff.Mode.SRC_ATOP
14 -> PorterDuff.Mode.MULTIPLY
15 -> PorterDuff.Mode.SCREEN
16 -> PorterDuff.Mode.ADD
else -> defaultMode
}
}
}
}
| apache-2.0 | 7b4718157e5fbe07a681b67dc285781f | 35.495479 | 127 | 0.670102 | 5.056878 | false | false | false | false |
Litote/kmongo | kmongo-native-mapping/src/main/kotlin/org/bson/codecs/pojo/KeyObjectMapPropertyCodecProvider.kt | 1 | 4205 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.bson.codecs.pojo
import org.bson.BsonReader
import org.bson.BsonType
import org.bson.BsonWriter
import org.bson.codecs.Codec
import org.bson.codecs.DecoderContext
import org.bson.codecs.EncoderContext
import org.bson.codecs.configuration.CodecConfigurationException
import org.litote.kmongo.Id
import org.litote.kmongo.id.IdGenerator.Companion.defaultGenerator
import java.util.HashMap
import java.util.Locale
/**
* Improves [MapPropertyCodecProvider].
*/
internal object KeyObjectMapPropertyCodecProvider : PropertyCodecProvider {
override fun <T> get(type: TypeWithTypeParameters<T>, registry: PropertyCodecRegistry): Codec<T>? {
if (Map::class.java.isAssignableFrom(type.type) && type.typeParameters.size == 2) {
val keyType = type.typeParameters[0].type
if (keyType.isAssignableFrom(Id::class.java)) {
@Suppress("UNCHECKED_CAST")
return IdMapCodec(
type.type as Class<Map<Id<*>, Any>>,
registry.get(type.typeParameters[1]) as Codec<Any>
) as Codec<T>
} else if (keyType == Locale::class.java) {
@Suppress("UNCHECKED_CAST")
return LocaleMapCodec(
type.type as Class<Map<Locale, Any>>,
registry.get(type.typeParameters[1]) as Codec<Any>
) as Codec<T>
}
}
return null
}
abstract class KeyObjectMapCodec<K, T>(
val mapEncoderClass: Class<Map<K, T>>,
val codec: Codec<T>) : Codec<Map<K, T>> {
private val instance: MutableMap<K, T>
get() {
if (mapEncoderClass.isInterface) {
return HashMap()
}
try {
return mapEncoderClass.newInstance().toMutableMap()
} catch (e: Exception) {
throw CodecConfigurationException(e.message, e)
}
}
abstract fun encode(key: K): String
abstract fun decode(key: String): K
override fun encode(writer: BsonWriter, map: Map<K, T>, encoderContext: EncoderContext) {
writer.writeStartDocument()
for ((key, value) in map) {
writer.writeName(key.toString())
codec.encode(writer, value, encoderContext)
}
writer.writeEndDocument()
}
override fun decode(reader: BsonReader, context: DecoderContext): Map<K, T> {
reader.readStartDocument()
val map = instance
while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
map.put(decode(reader.readName()), codec.decode(reader, context))
}
reader.readEndDocument()
return map
}
override fun getEncoderClass(): Class<Map<K, T>> {
return mapEncoderClass
}
}
class IdMapCodec<T>(mapEncoderClass: Class<Map<Id<*>, T>>,
codec: Codec<T>) : KeyObjectMapCodec<Id<*>, T>(mapEncoderClass, codec) {
override fun encode(key: Id<*>): String = key.toString()
override fun decode(key: String): Id<*> = defaultGenerator.create(key)
}
class LocaleMapCodec<T>(mapEncoderClass: Class<Map<Locale, T>>,
codec: Codec<T>) : KeyObjectMapCodec<Locale, T>(mapEncoderClass, codec) {
override fun encode(key: Locale): String = key.toLanguageTag()
override fun decode(key: String): Locale = Locale.forLanguageTag(key)
}
} | apache-2.0 | 696636e60d1d70cf88526c912766ccf0 | 34.948718 | 103 | 0.606421 | 4.403141 | false | false | false | false |
OpenConference/OpenConference-android | app/src/droidconBerlin/java/de/droidcon/dagger/DroidconBerlinNetworkModule.kt | 1 | 1386 | package de.droidcon.dagger
import android.content.Context
import com.github.aurae.retrofit2.LoganSquareConverterFactory
import com.openconference.dagger.NetworkModule
import com.openconference.model.backend.schedule.BackendScheduleAdapter
import de.droidcon.model.backend.DroidconBerlinBackend
import de.droidcon.model.backend.DroidconBerlinBackendScheduleAdapter
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
class DroidconBerlinNetworkModule(context: Context) : NetworkModule(context) {
private val retrofit: Retrofit
private val okHttp: OkHttpClient
private val backendAdapter: BackendScheduleAdapter
private val backend: DroidconBerlinBackend
init {
okHttp = OkHttpClient.Builder().cache(Cache(context.cacheDir, 48 * 1024 * 1024))
.build()
retrofit = Retrofit.Builder()
.client(okHttp)
.baseUrl("http://droidcon.de/rest/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(LoganSquareConverterFactory.create())
.build()
backend = retrofit.create(DroidconBerlinBackend::class.java)
backendAdapter = DroidconBerlinBackendScheduleAdapter(backend)
}
override fun provideOkHttp(): OkHttpClient = okHttp
override fun provideBackendAdapter(): BackendScheduleAdapter = backendAdapter
} | apache-2.0 | 9e00bc99212efad72b3cd0befdad6be4 | 32.829268 | 84 | 0.795815 | 5.058394 | false | false | false | false |
yrsegal/CommandControl | src/main/java/wiresegal/cmdctrl/common/core/NBTGetter.kt | 1 | 5418 | package wiresegal.cmdctrl.common.core
import net.minecraft.nbt.*
import net.minecraftforge.common.util.Constants
/**
* @author WireSegal
* Created at 9:21 AM on 12/14/16.
*/
private val MATCHER = "(?:(?:(?:\\[\\d+\\])|(?:[^.\\[\\]]+))(\\.|$|(?=\\[)))+".toRegex()
private val TOKENIZER = "((?:\\[\\d+\\])|(?:[^.\\[\\]]+))(?=[.\\[]|$)".toRegex()
fun NBTTagCompound.getObject(key: String): NBTBase? {
if (!MATCHER.matches(key)) return null
var currentElement: NBTBase = this
val matched = TOKENIZER.findAll(key)
for (match in matched) {
val m = match.groupValues[1]
if (m.startsWith("[")) {
val ind = m.removePrefix("[").removeSuffix("]").toInt()
if (currentElement is NBTTagList) {
if (currentElement.tagCount() < ind + 1) return null
currentElement = currentElement[ind]
} else if (currentElement is NBTTagByteArray) {
if (currentElement.byteArray.size < ind + 1) return null
currentElement = NBTTagByte(currentElement.byteArray[ind])
} else if (currentElement is NBTTagIntArray) {
if (currentElement.intArray.size < ind + 1) return null
currentElement = NBTTagInt(currentElement.intArray[ind])
} else return null
} else if (currentElement is NBTTagCompound) {
if (!currentElement.hasKey(m)) return null
currentElement = currentElement.getTag(m)
} else return null
}
return currentElement
}
private val CLASSES = arrayOf(
NBTTagEnd::class.java,
NBTTagByte::class.java,
NBTTagShort::class.java,
NBTTagInt::class.java,
NBTTagLong::class.java,
NBTTagFloat::class.java,
NBTTagDouble::class.java,
NBTTagByteArray::class.java,
NBTTagString::class.java,
NBTTagList::class.java,
NBTTagCompound::class.java,
NBTTagIntArray::class.java
)
fun NBTTagCompound.setObject(key: String, tag: NBTBase): Boolean {
if (!MATCHER.matches(key)) return false
var currentElement: NBTBase = this
val matched = TOKENIZER.findAll(key).toList()
val max = matched.size - 1
for ((index, match) in matched.withIndex()) {
val m = match.groupValues[1]
val done = index == max
if (m.startsWith("[")) {
val ind = m.removePrefix("[").removeSuffix("]").toInt()
if (currentElement is NBTTagList) {
if (currentElement.tagCount() < ind + 1 && !done) {
val new = if ((currentElement.tagType == 0 || currentElement.tagType == Constants.NBT.TAG_LIST)
&& matched[index + 1].groupValues[1].startsWith("[")) NBTTagList()
else if ((currentElement.tagType == 0 || currentElement.tagType == Constants.NBT.TAG_COMPOUND))
NBTTagCompound()
else return false
currentElement.appendTag(new)
currentElement = new
} else {
if (!done) currentElement = currentElement[ind]
else {
var type = currentElement.tagType
if (type == 0) type = Constants.NBT.TAG_DOUBLE
val transformedTag = tag.safeCast(CLASSES[type])
if (ind >= currentElement.tagCount()) currentElement.appendTag(transformedTag)
else currentElement.set(ind, transformedTag)
}
}
} else if (currentElement is NBTTagByteArray) {
if (currentElement.byteArray.size < ind + 1 || !done || tag !is NBTPrimitive) return false
currentElement.byteArray[ind] = tag.byte
} else if (currentElement is NBTTagIntArray) {
if (currentElement.intArray.size < ind + 1 || !done || tag !is NBTPrimitive) return false
currentElement.intArray[ind] = tag.int
} else return false
} else if (currentElement is NBTTagCompound) {
if (!currentElement.hasKey(m) && !done) {
val new = if (matched[index + 1].groupValues[1].startsWith("[")) NBTTagList() else NBTTagCompound()
currentElement.setTag(m, new)
currentElement = new
} else {
if (!done) currentElement = currentElement.getTag(m)
else currentElement.setTag(m, tag)
}
} else return false
}
return true
}
@Suppress("UNCHECKED_CAST")
fun <T : NBTBase> NBTBase.safeCast(clazz: Class<T>): T {
return (
if (clazz.isAssignableFrom(this.javaClass))
this
else if (clazz == NBTPrimitive::class.java)
NBTTagByte(0)
else if (clazz == NBTTagByteArray::class.java)
NBTTagByteArray(ByteArray(0))
else if (clazz == NBTTagString::class.java)
NBTTagString("")
else if (clazz == NBTTagList::class.java)
NBTTagList()
else if (clazz == NBTTagCompound::class.java)
NBTTagCompound()
else if (clazz == NBTTagIntArray::class.java)
NBTTagIntArray(IntArray(0))
else
throw IllegalArgumentException("Unknown NBT type to cast to: $clazz")
) as T
}
| mit | 10f620b30a323bba7b8446ffdc650201 | 40.676923 | 115 | 0.559616 | 4.736014 | false | false | false | false |
AK-47-D/cms | src/main/kotlin/com/ak47/cms/cms/api/ImageSearchApiBuilder.kt | 1 | 231 | package com.ak47.cms.cms.api
object ImageSearchApiBuilder {
fun build(word: String, page: Int): String {
return "http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&fp=result&word=${word}&pn=${page}"
}
}
| apache-2.0 | 400621e024dfc263c34df78c9cf1a710 | 32 | 112 | 0.683983 | 2.924051 | false | false | false | false |
rharter/windy-city-devcon-android | app/src/main/kotlin/com/gdgchicagowest/windycitydevcon/data/FirebaseSessionDateProvider.kt | 1 | 1087 | package com.gdgchicagowest.windycitydevcon.data
import com.google.firebase.database.*
import java.util.*
class FirebaseSessionDateProvider : SessionDateProvider {
private val ref: DatabaseReference = FirebaseDatabase.getInstance().reference.child("session_dates")
private val listeners: MutableMap<Any, ValueEventListener> = HashMap<Any, ValueEventListener>()
override fun addSessionDateListener(key: Any, onComplete: (List<String>?) -> Unit) {
val listener = object : ValueEventListener {
override fun onDataChange(data: DataSnapshot?) {
val typeIndicator = object : GenericTypeIndicator<ArrayList<String>>() {}
val dates = data?.getValue(typeIndicator)
onComplete(dates)
}
override fun onCancelled(error: DatabaseError?) {
onComplete(null)
}
}
listeners[key] = listener
ref.addValueEventListener(listener)
}
override fun removeSessionDateListener(key: Any) {
ref.removeEventListener(listeners[key])
}
} | apache-2.0 | 9d2badee48b1fe56dc7f71530df74a75 | 34.096774 | 104 | 0.666053 | 5.200957 | false | false | false | false |
sproshev/tcity | app/src/main/kotlin/com/tcity/android/background/runnable/FavouriteProjectsRunnable.kt | 1 | 3000 | /*
* Copyright 2014 Semyon Proshev
*
* 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.tcity.android.background.runnable
import com.tcity.android.db.DB
import com.tcity.android.background.rest.RestClient
import org.apache.http.HttpStatus
import com.tcity.android.background.HttpStatusException
import java.io.IOException
import java.util.ArrayList
import org.apache.http.util.EntityUtils
import org.apache.http.ParseException
import android.util.Log
import com.tcity.android.app.Preferences
public class FavouriteProjectsRunnable(
private val db: DB,
private val client: RestClient,
private val preferences: Preferences
) : Runnable {
throws(javaClass<IOException>(), javaClass<ParseException>())
override fun run() {
val newIds = loadIds(loadInternalIds()).filter { !db.isProjectFavourite(it) }
db.addFavouriteProjects(newIds)
loadStatusesQuietly(newIds)
preferences.setFavouriteProjectsLastUpdate(System.currentTimeMillis())
}
throws(javaClass<IOException>(), javaClass<ParseException>())
private fun loadInternalIds(): Array<String> {
val response = client.getOverviewProjects(preferences.getLogin())
val statusLine = response.getStatusLine()
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw HttpStatusException(statusLine)
} else {
return EntityUtils.toString(response.getEntity()).split(':')
}
}
throws(javaClass<IOException>(), javaClass<ParseException>())
private fun loadIds(internalIds: Array<String>): List<String> {
val result = ArrayList<String>(internalIds.size())
internalIds.forEach {
val response = client.getProjectId(it)
val statusLine = response.getStatusLine()
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw HttpStatusException(statusLine)
} else {
result.add(
EntityUtils.toString(response.getEntity())
)
}
}
return result
}
private fun loadStatusesQuietly(ids: Collection<String>) {
ids.forEach {
try {
ProjectStatusRunnable(it, db, client).run()
} catch (e: Exception) {
Log.i(
javaClass<FavouriteProjectsRunnable>().getSimpleName(), e.getMessage(), e
)
}
}
}
}
| apache-2.0 | 159997a66d0cd3a9879dc78b6dd1fe54 | 31.608696 | 97 | 0.659667 | 4.643963 | false | false | false | false |
industrial-data-space/trusted-connector | ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/SettingsApi.kt | 1 | 4923 | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api
import de.fhg.aisec.ids.api.infomodel.ConnectorProfile
import de.fhg.aisec.ids.api.infomodel.InfoModel
import de.fraunhofer.iais.eis.util.TypedLiteral
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.Authorization
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.stream.Collectors
import javax.ws.rs.Consumes
import javax.ws.rs.DELETE
import javax.ws.rs.GET
import javax.ws.rs.InternalServerErrorException
import javax.ws.rs.POST
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
/**
* REST API interface for Connector settings in the connector.
*
*
* The API will be available at http://localhost:8181/cxf/api/v1/settings/<method>.
</method> */
// ConnectorProfile will be processed by custom Jackson deserializer
@Component
@Path("/settings")
@Api(value = "Self-Description and Connector Profiles", authorizations = [Authorization(value = "oauth2")])
class SettingsApi {
@Autowired
private lateinit var im: InfoModel
@POST
@Path("/connectorProfile")
@ApiOperation(value = "Configure the connector's self-description (\"Connector Profile\").")
@Consumes(
MediaType.APPLICATION_JSON
)
@AuthorizationRequired
fun postConnectorProfile(profile: ConnectorProfile?): String {
return if (im.setConnector(profile!!)) {
"ConnectorProfile successfully stored."
} else {
throw InternalServerErrorException("Error while storing ConnectorProfile")
}
}
/** Returns Connector profile based on currently stored preferences or empty Connector profile */
@get:AuthorizationRequired
@get:ApiOperation(
value = "Returns this connector's self-description (\"Connector Profile\")",
response = ConnectorProfile::class
)
@get:Produces(MediaType.APPLICATION_JSON)
@get:Path("/connectorProfile")
@get:GET
val connectorProfile: ConnectorProfile
get() {
val c = im.connector
return if (c == null) {
ConnectorProfile()
} else {
ConnectorProfile(
c.securityProfile,
c.id,
c.maintainer,
c.description.stream().map { obj: Any? -> TypedLiteral::class.java.cast(obj) }
.collect(Collectors.toList())
)
}
}
/**
* Returns connector profile based on currently stored preferences or statically provided JSON-LD
* model, or empty connector profile if none of those are available.
*/
@get:Produces("application/ld+json")
@get:Path("/selfInformation")
@get:GET
@set:AuthorizationRequired
@set:Consumes("application/ld+json")
@set:Path("/selfInformation")
@set:POST
var selfInformation: String?
// TODO Document ApiOperation
get() = try {
im.connectorAsJsonLd
} catch (e: NullPointerException) {
LOG.warn("Connector description build failed, building empty description.", e)
null
}
// TODO Document ApiOperation
set(selfInformation) {
try {
im.setConnectorByJsonLd(selfInformation)
} catch (e: NullPointerException) {
LOG.warn("Connector description build failed, building empty description.", e)
}
}
/** Remove static connector profile based on JSON-LD data */
// TODO Document ApiOperation
@DELETE
@Path("/selfInformation")
@Consumes("application/ld+json")
@AuthorizationRequired
fun removeSelfInformation() {
try {
im.setConnectorByJsonLd(null)
} catch (e: NullPointerException) {
LOG.warn("Connector description build failed, building empty description.", e)
}
}
companion object {
private val LOG = LoggerFactory.getLogger(SettingsApi::class.java)
}
}
| apache-2.0 | 84acdcf0ae83d886ece1eb9c2e02af14 | 33.914894 | 107 | 0.649807 | 4.579535 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/trans/ErrorInfo.kt | 1 | 1895 | package cn.yiiguxing.plugin.translate.trans
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import javax.swing.Icon
/**
* Translation error information.
*
* @property message The error message
* @property continueActions The continue actions after the error
*/
data class ErrorInfo(
val message: String,
val continueActions: List<AnAction> = emptyList()
) {
constructor(message: String, vararg continueActions: AnAction) : this(message, continueActions.toList())
companion object {
/**
* Creates a continue action.
*
* @param name The action name
* @param description Describes current action
* @param icon Action's icon
*/
inline fun continueAction(
name: String,
description: String? = null,
icon: Icon? = null,
crossinline action: ((AnActionEvent) -> Unit)
): AnAction = object : DumbAwareAction(name, description, icon) {
override fun actionPerformed(e: AnActionEvent) = action(e)
}
/**
* Creates a continue actions to browse the specified [url].
*
* @param name The action name
* @param url The url to browse
* @param description Describes current action
* @param icon Action's icon
*/
fun browseUrlAction(
name: String,
url: String,
description: String? = null,
icon: Icon? = AllIcons.General.Web
): AnAction {
return object : DumbAwareAction(name, description, icon) {
override fun actionPerformed(e: AnActionEvent) = BrowserUtil.browse(url)
}
}
}
} | mit | 48c9717e9f0e0107422e3e5e249281f1 | 31.135593 | 108 | 0.62533 | 4.896641 | false | false | false | false |
DreamTeamGDL/SkyNet | SkyNet/app/src/main/java/gdl/dreamteam/skynet/Fragments/DeviceFanFragment.kt | 2 | 3090 | package gdl.dreamteam.skynet.Fragments
import android.app.Fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import gdl.dreamteam.skynet.Others.RestRepository
import gdl.dreamteam.skynet.R
import android.support.annotation.Nullable
import gdl.dreamteam.skynet.Models.Fan
import android.databinding.DataBindingUtil
import android.util.Log
import android.widget.Button
import gdl.dreamteam.skynet.Bindings.DeviceFanBinding
import gdl.dreamteam.skynet.Models.ActionMessage
import gdl.dreamteam.skynet.Others.QueueService
import gdl.dreamteam.skynet.databinding.FanBinding
import java.util.*
/**
* Created by Cesar on 18/09/17.
*/
class DeviceFanFragment : Fragment() {
private lateinit var mListener: OnFragmentInteractionListener
private lateinit var binding: FanBinding
// Factory method to create an instance of this fragment
companion object {
const val ARG_STATUS = "status"
const val ARG_TEMPERATURE = "temperature"
const val ARG_HUMIDITY = "humidity"
const val ARG_SPEED = "speed"
fun newInstance(data: String): DeviceFanFragment {
Log.d("FRAGMENT", data)
val device = RestRepository.gson.fromJson(data, Fan::class.java)
val fragment = DeviceFanFragment()
val args = Bundle()
fragment.arguments = args
args.putBoolean(ARG_STATUS, device.status)
args.putFloat(ARG_TEMPERATURE, device.temperature)
args.putFloat(ARG_HUMIDITY, device.humidity)
args.putInt(ARG_SPEED, device.speed)
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater?,
@Nullable container: ViewGroup?,
@Nullable savedInstanceState: Bundle?): View? {
binding= DataBindingUtil.inflate(inflater, R.layout.fragment_device_fan, container, false)
val view = binding.root
val button = view.findViewById<Button>(R.id.queueButton)
button.setOnClickListener {
mListener.somethingHappened("SPEED CHANGE ${binding.deviceFan.speed}")
}
binding.deviceFan = DeviceFanBinding(
arguments.getBoolean(ARG_STATUS),
arguments.getFloat(ARG_TEMPERATURE),
arguments.getFloat(ARG_HUMIDITY),
arguments.getInt(ARG_SPEED)
)
return view
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
mListener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
}
interface OnFragmentInteractionListener {
fun somethingHappened(message: String)
}
}
| mit | 34bc7f43b51eb1136ac6caeb446cc07d | 30.212121 | 104 | 0.673786 | 4.667674 | false | false | false | false |
guloggratis/srvc-google-analytics | src/main/kotlin/gg/analytics/DataVerticle.kt | 1 | 3972 | package gg.analytics
import com.google.api.services.analytics.model.GaData
import gg.util.*
import gg.util.DateTimespan.getDateTimespan
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import org.joda.time.DateTime
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import redis.client.RedisClient
import redis.client.cmdDel
import redis.client.cmdHGet
import redis.client.cmdHSet
import redis.protocol.reply.NullBulkString
@Suppress("unused")
class DataVerticle : AbstractVerticle() {
private val logger = LoggerFactory.getLogger(this::class.java)
private var redisConfPort = 6479
private var redisConfHost = "localhost"
private var busConf = "redis_bus"
private var page = 0
private val pageSize = 10000
private var datetime_import = DateTime();
override fun start(startFuture: Future<Void>?) {
MDC.put("verticle", "data")
val conf = Config.get()
redisConfPort = conf.getJsonObject("redis").getInteger("port")
redisConfHost = conf.getJsonObject("redis").getString("host")
busConf = conf.getJsonObject("event_bus").getString("bus_name")
logger.debug("initialising api version {}", conf.getString("version"))
logger.debug("Fetching data from GA...")
startFuture?.complete()
vertx.eventBus().consumer<Int>(busConf) { message ->
run {
page=message.body()
doAnalyticsQueryandStore()
message.reply(true);
}
}
// doAnalyticsQueryandStore()
}
private fun doAnalyticsQueryandStore() {
logger.debug( "Doing analytics for page " + page)
/* Adding arguments for google analytics */
val params = mutableMapOf<String, Int>()
params.put("pageSize",pageSize)
params.put("page",page)
params.put("dateTimespan", getDateTimespan())
val result = QueryAnalytics.main(params)
var initialResult = if (page == 0) 0 else (1 + pageSize * page)
val maxResults = result.totalResults
logger.debug("Got results, putting it in redis")
storeInRedis(result)
if(initialResult == 0) {
logger.debug("IS FIRST PAGE, adding new events")
initialResult = (1 + pageSize * ++page)
while(initialResult < maxResults) {
logger.debug(" Adding page " + page + " to event bus")
/* Invoke using the event bus. */
EventBusHandler.sendIntEvent(busConf, page, this)
initialResult = (1 + pageSize * ++page)
}
}
}
private fun storeInRedis(result: GaData) {
val rs = RedisClient(redisConfHost, redisConfPort)
rs.connect()
for (item in result.rows){
// Now create matcher object.
val key = AdViewRegex.getAdId(item[0]);
val datetime_import_reply = rs.execute { cmdHGet(key, "datetime_import")}
if(datetime_import_reply !is NullBulkString) {
val obj_datetime = DateTime(datetime_import_reply.toString())
if(!DateTimeImport.equals(obj_datetime))
{
rs.execute { cmdDel(key) }
}
}
rs.execute { cmdHSet(key, item[0], item[1]) }
rs.execute { cmdHSet(key, "timespan", Integer.toString(DateTimespan.getDateTimespan())) }
rs.execute { cmdHSet(key, "datetime_import", datetime_import.toString()) }
val total_views_reply = rs.execute { cmdHGet(key, "total_views")}
var total_views = Integer.parseInt(item[1])
if(total_views_reply !is NullBulkString) {
total_views = (Integer.parseInt(total_views_reply.toString()) + Integer.parseInt(item[1]))
}
rs.execute { cmdHSet(key, "total_views", total_views.toString()) }
}
rs.close()
}
override fun stop(stopFuture: Future<Void>?) {
}
} | apache-2.0 | 1cab6d7894dc7921e3f6d702ea644b3f | 36.130841 | 106 | 0.614048 | 4.181053 | false | false | false | false |
wax911/android-emojify | emojify/src/androidTest/java/io/wax911/emojify/EmojiUtilTest.kt | 1 | 8684 | package io.wax911.emojify
import androidx.startup.AppInitializer
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.platform.app.InstrumentationRegistry
import io.wax911.emojify.initializer.EmojiInitializer
import io.wax911.emojify.parser.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4ClassRunner::class)
class EmojiUtilTest {
private val context by lazy { InstrumentationRegistry.getInstrumentation().context }
private val emojiManager by lazy {
AppInitializer.getInstance(context)
.initializeComponent(EmojiInitializer::class.java)
}
@Before
fun testApplicationContext() {
assertNotNull(context)
}
@Before
fun testEmojiLoading() {
assertNotNull(emojiManager)
assertTrue(emojiManager.emojiList.isNotEmpty())
}
@Test
fun testEmojiByUnicode() {
val emoji = emojiManager.getByUnicode("\uD83D\uDC2D")
assertNotNull(emoji)
assertEquals("🐭", emoji?.htmlHex)
}
@Test
fun testEmojiByShortCode() {
// existing emoji
var emoji = emojiManager.getForAlias("blue_car")
assertNotNull(emoji)
assertEquals("🚙", emoji!!.emoji)
// not an emoji character
emoji = emojiManager.getForAlias("bluecar")
assertNull(emoji)
}
@Test
fun testEmojiByShortCodeWithColons() {
// existing emoji
var emoji = emojiManager.getForAlias(":blue_car:")
assertNotNull(emoji)
assertEquals("🚙", emoji!!.emoji)
// not an emoji character
emoji = emojiManager.getForAlias(":bluecar:")
assertNull(emoji)
}
@Test
fun testEmojiByHexHtml() {
// get by hexhtml
val unicode = emojiManager.parseToUnicode("🐭")
assertNotNull(unicode)
val emoji = emojiManager.getByUnicode(unicode)
assertNotNull(emoji)
assertEquals("🐭", emoji?.emoji)
}
@Test
fun testEmojiByDecimalHtml() {
// get by decimal html
val unicode = emojiManager.parseToUnicode("🐭")
assertNotNull(unicode)
val emoji = emojiManager.getByUnicode(unicode)
assertNotNull(emoji)
assertEquals("🐭", emoji?.emoji)
}
@Test
fun testIsEmoji() {
assertFalse(emojiManager.isEmoji("{"))
assertTrue(emojiManager.isEmoji("🐭"))
assertFalse(emojiManager.isEmoji("smile"))
assertTrue(emojiManager.isEmoji(emojiManager.parseToUnicode(":smiley:")))
assertFalse(emojiManager.isEmoji("🐭"))
}
@Test
fun testEmojify1() {
var text = "A :cat:, :dog: and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."
assertEquals("A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", emojiManager.parseToUnicode(text))
text = "A :cat:, :dog:, :coyote: and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."
assertEquals("A 🐱, 🐶, :coyote: and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", emojiManager.parseToUnicode(text))
}
@Test
fun testEmojify2() {
var text = "A 🐱, 🐶 and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."
assertEquals("A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", emojiManager.parseToUnicode(text))
text = "A 🐱, 🐶, and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."
assertEquals("A 🐱, 🐶, and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", emojiManager.parseToUnicode(text))
}
@Test
fun testCountEmojis() {
val text = "A 🐱, 🐶, :coyote: and a :mouse: became friends. For :dog:'s birthday party, they all had 🍔s, :fries:s, :cookie:s and :cake:."
val emojiText = emojiManager.parseToUnicode(text)
val emojiCount = emojiManager.extractEmojis(emojiText).size
assertEquals(8, emojiCount)
}
@Test
fun testHtmlify() {
val text = "A :cat:, :dog: and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."
val emojiText = emojiManager.parseToUnicode(text)
val htmlifiedText = emojiManager.parseToHtmlDecimal(emojiText)
assertEquals("A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", htmlifiedText)
// also verify by emojifying htmlified text
assertEquals("A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", emojiManager.parseToUnicode(htmlifiedText))
}
@Test
fun testHexHtmlify() {
val text = "A :cat:, :dog: and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."
val emojiText = emojiManager.parseToUnicode(text)
val htmlifiedText = emojiManager.parseToHtmlHexadecimal(emojiText)
assertNotNull(htmlifiedText)
assertEquals("A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", htmlifiedText)
// also verify by emojifying htmlified text
assertEquals("A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰.", emojiManager.parseToUnicode(htmlifiedText!!))
}
@Test
fun testShortCodifyFromEmojis() {
val text = "A 🐱, 🐶 and a 🐭 became friends❤️. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰."
val expected = "A :cat:, :dog: and a :mouse: became friends:heart:️. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."
val aliasText = emojiManager.parseToAliases(text)
assertEquals(expected, aliasText)
}
@Test
fun testShortCodifyFromHtmlEntities() {
var text = "A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰."
var emojiText = emojiManager.parseToUnicode(text)
assertEquals("A :cat:, :dog: and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:.", emojiManager.parseToAliases(emojiText))
text = "A 🐱, 🐶 and a 🐭 became friends. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰."
emojiText = emojiManager.parseToUnicode(text)
assertEquals("A :cat:, :dog: and a :mouse: became friends. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:.", emojiManager.parseToAliases(emojiText))
}
@Test
fun toSurrogateDecimalAndBackTest() {
val text = "😃😃😅😃😶😝😗😗❤️😛😛😅❤️😛"
val htmlifiedText = emojiManager.parseToHtmlDecimal(text)
assertEquals("😃😃😅😃😶😝😗😗❤️😛😛😅❤️😛", htmlifiedText)
assertEquals(text, emojiManager.parseToUnicode(htmlifiedText))
}
@Test
fun surrogateToHTMLTest() {
val emojiText = "😃😃😅😃😶😝😗😗❤️😛😛😅❤️😛"
val decHtmlString = emojiManager.parseToHtmlDecimal(emojiText)
val hexHtmlString = emojiManager.parseToHtmlHexadecimal(emojiText)
assertNotNull(hexHtmlString)
assertEquals("😃😃😅😃😶😝😗😗❤️😛😛😅❤️😛", decHtmlString)
assertEquals("😃😃😅😃😶😝😗😗❤️😛😛😅❤️😛", hexHtmlString)
assertEquals(emojiText, emojiManager.parseToUnicode(decHtmlString))
assertEquals(emojiText, emojiManager.parseToUnicode(hexHtmlString!!))
}
} | mit | 14142f7e08fd0b1588e89ec3117ea26b | 37.5 | 195 | 0.64919 | 3.326199 | false | true | false | false |
hyst329/OpenFool | core/src/ru/hyst329/openfool/ResultScreen.kt | 1 | 4504 | package ru.hyst329.openfool
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.g2d.GlyphLayout
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.utils.viewport.FitViewport
/**
* Created by main on 18.03.2017.
* Licensed under MIT License.
*/
internal class ResultScreen(private val game: OpenFoolGame,
private val result: ResultScreen.Result,
private val playersPlaces: Map<Int, String>) : Screen {
private val stage: Stage
internal enum class Result {
TEAM_WON,
TEAM_LOST,
TEAM_PARTNER_LOST,
TEAM_DRAW,
WON,
LOST,
DRAW
}
init {
game.orientationHelper.requestOrientation(OrientationHelper.Orientation.LANDSCAPE)
stage = Stage(FitViewport(800f, 480f))
}
override fun show() {
}
override fun render(delta: Float) {
var color = Color.BLACK
var header = ""
var text = ""
when (result) {
ResultScreen.Result.TEAM_WON -> {
color = Color(0.2f, 0.6f, 0.125f, 1f)
header = game.localeBundle.get("TeamVictoryHeader")
text = game.localeBundle.get("TeamVictoryText")
}
ResultScreen.Result.TEAM_LOST -> {
color = Color(0.6f, 0.2f, 0.125f, 1f)
header = game.localeBundle.get("TeamDefeatHeader")
text = game.localeBundle.get("TeamDefeatText")
}
ResultScreen.Result.TEAM_PARTNER_LOST -> {
color = Color(0.6f, 0.4f, 0.125f, 1f)
header = game.localeBundle.get("TeamPartnerDefeatHeader")
text = game.localeBundle.get("TeamPartnerDefeatText")
}
ResultScreen.Result.TEAM_DRAW -> {
color = Color(0.6f, 0.6f, 0.125f, 1f)
header = game.localeBundle.get("TeamDrawHeader")
text = game.localeBundle.get("TeamDrawText")
}
ResultScreen.Result.WON -> {
color = Color(0.2f, 0.6f, 0.125f, 1f)
header = game.localeBundle.get("VictoryHeader")
text = game.localeBundle.get("VictoryText")
}
ResultScreen.Result.LOST -> {
color = Color(0.6f, 0.2f, 0.125f, 1f)
header = game.localeBundle.get("DefeatHeader")
text = game.localeBundle.get("DefeatText")
}
ResultScreen.Result.DRAW -> {
color = Color(0.6f, 0.6f, 0.125f, 1f)
header = game.localeBundle.get("DrawHeader")
text = game.localeBundle.get("DrawText")
}
}
var places = ""
for ((p, n) in playersPlaces.entries.toList().sortedBy { it.key }) {
places += game.localeBundle.format("PlayerPlace", n, p) + "\n"
}
val headerLayout = GlyphLayout(game.font, header)
val textLayout = GlyphLayout(game.font, text)
val placesLayout = GlyphLayout(game.font, places)
Gdx.gl.glClearColor(color.r, color.g, color.b, color.a)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
game.batch.transformMatrix = stage.viewport.camera.view
game.batch.projectionMatrix = stage.viewport.camera.projection
game.batch.begin()
game.font.draw(game.batch, headerLayout,
stage.viewport.worldWidth * 0.5f - headerLayout.width / 2,
stage.viewport.worldHeight * 0.833f - headerLayout.height / 2)
game.font.draw(game.batch, textLayout,
stage.viewport.worldWidth * 0.5f - textLayout.width / 2,
stage.viewport.worldHeight * 0.58f - textLayout.height / 2)
game.font.draw(game.batch, placesLayout,
stage.viewport.worldWidth * 0.5f - textLayout.width / 2,
stage.viewport.worldHeight * 0.4f - textLayout.height / 2)
game.batch.end()
if (Gdx.input.isKeyJustPressed(Input.Keys.BACK) || Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
game.screen = MainMenuScreen(game)
dispose()
}
}
override fun resize(width: Int, height: Int) {
}
override fun pause() {
}
override fun resume() {
}
override fun hide() {
}
override fun dispose() {
}
}
| gpl-3.0 | 161d8ba64510585bb0d3946baf3ac79e | 33.646154 | 107 | 0.577709 | 3.933624 | false | false | false | false |
MichaelRocks/lightsaber | processor/src/test/java/io/michaelrocks/lightsaber/processor/annotations/proxy/ArrayClassLoader.kt | 1 | 1648 | /*
* Copyright 2018 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.annotations.proxy
import java.util.HashMap
import java.util.HashSet
class ArrayClassLoader : ClassLoader {
private val loadedClasses = HashSet<String>()
private val pendingClasses = HashMap<String, ByteArray>()
constructor()
constructor(parentClassLoader: ClassLoader) : super(parentClassLoader)
fun addClass(name: String, bytes: ByteArray) {
check(!loadedClasses.contains(name))
pendingClasses.put(name, bytes)
}
fun hasClass(name: String): Boolean = loadedClasses.contains(name) || pendingClasses.containsKey(name)
@Throws(ClassNotFoundException::class)
override fun findClass(name: String): Class<*> {
val loadedClass: Class<*>?
val bytes = pendingClasses.remove(name)
if (bytes == null) {
loadedClass = findLoadedClass(name)
} else {
loadedClass = defineClass(name, bytes, 0, bytes.size)
loadedClasses.add(name)
}
if (loadedClass != null) {
return loadedClass
}
throw ClassNotFoundException(name)
}
}
| apache-2.0 | 2b397e07be6b0c7595bac88ed4d760f2 | 29.518519 | 104 | 0.725121 | 4.280519 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/sync/MessengerWorker.kt | 1 | 17058 | package me.proxer.app.chat.prv.sync
import android.content.Context
import androidx.work.Constraints
import androidx.work.Data
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.rubengees.rxbus.RxBus
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.chat.prv.LocalMessage
import me.proxer.app.chat.prv.conference.ConferenceFragmentPingEvent
import me.proxer.app.chat.prv.message.MessengerFragmentPingEvent
import me.proxer.app.exception.ChatException
import me.proxer.app.exception.ChatMessageException
import me.proxer.app.exception.ChatSendMessageException
import me.proxer.app.exception.ChatSynchronizationException
import me.proxer.app.util.WorkerUtils
import me.proxer.app.util.data.PreferenceHelper
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.toInstantBP
import me.proxer.app.util.extension.toLocalConference
import me.proxer.app.util.extension.toLocalMessage
import me.proxer.library.ProxerApi
import me.proxer.library.ProxerCall
import me.proxer.library.ProxerException
import me.proxer.library.entity.messenger.Conference
import me.proxer.library.entity.messenger.Message
import timber.log.Timber
import java.util.LinkedHashSet
import java.util.concurrent.TimeUnit
/**
* @author Ruben Gees
*/
class MessengerWorker(
context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams) {
companion object {
const val CONFERENCES_ON_PAGE = 48
const val MESSAGES_ON_PAGE = 30
private const val NAME = "MessengerWorker"
private const val CONFERENCE_ID_ARGUMENT = "conference_id"
val isRunning
get() = workManager.getWorkInfosForUniqueWork(NAME).get()
.all { info -> info.state == WorkInfo.State.RUNNING }
private val bus by safeInject<RxBus>()
private val workManager by safeInject<WorkManager>()
private val storageHelper by safeInject<StorageHelper>()
private val preferenceHelper by safeInject<PreferenceHelper>()
fun enqueueSynchronizationIfPossible() = when {
canSchedule() -> enqueueSynchronization()
else -> cancel()
}
fun enqueueSynchronization() = doEnqueue()
fun enqueueMessageLoad(conferenceId: Long) = doEnqueue(conferenceId = conferenceId)
fun cancel() {
workManager.cancelUniqueWork(NAME)
}
private fun reschedule(synchronizationResult: SynchronizationResult) {
if (canSchedule() && synchronizationResult != SynchronizationResult.ERROR) {
if (synchronizationResult == SynchronizationResult.CHANGES || bus.post(MessengerFragmentPingEvent())) {
storageHelper.resetChatInterval()
doEnqueue(3_000L)
} else if (bus.post(ConferenceFragmentPingEvent())) {
storageHelper.resetChatInterval()
doEnqueue(10_000L)
} else {
storageHelper.incrementChatInterval()
doEnqueue(storageHelper.chatInterval)
}
}
}
private fun doEnqueue(startTime: Long? = null, conferenceId: Long? = null) {
val workRequest = OneTimeWorkRequestBuilder<MessengerWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.apply { if (startTime != null) setInitialDelay(startTime, TimeUnit.MILLISECONDS) }
.setInputData(
Data.Builder()
.apply { if (conferenceId != null) putLong(CONFERENCE_ID_ARGUMENT, conferenceId) }
.build()
)
.build()
workManager.beginUniqueWork(NAME, ExistingWorkPolicy.REPLACE, workRequest).enqueue()
}
private fun canSchedule() = preferenceHelper.areChatNotificationsEnabled ||
bus.post(ConferenceFragmentPingEvent()) || bus.post(MessengerFragmentPingEvent())
private fun canShowNotification() = preferenceHelper.areChatNotificationsEnabled &&
!bus.post(ConferenceFragmentPingEvent()) && !bus.post(MessengerFragmentPingEvent())
}
private val conferenceId: Long
get() = inputData.getLong(CONFERENCE_ID_ARGUMENT, 0L)
private val api by safeInject<ProxerApi>()
private val storageHelper by safeInject<StorageHelper>()
private val messengerDatabase by safeInject<MessengerDatabase>()
private val messengerDao by safeInject<MessengerDao>()
private var currentCall: ProxerCall<*>? = null
override fun onStopped() {
currentCall?.cancel()
}
override fun doWork(): Result {
if (!storageHelper.isLoggedIn) return Result.failure()
val synchronizationResult = when (conferenceId) {
0L ->
try {
handleSynchronization()
} catch (error: Throwable) {
handleSynchronizationError(error)
}
else ->
try {
handleLoadMoreMessages(conferenceId)
} catch (error: Throwable) {
handleLoadMoreMessagesError(error)
}
}
reschedule(synchronizationResult)
return if (synchronizationResult != SynchronizationResult.ERROR) Result.success() else Result.failure()
}
private fun handleSynchronization(): SynchronizationResult {
val newConferencesAndMessages = synchronize()
storageHelper.areConferencesSynchronized = true
val maxNewDate = newConferencesAndMessages.flatMap { it.value }.maxByOrNull { it.date }?.date
if (!isStopped && newConferencesAndMessages.isNotEmpty()) {
bus.post(SynchronizationEvent())
}
if (!isStopped && maxNewDate != null && maxNewDate > storageHelper.lastChatMessageDate) {
if (canShowNotification()) {
showNotification(applicationContext)
}
storageHelper.lastChatMessageDate = maxNewDate
}
MessengerShortcuts.updateShareTargets(applicationContext)
return when (newConferencesAndMessages.isNotEmpty()) {
true -> SynchronizationResult.CHANGES
false -> SynchronizationResult.NO_CHANGES
}
}
private fun handleSynchronizationError(error: Throwable): SynchronizationResult {
Timber.e(error)
if (!isStopped) {
when (error) {
is ChatException -> bus.post(MessengerErrorEvent(error))
else -> bus.post(MessengerErrorEvent(ChatSynchronizationException(error)))
}
}
return when (WorkerUtils.shouldRetryForError(error)) {
true -> SynchronizationResult.NO_CHANGES
false -> SynchronizationResult.ERROR
}
}
private fun handleLoadMoreMessagesError(error: Throwable): SynchronizationResult {
Timber.e(error)
if (!isStopped) {
when (error) {
is ChatException -> bus.post(MessengerErrorEvent(error))
else -> bus.post(MessengerErrorEvent(ChatMessageException(error)))
}
}
return when (WorkerUtils.shouldRetryForError(error)) {
true -> SynchronizationResult.NO_CHANGES
false -> SynchronizationResult.ERROR
}
}
private fun handleLoadMoreMessages(conferenceId: Long): SynchronizationResult {
val fetchedMessages = loadMoreMessages(conferenceId)
fetchedMessages.maxByOrNull { it.date }?.date?.toInstantBP()?.let { mostRecentDate ->
if (mostRecentDate.isAfter(storageHelper.lastChatMessageDate)) {
storageHelper.lastChatMessageDate = mostRecentDate
}
}
return SynchronizationResult.CHANGES
}
@Suppress("RethrowCaughtException")
private fun synchronize(): Map<LocalConference, List<LocalMessage>> {
val sentMessages = sendMessages()
val newConferencesAndMessages = try {
markConferencesAsRead(
messengerDao.getConferencesToMarkAsRead()
.asSequence()
.plus(sentMessages.map { messengerDao.findConference(it.conferenceId) })
.distinct()
.filterNotNull()
.toList()
)
fetchConferences().associate { conference ->
fetchNewMessages(conference).let { (messages, isFullyLoaded) ->
val isLocallyFullyLoaded = messengerDao.findConference(conference.id.toLong())
?.isFullyLoaded == true
conference.toLocalConference(isLocallyFullyLoaded || isFullyLoaded) to
messages.map { it.toLocalMessage() }.asReversed()
}
}
} catch (error: Throwable) {
messengerDatabase.runInTransaction {
sentMessages.forEach {
messengerDao.deleteMessageToSend(it.id)
}
}
throw error
}
messengerDatabase.runInTransaction {
newConferencesAndMessages.let {
messengerDao.insertConferences(it.keys.toList())
messengerDao.insertMessages(it.values.flatten())
}
sentMessages.forEach {
messengerDao.deleteMessageToSend(it.id)
}
}
return newConferencesAndMessages
}
private fun loadMoreMessages(conferenceId: Long): List<Message> {
val fetchedMessages = fetchMoreMessages(conferenceId)
messengerDatabase.runInTransaction {
messengerDao.insertMessages(fetchedMessages.map { it.toLocalMessage() })
if (fetchedMessages.size < MESSAGES_ON_PAGE) {
messengerDao.markConferenceAsFullyLoaded(conferenceId)
}
}
return fetchedMessages
}
@Suppress("RethrowCaughtException")
private fun sendMessages() = messengerDao.getMessagesToSend().apply {
forEachIndexed { index, (messageId, conferenceId, _, _, message) ->
val result = try {
api.messenger.sendMessage(conferenceId.toString(), message)
.build()
.also { currentCall = it }
.execute()
} catch (error: ProxerException) {
if (error.cause?.stackTrace?.find { it.methodName.contains("read") } != null) {
Timber.w("Error while sending message. Removing it to avoid sending duplicate.")
// The message was sent, but we did not receive a proper api answer due to slow network, return
// non-null to handle it like the non-empty result case.
"error"
} else {
// The message was most likely not sent, but the previous ones are. Delete them to avoid resending.
messengerDatabase.runInTransaction {
for (i in 0 until index) {
messengerDao.deleteMessageToSend(get(i).id)
}
}
throw error
}
}
// Per documentation: The api may return some String in case something went wrong.
if (result != null) {
// Delete all messages we have correctly sent already.
messengerDatabase.runInTransaction {
for (i in 0..index) {
messengerDao.deleteMessageToSend(get(i).id)
}
}
throw ChatSendMessageException(
ProxerException(
ProxerException.ErrorType.SERVER,
ProxerException.ServerErrorType.MESSAGES_INVALID_MESSAGE,
result
),
messageId
)
}
}
}
private fun markConferencesAsRead(conferenceToMarkAsRead: List<LocalConference>) = conferenceToMarkAsRead.forEach {
api.messenger.markConferenceAsRead(it.id.toString())
.build()
.also { call -> currentCall = call }
.execute()
}
private fun fetchConferences(): Collection<Conference> {
val changedConferences = LinkedHashSet<Conference>()
var page = 0
while (true) {
val fetchedConferences = api.messenger.conferences()
.page(page)
.build()
.also { currentCall = it }
.safeExecute()
changedConferences += fetchedConferences.filter {
it != messengerDao.findConference(it.id.toLong())?.toNonLocalConference()
}
if (changedConferences.size / (page + 1) < CONFERENCES_ON_PAGE) {
break
} else {
page++
}
}
return changedConferences
}
private fun fetchNewMessages(conference: Conference): Pair<List<Message>, Boolean> {
val mostRecentLocalMessage = messengerDao.findMostRecentMessageForConference(conference.id.toLong())
return when (val mostRecentMessage = mostRecentLocalMessage?.toNonLocalMessage()) {
null -> fetchForEmptyConference(conference)
else -> fetchForExistingConference(conference, mostRecentMessage)
}
}
private fun fetchForEmptyConference(conference: Conference): Pair<List<Message>, Boolean> {
val newMessages = mutableListOf<Message>()
var unreadAmount = 0
var nextId = "0"
while (unreadAmount < conference.unreadMessageAmount) {
val fetchedMessages = api.messenger.messages()
.conferenceId(conference.id)
.messageId(nextId)
.markAsRead(false)
.build()
.also { currentCall = it }
.safeExecute()
newMessages += fetchedMessages
if (fetchedMessages.size < MESSAGES_ON_PAGE) {
return newMessages to true
} else {
unreadAmount += fetchedMessages.size
nextId = fetchedMessages.first().id
}
}
return newMessages to false
}
private fun fetchForExistingConference(
conference: Conference,
mostRecentMessage: Message
): Pair<List<Message>, Boolean> {
val mostRecentMessageIdBeforeUpdate = mostRecentMessage.id.toLong()
val newMessages = mutableListOf<Message>()
var existingUnreadMessageAmount = messengerDao.getUnreadMessageAmountForConference(
conference.id.toLong(),
conference.lastReadMessageId.toLong()
)
var currentMessage: Message = mostRecentMessage
var nextId = "0"
while (currentMessage.date < conference.date || existingUnreadMessageAmount < conference.unreadMessageAmount) {
val fetchedMessages = api.messenger.messages()
.conferenceId(conference.id)
.messageId(nextId)
.markAsRead(false)
.build()
.also { currentCall = it }
.safeExecute()
newMessages += fetchedMessages
if (fetchedMessages.size < MESSAGES_ON_PAGE) {
return newMessages.filter { it.id.toLong() > mostRecentMessageIdBeforeUpdate } to true
} else {
existingUnreadMessageAmount += fetchedMessages.size
currentMessage = fetchedMessages.last()
nextId = fetchedMessages.first().id
}
}
return newMessages.filter { it.id.toLong() > mostRecentMessageIdBeforeUpdate } to false
}
private fun fetchMoreMessages(conferenceId: Long) = api.messenger.messages()
.conferenceId(conferenceId.toString())
.messageId(messengerDao.findOldestMessageForConference(conferenceId)?.id?.toString() ?: "0")
.markAsRead(false)
.build()
.also { currentCall = it }
.safeExecute()
.asReversed()
private fun showNotification(context: Context) {
val unreadMap = messengerDao.getUnreadConferences().associateWith {
messengerDao
.getMostRecentMessagesForConference(it.id, it.unreadMessageAmount)
.asReversed()
}
MessengerNotifications.showOrUpdate(context, unreadMap)
}
class SynchronizationEvent
private enum class SynchronizationResult {
CHANGES, NO_CHANGES, ERROR
}
}
| gpl-3.0 | 77a59b7cc794a2c695ca8e40cf04f3d9 | 35.60515 | 119 | 0.61074 | 5.370907 | false | false | false | false |
cloverrose/KlickModel | src/test/kotlin/com/github/cloverrose/klickmodel/examples/YandexExample.kt | 1 | 1714 | package com.github.cloverrose.klickmodel.examples
import com.github.cloverrose.klickmodel.evaluations.LogLikelihood
import com.github.cloverrose.klickmodel.evaluations.Perplexity
import com.github.cloverrose.klickmodel.models.ubm.UBM
import com.github.cloverrose.klickmodel.parsers.YandexRelPredChallengeParser
import com.github.cloverrose.klickmodel.utils.Utils
fun main(args: Array<String>) {
val searchSessionsPath = "YandexRelPredChallenge"
val searchSessionNum = 10000
var clickModel = UBM()
val searchSessions = YandexRelPredChallengeParser.parse(searchSessionsPath, searchSessionNum)
val trainTestSplit = (searchSessions.size * 0.75).toInt()
val trainSessions = searchSessions.subList(0, trainTestSplit)
val trainQueries = Utils.getUniqueQueries(trainSessions)
val testSessions = Utils.filterSessions(searchSessions.subList(trainTestSplit, searchSessions.size), trainQueries)
val testQueries = Utils.getUniqueQueries(testSessions)
println("-------------------------------")
println("Training on ${trainSessions.size} search sessions (${trainQueries.size} unique queries).")
println("-------------------------------")
clickModel.train(trainSessions)
println("\tTrained ${clickModel.javaClass.name} click model")
println("-------------------------------")
println("Testing on ${testSessions.size} search sessions (${testQueries.size} unique queries).")
println("-------------------------------")
val loglikelihood = LogLikelihood().evaluate(clickModel, testSessions)
println("\tlog-likelihood: $loglikelihood")
val perplexity = Perplexity().evaluate(clickModel, testSessions)
println("\tperplexity: $perplexity")
} | gpl-3.0 | 1b9ea2b8e1c596e8de157c607d541dc4 | 41.875 | 118 | 0.717036 | 4.20098 | false | true | false | false |
ashdavies/brlo-hopfen | feature/src/main/kotlin/de/brlo/hopfen/feature/inject/ApplicationModule.kt | 1 | 1024 | package de.brlo.hopfen.feature.inject
import android.app.Application
import android.content.SharedPreferences
import android.content.res.Resources
import android.preference.PreferenceManager
import android.view.LayoutInflater
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import de.brlo.hopfen.feature.network.SchedulingStrategy
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
@Module
internal class ApplicationModule {
@Provides
fun inflater(application: Application): LayoutInflater = LayoutInflater.from(application)
@Provides
fun preferences(application: Application): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(application)
@Provides
fun resource(application: Application): Resources = application.resources
@Provides
fun strategy() = SchedulingStrategy(Schedulers.io(), AndroidSchedulers.mainThread())
@Provides
fun gson(): Gson = GsonBuilder().create()
}
| apache-2.0 | 086dcceab89dcf0ab0a90bcf290c3c0c | 30.030303 | 123 | 0.826172 | 4.923077 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/incoming/VideoMuteNode.kt | 1 | 818 | package org.jitsi.nlj.transform.node.incoming
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.rtp.VideoRtpPacket
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.transform.node.ObserverNode
class VideoMuteNode : ObserverNode("Video mute node") {
private var numMutedPackets = 0
var forceMute: Boolean = false
override fun observe(packetInfo: PacketInfo) {
if (packetInfo.packet !is VideoRtpPacket) return
if (this.forceMute) {
packetInfo.shouldDiscard = true
numMutedPackets++
}
}
override fun getNodeStats(): NodeStatsBlock = super.getNodeStats().apply {
addNumber("num_video_packets_discarded", numMutedPackets)
addBoolean("force_mute", forceMute)
}
override fun trace(f: () -> Unit) = f.invoke()
}
| apache-2.0 | 382ac6ff57f3346c3526419a0775b658 | 29.296296 | 78 | 0.695599 | 4.049505 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/playground/PlaygroundKComponent.kt | 1 | 1518 | /*
* Copyright (c) Meta Platforms, Inc. and 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.samples.litho.kotlin.playground
import android.graphics.Typeface.ITALIC
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.core.padding
import com.facebook.litho.dp
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.sp
import com.facebook.litho.useState
import com.facebook.litho.view.onClick
class PlaygroundKComponent : KComponent() {
override fun ComponentScope.render(): Component {
val counter = useState { 1 }
return Column(style = Style.padding(16.dp).onClick { counter.update { value -> value + 1 } }) {
child(Text(text = "Hello, Kotlin World!", textSize = 20.sp))
child(Text(text = "with ${"❤️".repeat(counter.value)} from London", textStyle = ITALIC))
}
}
}
| apache-2.0 | ebd947e22fab350e99a4cfa5200ed0b5 | 35.926829 | 99 | 0.747028 | 3.892031 | false | false | false | false |
camsteffen/polite | src/test/java/me/camsteffen/polite/state/PoliteStateManagerTest.kt | 1 | 8324 | package me.camsteffen.polite.state
import io.mockk.Called
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import io.mockk.verifyAll
import me.camsteffen.polite.db.PoliteStateDao
import me.camsteffen.polite.db.RuleDao
import me.camsteffen.polite.defaultAppTimingConfig
import me.camsteffen.polite.settings.AppPreferences
import me.camsteffen.polite.util.AppPermissionChecker
import me.camsteffen.polite.util.RuleEvent
import me.camsteffen.polite.util.RuleEventFinders
import me.camsteffen.polite.util.TestObjects
import org.junit.Before
import org.junit.Test
import org.threeten.bp.Clock
import org.threeten.bp.Duration
import org.threeten.bp.Instant
import org.threeten.bp.ZoneId
class PoliteStateManagerTest {
private lateinit var politeStateManager: PoliteStateManager
private val permissionChecker: AppPermissionChecker = mockk()
private val politeModeController: PoliteModeController = mockk(relaxUnitFun = true)
private val preferences: AppPreferences = mockk()
private val refreshScheduler: RefreshScheduler = mockk(relaxUnitFun = true)
private val ruleDao: RuleDao = mockk()
private val ruleEventFinders: RuleEventFinders = mockk()
private val stateDao: PoliteStateDao = mockk(relaxUnitFun = true)
private val timingConfig = defaultAppTimingConfig
private val now = Instant.now()
@Before
fun setUp() {
politeStateManager = PoliteStateManager(
clock = Clock.fixed(now, ZoneId.systemDefault()),
permissionChecker = permissionChecker,
politeModeController = politeModeController,
preferences = preferences,
refreshScheduler = refreshScheduler,
ruleDao = ruleDao,
ruleEventFinders = ruleEventFinders,
stateDao = stateDao,
timingConfig = timingConfig
)
every { ruleDao.getEnabledCalendarRulesExist() } returns false
}
@Test
fun `refresh polite disabled`() {
refreshGiven(
politeEnabled = false,
hasNotificationPolicyAccess = true
)
politeStateManager.refresh()
verifyAll {
ruleEventFinders wasNot Called
politeModeController.setCurrentEvent(null)
refreshScheduler.cancelAll()
}
}
@Test
fun `no rule events`() {
refreshGiven()
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(null)
refreshScheduler.scheduleRefresh()
}
}
@Test
fun `one current event`() {
val eventEnd = now + Duration.ofHours(1)
val ruleEvent = TestObjects.calendarRuleEvent(
begin = now,
end = eventEnd
)
refreshGiven(
events = listOf(ruleEvent)
)
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(ruleEvent)
refreshScheduler.scheduleRefresh(eventEnd)
}
}
@Test
fun `silent event overlaps vibrate event`() {
val currentEvent = TestObjects.calendarRuleEvent(
begin = now - Duration.ofMinutes(30),
end = now + Duration.ofMinutes(30),
vibrate = false
)
val nextEvent = TestObjects.calendarRuleEvent(
begin = now,
// ends before the active event but should not affect refresh time
end = now + Duration.ofMinutes(20),
vibrate = true
)
refreshGiven(
events = listOf(currentEvent, nextEvent)
)
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(currentEvent)
refreshScheduler.scheduleRefresh(now + Duration.ofMinutes(30))
}
}
@Test
fun `vibrate event overlaps silent event`() {
val currentEvent = TestObjects.calendarRuleEvent(
begin = now - Duration.ofMinutes(30),
end = now + Duration.ofMinutes(30),
vibrate = true
)
val nextEvent = TestObjects.calendarRuleEvent(
begin = now,
end = now + Duration.ofMinutes(20),
vibrate = false
)
refreshGiven(
events = listOf(currentEvent, nextEvent)
)
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(nextEvent)
refreshScheduler.scheduleRefresh(now + Duration.ofMinutes(20))
}
}
@Test
fun `future event only`() {
refreshGiven(
events = listOf(TestObjects.calendarRuleEvent(begin = now + Duration.ofHours(1)))
)
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(null)
refreshScheduler.scheduleRefresh(now + Duration.ofHours(1))
}
}
@Test
fun `current event ends before future event`() {
val currentEvent = TestObjects.calendarRuleEvent(
begin = now,
end = now + Duration.ofMinutes(10),
vibrate = true
)
refreshGiven(
events = listOf(
currentEvent,
TestObjects.calendarRuleEvent(
begin = now + Duration.ofMinutes(20),
end = now + Duration.ofMinutes(30),
// higher precedence should not matter
vibrate = false
)
)
)
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(currentEvent)
refreshScheduler.scheduleRefresh(now + Duration.ofMinutes(10))
}
}
@Test
fun `future silent event begins before current silent event ends`() {
val activeEvent = TestObjects.calendarRuleEvent(
begin = now - Duration.ofMinutes(10),
end = now + Duration.ofMinutes(20),
vibrate = false
)
refreshGiven(
events = listOf(
activeEvent,
TestObjects.calendarRuleEvent(
begin = now + Duration.ofMinutes(10),
end = now + Duration.ofMinutes(30),
vibrate = false
)
)
)
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(activeEvent)
refreshScheduler.scheduleRefresh(now + Duration.ofMinutes(10))
}
}
@Test
fun `future vibrate event begins before current silent event ends`() {
val currentEvent = TestObjects.calendarRuleEvent(
begin = now - Duration.ofMinutes(10),
end = now + Duration.ofMinutes(20),
vibrate = false
)
refreshGiven(
events = listOf(
currentEvent,
TestObjects.calendarRuleEvent(
begin = now + Duration.ofMinutes(10),
end = now + Duration.ofMinutes(30),
vibrate = true
)
)
)
politeStateManager.refresh()
verify {
eventsInRange()
politeModeController.setCurrentEvent(currentEvent)
refreshScheduler.scheduleRefresh(now + Duration.ofMinutes(20))
}
}
private fun eventsInRange() {
ruleEventFinders.all.eventsInRange(
now + timingConfig.ruleEventBoundaryTolerance,
now + timingConfig.lookahead
)
}
private fun refreshGiven(
events: List<RuleEvent> = emptyList(),
politeEnabled: Boolean = true,
hasNotificationPolicyAccess: Boolean = true
) {
every { preferences.enable } returns politeEnabled
every { permissionChecker.checkNotificationPolicyAccess() } returns
hasNotificationPolicyAccess
every {
ruleEventFinders.all.eventsInRange(
now + timingConfig.ruleEventBoundaryTolerance,
now + timingConfig.lookahead
)
} returns events.asSequence()
}
}
| mpl-2.0 | dc3c4cdfaff183b69c2a9d0c2abd5d92 | 29.379562 | 93 | 0.599231 | 5.215539 | false | true | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/renderers/html/htmlFormatingUtils.kt | 1 | 2022 | package org.jetbrains.dokka.base.renderers.html
import kotlinx.html.FlowContent
import kotlinx.html.span
fun FlowContent.buildTextBreakableAfterCapitalLetters(name: String, hasLastElement: Boolean = false) {
if (name.contains(" ")) {
val withOutSpaces = name.split(" ")
withOutSpaces.dropLast(1).forEach {
buildBreakableText(it)
+" "
}
buildBreakableText(withOutSpaces.last())
} else {
val content = name.replace(Regex("(?<=[a-z])([A-Z])"), " $1").split(" ")
joinToHtml(content, hasLastElement) {
it
}
}
}
fun FlowContent.buildBreakableDotSeparatedHtml(name: String) {
val phrases = name.split(".")
phrases.forEachIndexed { i, e ->
val elementWithOptionalDot = e.takeIf { i == phrases.lastIndex } ?: "$e."
if (e.length > 10) {
buildTextBreakableAfterCapitalLetters(elementWithOptionalDot, hasLastElement = i == phrases.lastIndex)
} else {
buildBreakableHtmlElement(elementWithOptionalDot, i == phrases.lastIndex)
}
}
}
private fun FlowContent.joinToHtml(elements: List<String>, hasLastElement: Boolean = true, onEach: (String) -> String) {
elements.dropLast(1).forEach {
buildBreakableHtmlElement(onEach(it))
}
elements.takeIf { it.isNotEmpty() && it.last().isNotEmpty() }?.let {
if (hasLastElement) {
span {
buildBreakableHtmlElement(it.last(), last = true)
}
} else {
buildBreakableHtmlElement(it.last(), last = false)
}
}
}
private fun FlowContent.buildBreakableHtmlElement(element: String, last: Boolean = false) {
element.takeIf { it.isNotBlank() }?.let {
span {
+it
}
}
if (!last) {
wbr { }
}
}
fun FlowContent.buildBreakableText(name: String) =
if (name.contains(".")) buildBreakableDotSeparatedHtml(name)
else buildTextBreakableAfterCapitalLetters(name, hasLastElement = true) | apache-2.0 | d7716e9272500f1d5877c75494d02fc9 | 31.629032 | 120 | 0.621167 | 4.118126 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/modules/Spam.kt | 1 | 12351 | package me.mrkirby153.KirBot.modules
import com.mrkirby153.bfs.model.Model
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.database.models.guild.GuildMessage
import me.mrkirby153.KirBot.event.Subscribe
import me.mrkirby153.KirBot.infraction.Infractions
import me.mrkirby153.KirBot.logger.LogEvent
import me.mrkirby153.KirBot.module.Module
import me.mrkirby153.KirBot.utils.Bucket
import me.mrkirby153.KirBot.utils.EMOJI_RE
import me.mrkirby153.KirBot.utils.checkPermissions
import me.mrkirby153.KirBot.utils.getClearance
import me.mrkirby153.KirBot.utils.kirbotGuild
import me.mrkirby153.KirBot.utils.logName
import me.mrkirby153.KirBot.utils.settings.GuildSettings
import me.mrkirby153.KirBot.utils.toTypedArray
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.MessageChannel
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import org.json.JSONArray
import org.json.JSONObject
import java.sql.Timestamp
import java.time.Instant
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class Spam @Inject constructor(private val redis: Redis, private val infractions: Infractions) : Module("spam") {
private val locks = mutableMapOf<String, Semaphore>()
init {
dependencies.add(Redis::class.java)
}
override fun onLoad() {
}
@Subscribe
fun onGuildMessageReceived(event: GuildMessageReceivedEvent) {
if (event.author.id == event.guild.selfMember.user.id)
return // Ignore ourselves
if (event.guild.id !in locks.keys)
locks[event.guild.id] = Semaphore(1)
locks[event.guild.id]!!.acquire()
val rules = getEffectiveRules(event.guild, event.author)
try {
rules.forEach {
checkMessage(event.message, it)
}
} catch (e: ViolationException) {
violate(e)
}
locks[event.guild.id]!!.release()
}
private fun checkMessage(message: Message, level: Int) {
fun checkBucket(check: String, friendlyText: String, amount: Int) {
if (amount == 0)
return
val bucket = getBucket(check, message.guild.id, level) ?: return
if (bucket.check(message.author.id, amount)) {
throw ViolationException(check.toUpperCase(), "$friendlyText (${bucket.count(
message.author.id)}/${bucket.size(message.author.id)}s)", message.author,
level, message.guild, message.channel)
}
}
checkBucket("max_messages", "Too many messages", 1)
checkBucket("max_newlines", "Too many newlines",
message.contentRaw.split(Regex("\\r\\n|\\r|\\n")).count())
checkBucket("max_mentions", "Too many mentions", {
val pattern = Regex("<@[!&]?\\d+>")
pattern.findAll(message.contentRaw).count()
}.invoke())
checkBucket("max_links", "Too many links", {
val pattern = Regex("https?://")
pattern.findAll(message.contentRaw).count()
}.invoke())
checkBucket("max_emoji", "Too many emoji", {
EMOJI_RE.findAll(message.contentRaw).count()
}.invoke())
checkBucket("max_uppercase", "Too many uppercase", {
val pattern = Regex("[A-Z]")
pattern.findAll(message.contentRaw).count()
}.invoke())
checkBucket("max_attachments", "Too many attachments", message.attachments.size)
checkDuplicates(message, level)
}
private fun checkDuplicates(message: Message, level: Int) {
val rule = getRule(message.guild.id, level) ?: return
val dupeSettings = rule.optJSONObject("max_duplicates") ?: return
val count = dupeSettings.getInt("count")
val period = dupeSettings.getInt("period")
redis.getConnection().use { jedis ->
val key = "spam:duplicates:${message.guild.id}:${message.author.id}:${message.contentRaw}"
val n = jedis.incr(key)
if (n == 1L) {
jedis.expire(key, period)
}
if (n > count) {
throw ViolationException("MAX_DUPLICATES", "Too many duplicates ($n)",
message.author, level, message.guild, message.channel)
}
}
}
private fun violate(violation: ViolationException) {
redis.getConnection().use { con ->
val key = "lv:${violation.guild.id}:${violation.user.id}"
val last = (con.get(key) ?: "0").toLong()
con.setex(key, 60, System.currentTimeMillis().toString())
if (last + (10 * 1000) < System.currentTimeMillis()) {
val settings = getSettings(violation.guild.id)
val rule = getRule(violation.guild.id, violation.level)
val punishment = rule?.optString("punishment", settings.optString("punishment"))
?: "NONE"
val duration = rule?.optLong("punishment_duration",
settings.optLong("punishment_duration", -1)) ?: -1
// Modlog
violation.guild.kirbotGuild.logManager.genericLog(LogEvent.SPAM_VIOLATE,
":helmet_with_cross:",
"${violation.user.logName} Has violated ${violation.type} in <#${violation.channel.id}>: ${violation.message}")
val reason = "Spam detected: ${violation.type} in #${violation.channel.name}: ${violation.msg}"
when (punishment.toUpperCase()) {
"NONE" -> {
// Do nothing
}
"MUTE" -> {
infractions.mute(violation.user.id, violation.guild,
violation.guild.selfMember.user.id,
reason)
}
"KICK" -> {
infractions.kick(violation.user.id, violation.guild,
violation.guild.selfMember.user.id,
reason)
}
"BAN" -> {
infractions.ban(violation.user.id, violation.guild,
violation.guild.selfMember.user.id,
reason)
}
"TEMPMUTE" -> {
infractions.tempMute(violation.user.id, violation.guild,
violation.guild.selfMember.user.id,
duration, TimeUnit.SECONDS, reason)
}
"TEMPBAN" -> {
infractions.tempban(violation.user.id, violation.guild,
violation.guild.selfMember.user.id, duration, TimeUnit.SECONDS,
reason)
}
else -> {
Bot.LOG.warn("Unknown punishment $punishment on guild ${violation.guild}")
violation.guild.kirbotGuild.logManager.genericLog(LogEvent.SPAM_VIOLATE,
":warning:",
"Unknown punishment `${punishment.toUpperCase()}`. No action has been taken")
}
}
if (settings.has("clean_count") || settings.has("clean_duration") || rule?.has(
"clean_count") == true || rule?.has("clean_duration") == true) {
Bot.LOG.debug("Performing clean")
val cleanCount = rule?.optString("clean_count",
settings.optString("clean_count", null))
val cleanDuration = rule?.optString("clean_duration",
settings.optString("clean_duration", null))
Thread.sleep(
250) // Wait to make sure in-flight stuff has been committed to the db
val messageQuery = Model.query(GuildMessage::class.java).where("author",
violation.user.id).where("server_id", violation.guild.id).where(
"deleted", false)
if (cleanCount != null) {
messageQuery.limit(cleanCount.toLong())
}
if (cleanDuration != null) {
val instant = Instant.now().minusSeconds(cleanDuration.toLong())
val after = Timestamp(instant.toEpochMilli())
messageQuery.where("created_at", ">", after)
}
val messages = messageQuery.get()
Bot.LOG.debug("Deleting ${messages.size} in ${violation.guild}")
val messageByChannel = mutableMapOf<String, MutableList<String>>()
messages.forEach { m ->
if (messageByChannel[m.channel] == null)
messageByChannel[m.channel] = mutableListOf()
messageByChannel[m.channel]?.add(m.id)
}
messageByChannel.forEach { chan, msgs ->
val channel = violation.guild.getTextChannelById(chan)
if (channel == null) {
Bot.LOG.debug("No channel found with $chan")
return@forEach
}
// Check for delete perms
if (!channel.checkPermissions(Permission.MESSAGE_MANAGE)) {
Bot.LOG.debug("No permissions in $channel")
return@forEach
}
val mutableMsgs = msgs.toMutableList()
while (mutableMsgs.isNotEmpty()) {
val list = mutableMsgs.subList(0, Math.min(100, mutableMsgs.size))
if (list.size == 1) {
channel.deleteMessageById(list.first()).queue()
} else {
channel.deleteMessagesByIds(list).queue()
}
mutableMsgs.removeAll(list)
}
}
}
} else {
// Ignore
Bot.LOG.debug(
"Last violation for ${violation.user} was < 10 seconds ago. Ignoring")
}
}
}
private fun getBucket(rule: String, guild: String, level: Int): Bucket? {
val ruleJson = getRule(guild, level)?.optJSONObject(rule) ?: return null
if (!ruleJson.has("count") || !ruleJson.has("period"))
return null
return Bucket(redis, "spam:$rule:$guild:%s", ruleJson.getInt("count"),
ruleJson.getInt("period") * 1000)
}
private fun getSettings(guild: String): JSONObject {
return GuildSettings.spamSettings.get(guild)
}
private fun getRule(guild: String, level: Int): JSONObject? {
val rawRules = getSettings(guild).optJSONArray("rules") ?: JSONArray()
return rawRules.toTypedArray(JSONObject::class.java).firstOrNull {
it.optInt("_level", -1) == level
}
}
private fun getEffectiveRules(guild: Guild, user: User): List<Int> {
val clearance = user.getClearance(guild)
val settings = getSettings(guild.id)
val rawRules = settings.optJSONArray("rules") ?: JSONArray()
return rawRules.toTypedArray(JSONObject::class.java).map {
it.optInt("_level", -1)
}.filter { it >= clearance }
}
private class ViolationException(val type: String, val msg: String, val user: User,
val level: Int, val guild: Guild,
val channel: MessageChannel) :
Exception(msg) {
override fun toString(): String {
return "ViolationException(type='$type', msg='$msg', user=$user, level=$level, guild=$guild, channel=$channel)"
}
}
} | mit | 97a87b1cb56ab3a31f956ce825d7ed39 | 44.918216 | 135 | 0.538661 | 4.714122 | false | false | false | false |
outadoc/Twistoast-android | twistoast/src/main/kotlin/fr/outadev/twistoast/FragmentAbout.kt | 1 | 2798 | /*
* Twistoast - FragmentAbout.kt
* Copyright (C) 2013-2016 Baptiste Candellier
*
* Twistoast 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.
*
* Twistoast is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.outadev.twistoast
import android.content.pm.PackageManager.NameNotFoundException
import android.os.Bundle
import android.preference.Preference
import android.preference.PreferenceFragment
import android.widget.Toast
/**
* A preferences fragment for the preferences of the app.
*
* @author outadoc
*/
class FragmentAbout : PreferenceFragment() {
private var easterEggCount = 5
private var easterEggToast: Toast? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val config = ConfigurationManager()
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.about_prefs)
findPreference("version").onPreferenceClickListener = Preference.OnPreferenceClickListener {
easterEggCount--
easterEggToast?.cancel()
if (config.adsAreRemoved) {
// Already disabled the ads
easterEggToast = toast(R.string.prefs_ads_already_disabled)
} else if (easterEggCount == 0) {
// Ready to disable the ads
config.adsAreRemoved = true
easterEggToast = toast(R.string.prefs_ads_disabled)
} else if (easterEggCount <= 3) {
// Decrement teh counter
easterEggToast = toast(activity.getString(R.string.prefs_ads_step_count, easterEggCount))
}
true
}
}
fun toast(resId: Int) : Toast? {
return toast(activity.getString(resId))
}
fun toast(str: String) : Toast? {
val t = Toast.makeText(activity, str, Toast.LENGTH_SHORT)
t.show()
return t
}
override fun onResume() {
super.onResume()
try {
val info = activity.packageManager.getPackageInfo(activity.packageName, 0)
findPreference("version").summary = getString(R.string.app_name) + " v" + info.versionName
} catch (e1: NameNotFoundException) {
e1.printStackTrace()
}
}
}
| gpl-3.0 | 859971512d536aca33fbf2d469588f9f | 30.795455 | 105 | 0.6594 | 4.448331 | false | false | false | false |
MaisonWan/AppFileExplorer | FileExplorer/src/main/java/com/domker/app/explorer/file/FileLoader.kt | 1 | 1704 | package com.domker.app.explorer.file
import android.os.AsyncTask
import java.io.File
/**
* Created by wanlipeng on 2017/9/2.
*/
class FileLoader(private val callback: FileLoaderCallback) : AsyncTask<String, Void, List<FileInfo>>() {
private val fileManager: FileManager = FileManager()
/**
* 文件排序
*/
var fileSortType: String = "1"
/**
* 当前分类的根目录
*/
var rootPath: String = "/"
override fun doInBackground(vararg args: String?): List<FileInfo> {
val path = args[0] as String
var fileList = fileManager.getFileList(path)
fileList = when (fileSortType) {
"1" -> fileList.sortedBy { it.fileName }
"2" -> fileList.sortedBy { it.file.length() }
"3" -> fileList.sortedBy { it.file.lastModified() }
"4" -> fileList.sortedBy { it.isFile() }
else -> fileList
}
if (path == "/") {
return fileList
}
val arrayList = ArrayList<FileInfo>()
if (path != rootPath) {
arrayList.add(0, createParentDirFileInfo())
}
arrayList.addAll(fileList)
return arrayList
}
/**
* 创建跳转会上一层目录
*/
private fun createParentDirFileInfo(): FileInfo {
val info = FileInfo(File(".."))
info.isJumpParentPath = true
return info
}
override fun onPostExecute(result: List<FileInfo>?) {
super.onPostExecute(result)
callback?.onReceiveResult(result!!)
}
interface FileLoaderCallback {
/**
* 接受到结果的回调
*/
fun onReceiveResult(result: List<FileInfo>)
}
} | apache-2.0 | 3d31f608f900e646f7e1df746e3dbd47 | 25.111111 | 104 | 0.572993 | 4.27013 | false | false | false | false |
venator85/log | log/src/main/java/eu/alessiobianchi/log/Log.kt | 1 | 5135 | @file:JvmName("Log")
@file:Suppress("unused")
package eu.alessiobianchi.log
import android.os.Build
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
object Log {
private const val MAX_TAG_LENGTH = 23
private const val MSG_FORMAT = "%s [%s][%s]: %s\n"
@JvmStatic
private val TIMESTAMP_FORMAT by lazy(LazyThreadSafetyMode.NONE) {
SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
}
@JvmStatic
val lock = ReentrantLock()
@JvmStatic
var enabled = true
@JvmName("isEnabled") get
@JvmStatic
var impl: ILogger = AndroidLogcat()
@JvmStatic
var logFile: File? = null
private set
get() {
lock.withLock {
if (writer != null) {
try {
writer!!.flush()
} catch (e: IOException) {
logcat(android.util.Log.ERROR, "Log", "Error flushing log file")
logcat(android.util.Log.ERROR, "Log", e.stackTraceToString())
}
}
return logFile
}
}
@JvmStatic
private var writer: BufferedWriter? = null
@JvmStatic
fun init(enableLogcat: Boolean, logFile: File?) {
enabled = enableLogcat
this.logFile = logFile
if (logFile != null) {
lock.withLock {
if (writer != null) {
try {
writer!!.close()
} catch (ignore: IOException) {
}
}
writer = try {
BufferedWriter(FileWriter(logFile, false))
} catch (e: IOException) {
throw RuntimeException(e.message, e)
}
}
}
}
@JvmStatic
inline fun withLock(crossinline block: () -> Unit) {
lock.withLock {
block()
}
}
@JvmStatic
@JvmOverloads
fun v(msg: String?, t: Throwable?, tag: Any? = null) = log(android.util.Log.VERBOSE, getTag(tag), msg, t)
@JvmStatic
@JvmOverloads
fun d(msg: String?, t: Throwable?, tag: Any? = null) = log(android.util.Log.DEBUG, getTag(tag), msg, t)
@JvmStatic
@JvmOverloads
fun i(msg: String?, t: Throwable?, tag: Any? = null) = log(android.util.Log.INFO, getTag(tag), msg, t)
@JvmStatic
@JvmOverloads
fun w(msg: String?, t: Throwable?, tag: Any? = null) = log(android.util.Log.WARN, getTag(tag), msg, t)
@JvmStatic
@JvmOverloads
fun e(msg: String?, t: Throwable?, tag: Any? = null) = log(android.util.Log.ERROR, getTag(tag), msg, t)
@JvmStatic
@JvmOverloads
fun v(msg: String?, tag: Any? = null) = log(android.util.Log.VERBOSE, getTag(tag), msg, null)
@JvmStatic
@JvmOverloads
fun d(msg: String?, tag: Any? = null) = log(android.util.Log.DEBUG, getTag(tag), msg, null)
@JvmStatic
@JvmOverloads
fun i(msg: String?, tag: Any? = null) = log(android.util.Log.INFO, getTag(tag), msg, null)
@JvmStatic
@JvmOverloads
fun w(msg: String?, tag: Any? = null) = log(android.util.Log.WARN, getTag(tag), msg, null)
@JvmStatic
@JvmOverloads
fun e(msg: String?, tag: Any? = null) = log(android.util.Log.ERROR, getTag(tag), msg, null)
@JvmStatic
private fun log(level: Int, tag: String, message: String?, t: Throwable?) {
val msg = message ?: "null"
val stacktrace = t?.stackTraceToString()
if (stacktrace == null) {
// fast path without single locking
logcat(level, tag, msg)
} else {
lock.withLock {
logcat(level, tag, msg)
logcat(level, tag, stacktrace)
}
}
if (writer != null) {
lock.withLock {
logToFile(level, tag, msg)
if (stacktrace != null) logToFile(level, tag, stacktrace)
}
}
}
@JvmStatic
private fun logcat(level: Int, tag: String, msg: String) {
impl.doLog(lock, level, msg, tag)
}
@JvmStatic
private fun logToFile(level: Int, tag: String, msg: String) {
try {
val sLevel = logLevelToString(level)
writer!!.write(String.format(Locale.US, MSG_FORMAT, TIMESTAMP_FORMAT.format(Date()), sLevel, tag, msg))
} catch (e: IOException) {
logcat(android.util.Log.ERROR, "Log", "Error writing log to file")
logcat(android.util.Log.ERROR, "Log", e.stackTraceToString())
}
}
@JvmStatic
fun logLevelToString(level: Int) = when (level) {
android.util.Log.VERBOSE -> "V"
android.util.Log.DEBUG -> "D"
android.util.Log.INFO -> "I"
android.util.Log.WARN -> "W"
android.util.Log.ERROR -> "E"
android.util.Log.ASSERT -> "A"
else -> level.toString()
}
@JvmStatic
fun getTag(obj: Any?): String {
val tag = if (obj != null) {
if (obj is CharSequence) {
if (obj.isEmpty()) null else obj.toString()
} else {
val c: Class<*> = if (obj is Class<*>) obj else obj.javaClass
when {
c.name == "kotlinx.coroutines.DispatchedCoroutine" -> null
c.isAnonymousClass -> c.name.substringAfterLast('.')
else -> c.simpleName
}
}
} else {
null
} ?: createTag()
// Tag length limit was removed in API 24.
return if (tag.length <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
tag
} else {
tag.substring(0, MAX_TAG_LENGTH)
}
}
private fun createTag(): String {
return Throwable().stackTrace
.first { it.className !in fqcnIgnore }
.className
.substringAfterLast('.')
.substringBefore('$')
}
private val fqcnIgnore = listOf(
Log::class.java.name,
)
}
| apache-2.0 | e2440348dbcb9c2138416cb645f9e498 | 23.6875 | 106 | 0.655307 | 3.063842 | false | false | false | false |
http4k/http4k | src/docs/guide/reference/digest/example_provider_digest.kt | 1 | 927 | package guide.reference.digest
import org.http4k.core.Method.GET
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.then
import org.http4k.filter.DigestAuth
import org.http4k.filter.ServerFilters
import org.http4k.routing.bind
import org.http4k.routing.path
import org.http4k.routing.routes
import org.http4k.server.SunHttp
import org.http4k.server.asServer
fun main() {
val users = mapOf(
"admin" to "password",
"user" to "hunter2"
)
val routes = routes(
"/hello/{name}" bind GET to { request ->
val name = request.path("name")
Response(OK).body("Hello $name")
}
)
val authFilter = ServerFilters.DigestAuth(
realm = "http4k",
passwordLookup = { username -> users[username] })
authFilter
.then(routes)
.asServer(SunHttp(8000))
.start()
.block()
}
| apache-2.0 | 02ba156ab9889b405ce287de751e46d1 | 24.054054 | 57 | 0.6548 | 3.47191 | false | false | false | false |
jpmoreto/play-with-robots | android/testsApp/src/test/java/jpm/lib/TestKDTreeDSpaceFree2.kt | 1 | 5649 | package jpm.lib
/**
* Created by jm on 18/03/17.
*/
import it.unimi.dsi.fastutil.objects.ObjectAVLTreeSet
import javafx.application.Application
import javafx.scene.canvas.GraphicsContext
import javafx.scene.paint.Color
import javafx.stage.Stage
import jpm.lib.maps.*
import jpm.lib.math.*
import org.junit.Test
import java.util.*
class TestKDTreeDSpaceFree2 {
@Test
fun test() {
try {
KDTreeDSpaceFree2().run(arrayOf<String>())
} catch (e: Throwable) {
// ignore
}
}
}
class KDTreeDSpaceFree2 : TestKDTreeDBase, Application() {
override val iterations = 200
override val deltaX = 100
override val deltaY = 100
override val rndX = 700
override val rndY = 500
override val dimMin = 4.0
override val initialDim = Math.round(Math.pow(2.0, 10.0).toFloat())
override val centerPointD = DoubleVector2D(500.0, 500.0)
val occupiedThreshold = 0.7
val minOccup = 0.49999999
val maxOccup =0.50000001
val robotCircleRadius = 0.07 // BW / 2
val bodyWidth = 2 * robotCircleRadius // BW
val wheelBodyDistance = 0.005 //
val wheelWidth = 0.026 // Ww
val robotTotalWidth = (bodyWidth + 2 * (wheelBodyDistance + wheelWidth)) * 100
val halfRobotTotalWidth = robotTotalWidth / 2.0
override fun start(primaryStage: Stage) {
startDraw(primaryStage)
}
fun run(args: Array<String>) {
launch(*args)
}
override fun drawShapesKDTreeD(gc: GraphicsContext) {
println("robotTotalWidth = $robotTotalWidth")
KDTreeD.dimMin = dimMin
val tree = KDTreeD.Node(centerPointD, KDTreeAbs.SplitAxis.XAxis, initialDim.toDouble())
val rndX_a = Random(43)
val rndY_a = Random(101)
setOccupiedD(tree, rndX_a, rndY_a)
setGcColor(gc, Color.RED, Color.RED, 1.0)
drawKDTreeD(gc,tree,occupiedThreshold)
val treeWithRobotWith = KDTreeD.Node(centerPointD, KDTreeAbs.SplitAxis.XAxis, initialDim.toDouble())
val t_1 = System.currentTimeMillis()
val steep = KDTreeD.dimMin
/*
tree.visitAll { t ->
if (t.isLeaf && t.occupied() > occupiedThreshold) {
val xMin = t.center.x - t.getDimVector().x - halfRobotTotalWidth
val xMax = t.center.x + t.getDimVector().x + halfRobotTotalWidth
val yMin = t.center.y - t.getDimVector().y - halfRobotTotalWidth
val yMax = t.center.y + t.getDimVector().y + halfRobotTotalWidth
var x = xMin
while( x <= xMax) {
treeWithRobotWith.setOccupied(DoubleVector2D(x,yMin))
treeWithRobotWith.setOccupied(DoubleVector2D(x,yMax))
x += steep
}
var y = yMin
while( y <= yMax) {
treeWithRobotWith.setOccupied(DoubleVector2D(xMin,y))
treeWithRobotWith.setOccupied(DoubleVector2D(xMax,y))
y += steep
}
}
}
*/
tree.visitAll { t ->
if (t.isLeaf && t.occupied() > occupiedThreshold) {
val xMin = t.center.x - t.getDimVector().x - halfRobotTotalWidth
val xMax = t.center.x + t.getDimVector().x + halfRobotTotalWidth
val yMin = t.center.y - t.getDimVector().y - halfRobotTotalWidth
val yMax = t.center.y + t.getDimVector().y + halfRobotTotalWidth
var x = xMin
while( x <= xMax) {
var y = yMin
while( y <= yMax) {
treeWithRobotWith.setOccupied(DoubleVector2D(x, y))
treeWithRobotWith.setOccupied(DoubleVector2D(x, y))
y += steep
}
x += steep
}
}
}
setOccupiedDBound(treeWithRobotWith)
val red = Color(Color.ROSYBROWN.red, Color.ROSYBROWN.green, Color.ROSYBROWN.blue, 0.5)
setGcColor(gc,red,red,1.0)
drawKDTreeD(gc,treeWithRobotWith,occupiedThreshold)
val blue = Color(Color.BLUE.red, Color.BLUE.green, Color.BLUE.blue, 0.7)
setGcColor(gc,blue,blue,1.0)
val result = ObjectAVLTreeSet<KDTreeD.Node>(KDTreeD.CompareNodesX)
val t0 = System.currentTimeMillis()
treeWithRobotWith.visitAll { t ->
if(t.isLeaf) {
val occup = t.occupied()
if(minOccup <= occup && occup <= maxOccup) {
if(deltaX <= t.left() && t.right() <= deltaX + rndX && deltaY <= t.bottom() && t.top() <= deltaY + rndY)
result.add(t)
}
}
}
val t1 = System.currentTimeMillis()
val toRectangles = KDTreeD.fromNodeToRectangle(result)
val t2 = System.currentTimeMillis()
val compactRectangles = compactRectangles(toRectangles)
val t3 = System.currentTimeMillis()
compactRectangles.forEach { r ->
gc.strokeRect(r.p1.x, r.p1.y, r.width(), r.height())
//println("visit($r)")
}
println("time to build tree with robot = ${t0-t_1} ms")
println("time to build initial free rectangle set = ${t1-t0} ms")
println("time to from node to rectangles = ${t2-t1} ms")
println("time to compact rectangle set = ${t3-t2} ms")
}
} | mit | a8e4bc1622b220336ed7454914e8c44f | 32.235294 | 124 | 0.553903 | 3.909343 | false | false | false | false |
BoD/android-wear-color-picker | library/src/main/kotlin/org/jraf/android/androidwearcolorpicker/ColorAdapter.kt | 1 | 9372 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2015-present Benoit 'BoD' Lubek ([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 org.jraf.android.androidwearcolorpicker
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import org.jraf.android.androidwearcolorpicker.ColorAdapter.Companion.HUE_COUNT
import org.jraf.android.androidwearcolorpicker.ColorAdapter.Companion.SATURATION_COUNT
import org.jraf.android.androidwearcolorpicker.databinding.AwcpColorPickItemBinding
import kotlin.math.ceil
import kotlin.math.cos
class ColorAdapter(
context: Context,
private val colors: IntArray?,
private val colorPickCallbacks: (Int, ImageView) -> Unit
) :
RecyclerView.Adapter<ColorAdapter.ViewHolder>() {
companion object {
const val HUE_COUNT = 36
const val SATURATION_COUNT = 3
const val VALUE_COUNT = 4
private const val VALUE_MIN = .15F
/**
* Turns a wrapped adapter position into a hue-saturation pair.
*
* If you want to use this as a full HSV triple, use [floatArrayOf] and the spread operator.
*
* @param position adapter position of the color row, mod ([HUE_COUNT] * [SATURATION_COUNT] + 1)
* @return a [FloatArray] with two elements: the hue and saturation values
*/
private fun positionToHS(position: Int) = if (position == 0) floatArrayOf(0f, 0f) else floatArrayOf(
(((position - 1) / SATURATION_COUNT) / HUE_COUNT.toFloat()) * 360f,
(((position - 1) % SATURATION_COUNT) + 1) / (SATURATION_COUNT.toFloat())
)
/**
* Turns a wrapped adapter position and a row index into a [Color].
*
* @param position adapter position of the color row, mod ([HUE_COUNT] * [SATURATION_COUNT] + 1)
* @return the corresponding [Int] color
*/
fun positionAndSubPositionToColor(position: Int, subPosition: Int) = Color.HSVToColor(
floatArrayOf(
*positionToHS(position),
// Special case for white: no minimum
if (position == 0) subPosition / (VALUE_COUNT - 1).toFloat()
// Other colors
else VALUE_MIN + (subPosition.toFloat() / (VALUE_COUNT - 1)) * (1F - VALUE_MIN)
)
)
/**
* Approximates a hue-saturation pair's adapter position.
*
* Due to numerical errors, [positionToHS] is not trivially reversible; this function should
* therefore not be used as is in an attempt to revert the conversion.
*
* @param hs the [Color.colorToHSV] components of a color, although only hue and saturation are needed
* @return a positive integer such that, when [positionToHS] is applied to it, the result is
* close to the input values
*/
private fun hsToPosition(hs: FloatArray) =
if (ceil(hs[1] * SATURATION_COUNT).toInt() == 0) 0
else ceil(hs[0] / 360f * HUE_COUNT).toInt() * SATURATION_COUNT +
ceil(hs[1] * SATURATION_COUNT).toInt() // - 1 + 1
/**
* Computes a hue-saturation pair's most fitting adapter position.
*
* This actually compares positions surrounding the output of [hsToPosition] regarding their fitness to
* represent the hue-saturation pair.
*
* @param hs the [Color.colorToHSV] components of a color, although only hue and saturation are needed
* @return a positive integer such that, when [positionToHS] is applied to it, the result is the closest
* possible to the input values
*/
private fun hsToNearestPosition(hs: FloatArray): Int {
val position = hsToPosition(hs)
if (position == 0) {
return position
}
var nearest = position
var minDistanceSquared: Double = Double.POSITIVE_INFINITY
for (i in -2 * SATURATION_COUNT..2 * SATURATION_COUNT) {
val correctedPosition = when {
position + i <= 0 -> position + HUE_COUNT * SATURATION_COUNT + i
position + i > HUE_COUNT * SATURATION_COUNT -> position + i - HUE_COUNT * SATURATION_COUNT
else -> position + i
} // in case the saturation==0 line is crossed
val trying = positionToHS(correctedPosition)
val a2 = hs[1].toDouble() * hs[1].toDouble()
val b2 = trying[1].toDouble() * trying[1].toDouble()
val ab = hs[1].toDouble() * trying[1].toDouble()
val gamma = 2.0 * Math.PI * (hs[0].toDouble() - trying[0].toDouble()) / 360.0
val c2 = a2 + b2 - 2.0 * ab * cos(gamma) // Law of cosines
if (c2 < minDistanceSquared) {
nearest = correctedPosition
minDistanceSquared = c2
}
}
return nearest
}
}
private val layoutInflater: LayoutInflater = LayoutInflater.from(context)
class ViewHolder(val binding: AwcpColorPickItemBinding) : RecyclerView.ViewHolder(binding.root)
init {
if (colors != null && (colors.size < VALUE_COUNT || colors.size % VALUE_COUNT != 0)) {
throw IllegalArgumentException("colors.size must be at least, and a multiple of $VALUE_COUNT")
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = DataBindingUtil.inflate<AwcpColorPickItemBinding>(
layoutInflater,
R.layout.awcp_color_pick_item,
parent,
false
)!!
for (i in 0 until VALUE_COUNT) {
binding.ctnColors.addView(
layoutInflater.inflate(R.layout.awcp_color_pick_item_color, binding.ctnColors, false)
)
}
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, realPosition: Int) {
if (colors != null) {
// Specific colors mode
val position = (realPosition % (colors.size / VALUE_COUNT)) * VALUE_COUNT
for (i in 0 until VALUE_COUNT) {
val imgColor = holder.binding.ctnColors.getChildAt(i) as ImageView
val color = colors[position + i]
(imgColor.drawable as GradientDrawable).setColor(color)
imgColor.setOnClickListener { colorPickCallbacks(color, imgColor) }
}
} else {
// "Rainbow" mode
val position = realPosition % (HUE_COUNT * SATURATION_COUNT + 1)
for (i in 0 until VALUE_COUNT) {
val imgColor = holder.binding.ctnColors.getChildAt(i) as ImageView
val color = positionAndSubPositionToColor(position, i)
(imgColor.drawable as GradientDrawable).setColor(color)
imgColor.setOnClickListener { colorPickCallbacks(color, imgColor) }
}
}
}
override fun getItemCount() = Int.MAX_VALUE
fun getMiddlePosition(): Int {
val actualNumberOfLines = if (colors != null) {
colors.size / VALUE_COUNT
} else {
// Add one for the "shades of grey" line
HUE_COUNT * SATURATION_COUNT + 1
}
return Int.MAX_VALUE / 2 - ((Int.MAX_VALUE / 2) % actualNumberOfLines)
}
/**
* Computes a [Color]'s closest neighbour within the color picker.
*
* @param color the color to search a neighbour for
* @return a pair consisting of an adapter position and an index within the value row
*/
fun colorToPositions(color: Int): Pair<Int, Int> {
if (colors != null) {
// Specific colors mode
val idx = colors.indexOf(color)
if (idx == -1) return 0 to 0
return idx / VALUE_COUNT to idx % VALUE_COUNT
} else {
// "Rainbow" mode
val hsv = floatArrayOf(0f, 0f, 0f)
Color.colorToHSV(color, hsv)
val position = hsToNearestPosition(hsv)
val value = hsv[2]
return Pair(
position,
if (position == 0) ceil(value * (VALUE_COUNT - 1).toFloat()).toInt()
else ((value - VALUE_MIN) / (1F - VALUE_MIN) * (VALUE_COUNT - 1)).toInt()
)
}
}
}
| apache-2.0 | 3f717af2a75807a9124f74c893cf4bd3 | 41.794521 | 112 | 0.591656 | 4.352996 | false | false | false | false |
craigjbass/pratura | src/main/kotlin/uk/co/craigbass/pratura/usecase/checkout/ViewDraftOrder.kt | 1 | 1679 | package uk.co.craigbass.pratura.usecase.checkout
import uk.co.craigbass.pratura.boundary.checkout.ViewDraftOrder
import uk.co.craigbass.pratura.boundary.checkout.ViewDraftOrder.*
import uk.co.craigbass.pratura.domain.ShippingAddress
import uk.co.craigbass.pratura.usecase.BasketReader
class ViewDraftOrder(private val basketReader: BasketReader,
private val shippingAddressRetriever: ShippingAddressRetriever) : ViewDraftOrder {
private var shippingAddress: ShippingAddress? = null
override fun execute(request: Request): ViewDraftOrder.Response {
if (basketNotFound(request)) return basketNotFound()
shippingAddress = shippingAddressRetriever.getShippingAddress()
return ViewDraftOrder.Response(
`readyToComplete?` = `shippingAddress?`() && hasBasketItems(request.basketId),
shippingAddress = shippingAddress.toPresentableAddress(),
errors = setOf()
)
}
private fun basketNotFound(request: Request) = !basketReader.`basketExists?`(request.basketId)
private fun basketNotFound() = Response(
`readyToComplete?` = false,
shippingAddress = null,
errors = setOf("BASKET_NOT_FOUND")
)
private fun hasBasketItems(basketId: String) = basketReader.getAll(basketId).count() > 0
private fun `shippingAddress?`() = shippingAddress != null
private fun ShippingAddress?.toPresentableAddress() = this?.let {
ViewDraftOrder.PresentableAddress(
name = name,
companyName = companyName,
addressLine1 = addressLine1,
addressLine2 = addressLine2 ?: "",
addressLine3 = addressLine3 ?: "",
city = city,
province = province,
zipcode = zipcode
)
}
}
| bsd-3-clause | f2d44468fd10dd014ece34b84e8a691a | 33.979167 | 103 | 0.731388 | 4.32732 | false | false | false | false |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/network/HttpHelper.kt | 1 | 4696 | package im.fdx.v2ex.network
import android.util.Log
import com.chuckerteam.chucker.api.ChuckerInterceptor
import com.google.firebase.crashlytics.FirebaseCrashlytics
import im.fdx.v2ex.MyApp
import im.fdx.v2ex.network.cookie.MyCookieJar
import im.fdx.v2ex.network.cookie.SharedPrefsPersistor
import im.fdx.v2ex.utils.extensions.logd
import im.fdx.v2ex.utils.extensions.logi
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException
import java.util.concurrent.TimeUnit
import java.util.logging.Level
import java.util.logging.Logger
/**
* Created by fdx on 2016/11/20.
* fdx will maintain it
*/
object HttpHelper {
val cookiePersistor = SharedPrefsPersistor(MyApp.get())
val myCookieJar: MyCookieJar = MyCookieJar(cookiePersistor)
val OK_CLIENT: OkHttpClient = OkHttpClient().newBuilder()
// .addInterceptor(HttpLoggingInterceptor())
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.followRedirects(false) //禁止重定向
.addNetworkInterceptor(
HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
override fun log(message: String) {
logd("okhttp: $message")
}
}).apply { level = HttpLoggingInterceptor.Level.HEADERS }
)
.addInterceptor(ChuckerInterceptor(MyApp.get()))//好东西,查看Okhttp数据
.addInterceptor { chain ->
val request = chain.request()
.newBuilder()
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
.header("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7")
// .header("Accept-Encoding", "gzip, deflate, br")
.header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6")
.header("Host", "www.v2ex.com")
.header("Authority", "v2ex.com")
.header("Cache-Control", "max-age=0")
// .header("User-Agent", "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Mobile Safari/537.36")
//换回PC端的User-Agent, 因为一些奇怪的问题
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36")
.build()
chain.proceed(request)
}
.cookieJar(myCookieJar)
.build()
}
fun vCall(url: String): Call {
Log.d("fdx", "vCall: $url ")
return HttpHelper.OK_CLIENT.newCall(Request.Builder().url(url).build())
}
fun Call.start(callback: Callback) {
enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
try {
callback.onFailure(call, e)
} catch (e2: Exception) {
e2.printStackTrace()
}
}
override fun onResponse(call: Call, response: Response) {
try {
callback.onResponse(call, response)
} catch (e: Exception) {
FirebaseCrashlytics.getInstance().recordException(e)
e.printStackTrace()
}
}
})
}
@Deprecated("暂时还用不上,简化代码之用")
fun Call.start(onResp: (Call, Response) -> Unit, onFail: (Call, IOException)-> Unit){
val callback = object: Callback {
override fun onResponse(call: Call, response: Response) {
onResp(call, response)
}
override fun onFailure(call: Call, e: IOException) {
onFail(call , e)
}
}
enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
try {
callback.onFailure(call, e)
} catch (e2: Exception) {
FirebaseCrashlytics.getInstance().recordException(e2)
e2.printStackTrace()
}
}
override fun onResponse(call: Call, response: Response) {
try {
callback.onResponse(call, response)
} catch (e: Exception) {
FirebaseCrashlytics.getInstance().recordException(e)
e.printStackTrace()
}
}
})
}
| apache-2.0 | b15ba8662693e0774893cb052b46a49d | 36.241935 | 195 | 0.565613 | 4.175407 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.