content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/**
* SandstoneBukkit - Bukkit implementation of SandstoneCommon
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Sandstone <https://github.com/ProjectSandstone/>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.projectsandstone.bukkit.logger
import com.github.projectsandstone.api.logging.Logger
import com.github.projectsandstone.api.logging.LoggerFactory
import com.github.projectsandstone.api.plugin.PluginContainer
/**
* Created by jonathan on 22/08/16.
*/
object BukkitLoggerFactory : LoggerFactory {
override fun createLogger(pluginContainer: PluginContainer): Logger {
return BukkitLogger(SandstonePluginLogger(pluginContainer))
}
} | src/main/kotlin/com/github/projectsandstone/bukkit/logger/BukkitLoggerFactory.kt | 3889917698 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.event.prefix
import com.rpkit.chat.bukkit.prefix.RPKPrefix
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitPrefixUpdateEvent(
override val prefix: RPKPrefix,
isAsync: Boolean
) : RPKBukkitEvent(isAsync), RPKPrefixUpdateEvent, Cancellable {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/event/prefix/RPKBukkitPrefixUpdateEvent.kt | 2842931232 |
/*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider
import android.view.View
import androidx.recyclerview.widget.StaggeredGridLayoutManager
/**
* Creates a [StaggeredCell] from a [View] inside a [StaggeredGridLayoutManager].
*
* @return the [StaggeredCell] identifying the given view.
*/
internal fun View.staggeredCell(): StaggeredCell {
val layoutParams = layoutParams as StaggeredGridLayoutManager.LayoutParams
return StaggeredCell(layoutParams.spanIndex, layoutParams.isFullSpan)
}
| recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/CreateStaggeredCell.kt | 1225742975 |
/*
*
* * Copyright (C) 2018 The Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.example.background
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
/**
* A [LifecycleOwner] which is always in a [Lifecycle.State.STARTED] state.
*/
class TestLifeCycleOwner : LifecycleOwner {
private val registry = LifecycleRegistry(this)
init {
registry.markState(Lifecycle.State.STARTED)
}
override fun getLifecycle(): Lifecycle = registry
}
| WorkManager/app/src/androidTest/java/com/example/background/TestLifeCycleOwner.kt | 2422034000 |
package com.beust.kobalt.internal.build
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
/**
* Sometimes, build files are moved to temporary files, so we give them a specific name for clarity.
* @param path is the path where that file was moved, @param realPath is where the actual file is.
*/
class BuildFile(val path: Path, val name: String, val realPath: Path = path) {
fun exists() : Boolean = Files.exists(path)
val directory : File get() = path.toFile().parentFile
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/build/BuildFile.kt | 587704031 |
package fr.geobert.efficio.drag
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import com.crashlytics.android.Crashlytics
import fr.geobert.efficio.*
import fr.geobert.efficio.adapter.DepartmentViewHolder
import fr.geobert.efficio.data.*
import fr.geobert.efficio.db.StoreCompositionTable
import java.util.*
class DepartmentDragHelper(val activity: EditDepartmentsActivity,
val depManager: DepartmentManager) :
ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) {
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder): Boolean {
Collections.swap(depManager.departmentsList, viewHolder.adapterPosition,
target.adapterPosition)
depManager.depAdapter.notifyItemMoved(viewHolder.adapterPosition,
target.adapterPosition)
return true
}
private var orig: Float = 0f
private var lastDragTask: DepartmentViewHolder? = null
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
// end of drag n drop, adapter is correctly ordered but not our representation here
val vh = viewHolder as DepartmentViewHolder?
if (vh == null) {
val last = lastDragTask
if (last != null) {
last.cardView.cardElevation = orig
updateDepWeight(last)
StoreCompositionTable.updateDepWeight(activity, last.dep!!)
}
} else {
orig = vh.cardView.cardElevation
vh.cardView.cardElevation = 20.0f
}
lastDragTask = vh
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
// nothing
}
private fun updateDepWeight(dragged: DepartmentViewHolder) {
val pos = dragged.adapterPosition
val dep = dragged.dep!!
if (depManager.nbDepartment() > 1)
if (pos == 0) { // first
val next = depManager.getDepartment(pos + 1)
if (dep.weight >= next.weight)
dep.weight = next.weight - 1.0
} else if (pos == (depManager.nbDepartment() - 1)) { // last
val prev = depManager.getDepartment(pos - 1)
if (dep.weight <= prev.weight)
dep.weight = prev.weight + 1.0
} else { // between
val next = depManager.getDepartment(pos + 1)
val prev = depManager.getDepartment(pos - 1)
if (dep.weight <= prev.weight || dep.weight >= next.weight) {
dep.weight = (prev.weight + next.weight) / 2.0
if (dep.weight <= prev.weight || dep.weight >= next.weight)
handleDoubleCollision(pos, dep, next, prev)
}
}
}
private fun handleDoubleCollision(pos: Int, dep: Department, next: Department, prev: Department) {
if (!BuildConfig.DEBUG)
Crashlytics.log("double collision occurred for Department!!! handleDoubleCollision")
}
} | app/src/main/kotlin/fr/geobert/efficio/drag/DepartmentDragHelper.kt | 3698854183 |
package com.example.examplescomposemotionlayout
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.datasource.LoremIpsum
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.ExperimentalMotionApi
import androidx.constraintlayout.compose.MotionLayout
import androidx.constraintlayout.compose.MotionScene
import java.lang.Float.min
/**
* A demo of using MotionLayout as a collapsing Toolbar using the DSL to define the MotionScene
*/
@OptIn(ExperimentalMotionApi::class)
@Preview(group = "scroll", device = "spec:shape=Normal,width=480,height=800,unit=dp,dpi=440")
@Composable
fun ToolBarExampleDsl() {
val scroll = rememberScrollState(0)
val big = 250.dp
val small = 50.dp
var scene = MotionScene() {
val title = createRefFor("title")
val image = createRefFor("image")
val icon = createRefFor("icon")
val start1 = constraintSet {
constrain(title) {
bottom.linkTo(image.bottom)
start.linkTo(image.start)
}
constrain(image) {
width = Dimension.matchParent
height = Dimension.value(big)
top.linkTo(parent.top)
customColor("cover", Color(0x000000FF))
}
constrain(icon) {
top.linkTo(image.top, 16.dp)
start.linkTo(image.start, 16.dp)
alpha = 0f
}
}
val end1 = constraintSet {
constrain(title) {
bottom.linkTo(image.bottom)
start.linkTo(icon.end)
centerVerticallyTo(image)
scaleX = 0.7f
scaleY = 0.7f
}
constrain(image) {
width = Dimension.matchParent
height = Dimension.value(small)
top.linkTo(parent.top)
customColor("cover", Color(0xFF0000FF))
}
constrain(icon) {
top.linkTo(image.top, 16.dp)
start.linkTo(image.start, 16.dp)
}
}
transition("default", start1, end1) {}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.verticalScroll(scroll)
) {
Spacer(Modifier.height(big))
repeat(5) {
Text(
text = LoremIpsum(222).values.first(),
modifier = Modifier
.background(Color.White)
.padding(16.dp)
)
}
}
val gap = with(LocalDensity.current){big.toPx() - small.toPx()}
val progress = min(scroll.value / gap, 1f);
MotionLayout(
modifier = Modifier.fillMaxSize(),
motionScene = scene,
progress = progress
) {
Image(
modifier = Modifier.layoutId("image"),
painter = painterResource(R.drawable.bridge),
contentDescription = null,
contentScale = ContentScale.Crop
)
Box(modifier = Modifier
.layoutId("image")
.background(motionProperties("image").value.color("cover"))) {
}
Image(
modifier = Modifier.layoutId("icon"),
painter = painterResource(R.drawable.menu),
contentDescription = null
)
Text(
modifier = Modifier.layoutId("title"),
text = "San Francisco",
fontSize = 30.sp,
color = Color.White
)
}
} | demoProjects/ExamplesComposeMotionLayout/app/src/main/java/com/example/examplescomposemotionlayout/CollapsingToolbarDsl.kt | 3125101515 |
package org.luxons.sevenwonders.ui.components.errors
import com.palantir.blueprintjs.Classes
import com.palantir.blueprintjs.Intent
import com.palantir.blueprintjs.bpButton
import com.palantir.blueprintjs.bpDialog
import kotlinx.browser.window
import org.luxons.sevenwonders.ui.redux.*
import org.luxons.sevenwonders.ui.router.Navigate
import org.luxons.sevenwonders.ui.router.Route
import react.RBuilder
import react.RComponent
import react.RProps
import react.RState
import react.dom.p
import styled.css
import styled.styledDiv
interface ErrorDialogStateProps : RProps {
var errorMessage: String?
}
interface ErrorDialogDispatchProps : RProps {
var goHome: () -> Unit
}
interface ErrorDialogProps : ErrorDialogDispatchProps, ErrorDialogStateProps
class ErrorDialogPresenter(props: ErrorDialogProps) : RComponent<ErrorDialogProps, RState>(props) {
override fun RBuilder.render() {
val errorMessage = props.errorMessage
bpDialog(
isOpen = errorMessage != null,
title = "Oops!",
icon = "error",
iconIntent = Intent.DANGER,
onClose = { goHomeAndRefresh() }
) {
styledDiv {
css {
classes.add(Classes.DIALOG_BODY)
}
p {
+(errorMessage ?: "fatal error")
}
}
styledDiv {
css {
classes.add(Classes.DIALOG_FOOTER)
}
bpButton(icon = "log-out", onClick = { goHomeAndRefresh() }) {
+"HOME"
}
}
}
}
}
private fun goHomeAndRefresh() {
// we don't use a redux action here because we actually want to redirect and refresh the page
window.location.href = Route.HOME.path
}
fun RBuilder.errorDialog() = errorDialog {}
private val errorDialog = connectStateAndDispatch<ErrorDialogStateProps, ErrorDialogDispatchProps, ErrorDialogProps>(
clazz = ErrorDialogPresenter::class,
mapStateToProps = { state, _ ->
errorMessage = state.fatalError
},
mapDispatchToProps = { dispatch, _ ->
goHome = { dispatch(Navigate(Route.HOME)) }
},
)
| sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/errors/ErrorDialog.kt | 958701429 |
package org.luxons.sevenwonders.engine.effects
import org.luxons.sevenwonders.engine.boards.Board
import org.luxons.sevenwonders.engine.boards.Science
internal class ScienceProgress(val science: Science) : InstantOwnBoardEffect() {
public override fun applyTo(board: Board) = board.science.addAll(science)
}
| sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/effects/ScienceProgress.kt | 2743868885 |
package net.perfectdreams.loritta.morenitta.utils
import java.time.LocalDateTime
import java.time.ZonedDateTime
object TimeUtils {
private val TIME_PATTERN = "(([01]?\\d|2[0-3]):([0-5]\\d?)(:([0-5]\\d))?) ?(am|pm)?".toPattern()
private val DATE_PATTERN = "(0[1-9]|[12][0-9]|3[01])[-/.](0[1-9]|1[012])[-/.]([0-9]+)".toPattern()
private val YEAR_PATTERN = "([0-9]+) ?(y|a)".toPattern()
private val MONTH_PATTERN = "([0-9]+) ?(month(s)?|m(e|ê)s(es)?)".toPattern()
private val WEEK_PATTERN = "([0-9]+) ?(w)".toPattern()
private val DAY_PATTERN = "([0-9]+) ?(d)".toPattern()
private val HOUR_PATTERN = "([0-9]+) ?(h)".toPattern()
private val SHORT_MINUTE_PATTERN = "([0-9]+) ?(m)".toPattern()
private val MINUTE_PATTERN = "([0-9]+) ?(min)".toPattern()
private val SECONDS_PATTERN = "([0-9]+) ?(s)".toPattern()
// TODO: Would be better to not hardcode it
val TIME_ZONE = Constants.LORITTA_TIMEZONE
fun convertToMillisRelativeToNow(input: String) = convertToLocalDateTimeRelativeToNow(input)
.toInstant()
.toEpochMilli()
fun convertToLocalDateTimeRelativeToNow(input: String) = convertToLocalDateTimeRelativeToTime(input, ZonedDateTime.now(TIME_ZONE))
fun convertToLocalDateTimeRelativeToTime(input: String, relativeTo: ZonedDateTime): ZonedDateTime {
val content = input.toLowerCase()
var localDateTime = relativeTo
.withNano(0)
var foundViaTime = false
if (content.contains(":")) { // horário
val matcher = TIME_PATTERN.matcher(content)
if (matcher.find()) { // Se encontrar...
val hour = matcher.group(2).toIntOrNull() ?: 0
val minute = matcher.group(3).toIntOrNull() ?: 0
val seconds = try {
matcher.group(5)?.toIntOrNull() ?: 0
} catch (e: IllegalStateException) {
0
}
var meridiem = try {
matcher.group(6)
} catch (e: IllegalStateException) {
null
}
// Horários que usam o meridiem
if (meridiem != null) {
meridiem = meridiem.replace(".", "").replace(" ", "")
if (meridiem.equals("pm", true)) { // Se for PM, aumente +12
localDateTime = localDateTime.withHour((hour % 12) + 12)
} else { // Se for AM, mantenha do jeito atual
localDateTime = localDateTime.withHour(hour % 12)
}
} else {
localDateTime = localDateTime.withHour(hour)
}
localDateTime = localDateTime
.withMinute(minute)
.withSecond(seconds)
foundViaTime = true
}
}
if (content.contains("/")) { // data
val matcher = DATE_PATTERN.matcher(content)
if (matcher.find()) { // Se encontrar...
val day = matcher.group(1).toIntOrNull() ?: 1
val month = matcher.group(2).toIntOrNull() ?: 1
val year = matcher.group(3).toIntOrNull() ?: 1999
localDateTime = localDateTime
.withDayOfMonth(day)
.withMonth(month)
.withYear(year)
}
} else if (foundViaTime && localDateTime.isBefore(LocalDateTime.now().atZone(TIME_ZONE))) {
// If it was found via time but there isn't any day set, we are going to check if it is in the past and, if true, we are going to add one day
localDateTime = localDateTime
.plusDays(1)
}
val yearsMatcher = YEAR_PATTERN.matcher(content)
if (yearsMatcher.find()) {
val addYears = yearsMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusYears(addYears)
}
val monthMatcher = MONTH_PATTERN.matcher(content)
var foundMonths = false
if (monthMatcher.find()) {
foundMonths = true
val addMonths = monthMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusMonths(addMonths)
}
val weekMatcher = WEEK_PATTERN.matcher(content)
if (weekMatcher.find()) {
val addWeeks = weekMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusWeeks(addWeeks)
}
val dayMatcher = DAY_PATTERN.matcher(content)
if (dayMatcher.find()) {
val addDays = dayMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusDays(addDays)
}
val hourMatcher = HOUR_PATTERN.matcher(content)
if (hourMatcher.find()) {
val addHours = hourMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusHours(addHours)
}
// This check is needed due to the month pattern also checking for "m"
// So, if the month was not found, we will check with the short minute pattern
// If it was found, we will ignore the short minute pattern and only use the long pattern
var foundMinutes = false
if (!foundMonths) {
val minuteMatcher = SHORT_MINUTE_PATTERN.matcher(content)
if (minuteMatcher.find()) {
foundMinutes = true
val addMinutes = minuteMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusMinutes(addMinutes)
}
}
if (!foundMinutes) {
val minuteMatcher = MINUTE_PATTERN.matcher(content)
if (minuteMatcher.find()) {
val addMinutes = minuteMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusMinutes(addMinutes)
}
}
val secondsMatcher = SECONDS_PATTERN.matcher(content)
if (secondsMatcher.find()) {
val addSeconds = secondsMatcher.group(1).toLongOrNull() ?: 0
localDateTime = localDateTime
.plusSeconds(addSeconds)
}
return localDateTime
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/TimeUtils.kt | 266747261 |
package com.thunderclouddev.deeplink.ui.edit
import android.content.Context
import android.databinding.DataBindingUtil
import android.databinding.ObservableArrayList
import android.databinding.ObservableList
import android.view.ViewGroup
import com.thunderclouddev.deeplink.R
import com.thunderclouddev.deeplink.databinding.EditViewHandlingAppIconItemBinding
import com.thunderclouddev.deeplink.ui.BaseRecyclerViewAdapter
import org.jetbrains.anko.layoutInflater
/**
* @author David Whitman on 27 Feb, 2017.
*/
class HandlingAppsAdapter(private val context: Context, val items: ObservableArrayList<AppViewModel>) : BaseRecyclerViewAdapter<HandlingAppsAdapter.ViewHolder>() {
init {
items.addOnListChangedCallback(object : ObservableList.OnListChangedCallback<ObservableArrayList<AppViewModel>>() {
override fun onItemRangeInserted(sender: ObservableArrayList<AppViewModel>?, positionStart: Int, itemCount: Int) {
notifyItemRangeInserted(positionStart, itemCount)
}
override fun onChanged(sender: ObservableArrayList<AppViewModel>?) {
notifyDataSetChanged()
}
override fun onItemRangeRemoved(sender: ObservableArrayList<AppViewModel>?, positionStart: Int, itemCount: Int) {
notifyItemRangeRemoved(positionStart, itemCount)
}
override fun onItemRangeMoved(sender: ObservableArrayList<AppViewModel>?, fromPosition: Int, toPosition: Int, itemCount: Int) {
notifyItemMoved(fromPosition, itemCount)
}
override fun onItemRangeChanged(sender: ObservableArrayList<AppViewModel>?, positionStart: Int, itemCount: Int) {
notifyItemRangeChanged(positionStart, itemCount)
}
})
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
return ViewHolder(DataBindingUtil.inflate<EditViewHandlingAppIconItemBinding>(context.layoutInflater, R.layout.edit_view_handling_app_icon_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
holder?.bind(items[position])
}
override fun getItemCount() = items.size
data class ViewHolder(val binding: EditViewHandlingAppIconItemBinding) : BaseRecyclerViewAdapter.ViewHolder<AppViewModel>(binding) {
override fun performBind(item: AppViewModel) {
binding.model = item
}
}
} | app/src/main/kotlin/com/thunderclouddev/deeplink/ui/edit/HandlingAppsAdapter.kt | 1728576784 |
package net.perfectdreams.loritta.morenitta.commands.vanilla.administration
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.isValidSnowflake
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.extensions.getGuildMessageChannelById
class LockCommand(loritta: LorittaBot) : AbstractCommand(loritta, "lock", listOf("trancar", "fechar"), net.perfectdreams.loritta.common.commands.CommandCategory.MODERATION) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.lock.description")
override fun getDiscordPermissions(): List<Permission> {
return listOf(Permission.MANAGE_SERVER)
}
override fun canUseInPrivateChannel(): Boolean {
return false
}
override fun getBotPermissions(): List<Permission> {
return listOf(Permission.MANAGE_CHANNEL, Permission.MANAGE_PERMISSIONS)
}
override suspend fun run(context: CommandContext, locale: BaseLocale) {
val channel = getTextChannel(context, context.args.getOrNull(0)) ?: context.event.textChannel!! // Já que o comando não será executado via DM, podemos assumir que textChannel nunca será nulo
val publicRole = context.guild.publicRole
val override = channel.getPermissionOverride(publicRole)
if (override != null) {
if (Permission.MESSAGE_SEND !in override.denied) {
override.manager
.deny(Permission.MESSAGE_SEND)
.queue()
context.reply(
LorittaReply(
locale["commands.command.lock.denied", context.config.commandPrefix],
"\uD83C\uDF89"
)
)
} else {
context.reply(
LorittaReply(
locale["commands.command.lock.channelAlreadyIsLocked", context.config.commandPrefix],
Emotes.LORI_CRYING
)
)
}
} else {
channel.permissionContainer.upsertPermissionOverride(publicRole)
.deny(Permission.MESSAGE_SEND)
.queue()
context.reply(
LorittaReply(
locale["commands.command.lock.denied", context.config.commandPrefix],
"\uD83C\uDF89"
)
)
}
}
fun getTextChannel(context: CommandContext, input: String?): TextChannel? {
if (input == null)
return null
val guild = context.guild
val channels = guild.getTextChannelsByName(input, false)
if (channels.isNotEmpty()) {
return channels[0]
}
val id = input
.replace("<", "")
.replace("#", "")
.replace(">", "")
if (!id.isValidSnowflake())
return null
val channel = guild.getTextChannelById(id)
if (channel != null) {
return channel
}
return null
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/administration/LockCommand.kt | 1461299467 |
package org.rocfish.acl
/**
* 角色,是数据权限和职能权限的命名包装
*/
interface Role {
var name:String
/**
* 获取数据权限
*/
fun getDataAccess():DataAccess
/**
* 获取职能权限
*/
fun getActionAccess():ActionAccess
} | src/main/kotlin/org/rocfish/acl/Role.kt | 3277339822 |
package com.angcyo.uiview.kotlin
import com.angcyo.uiview.utils.RUtils
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:
* 创建人员:Robi
* 创建时间:2017/09/12 10:04
* 修改人员:Robi
* 修改时间:2017/09/12 10:04
* 修改备注:
* Version: 1.0.0
*/
/**保留小数点后几位*/
public fun Float.decimal(bitNum: Int = 2 /*小数点后几位*/, halfUp: Boolean = true /*四舍五入*/): String {
return RUtils.decimal(this, bitNum, halfUp)
} | uiview/src/main/java/com/angcyo/uiview/kotlin/FloatEx.kt | 719417300 |
/*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.util.GlobPatternMapper
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IGlobPatternMapperNested {
fun globmapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addGlobPatternMapper(GlobPatternMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun _addGlobPatternMapper(value: GlobPatternMapper)
}
fun IFileNameMapperNested.globmapper(
handledirsep: Boolean? = null,
casesensitive: Boolean? = null,
from: String? = null,
to: String? = null)
{
_addFileNameMapper(GlobPatternMapper().apply {
_init(handledirsep, casesensitive, from, to)
})
}
fun GlobPatternMapper._init(
handledirsep: Boolean?,
casesensitive: Boolean?,
from: String?,
to: String?)
{
if (handledirsep != null)
setHandleDirSep(handledirsep)
if (casesensitive != null)
setCaseSensitive(casesensitive)
if (from != null)
setFrom(from)
if (to != null)
setTo(to)
}
| src/main/kotlin/com/devcharly/kotlin/ant/util/globpatternmapper.kt | 3274652972 |
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.api.model
import org.openapitools.server.api.model.Link
import com.google.gson.annotations.SerializedName
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
/**
*
* @param self
* @param propertyClass
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class GithubRespositoryContainerlinks (
val self: Link? = null,
val propertyClass: kotlin.String? = null
) {
}
| clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/GithubRespositoryContainerlinks.kt | 2038388872 |
package org.DUCodeWars.framework.server.tournament
import org.DUCodeWars.framework.server.net.PlayerConnection
import org.DUCodeWars.framework.server.net.server.Server
data class Tournament(val server: Server, val players: Set<PlayerConnection>) | src/main/java/org/DUCodeWars/framework/server/tournament/Tournament.kt | 170557509 |
package com.ruuvi.station.network.data.response
typealias UploadImageResponse = RuuviNetworkResponse<UploadImageResponseBody>
data class UploadImageResponseBody (
val uploadURL: String,
val guid: String
) | app/src/main/java/com/ruuvi/station/network/data/response/UploadImageResponse.kt | 3470004876 |
/*
* Copyright (c) 2019 David Aguiar Gonzalez
*
* 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 gc.david.dfm.dagger
import dagger.Component
import gc.david.dfm.ui.fragment.OpenSourceMasterFragment
import javax.inject.Singleton
/**
* Created by david on 27.12.16.
*/
@Singleton
@Component(modules = [RootModule::class, OpenSourceModule::class])
interface OpenSourceComponent {
fun inject(openSourceMasterFragment: OpenSourceMasterFragment)
}
| app/src/main/java/gc/david/dfm/dagger/OpenSourceComponent.kt | 828776098 |
/*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.views.xychart.model.provider
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.views.xychart.model.XYChartResolutionUtils
import com.efficios.jabberwocky.views.xychart.model.render.XYChartRender
import com.efficios.jabberwocky.views.xychart.model.render.XYChartSeries
import javafx.beans.property.BooleanProperty
import javafx.beans.property.SimpleBooleanProperty
import java.util.concurrent.FutureTask
import kotlin.math.max
abstract class XYChartSeriesProvider(val series: XYChartSeries) {
/** Indicate if this series is enabled or not. */
private val enabledProperty: BooleanProperty = SimpleBooleanProperty(true)
fun enabledProperty() = enabledProperty
var enabled
get() = enabledProperty.get()
set(value) = enabledProperty.set(value)
fun generateSeriesRender(range: TimeRange, numberOfDataPoints: Int, task: FutureTask<*>? = null): XYChartRender {
if (numberOfDataPoints < 3) throw IllegalArgumentException("XYChart render needs at least 3 data points.")
/**
* We want similar queries to "stay aligned" on a sort of grid, so that slight deviations do
* not cause aliasing. First compute the step of the grid we will use, then the start time
* to use (which will be earlier or equal to the query's time range). Then compute the actual
* timestamps.
*/
/* Determine the step */
val roughResolution = max(1.0, range.duration / (numberOfDataPoints - 1.0))
val step = XYChartResolutionUtils.GRID_RESOLUTIONS.floor(roughResolution.toLong())
?: XYChartResolutionUtils.GRID_RESOLUTIONS.first()!!
/* Determine the start time of the target range. Simply "star_time - (start_time % step). */
val renderStart = range.startTime - (range.startTime % step)
val timestamps = (renderStart..range.endTime step step).toList()
if (timestamps.size <= 1) {
/* We don't even have a range, so there should be no events returned. */
return XYChartRender.EMPTY_RENDER
}
val datapoints = fillSeriesRender(timestamps, task) ?: return XYChartRender.EMPTY_RENDER
return XYChartRender(series, range, step, datapoints)
}
protected abstract fun fillSeriesRender(timestamps: List<Long>, task: FutureTask<*>? = null): List<XYChartRender.DataPoint>?
}
| jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/views/xychart/model/provider/XYChartSeriesProvider.kt | 2287677880 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization.beans
import groovy.lang.Closure
import org.gradle.api.internal.GeneratedSubclasses
import org.gradle.api.internal.IConventionAware
import org.gradle.api.provider.Property
import org.gradle.instantexecution.InstantExecutionException
import org.gradle.instantexecution.extensions.uncheckedCast
import org.gradle.instantexecution.serialization.Codec
import org.gradle.instantexecution.serialization.PropertyKind
import org.gradle.instantexecution.serialization.WriteContext
import org.gradle.instantexecution.serialization.logPropertyError
import org.gradle.instantexecution.serialization.logPropertyInfo
import java.io.IOException
import java.util.concurrent.Callable
import java.util.function.Supplier
class BeanPropertyWriter(
beanType: Class<*>
) : BeanStateWriter {
private
val relevantFields = relevantStateOf(beanType)
/**
* Serializes a bean by serializing the value of each of its fields.
*/
override suspend fun WriteContext.writeStateOf(bean: Any) {
for (field in relevantFields) {
val fieldName = field.name
val fieldValue = valueOrConvention(field.get(bean), bean, fieldName)
writeNextProperty(fieldName, fieldValue, PropertyKind.Field)
}
}
private
fun conventionalValueOf(bean: Any, fieldName: String): Any? = (bean as? IConventionAware)?.run {
conventionMapping.getConventionValue<Any?>(null, fieldName, false)
}
private
fun valueOrConvention(fieldValue: Any?, bean: Any, fieldName: String): Any? = when (fieldValue) {
is Property<*> -> {
if (!fieldValue.isPresent) {
// TODO - disallow using convention mapping + property types
val convention = conventionalValueOf(bean, fieldName)
if (convention != null) {
(fieldValue.uncheckedCast<Property<Any>>()).convention(convention)
}
}
fieldValue
}
is Closure<*> -> fieldValue
// TODO - do not eagerly evaluate these types
is Callable<*> -> fieldValue.call()
is Supplier<*> -> fieldValue.get()
is Function0<*> -> fieldValue.invoke()
is Lazy<*> -> fieldValue.value
else -> fieldValue ?: conventionalValueOf(bean, fieldName)
}
}
/**
* Returns whether the given property could be written. A property can only be written when there's
* a suitable [Codec] for its [value].
*/
suspend fun WriteContext.writeNextProperty(name: String, value: Any?, kind: PropertyKind): Boolean {
withPropertyTrace(kind, name) {
try {
write(value)
} catch (passThrough: IOException) {
throw passThrough
} catch (passThrough: InstantExecutionException) {
throw passThrough
} catch (e: Exception) {
logPropertyError("write", e) {
text("error writing value of type ")
reference(value?.let { unpackedTypeNameOf(it) } ?: "null")
}
return false
}
logPropertyInfo("serialize", value)
return true
}
}
private
fun unpackedTypeNameOf(value: Any) = GeneratedSubclasses.unpackType(value).name
| subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/beans/BeanPropertyWriter.kt | 3139808054 |
/*
*
* Copyright 2019: Brad Newman
*
* 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.github.resilience4j.kotlin.ratelimiter
import io.github.resilience4j.ratelimiter.RateLimiter
import io.github.resilience4j.ratelimiter.RateLimiterConfig
import io.github.resilience4j.ratelimiter.RequestNotPermitted
import kotlinx.coroutines.delay
import java.util.concurrent.TimeUnit
/**
* Decorates and executes the given suspend function [block].
*
* If [RateLimiterConfig.timeoutDuration] is non-zero, the returned function suspends until a permission is available.
*/
suspend fun <T> RateLimiter.executeSuspendFunction(block: suspend () -> T): T {
awaitPermission()
return block()
}
/**
* Decorates the given suspend function [block] and returns it.
*
* If [RateLimiterConfig.timeoutDuration] is non-zero, the returned function suspends until a permission is available.
*/
fun <T> RateLimiter.decorateSuspendFunction(block: suspend () -> T): suspend () -> T = {
executeSuspendFunction(block)
}
internal suspend fun RateLimiter.awaitPermission() {
val waitTimeNs = reservePermission()
when {
waitTimeNs > 0 -> delay(TimeUnit.NANOSECONDS.toMillis(waitTimeNs))
waitTimeNs < 0 -> throw RequestNotPermitted.createRequestNotPermitted(this)
}
} | resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/ratelimiter/RateLimiter.kt | 3527985296 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.onboarding
import androidx.preference.PreferenceManager
import androidx.test.core.app.ApplicationProvider
import mozilla.components.support.test.robolectric.testContext
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.spy
import org.mozilla.focus.R
import org.mozilla.focus.fragment.onboarding.OnboardingStep
import org.mozilla.focus.fragment.onboarding.OnboardingStorage
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class OnboardingStorageTest {
private lateinit var onBoardingStorage: OnboardingStorage
@Before
fun setup() {
onBoardingStorage = spy(OnboardingStorage(testContext))
}
@Test
fun `GIVEN at the first onboarding step WHEN querying the current onboarding step from storage THEN get the first step`() {
doReturn(testContext.getString(R.string.pref_key_first_screen))
.`when`(onBoardingStorage).getCurrentOnboardingStepFromSharedPref()
assertEquals(
OnboardingStep.ON_BOARDING_FIRST_SCREEN,
onBoardingStorage.getCurrentOnboardingStep(),
)
}
@Test
fun `GIVEN at the second onboarding step WHEN querying the current onboarding step from storage THEN get the second step`() {
doReturn(testContext.getString(R.string.pref_key_second_screen))
.`when`(onBoardingStorage).getCurrentOnboardingStepFromSharedPref()
assertEquals(
OnboardingStep.ON_BOARDING_SECOND_SCREEN,
onBoardingStorage.getCurrentOnboardingStep(),
)
}
@Test
fun `GIVEN onboarding not started WHEN querying the current onboarding step from storage THEN get the first step`() {
assertEquals(
OnboardingStep.ON_BOARDING_FIRST_SCREEN,
onBoardingStorage.getCurrentOnboardingStep(),
)
}
@Test
fun `GIVEN saveCurrentOnBoardingStepInSharePref is called WHEN ONBOARDING_FIRST_SCREEN is saved, THEN value for pref_key_onboarding_step is pref_key_first_screen`() {
onBoardingStorage.saveCurrentOnboardingStepInSharePref(OnboardingStep.ON_BOARDING_FIRST_SCREEN)
val prefManager =
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
assertEquals(testContext.getString(OnboardingStep.ON_BOARDING_FIRST_SCREEN.prefId), prefManager.getString(testContext.getString(R.string.pref_key_onboarding_step), ""))
}
@Test
fun `GIVEN saveCurrentOnBoardingStepInSharePref is called WHEN ONBOARDING_SECOND_SCREEN is saved, THEN value for pref_key_onboarding_step is pref_key_second_screen`() {
onBoardingStorage.saveCurrentOnboardingStepInSharePref(OnboardingStep.ON_BOARDING_SECOND_SCREEN)
val prefManager =
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
assertEquals(testContext.getString(OnboardingStep.ON_BOARDING_SECOND_SCREEN.prefId), prefManager.getString(testContext.getString(R.string.pref_key_onboarding_step), ""))
}
}
| app/src/test/java/org/mozilla/focus/onboarding/OnboardingStorageTest.kt | 3986355976 |
package com.idapgroup.android.mvp
/** Represents view with three states(loading, contentView, error with retry) */
interface LceView : LcView {
/**
* Show an error message with retry ability
* @param errorMessage Message representing an error.
* @param retry Retry action
*/
fun showError(errorMessage: String, retry: (() -> Unit)? = null)
} | mvp/src/main/java/com/idapgroup/android/mvp/LceView.kt | 1748248624 |
package link.standen.michael.phonesaver.activity
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.widget.TextView
import link.standen.michael.phonesaver.R
import java.util.Locale
import android.os.Build
import android.view.View
import link.standen.michael.phonesaver.util.DebugLogger
/**
* Credits activity.
*/
class CreditsActivity : AppCompatActivity() {
private val defaultLocale = Locale("en").language
private lateinit var log: DebugLogger
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.credits_activity)
log = DebugLogger(this)
// Version
try {
val versionName = packageManager.getPackageInfo(packageName, 0).versionName
findViewById<TextView>(R.id.credits_version).text = resources.getString(R.string.credits_version, versionName)
} catch (e: PackageManager.NameNotFoundException) {
log.e("Unable to get package version", e)
}
// Linkify
findViewById<TextView>(R.id.credits_creator).movementMethod = LinkMovementMethod.getInstance()
findViewById<TextView>(R.id.credits_content1).movementMethod = LinkMovementMethod.getInstance()
findViewById<TextView>(R.id.credits_content2).movementMethod = LinkMovementMethod.getInstance()
findViewById<TextView>(R.id.credits_content3).movementMethod = LinkMovementMethod.getInstance()
if (getCurrentLocale().language == defaultLocale){
// English, hide the translator info
findViewById<TextView>(R.id.credits_content_translator).visibility = View.GONE
} else {
findViewById<TextView>(R.id.credits_content_translator).movementMethod = LinkMovementMethod.getInstance()
}
}
/**
* A version safe way to get the currently applied locale.
*/
private fun getCurrentLocale(): Locale =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
this.resources.configuration.locales.get(0)
} else {
@Suppress("DEPRECATION")
this.resources.configuration.locale
}
}
| app/src/main/java/link/standen/michael/phonesaver/activity/CreditsActivity.kt | 2220155400 |
package me.proxer.library.api.apps
import me.proxer.library.ProxerCall
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
/**
* @author Ruben Gees
*/
internal interface InternalApi {
@FormUrlEncoded
@POST("apps/errorlog")
fun errorLog(
@Field("id") id: String?,
@Field("message") message: String?,
@Field("anonym") anonym: Boolean?,
@Field("silent") silent: Boolean?
): ProxerCall<Unit?>
}
| library/src/main/kotlin/me/proxer/library/api/apps/InternalApi.kt | 3234626307 |
package mal
import java.util.*
fun read(input: String?): MalType = read_str(input)
fun eval(_ast: MalType, _env: Env): MalType {
var ast = _ast
var env = _env
while (true) {
ast = macroexpand(ast, env)
if (ast is MalList) {
when ((ast.first() as? MalSymbol)?.value) {
"def!" -> return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
"let*" -> {
val childEnv = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
childEnv.set(key as MalSymbol, eval(it.next(), childEnv))
}
env = childEnv
ast = ast.nth(2)
}
"fn*" -> return fn_STAR(ast, env)
"do" -> {
eval_ast(ast.slice(1, ast.count() - 1), env)
ast = ast.seq().last()
}
"if" -> {
val check = eval(ast.nth(1), env)
if (check !== NIL && check !== FALSE) {
ast = ast.nth(2)
} else if (ast.count() > 3) {
ast = ast.nth(3)
} else return NIL
}
"quote" -> return ast.nth(1)
"quasiquote" -> ast = quasiquote(ast.nth(1))
"defmacro!" -> return defmacro(ast, env)
"macroexpand" -> return macroexpand(ast.nth(1), env)
"try*" -> return try_catch(ast, env)
else -> {
val evaluated = eval_ast(ast, env) as ISeq
val firstEval = evaluated.first()
when (firstEval) {
is MalFnFunction -> {
ast = firstEval.ast
env = Env(firstEval.env, firstEval.params, evaluated.rest().seq())
}
is MalFunction -> return firstEval.apply(evaluated.rest())
else -> throw MalException("cannot execute non-function")
}
}
}
} else return eval_ast(ast, env)
}
}
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
private fun fn_STAR(ast: MalList, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val params = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) })
}
private fun is_pair(ast: MalType): Boolean = ast is ISeq && ast.seq().any()
private fun quasiquote(ast: MalType): MalType {
if (!is_pair(ast)) {
val quoted = MalList()
quoted.conj_BANG(MalSymbol("quote"))
quoted.conj_BANG(ast)
return quoted
}
val seq = ast as ISeq
var first = seq.first()
if ((first as? MalSymbol)?.value == "unquote") {
return seq.nth(1)
}
if (is_pair(first) && ((first as ISeq).first() as? MalSymbol)?.value == "splice-unquote") {
val spliced = MalList()
spliced.conj_BANG(MalSymbol("concat"))
spliced.conj_BANG(first.nth(1))
spliced.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return spliced
}
val consed = MalList()
consed.conj_BANG(MalSymbol("cons"))
consed.conj_BANG(quasiquote(ast.first()))
consed.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return consed
}
private fun is_macro_call(ast: MalType, env: Env): Boolean {
val symbol = (ast as? MalList)?.first() as? MalSymbol ?: return false
val function = env.find(symbol) as? MalFunction ?: return false
return function.is_macro
}
private fun macroexpand(_ast: MalType, env: Env): MalType {
var ast = _ast
while (is_macro_call(ast, env)) {
val symbol = (ast as MalList).first() as MalSymbol
val function = env.find(symbol) as MalFunction
ast = function.apply(ast.rest())
}
return ast
}
private fun defmacro(ast: MalList, env: Env): MalType {
val macro = eval(ast.nth(2), env) as MalFunction
macro.is_macro = true
return env.set(ast.nth(1) as MalSymbol, macro)
}
private fun try_catch(ast: MalList, env: Env): MalType =
try {
eval(ast.nth(1), env)
} catch (e: Exception) {
val thrown = if (e is MalException) e else MalException(e.message)
val symbol = (ast.nth(2) as MalList).nth(1) as MalSymbol
val catchBody = (ast.nth(2) as MalList).nth(2)
val catchEnv = Env(env)
catchEnv.set(symbol, thrown)
eval(catchBody, catchEnv)
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
repl_env.set(MalSymbol("*host-language*"), MalString("kotlin"))
repl_env.set(MalSymbol("*ARGV*"), MalList(args.drop(1).map({ it -> MalString(it) }).toCollection(LinkedList<MalType>())))
repl_env.set(MalSymbol("eval"), MalFunction({ a: ISeq -> eval(a.first(), repl_env) }))
rep("(def! not (fn* (a) (if a false true)))", repl_env)
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", repl_env)
rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", repl_env)
if (args.any()) {
rep("(load-file \"${args[0]}\")", repl_env)
return
}
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
| kotlin/src/mal/stepA_mal.kt | 202482325 |
import org.gradle.api.Project
/**
* Configures the current project as a Kotlin project by adding the Kotlin `stdlib` as a dependency.
*/
fun Project.versions(): Versions {
return Versions(this)
}
| buildSrc/src/main/kotlin/init.kt | 2183099337 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.template.postfix
import com.intellij.codeInsight.template.postfix.templates.LanguagePostfixTemplate
import com.intellij.codeInsight.template.postfix.templates.PostfixLiveTemplate
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate
import org.intellij.lang.annotations.Language
import org.rust.lang.RsLanguage
import org.rust.lang.RsTestBase
abstract class PostfixTemplateTest(val postfixTemplate: PostfixTemplate) : RsTestBase() {
protected fun doTest(
@Language("Rust") before: String,
@Language("Rust") after: String,
checkSyntaxErrors: Boolean = true
) {
InlineFile(before).withCaret()
checkApplicability(before, true)
myFixture.type('\t')
if (checkSyntaxErrors) myFixture.checkHighlighting(false, false, false)
myFixture.checkResult(replaceCaretMarker(after))
}
protected fun doTestNotApplicable(@Language("Rust") testCase: String) {
InlineFile(testCase).withCaret()
checkApplicability(testCase, false)
}
private fun checkApplicability(testCase: String, isApplicable: Boolean) {
val provider = LanguagePostfixTemplate.LANG_EP.allForLanguage(RsLanguage)
.first { descriptor ->
descriptor.templates.any { template ->
template.javaClass == this.postfixTemplate.javaClass
}
}
check(
PostfixLiveTemplate.isApplicableTemplate(
provider,
postfixTemplate.key,
myFixture.file,
myFixture.editor
) == isApplicable
) {
"postfixTemplate ${if (isApplicable) "should" else "shouldn't"} be applicable to given case:\n\n$testCase"
}
}
}
| src/test/kotlin/org/rust/ide/template/postfix/PostfixTemplateTest.kt | 1368367792 |
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputConnectionWrapper
import android.widget.EditText
import androidx.core.view.inputmethod.EditorInfoCompat
import androidx.core.view.inputmethod.InputConnectionCompat
import androidx.core.view.inputmethod.InputContentInfoCompat
import com.google.android.mms.ContentType
import com.moez.QKSMS.common.util.TextViewStyler
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.util.tryOrNull
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
/**
* Custom implementation of EditText to allow for dynamic text colors
*
* Beware of updating to extend AppCompatTextView, as this inexplicably breaks the view in
* the contacts chip view
*/
class QkEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : EditText(context, attrs) {
@Inject lateinit var textViewStyler: TextViewStyler
val backspaces: Subject<Unit> = PublishSubject.create()
val inputContentSelected: Subject<InputContentInfoCompat> = PublishSubject.create()
var supportsInputContent: Boolean = false
init {
if (!isInEditMode) {
appComponent.inject(this)
textViewStyler.applyAttributes(this, attrs)
} else {
TextViewStyler.applyEditModeAttributes(this, attrs)
}
}
override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection {
val inputConnection = object : InputConnectionWrapper(super.onCreateInputConnection(editorInfo), true) {
override fun sendKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_DEL) {
backspaces.onNext(Unit)
}
return super.sendKeyEvent(event)
}
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
if (beforeLength == 1 && afterLength == 0) {
backspaces.onNext(Unit)
}
return super.deleteSurroundingText(beforeLength, afterLength)
}
}
if (supportsInputContent) {
EditorInfoCompat.setContentMimeTypes(editorInfo, arrayOf(
ContentType.IMAGE_JPEG,
ContentType.IMAGE_JPG,
ContentType.IMAGE_PNG,
ContentType.IMAGE_GIF))
}
val callback = InputConnectionCompat.OnCommitContentListener { inputContentInfo, flags, opts ->
val grantReadPermission = flags and InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION != 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && grantReadPermission) {
return@OnCommitContentListener tryOrNull {
inputContentInfo.requestPermission()
inputContentSelected.onNext(inputContentInfo)
true
} ?: false
}
true
}
return InputConnectionCompat.createWrapper(inputConnection, editorInfo, callback)
}
} | presentation/src/main/java/com/moez/QKSMS/common/widget/QkEditText.kt | 1256106100 |
/*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
*
*/
package compiler.parser.postproc
import compiler.InternalCompilerError
import compiler.ast.type.TypeModifier
import compiler.ast.type.TypeReference
import compiler.lexer.*
import compiler.parser.rule.Rule
import compiler.parser.rule.RuleMatchingResult
import compiler.transact.Position
import compiler.transact.TransactionalSequence
fun TypePostprocessor(rule: Rule<List<RuleMatchingResult<*>>>): Rule<TypeReference> {
return rule
.flatten()
.mapResult(::toAST)
}
private fun toAST(tokens: TransactionalSequence<Any, Position>): TypeReference {
val nameOrModifier = tokens.next()!!
val typeModifier: TypeModifier?
val nameToken: IdentifierToken
if (nameOrModifier is TypeModifier) {
typeModifier = nameOrModifier
nameToken = tokens.next()!! as IdentifierToken
}
else {
typeModifier = null
nameToken = nameOrModifier as IdentifierToken
}
val isNullable = tokens.hasNext() && tokens.next()!! == OperatorToken(Operator.QUESTION_MARK)
return TypeReference(nameToken, isNullable, typeModifier)
}
fun TypeModifierPostProcessor(rule: Rule<List<RuleMatchingResult<*>>>): Rule<TypeModifier> {
return rule
.flatten()
.mapResult { tokens ->
val keyword = (tokens.next() as KeywordToken?)?.keyword
when(keyword) {
Keyword.MUTABLE -> TypeModifier.MUTABLE
Keyword.READONLY -> TypeModifier.READONLY
Keyword.IMMUTABLE -> TypeModifier.IMMUTABLE
else -> throw InternalCompilerError("$keyword is not a type modifier")
}
}
} | src/compiler/parser/postproc/type.kt | 2567536074 |
package com.denysnovoa.nzbmanager.radarr.movie.release.view.domain
import com.denysnovoa.nzbmanager.radarr.movie.release.repository.api.MovieReleaseApiClient
import com.denysnovoa.nzbmanager.radarr.movie.release.repository.model.MovieReleaseModel
import io.reactivex.Flowable
class GetMovieReleaseUseCase(val movieReleaseApiClient: MovieReleaseApiClient) {
fun get(id: Int): Flowable<List<MovieReleaseModel>> {
return movieReleaseApiClient.getReleases(id)
}
} | app/src/main/java/com/denysnovoa/nzbmanager/radarr/movie/release/domain/GetMovieReleaseUseCase.kt | 3446698350 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.audio.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.wear.compose.material.Scaffold
import com.google.android.horologist.audio.AudioOutput
import com.google.android.horologist.audio.VolumeState
import com.google.android.horologist.audio.ui.components.toAudioOutputUi
import com.google.android.horologist.compose.tools.WearLocalePreview
@WearLocalePreview
@Composable
fun VolumeScreenLocalePreview() {
val volume = VolumeState(5, 10)
Scaffold(
positionIndicator = {
VolumePositionIndicator(
volumeState = { volume },
autoHide = false
)
}
) {
VolumeScreen(
volume = { volume },
audioOutputUi = AudioOutput.WatchSpeaker(
id = "1",
name = LocalConfiguration.current.locales.get(0).displayName
)
.toAudioOutputUi(),
increaseVolume = { },
decreaseVolume = { },
onAudioOutputClick = {}
)
}
}
| audio-ui/src/debug/java/com/google/android/horologist/audio/ui/VolumeScreenLocalePreview.kt | 2413665460 |
package chat.willow.warren.handler
import chat.willow.kale.helper.CaseMapping
import chat.willow.kale.irc.message.rfc1459.ModeMessage
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.prefix
import chat.willow.kale.irc.tag.TagStore
import chat.willow.warren.IClientMessageSending
import chat.willow.warren.WarrenChannel
import chat.willow.warren.event.ChannelModeEvent
import chat.willow.warren.event.IWarrenEvent
import chat.willow.warren.event.IWarrenEventDispatcher
import chat.willow.warren.event.UserModeEvent
import chat.willow.warren.state.*
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class ModeHandlerTests {
lateinit var handler: ModeHandler
lateinit var mockEventDispatcher: IWarrenEventDispatcher
lateinit var channelsState: ChannelsState
lateinit var mockClientMessaging: IClientMessageSending
val caseMappingState = CaseMappingState(mapping = CaseMapping.RFC1459)
@Before fun setUp() {
mockEventDispatcher = mock()
val channelTypes = ChannelTypesState(types = setOf('#'))
channelsState = emptyChannelsState(caseMappingState)
val userPrefixesState = UserPrefixesState(prefixesToModes = mapOf('+' to 'v', '@' to 'o'))
mockClientMessaging = mock()
handler = ModeHandler(mockEventDispatcher, mockClientMessaging, channelTypes, channelsState.joined, userPrefixesState, caseMappingState)
}
@Test fun test_handle_ChannelModeChange_NoPrefix_FiresEvents() {
val firstExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'x', parameter = "someone")
val secondExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'y')
val channelState = emptyChannel("#channel")
channelsState.joined += channelState
handler.handle(ModeMessage.Message(source = prefix(""), target = "#channel", modifiers = listOf(firstExpectedModifier, secondExpectedModifier)), TagStore())
val channel = WarrenChannel(state = channelState, client = mockClientMessaging)
verify(mockEventDispatcher).fire(ChannelModeEvent(user = prefix(""), channel = channel, modifier = firstExpectedModifier))
verify(mockEventDispatcher).fire(ChannelModeEvent(user = prefix(""), channel = channel, modifier = secondExpectedModifier))
}
@Test fun test_handle_ChannelModeChange_WithPrefix_FiresEvents() {
val firstExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'x', parameter = "someone")
val secondExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'y')
val channelState = emptyChannel("#channel")
channelsState.joined += channelState
handler.handle(ModeMessage.Message(source = Prefix(nick = "admin"), target = "#channel", modifiers = listOf(firstExpectedModifier, secondExpectedModifier)), TagStore())
val channel = WarrenChannel(state = channelState, client = mockClientMessaging)
verify(mockEventDispatcher).fire(ChannelModeEvent(user = Prefix(nick = "admin"), channel = channel, modifier = firstExpectedModifier))
verify(mockEventDispatcher).fire(ChannelModeEvent(user = Prefix(nick = "admin"), channel = channel, modifier = secondExpectedModifier))
}
@Test fun test_handle_ChannelModeChange_ForChannelNotIn_DoesNothing() {
val dummyModifier = ModeMessage.ModeModifier(type = '+', mode = 'x', parameter = "someone")
handler.handle(ModeMessage.Message(source = Prefix(nick = "admin"), target = "#notInChannel", modifiers = listOf(dummyModifier)), TagStore())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
@Test fun test_handle_ChannelModeChange_UserPrefixAdded() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf()), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '+', mode = 'v', parameter = "someone")
handler.handle(ModeMessage.Message(target = "#channel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf('v'), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_ChannelModeChange_UserPrefixRemoved() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf('o')), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '-', mode = 'o', parameter = "someone")
handler.handle(ModeMessage.Message(target = "#channel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf<Char>(), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_ChannelModeChange_UserPrefixForNonExistentChannel_NothingHappens() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf('o')), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '-', mode = 'o', parameter = "someone")
handler.handle(ModeMessage.Message(target = "#anotherchannel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf('o'), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_ChannelModeChange_UserPrefixForNonExistentUser_NothingHappens() {
channelsState.joined += ChannelState("#channel", generateUsersWithModes(("someone" to mutableSetOf('o')), mappingState = caseMappingState))
val addVoiceModifier = ModeMessage.ModeModifier(type = '-', mode = 'o', parameter = "someone-else")
handler.handle(ModeMessage.Message(target = "#channel", modifiers = listOf(addVoiceModifier), source = prefix("")), TagStore())
assertEquals(mutableSetOf('o'), channelsState.joined["#channel"]!!.users["someone"]!!.modes)
}
@Test fun test_handle_UserModeChange_FiresEvents() {
val firstExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'v', parameter = "someone")
val secondExpectedModifier = ModeMessage.ModeModifier(type = '+', mode = 'x')
handler.handle(ModeMessage.Message(source = prefix(""), target = "someone", modifiers = listOf(firstExpectedModifier, secondExpectedModifier)), TagStore())
verify(mockEventDispatcher).fire(UserModeEvent(user = "someone", modifier = firstExpectedModifier))
verify(mockEventDispatcher).fire(UserModeEvent(user = "someone", modifier = secondExpectedModifier))
}
} | src/test/kotlin/chat/willow/warren/handler/ModeHandlerTests.kt | 2035502630 |
package siosio.doma.refactoring
import com.intellij.codeInsight.*
import com.intellij.psi.*
import com.intellij.refactoring.listeners.*
import com.intellij.refactoring.rename.*
import com.intellij.usageView.*
import siosio.doma.*
import siosio.doma.extension.*
class DaoClassNameRenameProcessor : RenameJavaClassProcessor() {
override fun canProcessElement(element: PsiElement): Boolean {
return if (super.canProcessElement(element)) {
return AnnotationUtil.isAnnotated(element as PsiClass, "org.seasar.doma.Dao", AnnotationUtil.CHECK_TYPE)
} else {
false
}
}
override fun renameElement(element: PsiElement,
newName: String,
usages: Array<out UsageInfo>,
listener: RefactoringElementListener?) {
val psiClass = element as PsiClass
getModule(element.project, element)
.findSqlFileFromRuntimeScope(toSqlFilePath(element.qualifiedName!!.replace(".", "/")), psiClass)
?.let { sqlDir ->
if (sqlDir.name == psiClass.name) {
sqlDir.rename(sqlDir, newName)
}
}
super.renameElement(element, newName, usages, listener)
}
}
| src/main/java/siosio/doma/refactoring/DaoClassNameRenameProcessor.kt | 3206071505 |
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION")
package debug
import kotlin.js.*
import kotlin.js.Json
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
typealias IDebug = Debug
typealias IDebugger = Debugger | src/jsMain/kotlin/debug/index.debug.module_debug._aliases.kt | 3760229121 |
package chat.willow.warren.extension.invite_notify
import chat.willow.kale.IKaleIrcMessageHandler
import chat.willow.kale.IKaleRouter
import chat.willow.warren.event.IWarrenEventDispatcher
import chat.willow.warren.extension.invite_notify.handler.InviteHandler
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.junit.Before
import org.junit.Test
class InviteNotifyExtensionTests {
private lateinit var sut: InviteNotifyExtension
private lateinit var mockKaleRouter: IKaleRouter<IKaleIrcMessageHandler>
private lateinit var mockEventDispatcher: IWarrenEventDispatcher
@Before fun setUp() {
mockKaleRouter = mock()
mockEventDispatcher = mock()
sut = InviteNotifyExtension(mockKaleRouter, mockEventDispatcher)
}
@Test fun test_setUp_RegistersCorrectHandlers() {
sut.setUp()
verify(mockKaleRouter).register(eq("INVITE"), any<InviteHandler>())
}
@Test fun test_tearDown_UnregistersCorrectHandlers() {
sut.tearDown()
verify(mockKaleRouter).unregister("INVITE")
}
} | src/test/kotlin/chat/willow/warren/extension/invite_notify/InviteNotifyExtensionTests.kt | 308684328 |
package remoter.compiler.kbuilder
import com.squareup.kotlinpoet.FunSpec
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.VariableElement
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
/**
* A [ParamBuilder] for long type parameters
*/
internal class LongParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) {
override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY) {
if (paramType == ParamType.OUT) {
writeArrayOutParamsToProxy(param, methodBuilder)
} else {
methodBuilder.addStatement("$DATA.writeLongArray(" + param.simpleName + ")")
}
} else {
methodBuilder.addStatement("$DATA.writeLong(" + param.simpleName + ")")
}
}
override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) {
if (resultType.kind == TypeKind.ARRAY) {
methodBuilder.addStatement("$REPLY.writeLongArray($RESULT)")
} else {
methodBuilder.addStatement("$REPLY.writeLong($RESULT)")
}
}
override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) {
val resultMirror = methodType.getReturnAsTypeMirror()
val resultType = methodType.getReturnAsKotlinType()
if (resultMirror.kind == TypeKind.ARRAY) {
val suffix = if (resultType.isNullable) "" else "!!"
methodBuilder.addStatement("$RESULT = $REPLY.createLongArray()$suffix")
} else {
methodBuilder.addStatement("$RESULT = $REPLY.readLong()")
}
}
override fun readOutResultsFromStub(param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY) {
methodBuilder.addStatement("$REPLY.writeLongArray($paramName)")
}
}
override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) {
super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder)
if (param.asType().kind == TypeKind.ARRAY) {
if (paramType == ParamType.OUT) {
writeOutParamsToStub(param, paramType, paramName, methodBuilder)
} else {
val suffix = if (param.isNullable()) "" else "!!"
methodBuilder.addStatement("$paramName = $DATA.createLongArray()$suffix")
}
} else {
methodBuilder.addStatement("$paramName = $DATA.readLong()")
}
}
override fun readOutParamsFromProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) {
if (param.asType().kind == TypeKind.ARRAY && paramType != ParamType.IN) {
if (param.isNullable()){
methodBuilder.beginControlFlow("if (${param.simpleName} != null)")
}
methodBuilder.addStatement("$REPLY.readLongArray(" + param.simpleName + ")")
if (param.isNullable()){
methodBuilder.endControlFlow()
}
}
}
}
| remoter/src/main/java/remoter/compiler/kbuilder/LongParamBuilder.kt | 1973346174 |
package com.orgecc.util.path
import com.m4u.util.WithLogging
import com.m4u.util.logger
import java.io.File
import java.io.IOException
import java.nio.file.*
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
interface PathHandler {
fun handle(path: Path)
}
fun Path.handleAndDelete(pathHandler: (Path) -> Unit): Unit =
try {
DirectoryWatcher.LOG.warn("Will handle '$this'")
pathHandler(this)
DirectoryWatcher.LOG.debug("Done. Deleting '$this'...")
try {
Files.delete(this)
} catch(e: Exception) {
DirectoryWatcher.LOG.error("Unable to delete '$this'")
}
} catch (e: Exception) {
logger(pathHandler.javaClass).error("Unable to handle file '$this'", e)
this.parent.resolveSibling("error").let { errorPath ->
Files.createDirectories(errorPath)
var errorFile = errorPath.resolve(this.fileName)
var tries = 0
while (tries < 1000 && Files.exists(errorFile)) {
tries++
errorFile = File("$errorFile.$tries").toPath()
}
Files.move(this, errorFile)
}
}
fun Path.enqueueExistingFiles(target: MutableCollection<Path>) =
Files.newDirectoryStream(this) {
!Files.isDirectory(it) &&
!it.fileName.toString().startsWith(".")
}.use { directoryStream ->
target += directoryStream
}
// Simple class to watch directory events.
class DirectoryWatcher(rootPathArg: String, executor: ExecutorService = Executors.newSingleThreadExecutor()) {
companion object : WithLogging()
private val rootPath = Paths.get(rootPathArg)
private val queue = ConcurrentLinkedQueue<Path>()
init {
executor.execute { rootPath.enqueuePaths(this.queue) }
LOG.warn("STARTED watching dir ${rootPath.toAbsolutePath()}")
}
val next: Path?
get() = queue.poll()?.let {
rootPath.resolve(it)
}
fun waitNext(sleepInMillis: Long = 5000): Path {
var result: Path? = null
while (result == null) {
result = next
if (result == null) Thread.sleep(sleepInMillis)
}
return result
}
fun loop(pathHandler: (Path) -> Unit, sleepInMillis: Long = 5000) {
while (!Thread.currentThread().isInterrupted) {
waitNext(sleepInMillis).handleAndDelete(pathHandler)
}
}
}
fun String.watchDir(executor: ExecutorService = Executors.newSingleThreadExecutor())
= DirectoryWatcher(this, executor)
fun String.watchDirLoop(pathHandler: (Path) -> Unit, sleepInMillis: Long = 5000, executor: ExecutorService = Executors.newFixedThreadPool(2))
= executor.execute { this.watchDir(executor).loop(pathHandler, sleepInMillis) }
fun Path.enqueuePaths(eventQueue: ConcurrentLinkedQueue<Path>,
sleepInMillis: Long = 500, kind: WatchEvent.Kind<Path> = StandardWatchEventKinds.ENTRY_CREATE): Unit {
Thread.currentThread().name = "enqueuePaths[$kind:${this.toAbsolutePath()}]"
Files.createDirectories(this)
try {
this.enqueueExistingFiles(eventQueue)
val watchService = [email protected]()
[email protected](watchService, kind)
// loop forever to watch directory
while (!Thread.currentThread().isInterrupted) {
val watchKey: WatchKey
watchKey = watchService.take() // this call is blocking until events are present
watchKey.pollEvents().map { it.context() as Path }.forEach {
while (!eventQueue.offer(it)) Thread.sleep(sleepInMillis)
}
// if the watched directed gets deleted, break loop
if (!watchKey.reset()) {
DirectoryWatcher.LOG.warn("[enqueuePaths] No longer valid")
watchKey.cancel()
watchService.close()
break
}
}
} catch (ex: InterruptedException) {
DirectoryWatcher.LOG.warn("Interrupted. Goodbye")
} catch (ex: IOException) {
DirectoryWatcher.LOG.warn("", ex)
}
}
fun Path.enqueueEvents(eventQueue: ConcurrentLinkedQueue<WatchEvent<*>>,
sleepInMillis: Long = 500, vararg kinds: WatchEvent.Kind<*> = arrayOf(StandardWatchEventKinds.ENTRY_CREATE)): Unit {
Thread.currentThread().name = "enqueueEvents[$kinds:${this.toAbsolutePath()}]"
try {
val watchService = [email protected]()
[email protected](watchService, *kinds)
// loop forever to watch directory
while (!Thread.currentThread().isInterrupted) {
val watchKey: WatchKey
watchKey = watchService.take() // this call is blocking until events are present
for (event in watchKey.pollEvents()) {
while (!eventQueue.offer(event)) Thread.sleep(sleepInMillis)
}
// if the watched directed gets deleted, break loop
if (!watchKey.reset()) {
DirectoryWatcher.LOG.warn("No longer valid")
watchKey.cancel()
watchService.close()
break
}
}
} catch (ex: InterruptedException) {
DirectoryWatcher.LOG.warn("Interrupted. Goodbye")
} catch (ex: IOException) {
DirectoryWatcher.LOG.warn("", ex)
}
}
| src/com/github/elifarley/kotlin/path/DirectoryWatcher.kt | 2919788393 |
package org.jetbrains.dokka.plugability
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule
import com.fasterxml.jackson.dataformat.xml.XmlMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.utilities.parseJson
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty1
abstract class DokkaPlugin {
private val extensionDelegates = mutableListOf<KProperty<*>>()
private val unsafePlugins = mutableListOf<Lazy<Extension<*, *, *>>>()
@PublishedApi
internal var context: DokkaContext? = null
protected inline fun <reified T : DokkaPlugin> plugin(): T = context?.plugin(T::class) ?: throwIllegalQuery()
protected fun <T : Any> extensionPoint() = ReadOnlyProperty<DokkaPlugin, ExtensionPoint<T>> { thisRef, property ->
ExtensionPoint(
thisRef::class.qualifiedName ?: throw AssertionError("Plugin must be named class"),
property.name
)
}
protected fun <T : Any> extending(definition: ExtendingDSL.() -> Extension<T, *, *>) = ExtensionProvider(definition)
protected class ExtensionProvider<T : Any> internal constructor(
private val definition: ExtendingDSL.() -> Extension<T, *, *>
) {
operator fun provideDelegate(thisRef: DokkaPlugin, property: KProperty<*>) = lazy {
ExtendingDSL(
thisRef::class.qualifiedName ?: throw AssertionError("Plugin must be named class"),
property.name
).definition()
}.also { thisRef.extensionDelegates += property }
}
internal fun internalInstall(ctx: DokkaContextConfiguration, configuration: DokkaConfiguration) {
val extensionsToInstall = extensionDelegates.asSequence()
.filterIsInstance<KProperty1<DokkaPlugin, Extension<*, *, *>>>() // should be always true
.map { it.get(this) } + unsafePlugins.map { it.value }
extensionsToInstall.forEach { if (configuration.(it.condition)()) ctx.installExtension(it) }
}
protected fun <T : Any> unsafeInstall(ext: Lazy<Extension<T, *, *>>) {
unsafePlugins.add(ext)
}
}
interface WithUnsafeExtensionSuppression {
val extensionsSuppressed: List<Extension<*, *, *>>
}
interface ConfigurableBlock
inline fun <reified P : DokkaPlugin, reified E : Any> P.query(extension: P.() -> ExtensionPoint<E>): List<E> =
context?.let { it[extension()] } ?: throwIllegalQuery()
inline fun <reified P : DokkaPlugin, reified E : Any> P.querySingle(extension: P.() -> ExtensionPoint<E>): E =
context?.single(extension()) ?: throwIllegalQuery()
fun throwIllegalQuery(): Nothing =
throw IllegalStateException("Querying about plugins is only possible with dokka context initialised")
inline fun <reified T : DokkaPlugin, reified R : ConfigurableBlock> configuration(context: DokkaContext): R? =
context.configuration.pluginsConfiguration.firstOrNull { it.fqPluginName == T::class.qualifiedName }
?.let { configuration ->
when (configuration.serializationFormat) {
DokkaConfiguration.SerializationFormat.JSON -> parseJson(configuration.values)
DokkaConfiguration.SerializationFormat.XML -> XmlMapper(JacksonXmlModule().apply {
setDefaultUseWrapper(
true
)
}).readValue<R>(configuration.values)
}
}
| core/src/main/kotlin/plugability/DokkaPlugin.kt | 1430911870 |
package com.github.siosio.upsource.bean
data class ParticipantInReview(
val userId: String,
val role: RoleInReviewEnum,
val state: ParticipantStateEnum? = null
)
| src/main/java/com/github/siosio/upsource/bean/ParticipantInReview.kt | 4190177843 |
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.processing
import com.google.devtools.ksp.symbol.KSType
interface KSBuiltIns {
/**
* Common Standard Library types. Use [Resolver.getClassDeclarationByName] for other types.
*/
val anyType: KSType
val nothingType: KSType
val unitType: KSType
val numberType: KSType
val byteType: KSType
val shortType: KSType
val intType: KSType
val longType: KSType
val floatType: KSType
val doubleType: KSType
val charType: KSType
val booleanType: KSType
val stringType: KSType
val iterableType: KSType
val annotationType: KSType
val arrayType: KSType
}
| api/src/main/kotlin/com/google/devtools/ksp/processing/KSBuiltIns.kt | 3275841151 |
package cz.softdeluxe.jlib.service
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.InputStreamSource
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.AsyncResult
import org.springframework.stereotype.Service
import java.util.concurrent.Future
/**
* Created by Petr on 9. 5. 2015.
*/
@Service
open class EmailServiceImpl(val mailSender: JavaMailSender,
@Value(value = "\${spring.mail.username}") val from: String) : EmailService {
private val logger = LoggerFactory.getLogger(javaClass)
@Async
override fun send(to: Array<String>, subject: String, text: String, html: Boolean,
attachments: Iterable<EmailAttachment>): Future<Boolean> {
try {
val mimeMessage = mailSender.createMimeMessage()
val multipart: Boolean = attachments.any()
val message = MimeMessageHelper(mimeMessage, multipart)
message.setFrom(from)
attachments.forEach {
message.addAttachment(it.name, it.stream)
}
message.setTo(to)
message.setSubject(subject)
message.setText(text, html)
mailSender.send(mimeMessage)
return AsyncResult(true)
} catch (ex: Exception) {
logger.error("Chyba při odeslání emailu", ex)
return AsyncResult(false)
}
}
}
interface EmailService {
fun send(to: Array<String>, subject: String, text: String, html: Boolean = true,
attachments: Iterable<EmailAttachment> = emptyList()): Future<Boolean>
}
class EmailAttachment(val name: String, val stream: InputStreamSource) | src/main/java/cz/softdeluxe/jlib/service/EmailService.kt | 3479991625 |
/*********************************************************************************
* Copyright 2017-present trivago GmbH
*
* 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.trivago.reportoire.core.common
import com.trivago.reportoire.core.sources.Source
import com.trivago.reportoire.core.sources.SyncSource
/**
* Source that stores a value within the memory for the given input.
*/
class MemorySource<TModel, in TInput> : SyncSource<TModel, TInput> {
// Members
private var mLatestInput: TInput? = null
private var mCachedModel: TModel? = null
// Public Api
/**
* Saves the model in relation to the given input.
*/
fun setModel(input: TInput?, model: TModel?) {
mLatestInput = input
mCachedModel = model
}
// SyncSource
override fun getResult(input: TInput?): Source.Result<TModel> {
if (mCachedModel != null && input?.equals(mLatestInput)!!) {
return Source.Result.Success(mCachedModel)
} else {
return Source.Result.Error(IllegalStateException("No model in memory found!"))
}
}
// Source
override fun reset() {
setModel(null, null)
}
}
| core/src/main/kotlin/com/trivago/reportoire/core/common/MemorySource.kt | 3877041432 |
package com.yodle.android.kotlindemo.dagger
import com.yodle.android.kotlindemo.MainApp
import com.yodle.android.kotlindemo.activity.MainActivity
import com.yodle.android.kotlindemo.activity.RepositoryDetailActivity
import com.yodle.android.kotlindemo.service.GitHubService
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
fun inject(mainApp: MainApp)
fun inject(mainActivity: MainActivity)
fun inject(repositoryDetailActivity: RepositoryDetailActivity)
fun inject(gitHubService: GitHubService)
} | app/src/main/kotlin/com/yodle/android/kotlindemo/dagger/AppComponent.kt | 1515569641 |
/*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.history.view
import android.net.Uri
import androidx.activity.ComponentActivity
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.model.OptionMenu
import jp.toastkid.lib.view.list.ListActionAttachment
import jp.toastkid.ui.dialog.DestructiveChangeConfirmDialog
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.history.ViewHistory
import jp.toastkid.yobidashi.libs.db.DatabaseFinder
import jp.toastkid.yobidashi.search.view.BindItemContent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
fun ViewHistoryListUi() {
val context = LocalContext.current as? ComponentActivity ?: return
val database = DatabaseFinder().invoke(context)
val viewHistoryRepository = database.viewHistoryRepository()
val fullItems = mutableListOf<ViewHistory>()
val viewHistoryItems = remember { mutableStateListOf<ViewHistory>() }
val listState = rememberLazyListState()
val clearConfirmDialogState = remember { mutableStateOf(false) }
val contentViewModel = viewModel(ContentViewModel::class.java, context)
LaunchedEffect(key1 = "first_launch", block = {
contentViewModel.optionMenus(
OptionMenu(titleId = R.string.title_clear_view_history, action = {
clearConfirmDialogState.value = true
})
)
CoroutineScope(Dispatchers.Main).launch {
val loaded = withContext(Dispatchers.IO) {
viewHistoryRepository.reversed()
}
fullItems.clear()
fullItems.addAll(loaded)
viewHistoryItems.addAll(fullItems)
}
})
val browserViewModel = viewModel(BrowserViewModel::class.java, context)
val onClick: (ViewHistory, Boolean) -> Unit = { viewHistory, isLongClick ->
when (isLongClick) {
true -> {
browserViewModel.openBackground(viewHistory.title, Uri.parse(viewHistory.url))
}
false -> {
browserViewModel.open(Uri.parse(viewHistory.url))
}
}
}
List(viewHistoryItems, listState, onClick) {
viewHistoryRepository.delete(it)
viewHistoryItems.remove(it)
}
ListActionAttachment.make(context)
.invoke(
listState,
LocalLifecycleOwner.current,
viewHistoryItems,
fullItems,
{ item, word -> item.title.contains(word) || item.url.contains(word) }
)
DestructiveChangeConfirmDialog(
clearConfirmDialogState,
R.string.title_clear_view_history
) {
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
viewHistoryRepository.deleteAll()
}
viewHistoryItems.clear()
contentViewModel.snackShort(R.string.done_clear)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun List(
viewHistoryItems: SnapshotStateList<ViewHistory>,
listState: LazyListState,
onClick: (ViewHistory, Boolean) -> Unit,
onDelete: (ViewHistory) -> Unit
) {
LazyColumn(state = listState) {
items(viewHistoryItems, { it._id }) { viewHistory ->
BindItemContent(
viewHistory,
onClick = {
onClick(viewHistory, false)
},
onLongClick = {
onClick(viewHistory, true)
},
onDelete = {
onDelete(viewHistory)
},
modifier = Modifier.animateItemPlacement()
)
}
}
} | app/src/main/java/jp/toastkid/yobidashi/browser/history/view/ViewHistoryListUi.kt | 3988580332 |
package com.youniversals.playupgo.flux
/**
* @author Gian Darren Aquino
*/
interface AliveUiThread {
/**
* Runs the [Runnable] if the current context is alive.
*/
fun runOnUiThreadIfAlive(runnable: Runnable)
/**
* Runs the [Runnable] if the current context is alive.
*/
fun runOnUiThreadIfAlive(runnable: Runnable, delayMillis: Long)
}
| app/src/main/java/com/youniversals/playupgo/flux/AliveUiThread.kt | 1356971579 |
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.gls.main.view
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import no.nordicsemi.android.gls.R
import no.nordicsemi.android.gls.data.ConcentrationUnit
import no.nordicsemi.android.gls.data.RecordType
import no.nordicsemi.android.gls.data.WorkingMode
@Composable
internal fun RecordType?.toDisplayString(): String {
return when (this) {
RecordType.CAPILLARY_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_capillary_whole_blood)
RecordType.CAPILLARY_PLASMA -> stringResource(id = R.string.gls_type_capillary_plasma)
RecordType.VENOUS_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_venous_whole_blood)
RecordType.VENOUS_PLASMA -> stringResource(id = R.string.gls_type_venous_plasma)
RecordType.ARTERIAL_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_arterial_whole_blood)
RecordType.ARTERIAL_PLASMA -> stringResource(id = R.string.gls_type_arterial_plasma)
RecordType.UNDETERMINED_WHOLE_BLOOD -> stringResource(id = R.string.gls_type_undetermined_whole_blood)
RecordType.UNDETERMINED_PLASMA -> stringResource(id = R.string.gls_type_undetermined_plasma)
RecordType.INTERSTITIAL_FLUID -> stringResource(id = R.string.gls_type_interstitial_fluid)
RecordType.CONTROL_SOLUTION -> stringResource(id = R.string.gls_type_control_solution)
null -> stringResource(id = R.string.gls_type_reserved)
}
}
@Composable
internal fun ConcentrationUnit.toDisplayString(): String {
return when (this) {
//TODO("Check unit_kgpl --> mgpdl")
ConcentrationUnit.UNIT_KGPL -> stringResource(id = R.string.gls_unit_mgpdl)
ConcentrationUnit.UNIT_MOLPL -> stringResource(id = R.string.gls_unit_mmolpl)
}
}
@Composable
internal fun WorkingMode.toDisplayString(): String {
return when (this) {
WorkingMode.ALL -> stringResource(id = R.string.gls__working_mode__all)
WorkingMode.LAST -> stringResource(id = R.string.gls__working_mode__last)
WorkingMode.FIRST -> stringResource(id = R.string.gls__working_mode__first)
}
}
@Composable
internal fun glucoseConcentrationDisplayValue(value: Float, unit: ConcentrationUnit): String {
val result = when (unit) {
ConcentrationUnit.UNIT_KGPL -> value * 100000.0f
ConcentrationUnit.UNIT_MOLPL -> value * 1000.0f
}
return String.format("%.2f %s", result, unit.toDisplayString())
}
| profile_gls/src/main/java/no/nordicsemi/android/gls/main/view/GLSMapper.kt | 745051254 |
package com.openlattice.collections
import com.google.common.base.Preconditions.checkArgument
import com.google.common.base.Preconditions.checkState
import com.google.common.collect.Sets
import com.google.common.eventbus.EventBus
import com.hazelcast.aggregation.Aggregators
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.query.Predicate
import com.hazelcast.query.Predicates
import com.openlattice.authorization.*
import com.openlattice.authorization.securable.SecurableObjectType
import com.openlattice.collections.aggregators.EntitySetCollectionConfigAggregator
import com.openlattice.collections.mapstores.ENTITY_SET_COLLECTION_ID_INDEX
import com.openlattice.collections.mapstores.ENTITY_TYPE_COLLECTION_ID_INDEX
import com.openlattice.collections.mapstores.ID_INDEX
import com.openlattice.collections.processors.AddPairToEntityTypeCollectionTemplateProcessor
import com.openlattice.collections.processors.RemoveKeyFromEntityTypeCollectionTemplateProcessor
import com.openlattice.collections.processors.UpdateEntitySetCollectionMetadataProcessor
import com.openlattice.collections.processors.UpdateEntityTypeCollectionMetadataProcessor
import com.openlattice.controllers.exceptions.ForbiddenException
import com.openlattice.datastore.services.EdmManager
import com.openlattice.datastore.services.EntitySetManager
import com.openlattice.edm.EntitySet
import com.openlattice.edm.events.EntitySetCollectionCreatedEvent
import com.openlattice.edm.events.EntitySetCollectionDeletedEvent
import com.openlattice.edm.events.EntityTypeCollectionCreatedEvent
import com.openlattice.edm.events.EntityTypeCollectionDeletedEvent
import com.openlattice.edm.requests.MetadataUpdate
import com.openlattice.edm.schemas.manager.HazelcastSchemaManager
import com.openlattice.edm.set.EntitySetFlag
import com.openlattice.hazelcast.HazelcastMap
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import org.springframework.stereotype.Service
import java.util.*
@Service
@SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE")
class CollectionsManager(
hazelcast: HazelcastInstance,
private val edmManager: EdmManager,
private val entitySetManager: EntitySetManager,
private val aclKeyReservations: HazelcastAclKeyReservationService,
private val schemaManager: HazelcastSchemaManager,
private val authorizations: AuthorizationManager,
private val eventBus: EventBus
) {
private val entityTypeCollections = HazelcastMap.ENTITY_TYPE_COLLECTIONS.getMap(hazelcast)
private val entitySetCollections = HazelcastMap.ENTITY_SET_COLLECTIONS.getMap(hazelcast)
private val entitySetCollectionConfig = HazelcastMap.ENTITY_SET_COLLECTION_CONFIG.getMap(hazelcast)
/** READ **/
fun getAllEntityTypeCollections(): Iterable<EntityTypeCollection> {
return entityTypeCollections.values
}
fun getEntityTypeCollection(id: UUID): EntityTypeCollection {
return entityTypeCollections[id] ?: throw IllegalStateException("EntityTypeCollection $id does not exist")
}
fun getEntityTypeCollections(ids: Set<UUID>): Map<UUID, EntityTypeCollection> {
return entityTypeCollections.getAll(ids)
}
fun getEntitySetCollection(id: UUID): EntitySetCollection {
val entitySetCollection = entitySetCollections[id]
?: throw IllegalStateException("EntitySetCollection $id does not exist")
entitySetCollection.template = getTemplatesForIds(setOf(id))[id] ?: mutableMapOf()
return entitySetCollection
}
fun getEntitySetCollections(ids: Set<UUID>): Map<UUID, EntitySetCollection> {
val templates = getTemplatesForIds(ids)
val collections = entitySetCollections.getAll(ids)
collections.forEach { it.value.template = templates[it.key] ?: mutableMapOf() }
return collections
}
fun getEntitySetCollectionsOfType(ids: Set<UUID>, entityTypeCollectionId: UUID): Iterable<EntitySetCollection> {
val templates = getTemplatesForIds(ids)
val collections = entitySetCollections.values(
Predicates.and(
idsPredicate(ids),
entityTypeCollectionIdPredicate(
entityTypeCollectionId
)
)
)
collections.map { it.template = templates[it.id] ?: mutableMapOf() }
return collections
}
/** CREATE **/
fun createEntityTypeCollection(entityTypeCollection: EntityTypeCollection): UUID {
val entityTypeIds = entityTypeCollection.template.map { it.entityTypeId }.toSet()
val nonexistentEntityTypeIds = Sets.difference(
entityTypeIds,
edmManager.getEntityTypesAsMap(entityTypeIds).keys
)
if (nonexistentEntityTypeIds.isNotEmpty()) {
throw IllegalStateException("EntityTypeCollection contains entityTypeIds that do not exist: $nonexistentEntityTypeIds")
}
aclKeyReservations.reserveIdAndValidateType(entityTypeCollection)
val existingEntityTypeCollection = entityTypeCollections.putIfAbsent(
entityTypeCollection.id,
entityTypeCollection
)
if (existingEntityTypeCollection == null) {
schemaManager.upsertSchemas(entityTypeCollection.schemas)
} else {
throw IllegalStateException("EntityTypeCollection ${entityTypeCollection.type} with id ${entityTypeCollection.id} already exists")
}
eventBus.post(EntityTypeCollectionCreatedEvent(entityTypeCollection))
return entityTypeCollection.id
}
fun createEntitySetCollection(entitySetCollection: EntitySetCollection, autoCreate: Boolean): UUID {
val principal = Principals.getCurrentUser()
Principals.ensureUser(principal)
val entityTypeCollectionId = entitySetCollection.entityTypeCollectionId
val template = entityTypeCollections[entityTypeCollectionId]?.template ?: throw IllegalStateException(
"Cannot create EntitySetCollection ${entitySetCollection.id} because EntityTypeCollection $entityTypeCollectionId does not exist."
)
if (!autoCreate) {
checkArgument(
template.map { it.id }.toSet() == entitySetCollection.template.keys,
"EntitySetCollection ${entitySetCollection.name} template keys do not match its EntityTypeCollection template."
)
}
validateEntitySetCollectionTemplate(entitySetCollection.name, entitySetCollection.template, template)
aclKeyReservations.reserveIdAndValidateType(entitySetCollection, entitySetCollection::name)
checkState(
entitySetCollections.putIfAbsent(entitySetCollection.id, entitySetCollection) == null,
"EntitySetCollection ${entitySetCollection.name} already exists."
)
val templateTypesToCreate = template.filter { !entitySetCollection.template.keys.contains(it.id) }
if (templateTypesToCreate.isNotEmpty()) {
val userPrincipal = Principals.getCurrentUser()
val entitySetsCreated = templateTypesToCreate.associate {
it.id to generateEntitySet(
entitySetCollection,
it,
userPrincipal
)
}
entitySetCollection.template.putAll(entitySetsCreated)
}
entitySetCollectionConfig.putAll(entitySetCollection.template.entries.associate {
CollectionTemplateKey(
entitySetCollection.id,
it.key
) to it.value
})
authorizations.setSecurableObjectType(AclKey(entitySetCollection.id), SecurableObjectType.EntitySetCollection)
authorizations.addPermission(
AclKey(entitySetCollection.id),
principal,
EnumSet.allOf(Permission::class.java)
)
eventBus.post(EntitySetCollectionCreatedEvent(entitySetCollection))
return entitySetCollection.id
}
/** UPDATE **/
fun updateEntityTypeCollectionMetadata(id: UUID, update: MetadataUpdate) {
ensureEntityTypeCollectionExists(id)
if (update.type.isPresent) {
aclKeyReservations.renameReservation(id, update.type.get())
}
entityTypeCollections.submitToKey(id, UpdateEntityTypeCollectionMetadataProcessor(update))
signalEntityTypeCollectionUpdated(id)
}
fun addTypeToEntityTypeCollectionTemplate(id: UUID, collectionTemplateType: CollectionTemplateType) {
ensureEntityTypeCollectionExists(id)
edmManager.ensureEntityTypeExists(collectionTemplateType.entityTypeId)
val entityTypeCollection = entityTypeCollections[id]!!
if (entityTypeCollection.template.any { it.id == collectionTemplateType.id || it.name == collectionTemplateType.name }) {
throw IllegalArgumentException("Id or name of CollectionTemplateType $collectionTemplateType is already used on template of EntityTypeCollection $id.")
}
updateEntitySetCollectionsForNewType(id, collectionTemplateType)
entityTypeCollections.executeOnKey(id, AddPairToEntityTypeCollectionTemplateProcessor(collectionTemplateType))
signalEntityTypeCollectionUpdated(id)
}
private fun updateEntitySetCollectionsForNewType(
entityTypeCollectionId: UUID, collectionTemplateType: CollectionTemplateType
) {
val entitySetCollectionsToUpdate = entitySetCollections.values(
entityTypeCollectionIdPredicate(
entityTypeCollectionId
)
).associate { it.id to it }
val entitySetCollectionOwners = authorizations.getOwnersForSecurableObjects(entitySetCollectionsToUpdate.keys.map {
AclKey(
it
)
}.toSet())
val entitySetsCreated = entitySetCollectionsToUpdate.values.associate {
it.id to generateEntitySet(
it,
collectionTemplateType,
entitySetCollectionOwners.get(AclKey(it.id)).first { p -> p.type == PrincipalType.USER })
}
val propertyTypeIds = edmManager.getEntityType(collectionTemplateType.entityTypeId).properties
val ownerPermissions = EnumSet.allOf(Permission::class.java)
val permissionsToAdd = mutableMapOf<AceKey, EnumSet<Permission>>()
entitySetsCreated.forEach {
val entitySetCollectionId = it.key
val entitySetId = it.value
entitySetCollectionOwners.get(AclKey(entitySetCollectionId)).forEach { owner ->
permissionsToAdd[AceKey(AclKey(entitySetId), owner)] = ownerPermissions
propertyTypeIds.forEach { ptId ->
permissionsToAdd[AceKey(
AclKey(entitySetId, ptId),
owner
)] = ownerPermissions
}
}
entitySetCollectionsToUpdate.getValue(entitySetCollectionId).template[collectionTemplateType.id] = entitySetId
}
authorizations.setPermissions(permissionsToAdd)
entitySetCollectionConfig.putAll(entitySetCollectionsToUpdate.keys.associate {
CollectionTemplateKey(
it,
collectionTemplateType.id
) to entitySetsCreated.getValue(it)
})
entitySetCollectionsToUpdate.values.forEach { eventBus.post(EntitySetCollectionCreatedEvent(it)) }
}
fun removeKeyFromEntityTypeCollectionTemplate(id: UUID, templateTypeId: UUID) {
ensureEntityTypeCollectionExists(id)
ensureEntityTypeCollectionNotInUse(id)
entityTypeCollections.executeOnKey(id, RemoveKeyFromEntityTypeCollectionTemplateProcessor(templateTypeId))
signalEntityTypeCollectionUpdated(id)
}
fun updateEntitySetCollectionMetadata(id: UUID, update: MetadataUpdate) {
ensureEntitySetCollectionExists(id)
if (update.name.isPresent) {
aclKeyReservations.renameReservation(id, update.name.get())
}
if (update.organizationId.isPresent) {
if (!authorizations.checkIfHasPermissions(
AclKey(update.organizationId.get()),
Principals.getCurrentPrincipals(),
EnumSet.of(Permission.READ)
)) {
throw ForbiddenException("Cannot update EntitySetCollection $id with organization id ${update.organizationId.get()}")
}
}
entitySetCollections.submitToKey(id, UpdateEntitySetCollectionMetadataProcessor(update))
signalEntitySetCollectionUpdated(id)
}
fun updateEntitySetCollectionTemplate(id: UUID, templateUpdates: Map<UUID, UUID>) {
val entitySetCollection = entitySetCollections[id]
?: throw IllegalStateException("EntitySetCollection $id does not exist")
val entityTypeCollectionId = entitySetCollection.entityTypeCollectionId
val template = entityTypeCollections[entityTypeCollectionId]?.template ?: throw IllegalStateException(
"Cannot update EntitySetCollection ${entitySetCollection.id} because EntityTypeCollection $entityTypeCollectionId does not exist."
)
entitySetCollection.template.putAll(templateUpdates)
validateEntitySetCollectionTemplate(entitySetCollection.name, entitySetCollection.template, template)
entitySetCollectionConfig.putAll(templateUpdates.entries.associate {
CollectionTemplateKey(
id,
it.key
) to it.value
})
eventBus.post(EntitySetCollectionCreatedEvent(entitySetCollection))
}
/** DELETE **/
fun deleteEntityTypeCollection(id: UUID) {
ensureEntityTypeCollectionNotInUse(id)
entityTypeCollections.remove(id)
aclKeyReservations.release(id)
eventBus.post(EntityTypeCollectionDeletedEvent(id))
}
fun deleteEntitySetCollection(id: UUID) {
entitySetCollections.remove(id)
aclKeyReservations.release(id)
entitySetCollectionConfig.removeAll(Predicates.equal(ENTITY_SET_COLLECTION_ID_INDEX, id))
eventBus.post(EntitySetCollectionDeletedEvent(id))
}
/** validation **/
fun ensureEntityTypeCollectionExists(id: UUID) {
if (!entityTypeCollections.containsKey(id)) {
throw IllegalStateException("EntityTypeCollection $id does not exist.")
}
}
fun ensureEntitySetCollectionExists(id: UUID) {
if (!entitySetCollections.containsKey(id)) {
throw IllegalStateException("EntitySetCollection $id does not exist.")
}
}
private fun ensureEntityTypeCollectionNotInUse(id: UUID) {
val numEntitySetCollectionsOfType = entitySetCollections.aggregate(
Aggregators.count(),
entityTypeCollectionIdPredicate(id)
)
checkState(
numEntitySetCollectionsOfType == 0L,
"EntityTypeCollection $id cannot be deleted or modified because there exist $numEntitySetCollectionsOfType EntitySetCollections that use it"
)
}
private fun validateEntitySetCollectionTemplate(
name: String, mappings: Map<UUID, UUID>, template: LinkedHashSet<CollectionTemplateType>
) {
val entitySets = entitySetManager.getEntitySetsAsMap(mappings.values.toSet())
val templateEntityTypesById = template.map { it.id to it.entityTypeId }.toMap()
mappings.forEach {
val id = it.key
val entitySetId = it.value
val entitySet = entitySets[entitySetId]
?: throw IllegalStateException("Could not create/update EntitySetCollection $name because entity set $entitySetId does not exist.")
if (entitySet.entityTypeId != templateEntityTypesById[id]) {
throw IllegalStateException(
"Could not create/update EntitySetCollection $name because entity set" +
" $entitySetId for key $id does not match template entity type ${templateEntityTypesById[id]}."
)
}
}
}
/** predicates **/
private fun idsPredicate(ids: Collection<UUID>): Predicate<UUID, EntitySetCollection> {
return Predicates.`in`(ID_INDEX, *ids.toTypedArray())
}
private fun entityTypeCollectionIdPredicate(entityTypeCollectionId: UUID): Predicate<UUID, EntitySetCollection> {
return Predicates.equal(ENTITY_TYPE_COLLECTION_ID_INDEX, entityTypeCollectionId)
}
private fun entitySetCollectionIdsPredicate(ids: Set<UUID>): Predicate<CollectionTemplateKey, UUID> {
return Predicates.`in`(ENTITY_SET_COLLECTION_ID_INDEX, *ids.toTypedArray())
}
/** helpers **/
private fun formatEntitySetName(prefix: String, templateTypeName: String): String {
var name = prefix + "_" + templateTypeName
name = name.toLowerCase().replace("[^a-z0-9_]".toRegex(), "")
return getNextAvailableName(name)
}
private fun generateEntitySet(
entitySetCollection: EntitySetCollection,
collectionTemplateType: CollectionTemplateType,
principal: Principal
): UUID {
val name = formatEntitySetName(entitySetCollection.name, collectionTemplateType.name)
val title = collectionTemplateType.title + " (" + entitySetCollection.name + ")"
val description = "${collectionTemplateType.description}\n\nAuto-generated for EntitySetCollection ${entitySetCollection.name}"
val flags = EnumSet.noneOf(EntitySetFlag::class.java)
val entitySet = EntitySet(
entityTypeId = collectionTemplateType.entityTypeId,
name = name,
_title = title,
_description = description,
contacts = mutableSetOf(),
organizationId = entitySetCollection.organizationId,
flags = flags
)
entitySetManager.createEntitySet(principal, entitySet)
return entitySet.id
}
private fun getNextAvailableName(name: String): String {
var nameAttempt = name
var counter = 1
while (aclKeyReservations.isReserved(nameAttempt)) {
nameAttempt = name + "_" + counter.toString()
counter++
}
return nameAttempt
}
private fun getTemplatesForIds(ids: Set<UUID>): MutableMap<UUID, MutableMap<UUID, UUID>> {
return entitySetCollectionConfig.aggregate(
EntitySetCollectionConfigAggregator(CollectionTemplates()),
entitySetCollectionIdsPredicate(ids)
).templates
}
private fun signalEntityTypeCollectionUpdated(id: UUID) {
eventBus.post(EntityTypeCollectionCreatedEvent(entityTypeCollections.getValue(id)))
}
private fun signalEntitySetCollectionUpdated(id: UUID) {
eventBus.post(EntitySetCollectionCreatedEvent(getEntitySetCollection(id)))
}
} | src/main/kotlin/com/openlattice/collections/CollectionsManager.kt | 896236163 |
/*
* Copyright 2017 Ze Hao Xiao
*
* 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 tests
import com.github.kvnxiao.kommandant.Kommandant
import com.github.kvnxiao.kommandant.command.CommandBuilder
import com.github.kvnxiao.kommandant.command.CommandBuilder.Companion.execute
fun main(args: Array<String>) {
val kommandant = Kommandant()
kommandant.addCommand(CommandBuilder<Unit>("hello_world")
.withPrefix("-")
.withAliases("hello", "print")
.build(execute {
context, opt ->
println("Hello world!")
}))
while (true) {
println("Please enter your input:")
kommandant.process<Any?>(readLine()!!)
}
} | kommandant-core/src/test/kotlin/tests/UserInputTest.kt | 3866580388 |
package syobotsum.screen
import syobotsum.Syobotsum
import syobotsum.actor.forResult
import syobotsum.actor.Block
import syobotsum.actor.Block.BlockType
import syobotsum.actor.BlockField
import syobotsum.actor.BlockResult
import syobotsum.actor.ExitDialog
import com.badlogic.gdx.scenes.scene2d.Action
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.Dialog
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
/**
* 結果画面
*
*/
class ResultScreen(syobotsum: Syobotsum, val blocks: BlockField) : ScreenSkeleton(syobotsum) {
init {
Image(skin, "resultBackground").let {
it.setPosition(0f, 0f)
stage.addActor(it)
}
Image(skin, "resultTitle").let {
it.setPosition(stage.width / 2f, stage.height - 50f, Align.center or Align.top)
stage.addActor(it)
}
val max = blocks.findMax()
val centerBottom = Align.center or Align.bottom
val centerX = stage.width / 2f
BlockResult(skin, "resultHeart", max, BlockType.HEART).let {
it.setPosition(centerX, 650f, centerBottom)
stage.addActor(it)
}
BlockResult(skin, "resultRedking", max, BlockType.REDKING).let {
it.setPosition(centerX, 530f, centerBottom)
stage.addActor(it)
}
val otherResult = BlockResult(skin, "resultOther", max, BlockType.OTHER)
otherResult.setPosition(centerX, 410f, centerBottom)
stage.addActor(otherResult)
var value = 0
var b = max
while (b != null) {
value = value + b.blockType.calc(1)
b = b.under
}
val result = Label(String.format("%03d", value), skin, "score")
result.setPosition(otherResult.getX(Align.right), 250f, Align.bottomRight)
stage.addActor(result)
Image(skin, "resultJoshiryoku").let {
it.setPosition(result.x, 230f, Align.bottomRight)
stage.addActor(it)
}
val restart = Button(skin, "resultRestart")
restart.setPosition((stage.width - (restart.width * 2f)) / 3f, restart.height / 2f)
stage.addActor(restart)
val exit = Button(skin, "resultExit")
exit.setPosition(exit.width + ((stage.width - (exit.width * 2f)) * 2f / 3f), exit.height / 2f)
stage.addActor(exit)
exit.addListener(object : ClickListener() {
override fun clicked(event: InputEvent, x: Float, y: Float) {
val dialog = forResult(skin)
dialog.show(stage)
}
})
restart.addListener(object : ClickListener() {
override fun clicked(event: InputEvent, x: Float, y: Float) {
val fadeOut = Actions.fadeOut(0.5f)
val toGameScreen = Actions.run(Runnable {
syobotsum.screen = GameScreen(syobotsum)
})
stage.addAction(Actions.sequence(fadeOut, toGameScreen))
}
})
val toTransparent = Actions.alpha(0f)
val fadeIn = Actions.fadeIn(0.5f)
stage.addAction(Actions.sequence(toTransparent, fadeIn))
}
}
| core/src/syobotsum/screen/ResultScreen.kt | 1037358680 |
package cs.ut.ui.controllers
import cs.ut.configuration.ConfigNode
import cs.ut.configuration.ConfigurationReader
import cs.ut.util.Cookies
import cs.ut.util.DEST
import cs.ut.util.NAVBAR
import org.apache.logging.log4j.ThreadContext
import org.zkoss.util.resource.Labels
import org.zkoss.zk.ui.Desktop
import org.zkoss.zk.ui.Executions
import org.zkoss.zk.ui.Page
import org.zkoss.zk.ui.event.Event
import org.zkoss.zk.ui.select.Selectors
import org.zkoss.zkmax.zul.Navbar
import org.zkoss.zkmax.zul.Navitem
import org.zkoss.zul.Include
import java.util.Timer
import kotlin.concurrent.timerTask
typealias PageEnum = cs.ut.util.Page
interface Redirectable {
/**
* Sets content of the page. Since application content is located in a single component, then we change is
* asynchronously. This is done using this method.
*
* @param dest - id of the page to which the content should be changed (defined in configuration.xml)
* @param page - caller page where Include element should be looked for.
*/
fun setContent(dest: String, page: Page, params: String = "") {
fun setThreadContext() {
val currExecution = Executions.getCurrent() ?: return
ThreadContext.put("${Thread.currentThread().name}-connId", Cookies.getCookieKey(currExecution.nativeRequest))
}
setThreadContext()
Executions.getCurrent().desktop.setBookmark(dest + (if (params.isNotBlank()) "?" else "") + params, false)
page.title = "${Labels.getLabel("header.$dest")} - Nirdizati"
val include = Selectors.iterable(page, "#contentInclude").iterator().next() as Include
include.src = null
include.src = pages.first { it.identifier == dest }.valueWithIdentifier("page").value
activateHeaderButton(if (dest == PageEnum.VALIDATION.value) PageEnum.MODEL_OVERVIEW.value else dest, page)
}
/**
* Update content of the page with a delay
*
* @param dest new destination
* @param page page where to update the destination
* @param delay delay in MS
* @param desktop client to update the content for
*/
fun setContent(dest: String, page: Page, delay: Int, desktop: Desktop) {
Timer().schedule(timerTask {
Executions.schedule(
desktop,
{ _ ->
setContent(dest, page)
},
Event("content change")
)
}, delay.toLong())
}
/**
* Active selected header button
*
* @param dest new selected value
* @param page where to update the header
*/
private fun activateHeaderButton(dest: String, page: Page) {
val navbar = page.desktop.components.first { it.id == NAVBAR } as Navbar
val navItem = page.desktop.components.firstOrNull { it.getAttribute(DEST) == dest } as Navitem?
navItem?.let { navbar.selectItem(navItem) }
}
companion object {
val pages: List<ConfigNode> = ConfigurationReader.findNode("pages").childNodes
}
} | src/main/kotlin/cs/ut/ui/controllers/Redirectable.kt | 3618646112 |
/*
* Copyright © 2017 Jorge Martín Espinosa
*/
package com.arasthel.spannedgridlayoutmanager
import android.graphics.PointF
import android.graphics.Rect
import android.os.Parcel
import android.os.Parcelable
import android.support.v7.widget.LinearSmoothScroller
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.util.SparseArray
import android.view.View
/**
* A [android.support.v7.widget.RecyclerView.LayoutManager] which layouts and orders its views
* based on width and height spans.
*
* @param orientation Whether the views will be layouted and scrolled in vertical or horizontal
* @param spans How many spans does the layout have per row or column
*/
open class SpannedGridLayoutManager(val orientation: Orientation,
val spans: Int) : RecyclerView.LayoutManager() {
//==============================================================================================
// ~ Orientation & Direction enums
//==============================================================================================
/**
* Orientations to layout and scroll views
* <li>VERTICAL</li>
* <li>HORIZONTAL</li>
*/
enum class Orientation {
VERTICAL, HORIZONTAL
}
/**
* Direction of scroll for layouting process
* <li>START</li>
* <li>END</li>
*/
enum class Direction {
START, END
}
//==============================================================================================
// ~ Properties
//==============================================================================================
/**
* Current scroll amount
*/
protected var scroll = 0
/**
* Helper get free rects to place views
*/
protected lateinit var rectsHelper: RectsHelper
/**
* First visible position in layout - changes with recycling
*/
open val firstVisiblePosition: Int get() {
if (childCount == 0) { return 0 }
return getPosition(getChildAt(0)!!)
}
/**
* Last visible position in layout - changes with recycling
*/
open val lastVisiblePosition: Int get() {
if (childCount == 0) { return 0 }
return getPosition(getChildAt(childCount-1)!!)
}
/**
* Start of the layout. Should be [getPaddingEndForOrientation] + first visible item top
*/
protected var layoutStart = 0
/**
* End of the layout. Should be [layoutStart] + last visible item bottom + [getPaddingEndForOrientation]
*/
protected var layoutEnd = 0
/**
* Total length of the layout depending on current orientation
*/
val size: Int get() = if (orientation == Orientation.VERTICAL) height else width
/**
* Cache of rects for layouted views
*/
protected val childFrames = mutableMapOf<Int, Rect>()
/**
* Temporary variable to store wanted scroll by [scrollToPosition]
*/
protected var pendingScrollToPosition: Int? = null
/**
* Whether item order will be kept along re-creations of this LayoutManager with different
* configurations of not. Default is false. Only set to true if this condition is met.
* Otherwise, scroll bugs will happen.
*/
var itemOrderIsStable = false
/**
* Provides SpanSize values for the LayoutManager. Otherwise they will all be (1, 1).
*/
var spanSizeLookup: SpanSizeLookup? = null
set(newValue) {
field = newValue
// If the SpanSizeLookup changes, the views need a whole re-layout
requestLayout()
}
/**
* SpanSize provider for this LayoutManager.
* SpanSizes can be cached to improve efficiency.
*/
open class SpanSizeLookup(
/** Used to provide an SpanSize for each item. */
var lookupFunction: ((Int) -> SpanSize)? = null
) {
private var cache = SparseArray<SpanSize>()
/**
* Enable SpanSize caching. Can be used to improve performance if calculating the SpanSize
* for items is a complex process.
*/
var usesCache = false
/**
* Returns an SpanSize for the provided position.
* @param position Adapter position of the item
* @return An SpanSize, either provided by the user or the default one.
*/
fun getSpanSize(position: Int): SpanSize {
if (usesCache) {
val cachedValue = cache[position]
if (cachedValue != null) return cachedValue
val value = getSpanSizeFromFunction(position)
cache.put(position, value)
return value
} else {
return getSpanSizeFromFunction(position)
}
}
private fun getSpanSizeFromFunction(position: Int): SpanSize {
return lookupFunction?.invoke(position) ?: getDefaultSpanSize()
}
protected open fun getDefaultSpanSize(): SpanSize {
return SpanSize(1, 1)
}
fun invalidateCache() {
cache.clear()
}
}
//==============================================================================================
// ~ Initializer
//==============================================================================================
init {
if (spans < 1) {
throw InvalidMaxSpansException(spans)
}
}
//==============================================================================================
// ~ Override parent
//==============================================================================================
override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
return RecyclerView.LayoutParams(
RecyclerView.LayoutParams.MATCH_PARENT,
RecyclerView.LayoutParams.WRAP_CONTENT
)
}
//==============================================================================================
// ~ View layouting methods
//==============================================================================================
override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
rectsHelper = RectsHelper(this, orientation)
layoutStart = getPaddingStartForOrientation()
layoutEnd = if (scroll != 0) {
val currentRow = (scroll - layoutStart) / rectsHelper.itemSize
currentRow * rectsHelper.itemSize
} else {
getPaddingEndForOrientation()
}
// Clear cache, since layout may change
childFrames.clear()
// If there were any views, detach them so they can be recycled
detachAndScrapAttachedViews(recycler)
val start = System.currentTimeMillis()
for (i in 0 until state.itemCount) {
val spanSize = spanSizeLookup?.getSpanSize(i) ?: SpanSize(1, 1)
val childRect = rectsHelper.findRect(i, spanSize)
rectsHelper.pushRect(i, childRect)
}
if (DEBUG) {
val elapsed = System.currentTimeMillis() - start
debugLog("Elapsed time: $elapsed ms")
}
// Restore scroll position based on first visible view
val pendingScrollToPosition = pendingScrollToPosition
if (itemCount != 0 && pendingScrollToPosition != null && pendingScrollToPosition >= spans) {
val currentRow = rectsHelper.rows.filter { (_, value) -> value.contains(pendingScrollToPosition) }.keys.firstOrNull()
if (currentRow != null) {
scroll = getPaddingStartForOrientation() + (currentRow * rectsHelper.itemSize)
}
this.pendingScrollToPosition = null
}
// Fill from start to visible end
fillGap(Direction.END, recycler, state)
recycleChildrenOutOfBounds(Direction.END, recycler)
// Check if after changes in layout we aren't out of its bounds
val overScroll = scroll + size - layoutEnd - getPaddingEndForOrientation()
val isLastItemInScreen = (0 until childCount).map { getPosition(getChildAt(it)!!) }.contains(itemCount - 1)
val allItemsInScreen = itemCount == 0 || (firstVisiblePosition == 0 && isLastItemInScreen)
if (!allItemsInScreen && overScroll > 0) {
// If we are, fix it
scrollBy(overScroll, state)
if (overScroll > 0) {
fillBefore(recycler)
} else {
fillAfter(recycler)
}
}
}
/**
* Measure child view using [RectsHelper]
*/
protected open fun measureChild(position: Int, view: View) {
val freeRectsHelper = this.rectsHelper
val itemWidth = freeRectsHelper.itemSize
val itemHeight = freeRectsHelper.itemSize
val spanSize = spanSizeLookup?.getSpanSize(position) ?: SpanSize(1, 1)
val usedSpan = if (orientation == Orientation.HORIZONTAL) spanSize.height else spanSize.width
if (usedSpan > this.spans || usedSpan < 1) {
throw InvalidSpanSizeException(errorSize = usedSpan, maxSpanSize = spans)
}
// This rect contains just the row and column number - i.e.: [0, 0, 1, 1]
val rect = freeRectsHelper.findRect(position, spanSize)
// Multiply the rect for item width and height to get positions
val left = rect.left * itemWidth
val right = rect.right * itemWidth
val top = rect.top * itemHeight
val bottom = rect.bottom * itemHeight
val insetsRect = Rect()
calculateItemDecorationsForChild(view, insetsRect)
// Measure child
val width = right - left - insetsRect.left - insetsRect.right
val height = bottom - top - insetsRect.top - insetsRect.bottom
val layoutParams = view.layoutParams
layoutParams.width = width
layoutParams.height = height
measureChildWithMargins(view, width, height)
// Cache rect
childFrames[position] = Rect(left, top, right, bottom)
}
/**
* Layout child once it's measured and its position cached
*/
protected open fun layoutChild(position: Int, view: View) {
val frame = childFrames[position]
if (frame != null) {
val scroll = this.scroll
val startPadding = getPaddingStartForOrientation()
if (orientation == Orientation.VERTICAL) {
layoutDecorated(view,
frame.left + paddingLeft,
frame.top - scroll + startPadding,
frame.right + paddingLeft,
frame.bottom - scroll + startPadding)
} else {
layoutDecorated(view,
frame.left - scroll + startPadding,
frame.top + paddingTop,
frame.right - scroll + startPadding,
frame.bottom + paddingTop)
}
}
// A new child was layouted, layout edges change
updateEdgesWithNewChild(view)
}
/**
* Ask the recycler for a view, measure and layout it and add it to the layout
*/
protected open fun makeAndAddView(position: Int, direction: Direction, recycler: RecyclerView.Recycler): View {
val view = makeView(position, direction, recycler)
if (direction == Direction.END) {
addView(view)
} else {
addView(view, 0)
}
return view
}
protected open fun makeView(position: Int, direction: Direction, recycler: RecyclerView.Recycler): View {
val view = recycler.getViewForPosition(position)
measureChild(position, view)
layoutChild(position, view)
return view
}
/**
* A new view was added, update layout edges if needed
*/
protected open fun updateEdgesWithNewChild(view: View) {
val childStart = getChildStart(view) + scroll + getPaddingStartForOrientation()
if (childStart < layoutStart) {
layoutStart = childStart
}
val newLayoutEnd = childStart + rectsHelper.itemSize
if (newLayoutEnd > layoutEnd) {
layoutEnd = newLayoutEnd
}
}
//==============================================================================================
// ~ Recycling methods
//==============================================================================================
/**
* Recycle any views that are out of bounds
*/
protected open fun recycleChildrenOutOfBounds(direction: Direction, recycler: RecyclerView.Recycler) {
if (direction == Direction.END) {
recycleChildrenFromStart(direction, recycler)
} else {
recycleChildrenFromEnd(direction, recycler)
}
}
/**
* Recycle views from start to first visible item
*/
protected open fun recycleChildrenFromStart(direction: Direction, recycler: RecyclerView.Recycler) {
val childCount = childCount
val start = getPaddingStartForOrientation()
val toDetach = mutableListOf<View>()
for (i in 0 until childCount) {
val child = getChildAt(i)!!
val childEnd = getChildEnd(child)
if (childEnd < start) {
toDetach.add(child)
}
}
for (child in toDetach) {
removeAndRecycleView(child, recycler)
updateEdgesWithRemovedChild(child, direction)
}
}
/**
* Recycle views from end to last visible item
*/
protected open fun recycleChildrenFromEnd(direction: Direction, recycler: RecyclerView.Recycler) {
val childCount = childCount
val end = size + getPaddingEndForOrientation()
val toDetach = mutableListOf<View>()
for (i in (0 until childCount).reversed()) {
val child = getChildAt(i)!!
val childStart = getChildStart(child)
if (childStart > end) {
toDetach.add(child)
}
}
for (child in toDetach) {
removeAndRecycleView(child, recycler)
updateEdgesWithRemovedChild(child, direction)
}
}
/**
* Update layout edges when views are recycled
*/
protected open fun updateEdgesWithRemovedChild(view: View, direction: Direction) {
val childStart = getChildStart(view) + scroll
val childEnd = getChildEnd(view) + scroll
if (direction == Direction.END) { // Removed from start
layoutStart = getPaddingStartForOrientation() + childEnd
} else if (direction == Direction.START) { // Removed from end
layoutEnd = getPaddingStartForOrientation() + childStart
}
}
//==============================================================================================
// ~ Scroll methods
//==============================================================================================
override fun computeVerticalScrollOffset(state: RecyclerView.State): Int {
return computeScrollOffset()
}
override fun computeHorizontalScrollOffset(state: RecyclerView.State): Int {
return computeScrollOffset()
}
private fun computeScrollOffset(): Int {
return if (childCount == 0) 0 else firstVisiblePosition
}
override fun computeVerticalScrollExtent(state: RecyclerView.State): Int {
return childCount
}
override fun computeHorizontalScrollExtent(state: RecyclerView.State): Int {
return childCount
}
override fun computeVerticalScrollRange(state: RecyclerView.State): Int {
return state.itemCount
}
override fun computeHorizontalScrollRange(state: RecyclerView.State): Int {
return state.itemCount
}
override fun canScrollVertically(): Boolean {
return orientation == Orientation.VERTICAL
}
override fun canScrollHorizontally(): Boolean {
return orientation == Orientation.HORIZONTAL
}
override fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
return scrollBy(dx, recycler, state)
}
override fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
return scrollBy(dy, recycler, state)
}
protected open fun scrollBy(delta: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): Int {
// If there are no view or no movement, return
if (delta == 0) {
return 0
}
val canScrollBackwards = (firstVisiblePosition) >= 0 &&
0 < scroll &&
delta < 0
val canScrollForward = (firstVisiblePosition + childCount) <= state.itemCount &&
(scroll + size) < (layoutEnd + rectsHelper.itemSize + getPaddingEndForOrientation())
delta > 0
// If can't scroll forward or backwards, return
if (!(canScrollBackwards || canScrollForward)) {
return 0
}
val correctedDistance = scrollBy(-delta, state)
val direction = if (delta > 0) Direction.END else Direction.START
recycleChildrenOutOfBounds(direction, recycler)
fillGap(direction, recycler, state)
return -correctedDistance
}
/**
* Scrolls distance based on orientation. Corrects distance if out of bounds.
*/
protected open fun scrollBy(distance: Int, state: RecyclerView.State): Int {
val paddingEndLayout = getPaddingEndForOrientation()
val start = 0
val end = layoutEnd + rectsHelper.itemSize + paddingEndLayout
scroll -= distance
var correctedDistance = distance
// Correct scroll if was out of bounds at start
if (scroll < start) {
correctedDistance += scroll
scroll = start
}
// Correct scroll if it would make the layout scroll out of bounds at the end
if (scroll + size > end && (firstVisiblePosition + childCount + spans) >= state.itemCount) {
correctedDistance -= (end - scroll - size)
scroll = end - size
}
if (orientation == Orientation.VERTICAL) {
offsetChildrenVertical(correctedDistance)
} else{
offsetChildrenHorizontal(correctedDistance)
}
return correctedDistance
}
override fun scrollToPosition(position: Int) {
pendingScrollToPosition = position
requestLayout()
}
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {
val smoothScroller = object: LinearSmoothScroller(recyclerView.context) {
override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
if (childCount == 0) {
return null
}
val direction = if (targetPosition < firstVisiblePosition) -1 else 1
return PointF(0f, direction.toFloat())
}
override fun getVerticalSnapPreference(): Int {
return LinearSmoothScroller.SNAP_TO_START
}
}
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
/**
* Fills gaps on the layout, on directions [Direction.START] or [Direction.END]
*/
protected open fun fillGap(direction: Direction, recycler: RecyclerView.Recycler, state: RecyclerView.State) {
if (direction == Direction.END) {
fillAfter(recycler)
} else {
fillBefore(recycler)
}
}
/**
* Fill gaps before the current visible scroll position
* @param recycler Recycler
*/
protected open fun fillBefore(recycler: RecyclerView.Recycler) {
val currentRow = (scroll - getPaddingStartForOrientation()) / rectsHelper.itemSize
val lastRow = (scroll + size - getPaddingStartForOrientation()) / rectsHelper.itemSize
for (row in (currentRow until lastRow).reversed()) {
val positionsForRow = rectsHelper.findPositionsForRow(row).reversed()
for (position in positionsForRow) {
if (findViewByPosition(position) != null) continue
makeAndAddView(position, Direction.START, recycler)
}
}
}
/**
* Fill gaps after the current layouted views
* @param recycler Recycler
*/
protected open fun fillAfter(recycler: RecyclerView.Recycler) {
val visibleEnd = scroll + size
val lastAddedRow = layoutEnd / rectsHelper.itemSize
val lastVisibleRow = visibleEnd / rectsHelper.itemSize
for (rowIndex in lastAddedRow .. lastVisibleRow) {
val row = rectsHelper.rows[rowIndex] ?: continue
for (itemIndex in row) {
if (findViewByPosition(itemIndex) != null) continue
makeAndAddView(itemIndex, Direction.END, recycler)
}
}
}
//==============================================================================================
// ~ Decorated position and sizes
//==============================================================================================
override fun getDecoratedMeasuredWidth(child: View): Int {
val position = getPosition(child)
return childFrames[position]!!.width()
}
override fun getDecoratedMeasuredHeight(child: View): Int {
val position = getPosition(child)
return childFrames[position]!!.height()
}
override fun getDecoratedTop(child: View): Int {
val position = getPosition(child)
val decoration = getTopDecorationHeight(child)
var top = childFrames[position]!!.top + decoration
if (orientation == Orientation.VERTICAL) {
top -= scroll
}
return top
}
override fun getDecoratedRight(child: View): Int {
val position = getPosition(child)
val decoration = getLeftDecorationWidth(child) + getRightDecorationWidth(child)
var right = childFrames[position]!!.right + decoration
if (orientation == Orientation.HORIZONTAL) {
right -= scroll - getPaddingStartForOrientation()
}
return right
}
override fun getDecoratedLeft(child: View): Int {
val position = getPosition(child)
val decoration = getLeftDecorationWidth(child)
var left = childFrames[position]!!.left + decoration
if (orientation == Orientation.HORIZONTAL) {
left -= scroll
}
return left
}
override fun getDecoratedBottom(child: View): Int {
val position = getPosition(child)
val decoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child)
var bottom = childFrames[position]!!.bottom + decoration
if (orientation == Orientation.VERTICAL) {
bottom -= scroll - getPaddingStartForOrientation()
}
return bottom
}
//==============================================================================================
// ~ Orientation Utils
//==============================================================================================
protected open fun getPaddingStartForOrientation(): Int {
return if (orientation == Orientation.VERTICAL) {
paddingTop
} else {
paddingLeft
}
}
protected open fun getPaddingEndForOrientation(): Int {
return if (orientation == Orientation.VERTICAL) {
paddingBottom
} else {
paddingRight
}
}
protected open fun getChildStart(child: View): Int {
return if (orientation == Orientation.VERTICAL) {
getDecoratedTop(child)
} else {
getDecoratedLeft(child)
}
}
protected open fun getChildEnd(child: View): Int {
return if (orientation == Orientation.VERTICAL) {
getDecoratedBottom(child)
} else {
getDecoratedRight(child)
}
}
//==============================================================================================
// ~ Save & Restore State
//==============================================================================================
override fun onSaveInstanceState(): Parcelable? {
return if (itemOrderIsStable && childCount > 0) {
debugLog("Saving first visible position: $firstVisiblePosition")
SavedState(firstVisiblePosition)
} else {
null
}
}
override fun onRestoreInstanceState(state: Parcelable) {
debugLog("Restoring state")
val savedState = state as? SavedState
if (savedState != null) {
val firstVisibleItem = savedState.firstVisibleItem
scrollToPosition(firstVisibleItem)
}
}
companion object {
const val TAG = "SpannedGridLayoutMan"
const val DEBUG = false
fun debugLog(message: String) {
if (DEBUG) Log.d(TAG, message)
}
}
class SavedState(val firstVisibleItem: Int): Parcelable {
companion object {
@JvmField val CREATOR = object: Parcelable.Creator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source.readInt())
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(firstVisibleItem)
}
override fun describeContents(): Int {
return 0
}
}
}
/**
* A helper to find free rects in the current layout.
*/
open class RectsHelper(val layoutManager: SpannedGridLayoutManager,
val orientation: SpannedGridLayoutManager.Orientation) {
/**
* Comparator to sort free rects by position, based on orientation
*/
private val rectComparator = Comparator<Rect> { rect1, rect2 ->
when (orientation) {
SpannedGridLayoutManager.Orientation.VERTICAL -> {
if (rect1.top == rect2.top) {
if (rect1.left < rect2.left) { -1 } else { 1 }
} else {
if (rect1.top < rect2.top) { -1 } else { 1 }
}
}
SpannedGridLayoutManager.Orientation.HORIZONTAL -> {
if (rect1.left == rect2.left) {
if (rect1.top < rect2.top) { -1 } else { 1 }
} else {
if (rect1.left < rect2.left) { -1 } else { 1 }
}
}
}
}
val rows = mutableMapOf<Int, Set<Int>>()
/**
* Cache of rects that are already used
*/
private val rectsCache = mutableMapOf<Int, Rect>()
/**
* List of rects that are still free
*/
private val freeRects = mutableListOf<Rect>()
/**
* Free space to divide in spans
*/
val size: Int get() {
return if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
layoutManager.width - layoutManager.paddingLeft - layoutManager.paddingRight
} else {
layoutManager.height - layoutManager.paddingTop - layoutManager.paddingBottom
}
}
/**
* Space occupied by each span
*/
val itemSize: Int get() = size / layoutManager.spans
/**
* Start row/column for free rects
*/
val start: Int get() {
return if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
freeRects[0].top * itemSize
} else {
freeRects[0].left * itemSize
}
}
/**
* End row/column for free rects
*/
val end: Int get() {
return if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
(freeRects.last().top + 1) * itemSize
} else {
(freeRects.last().left + 1) * itemSize
}
}
init {
// There will always be a free rect that goes to Int.MAX_VALUE
val initialFreeRect = if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL) {
Rect(0, 0, layoutManager.spans, Int.MAX_VALUE)
} else {
Rect(0, 0, Int.MAX_VALUE, layoutManager.spans)
}
freeRects.add(initialFreeRect)
}
/**
* Get a free rect for the given span and item position
*/
fun findRect(position: Int, spanSize: SpanSize): Rect {
return rectsCache[position] ?: findRectForSpanSize(spanSize)
}
/**
* Find a valid free rect for the given span size
*/
protected open fun findRectForSpanSize(spanSize: SpanSize): Rect {
val lane = freeRects.first {
val itemRect = Rect(it.left, it.top, it.left+spanSize.width, it.top + spanSize.height)
it.contains(itemRect)
}
return Rect(lane.left, lane.top, lane.left+spanSize.width, lane.top + spanSize.height)
}
/**
* Push this rect for the given position, subtract it from [freeRects]
*/
fun pushRect(position: Int, rect: Rect) {
val start = if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL)
rect.top else
rect.left
val startRow = rows[start]?.toMutableSet() ?: mutableSetOf()
startRow.add(position)
rows[start] = startRow
val end = if (orientation == SpannedGridLayoutManager.Orientation.VERTICAL)
rect.bottom else
rect.right
val endRow = rows[end - 1]?.toMutableSet() ?: mutableSetOf()
endRow.add(position)
rows[end - 1] = endRow
rectsCache[position] = rect
subtract(rect)
}
fun findPositionsForRow(rowPosition: Int): Set<Int> {
return rows[rowPosition] ?: emptySet()
}
/**
* Remove this rect from the [freeRects], merge and reorder new free rects
*/
protected open fun subtract(subtractedRect: Rect) {
val interestingRects = freeRects.filter { it.isAdjacentTo(subtractedRect) || it.intersects(subtractedRect) }
val possibleNewRects = mutableListOf<Rect>()
val adjacentRects = mutableListOf<Rect>()
for (free in interestingRects) {
if (free.isAdjacentTo(subtractedRect) && !subtractedRect.contains(free)) {
adjacentRects.add(free)
} else {
freeRects.remove(free)
if (free.left < subtractedRect.left) { // Left
possibleNewRects.add(Rect(free.left, free.top, subtractedRect.left, free.bottom))
}
if (free.right > subtractedRect.right) { // Right
possibleNewRects.add(Rect(subtractedRect.right, free.top, free.right, free.bottom))
}
if (free.top < subtractedRect.top) { // Top
possibleNewRects.add(Rect(free.left, free.top, free.right, subtractedRect.top))
}
if (free.bottom > subtractedRect.bottom) { // Bottom
possibleNewRects.add(Rect(free.left, subtractedRect.bottom, free.right, free.bottom))
}
}
}
for (rect in possibleNewRects) {
val isAdjacent = adjacentRects.firstOrNull { it != rect && it.contains(rect) } != null
if (isAdjacent) continue
val isContained = possibleNewRects.firstOrNull { it != rect && it.contains(rect) } != null
if (isContained) continue
freeRects.add(rect)
}
freeRects.sortWith(rectComparator)
}
}
/**
* Helper to store width and height spans
*/
class SpanSize(val width: Int, val height: Int) | spannedgridlayoutmanager/src/main/java/com/arasthel/spannedgridlayoutmanager/SpannedGridLayoutManager.kt | 3136620874 |
package com.github.mikegehard
data class Quote(val person: String, val text: String)
fun main(args: Array<String>) {
val quotes = listOf(
Quote("Ob-Wan Kenobi", "These aren't the droids you're looking for.")
)
quotes.forEach { println("${it.person} says, \"${it.text}\"") }
} | src/main/com/github/mikegehard/printingQuotes.kt | 1280883671 |
package org.swordess.persistence.json
import org.junit.Test
import org.swordess.persistence.json.java.test.model.User
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class JsonTableTest {
@Test
fun testExceptionShouldBeThrownIfGivenIdGeneratorLessThan1() {
try {
JsonTable<User>(metadata = JsonEntityMetadata(User::class), idGenerator = 0)
} catch (e: IllegalArgumentException) {
assertEquals("idGenerator must be greater than or equal to 1", e.message)
}
}
@Test
fun testRefreshTableIsEmpty() {
val table = createUserTable()
assertTrue(table.isEmpty())
assertEquals(0, table.size())
}
@Test
fun testReplaceShouldReturnFalseIfCannotBeFound() {
val table = createUserTable()
assertFalse(table.replace(
User().apply { username = "foo" },
User().apply { username = "bar" }
))
}
private fun createUserTable() = JsonTable<User>(JsonEntityMetadata(User::class))
} | src/test/kotlin/org/swordess/persistence/json/JsonTableTest.kt | 3797510203 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androidthings.endtoend.companion.auth
import androidx.lifecycle.MutableLiveData
import com.example.androidthings.endtoend.companion.domain.UploadUserIdUseCase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.UserInfo
/** AuthProvider implementation based on FirebaseAuth. */
object FirebaseAuthProvider : AuthProvider {
private val firebaseAuth = FirebaseAuth.getInstance()
private val uploadUserIdUseCase = UploadUserIdUseCase()
private var authUiHelper: FirebaseAuthUiHelper? = null
override val userLiveData = MutableLiveData<UserInfo?>()
init {
firebaseAuth.addAuthStateListener { auth ->
// Listener is invoked immediately after registration, when a user signs in, when the
// current user signs out, and when the current user changes.
val currentUser = auth.currentUser
userLiveData.postValue(currentUser)
// Ensure the email<>uid mapping is in Firestore
if (currentUser != null) {
uploadUserIdUseCase.execute(currentUser)
}
}
}
/**
* Set the FirebaseAuthUiHelper. Intended to be used in [Activity#oncreate]
* [android.app.Activity.onCreate].
*/
fun setAuthUiHelper(uiHelper: FirebaseAuthUiHelper) {
authUiHelper = uiHelper
}
/**
* Unset the FirebaseAuthUiHelper if the argument is the current helper. Intended to be used in
* [Activity#onDestroy][android.app.Activity.onDestroy].
*/
fun unsetAuthUiHelper(uiHelper: FirebaseAuthUiHelper) {
if (authUiHelper == uiHelper) {
authUiHelper = null
}
}
override fun performSignIn() {
requireNotNull(authUiHelper).performSignIn()
}
override fun performSignOut() {
requireNotNull(authUiHelper).performSignOut()
}
}
/** Separates auth UI from FirebaseAuthProvider logic. */
interface FirebaseAuthUiHelper {
fun performSignIn()
fun performSignOut()
}
| companionApp/src/main/java/com/example/androidthings/endtoend/companion/auth/FirebaseAuthProvider.kt | 2535498425 |
package me.panpf.sketch.sample.ui
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import kotlinx.android.synthetic.main.fragment_base64_test.*
import me.panpf.sketch.sample.AssetImage
import me.panpf.sketch.sample.base.BaseFragment
import me.panpf.sketch.sample.base.BindContentView
import me.panpf.sketch.sample.R
@BindContentView(R.layout.fragment_base64_test)
class Base64ImageTestFragment : BaseFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
edit_base64TestFragment.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
showImage(s.toString())
}
override fun afterTextChanged(s: Editable) {}
})
edit_base64TestFragment.setText(AssetImage.URI_TEST_BASE64)
}
private fun showImage(imageText: String) {
image_base64TestFragment.displayImage(imageText)
}
}
| sample/src/main/java/me/panpf/sketch/sample/ui/Base64ImageTestFragment.kt | 2733327150 |
package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.jsonProtocol.ProtocolMetaModel
import org.jetbrains.protocolReader.JSON_READER_PARAMETER_DEF
import org.jetbrains.protocolReader.TextOutput
import org.jetbrains.protocolReader.appendEnums
fun fixMethodName(name: String): String {
val i = name.indexOf("breakpoint")
return if (i > 0) name.substring(0, i) + 'B' + name.substring(i + 1) else name
}
interface TextOutConsumer {
fun append(out: TextOutput)
}
class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Domain) {
fun registerTypes() {
if (domain.types() != null) {
for (type in domain.types()!!) {
generator.typeMap.getTypeData(domain.domain(), type.id()).setType(type)
}
}
}
fun generateCommandsAndEvents() {
val requestsFileUpdater = generator.startJavaFile(generator.naming.params.getPackageNameVirtual(domain.domain()), "Requests.java")
val out = requestsFileUpdater.out
out.append("import org.jetbrains.annotations.NotNull;").newLine()
out.append("import org.jetbrains.jsonProtocol.Request;").newLine()
out.newLine().append("public final class ").append("Requests")
out.openBlock()
var isFirst = true
for (command in domain.commands()) {
val hasResponse = command.returns() != null
var onlyMandatoryParams = true
val params = command.parameters()
val hasParams = params != null && !params.isEmpty()
if (hasParams) {
for (parameter in params!!) {
if (parameter.optional()) {
onlyMandatoryParams = false
}
}
}
val returnType = if (hasResponse) generator.naming.commandResult.getShortName(command.name()) else "Void"
if (onlyMandatoryParams) {
if (isFirst) {
isFirst = false
}
else {
out.newLine().newLine()
}
out.append("@NotNull").newLine().append("public static Request<")
out.append(returnType)
out.append(">").space().append(fixMethodName(command.name())).append("(")
val classScope = OutputClassScope(this, generator.naming.params.getFullName(domain.domain(), command.name()))
val parameterTypes = if (hasParams) arrayOfNulls<BoxableType>(params!!.size()) else null
if (hasParams) {
classScope.writeMethodParameters<ProtocolMetaModel.Parameter>(out, params!!, parameterTypes!!)
}
out.append(')').openBlock()
val requestClassName = generator.naming.requestClassName.replace("Request", "SimpleRequest")
if (hasParams) {
out.append(requestClassName).append('<').append(returnType).append(">").append(" r =")
}
else {
out.append("return")
}
out.append(" new ").append(requestClassName).append("<").append(returnType).append(">(\"")
if (!domain.domain().isEmpty()) {
out.append(domain.domain()).append('.')
}
out.append(command.name()).append("\")").semi()
if (hasParams) {
classScope.writeWriteCalls<ProtocolMetaModel.Parameter>(out, params!!, parameterTypes!!, "r")
out.newLine().append("return r").semi()
}
out.closeBlock()
classScope.writeAdditionalMembers(out)
}
else {
generateRequest(command, returnType)
}
if (hasResponse) {
val fileUpdater = generator.startJavaFile(generator.naming.commandResult, domain, command.name())
generateJsonProtocolInterface(fileUpdater.out, generator.naming.commandResult.getShortName(command.name()), command.description(), command.returns(), null)
fileUpdater.update()
generator.jsonProtocolParserClassNames.add(generator.naming.commandResult.getFullName(domain.domain(), command.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), command.name(), generator.naming.commandResult))
}
}
out.closeBlock()
requestsFileUpdater.update()
if (domain.events() != null) {
for (event in domain.events()!!) {
generateEvenData(event)
generator.jsonProtocolParserClassNames.add(generator.naming.eventData.getFullName(domain.domain(), event.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), event.name(), generator.naming.eventData))
}
}
}
private fun generateRequest(command: ProtocolMetaModel.Command, returnType: String) {
val baseTypeBuilder = object : TextOutConsumer {
override fun append(out: TextOutput) {
out.space().append("extends ").append(generator.naming.requestClassName).append('<').append(returnType).append('>')
}
}
val memberBuilder = object : TextOutConsumer {
override fun append(out: TextOutput) {
out.append("@NotNull").newLine().append("@Override").newLine().append("public String getMethodName()").openBlock()
out.append("return \"")
if (!domain.domain().isEmpty()) {
out.append(domain.domain()).append('.')
}
out.append(command.name()).append('"').semi().closeBlock()
}
}
generateTopLevelOutputClass(generator.naming.params, command.name(), command.description(), baseTypeBuilder, memberBuilder, command.parameters())
}
fun generateCommandAdditionalParam(type: ProtocolMetaModel.StandaloneType) {
generateTopLevelOutputClass(generator.naming.additionalParam, type.id(), type.description(), null, null, type.properties())
}
private fun <P : ItemDescriptor.Named> generateTopLevelOutputClass(nameScheme: ClassNameScheme, baseName: String, description: String?, baseType: TextOutConsumer?, additionalMemberText: TextOutConsumer?, properties: List<P>?) {
val fileUpdater = generator.startJavaFile(nameScheme, domain, baseName)
if (nameScheme == generator.naming.params) {
fileUpdater.out.append("import org.jetbrains.annotations.NotNull;").newLine().newLine()
}
generateOutputClass(fileUpdater.out, nameScheme.getFullName(domain.domain(), baseName), description, baseType, additionalMemberText, properties)
fileUpdater.update()
}
private fun <P : ItemDescriptor.Named> generateOutputClass(out: TextOutput, classNamePath: NamePath, description: String?, baseType: TextOutConsumer?, additionalMemberText: TextOutConsumer?, properties: List<P>?) {
out.doc(description)
out.append("public final class ").append(classNamePath.lastComponent)
if (baseType == null) {
out.append(" extends ").append("org.jetbrains.jsonProtocol.OutMessage")
}
else {
baseType.append(out)
}
val classScope = OutputClassScope(this, classNamePath)
if (additionalMemberText != null) {
classScope.addMember(additionalMemberText)
}
out.openBlock()
classScope.generate<P>(out, properties)
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
fun createStandaloneOutputTypeBinding(type: ProtocolMetaModel.StandaloneType, name: String): StandaloneTypeBinding {
return switchByType(type, MyCreateStandaloneTypeBindingVisitorBase(this, type, name))
}
fun createStandaloneInputTypeBinding(type: ProtocolMetaModel.StandaloneType): StandaloneTypeBinding {
return switchByType(type, object : CreateStandaloneTypeBindingVisitorBase(this, type) {
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
return createStandaloneObjectInputTypeBinding(type, properties)
}
override fun visitEnum(enumConstants: List<String>): StandaloneTypeBinding {
val name = type.id()
return object : StandaloneTypeBinding {
override fun getJavaType() = StandaloneType(generator.naming.inputEnum.getFullName(domain.domain(), name), "writeEnum")
override fun generate() {
val fileUpdater = generator.startJavaFile(generator.naming.inputEnum, domain, name)
fileUpdater.out.doc(type.description())
appendEnums(enumConstants, generator.naming.inputEnum.getShortName(name), true, fileUpdater.out)
fileUpdater.update()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): StandaloneTypeBinding {
val resolveAndGenerateScope = object : ResolveAndGenerateScope {
// This class is responsible for generating ad hoc type.
// If we ever are to do it, we should generate into string buffer and put strings
// inside TypeDef class.
override fun getDomainName() = domain.domain()
override fun getTypeDirection() = TypeData.Direction.INPUT
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = throw UnsupportedOperationException()
}
val arrayType = ListType(generator.resolveType(items, resolveAndGenerateScope).type)
return createTypedefTypeBinding(type, object : Target {
override fun resolve(context: Target.ResolveContext): BoxableType {
return arrayType
}
}, generator.naming.inputTypedef, TypeData.Direction.INPUT)
}
})
}
fun createStandaloneObjectInputTypeBinding(type: ProtocolMetaModel.StandaloneType, properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
val name = type.id()
val fullTypeName = generator.naming.inputValue.getFullName(domain.domain(), name)
generator.jsonProtocolParserClassNames.add(fullTypeName.getFullText())
return object : StandaloneTypeBinding {
override fun getJavaType(): BoxableType {
return StandaloneType(fullTypeName, "writeMessage")
}
override fun generate() {
val className = generator.naming.inputValue.getFullName(domain.domain(), name)
val fileUpdater = generator.startJavaFile(generator.naming.inputValue, domain, name)
val out = fileUpdater.out
descriptionAndRequiredImport(type.description(), out)
out.append("public interface ").append(className.lastComponent).openBlock()
val classScope = InputClassScope(this@DomainGenerator, className)
if (properties != null) {
classScope.generateDeclarationBody(out, properties)
}
classScope.writeAdditionalMembers(out)
out.closeBlock()
fileUpdater.update()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
/**
* Typedef is an empty class that just holds description and
* refers to an actual type (such as String).
*/
fun createTypedefTypeBinding(type: ProtocolMetaModel.StandaloneType, target: Target, nameScheme: ClassNameScheme, direction: TypeData.Direction?): StandaloneTypeBinding {
val name = type.id()
val typedefJavaName = nameScheme.getFullName(domain.domain(), name)
val actualJavaType = target.resolve(object : Target.ResolveContext {
override fun generateNestedObject(shortName: String, description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType {
val classNamePath = NamePath(shortName, typedefJavaName)
if (direction == null) {
throw RuntimeException("Unsupported")
}
when (direction) {
TypeData.Direction.INPUT -> throw RuntimeException("TODO")
TypeData.Direction.OUTPUT -> {
val out = TextOutput(StringBuilder())
generateOutputClass(out, classNamePath, description, null, null, properties)
}
else -> throw RuntimeException()
}
return StandaloneType(NamePath(shortName, typedefJavaName), "writeMessage")
}
})
return object : StandaloneTypeBinding {
override fun getJavaType() = actualJavaType
override fun generate() {
}
override fun getDirection() = direction
}
}
private fun generateEvenData(event: ProtocolMetaModel.Event) {
val className = generator.naming.eventData.getShortName(event.name())
val fileUpdater = generator.startJavaFile(generator.naming.eventData, domain, event.name())
val domainName = domain.domain()
val fullName = generator.naming.eventData.getFullName(domainName, event.name()).getFullText()
generateJsonProtocolInterface(fileUpdater.out, className, event.description(), event.parameters(), object : TextOutConsumer {
override fun append(out: TextOutput) {
out.append("org.jetbrains.wip.protocol.WipEventType<").append(fullName).append("> TYPE").newLine()
out.append("\t= new org.jetbrains.wip.protocol.WipEventType<").append(fullName).append(">")
out.append("(\"").append(domainName).append('.').append(event.name()).append("\", ").append(fullName).append(".class)").openBlock()
run {
out.append("@Override").newLine().append("public ").append(fullName).append(" read(")
out.append(generator.naming.inputPackage).append('.').append(READER_INTERFACE_NAME + " protocolReader, ").append(JSON_READER_PARAMETER_DEF).append(")").openBlock()
out.append("return protocolReader.").append(generator.naming.eventData.getParseMethodName(domainName, event.name())).append("(reader);").closeBlock()
}
out.closeBlock()
out.semi()
}
})
fileUpdater.update()
}
private fun generateJsonProtocolInterface(out: TextOutput, className: String, description: String?, parameters: List<ProtocolMetaModel.Parameter>?, additionalMembersText: TextOutConsumer?) {
descriptionAndRequiredImport(description, out)
out.append("public interface ").append(className).openBlock()
val classScope = InputClassScope(this, NamePath(className, NamePath(getPackageName(generator.naming.inputPackage, domain.domain()))))
if (additionalMembersText != null) {
classScope.addMember(additionalMembersText)
}
if (parameters != null) {
classScope.generateDeclarationBody(out, parameters)
}
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
private fun descriptionAndRequiredImport(description: String?, out: TextOutput) {
out.append("import org.jetbrains.jsonProtocol.JsonType;").newLine().newLine()
if (description != null) {
out.doc(description)
}
out.append("@JsonType").newLine()
}
} | platform/script-debugger/protocol/protocol-model-generator/src/DomainGenerator.kt | 2956454195 |
/*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.ui
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.google.android.gms.R
import com.google.android.gms.databinding.SafetyNetFragmentBinding
import org.microg.gms.checkin.getCheckinServiceInfo
import org.microg.gms.snet.ServiceInfo
import org.microg.gms.snet.getSafetyNetServiceInfo
import org.microg.gms.snet.setSafetyNetServiceConfiguration
class SafetyNetFragment : Fragment(R.layout.safety_net_fragment) {
private lateinit var binding: SafetyNetFragmentBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = SafetyNetFragmentBinding.inflate(inflater, container, false)
binding.switchBarCallback = object : PreferenceSwitchBarCallback {
override fun onChecked(newStatus: Boolean) {
setEnabled(newStatus)
}
}
return binding.root
}
fun setEnabled(newStatus: Boolean) {
lifecycleScope.launchWhenResumed {
val info = getSafetyNetServiceInfo(requireContext())
val newConfiguration = info.configuration.copy(enabled = newStatus)
displayServiceInfo(setSafetyNetServiceConfiguration(requireContext(), newConfiguration))
}
}
fun displayServiceInfo(serviceInfo: ServiceInfo) {
binding.safetynetEnabled = serviceInfo.configuration.enabled
}
override fun onResume() {
super.onResume()
lifecycleScope.launchWhenResumed {
binding.checkinEnabled = getCheckinServiceInfo(requireContext()).configuration.enabled
displayServiceInfo(getSafetyNetServiceInfo(requireContext()))
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.add(0, MENU_ADVANCED, 0, R.string.menu_advanced)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
MENU_ADVANCED -> {
findNavController().navigate(requireContext(), R.id.openSafetyNetAdvancedSettings)
true
}
else -> super.onOptionsItemSelected(item)
}
}
companion object {
private const val MENU_ADVANCED = Menu.FIRST
}
}
| play-services-core/src/main/kotlin/org/microg/gms/ui/SafetyNetFragment.kt | 666077141 |
package de.westnordost.streetcomplete.quests.defibrillator
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddIsDefibrillatorIndoor : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes with
emergency = defibrillator
and access !~ private|no
and !indoor
"""
override val commitMessage = "Add whether defibrillator is inside building"
override val wikiLink = "Key:indoor"
override val icon = R.drawable.ic_quest_defibrillator
override val questTypeAchievements = emptyList<QuestTypeAchievement>()
override fun getTitle(tags: Map<String, String>) = R.string.quest_is_defibrillator_inside_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("indoor", answer.toYesNo())
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/defibrillator/AddIsDefibrillatorIndoor.kt | 4025734384 |
package com.aptyr.clonegithubtofirebase
import android.app.Application
import com.facebook.drawee.backends.pipeline.Fresco
class App : Application() {
override fun onCreate() {
super.onCreate()
Fresco.initialize(this)
}
}
| app/src/main/java/com/aptyr/clonegithubtofirebase/App.kt | 2811468530 |
/*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http
import com.google.gson.Gson
import org.hamcrest.Matchers
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.notNullValue
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.NumberGenerators
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.negativeIntegers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.smallPositiveIntegers
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.asString
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.hexadecimalString
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.GenerateLong
import tech.sirwellington.alchemy.test.junit.runners.Repeat
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit
/**
*
* @author SirWellington
*/
@Repeat(25)
@RunWith(AlchemyTestRunner::class)
class AlchemyHttpBuilderTest
{
@Mock
private lateinit var executor: ExecutorService
private lateinit var defaultHeaders: Map<String, String>
private lateinit var instance: AlchemyHttpBuilder
@GenerateLong(min = 100)
private var timeout: Long = 0L
@Before
fun setUp()
{
defaultHeaders = CollectionGenerators.mapOf(alphabeticStrings(), alphabeticStrings(), 20)
timeout = NumberGenerators.longs(100, 2000).get()
instance = AlchemyHttpBuilder()
.usingTimeout(Math.toIntExact(timeout), TimeUnit.MILLISECONDS)
.usingExecutor(executor)
.usingDefaultHeaders(defaultHeaders)
}
@Test
fun testNewInstance()
{
instance = AlchemyHttpBuilder.newInstance()
assertThat<AlchemyHttpBuilder>(instance, notNullValue())
}
@Repeat(50)
@Test
fun testUsingTimeout()
{
val socketTimeout = one(integers(15, 100))
val result = instance.usingTimeout(socketTimeout, TimeUnit.SECONDS)
assertThat(result, notNullValue())
}
@Repeat(10)
@Test
fun testUsingTimeoutWithBadArgs()
{
val negativeNumber = one(negativeIntegers())
assertThrows { instance.usingTimeout(negativeNumber, TimeUnit.SECONDS) }
.isInstanceOf(IllegalArgumentException::class.java)
}
@Test
fun testUsingGson()
{
val gson = Gson()
val result = instance.usingGson(gson)
assertThat(result, notNullValue())
}
@Repeat(100)
@Test
fun testUsingExecutorService()
{
val result = instance.usingExecutor(executor)
assertThat(result, notNullValue())
}
@Test
fun testDisableAsyncCallbacks()
{
val result = instance.disableAsyncCallbacks()
assertThat(result, notNullValue())
}
@Test
fun testEnableAsyncCallbacks()
{
val result = instance.enableAsyncCallbacks()
assertThat(result, notNullValue())
}
@Repeat(100)
@Test
fun testUsingDefaultHeaders()
{
instance = AlchemyHttpBuilder.newInstance()
val headers = CollectionGenerators.mapOf(alphabeticStrings(),
asString(smallPositiveIntegers()),
100)
val result = instance.usingDefaultHeaders(headers)
assertThat(result, notNullValue())
val http = result.build()
assertThat(http, notNullValue())
val expected = headers + Constants.DEFAULT_HEADERS
assertThat(http.defaultHeaders, equalTo(expected))
//Empty headers is ok
instance.usingDefaultHeaders(emptyMap())
}
@Repeat
@Test
fun testUsingDefaultHeader()
{
val key = one(alphabeticStrings())
val value = one(hexadecimalString(10))
val result = instance.usingDefaultHeader(key, value)
assertThat(result, notNullValue())
val http = result.build()
assertThat(http.defaultHeaders, Matchers.hasEntry(key, value))
}
@Test
fun testUsingDefaultHeaderEdgeCases()
{
val key = one(alphabeticStrings())
//should be ok
instance.usingDefaultHeader(key, "")
}
@Repeat(100)
@Test
fun testBuild()
{
val result = instance.build()
assertThat(result, notNullValue())
val expectedHeaders = this.defaultHeaders + Constants.DEFAULT_HEADERS
assertThat(result.defaultHeaders, equalTo(expectedHeaders))
}
@Test
fun testBuildEdgeCases()
{
//Nothing is set
instance = AlchemyHttpBuilder.newInstance()
instance.build()
//No Executor Service set
instance = AlchemyHttpBuilder.newInstance()
instance.build()
//No Timeout
instance = AlchemyHttpBuilder.newInstance().usingExecutor(executor)
instance.build()
}
@Test
fun testDefaultIncludesBasicRequestHeaders()
{
instance = AlchemyHttpBuilder.newInstance()
.usingExecutor(executor)
val result = instance.build()
assertThat(result, notNullValue())
val headers = result.defaultHeaders
assertThat(headers, Matchers.hasKey("Accept"))
assertThat(headers, Matchers.hasKey("Content-Type"))
}
}
| src/test/java/tech/sirwellington/alchemy/http/AlchemyHttpBuilderTest.kt | 378355318 |
package com.moviereel.ui.entertain.movie.nowplaying
import com.moviereel.data.db.entities.movie.MovieNowPlayingEntity
import com.moviereel.ui.entertain.base.EntertainPageBaseView
/**
* MovieReel
* com.moviereel.com.moviereel.ui.fragments.movienowplaying
* Created by lusinabrian on 26/10/16.
* Description: View Interface for [MovieNPFragment]
*/
interface MovieNPView : EntertainPageBaseView {
/**
* Sets adapter for the recycler view
* @param movieResultsResponseList data to use to update movie list
* *
*/
fun updateMoviesNowPlaying(movieResultsResponseList: List<MovieNowPlayingEntity>)
}
| app/src/main/kotlin/com/moviereel/ui/entertain/movie/nowplaying/MovieNPView.kt | 73149517 |
package com.boardgamegeek.service
import android.content.ContentValues
import android.content.Intent
import android.content.SyncResult
import android.database.Cursor
import android.provider.BaseColumns
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.core.database.getDoubleOrNull
import androidx.core.database.getIntOrNull
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull
import com.boardgamegeek.BggApplication
import com.boardgamegeek.R
import com.boardgamegeek.auth.Authenticator
import com.boardgamegeek.entities.CollectionItemForUploadEntity
import com.boardgamegeek.extensions.NotificationTags
import com.boardgamegeek.extensions.getBoolean
import com.boardgamegeek.extensions.intentFor
import com.boardgamegeek.extensions.whereNullOrBlank
import com.boardgamegeek.io.BggService
import com.boardgamegeek.provider.BggContract.Collection
import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID
import com.boardgamegeek.provider.BggContract.Games
import com.boardgamegeek.repository.GameCollectionRepository
import com.boardgamegeek.ui.CollectionActivity
import com.boardgamegeek.ui.GameActivity
import com.boardgamegeek.util.HttpUtils
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import timber.log.Timber
import java.util.concurrent.TimeUnit
class SyncCollectionUpload(application: BggApplication, service: BggService, syncResult: SyncResult) :
SyncUploadTask(application, service, syncResult) {
private val okHttpClient: OkHttpClient = HttpUtils.getHttpClientWithAuth(context)
private val uploadTasks: List<CollectionUploadTask>
private var currentGameId: Int = 0
private var currentGameName: String = ""
private var currentGameHeroImageUrl: String = ""
private var currentGameThumbnailUrl: String = ""
private val repository = GameCollectionRepository(application)
override val syncType = SyncService.FLAG_SYNC_COLLECTION_UPLOAD
override val notificationTitleResId = R.string.sync_notification_title_collection_upload
override val summarySuffixResId = R.plurals.collection_items_suffix
override val notificationSummaryIntent = context.intentFor<CollectionActivity>()
override val notificationIntent: Intent?
get() = if (currentGameId != INVALID_ID) {
GameActivity.createIntent(
context,
currentGameId,
currentGameName,
currentGameThumbnailUrl,
currentGameHeroImageUrl
)
} else super.notificationIntent
override val notificationMessageTag = NotificationTags.UPLOAD_COLLECTION
override val notificationErrorTag = NotificationTags.UPLOAD_COLLECTION_ERROR
init {
uploadTasks = createUploadTasks()
}
private fun createUploadTasks(): List<CollectionUploadTask> {
val tasks = ArrayList<CollectionUploadTask>()
tasks.add(CollectionStatusUploadTask(okHttpClient))
tasks.add(CollectionRatingUploadTask(okHttpClient))
tasks.add(CollectionCommentUploadTask(okHttpClient))
tasks.add(CollectionPrivateInfoUploadTask(okHttpClient))
tasks.add(CollectionWishlistCommentUploadTask(okHttpClient))
tasks.add(CollectionTradeConditionUploadTask(okHttpClient))
tasks.add(CollectionWantPartsUploadTask(okHttpClient))
tasks.add(CollectionHasPartsUploadTask(okHttpClient))
return tasks
}
override fun execute() {
fetchList(fetchDeletedCollectionItems()).forEach {
if (isCancelled) return@forEach
if (wasSleepInterrupted(1, TimeUnit.SECONDS)) return@forEach
processDeletedCollectionItem(it)
}
fetchList(fetchNewCollectionItems()).forEach {
if (isCancelled) return@forEach
if (wasSleepInterrupted(1, TimeUnit.SECONDS)) return@forEach
processNewCollectionItem(it)
}
fetchList(fetchDirtyCollectionItems()).forEach {
if (isCancelled) return@forEach
if (wasSleepInterrupted(1, TimeUnit.SECONDS)) return@forEach
processDirtyCollectionItem(it)
}
}
private fun fetchList(cursor: Cursor?): MutableList<CollectionItemForUploadEntity> {
val list = mutableListOf<CollectionItemForUploadEntity>()
cursor?.use {
if (it.moveToFirst()) {
do {
list.add(fromCursor(it))
} while (it.moveToNext())
}
}
return list
}
private fun fromCursor(cursor: Cursor): CollectionItemForUploadEntity {
return CollectionItemForUploadEntity(
internalId = cursor.getLong(0),
collectionId = cursor.getIntOrNull(1) ?: INVALID_ID,
gameId = cursor.getIntOrNull(2) ?: INVALID_ID,
collectionName = cursor.getStringOrNull(3).orEmpty(),
imageUrl = cursor.getStringOrNull(4).orEmpty().ifEmpty { cursor.getStringOrNull(7) }.orEmpty(),
thumbnailUrl = cursor.getStringOrNull(5).orEmpty().ifEmpty { cursor.getStringOrNull(8) }.orEmpty(),
heroImageUrl = cursor.getStringOrNull(6).orEmpty().ifEmpty { cursor.getStringOrNull(9) }.orEmpty(),
rating = cursor.getDoubleOrNull(10) ?: 0.0,
ratingTimestamp = cursor.getLongOrNull(11) ?: 0L,
comment = cursor.getStringOrNull(12).orEmpty(),
commentTimestamp = cursor.getLongOrNull(13) ?: 0L,
acquiredFrom = cursor.getStringOrNull(14).orEmpty(),
acquisitionDate = cursor.getStringOrNull(15).orEmpty(),
privateComment = cursor.getStringOrNull(16).orEmpty(),
currentValue = cursor.getDoubleOrNull(17) ?: 0.0,
currentValueCurrency = cursor.getStringOrNull(18).orEmpty(),
pricePaid = cursor.getDoubleOrNull(19) ?: 0.0,
pricePaidCurrency = cursor.getStringOrNull(20).orEmpty(),
quantity = cursor.getIntOrNull(21) ?: 1,
inventoryLocation = cursor.getStringOrNull(22).orEmpty(),
privateInfoTimestamp = cursor.getLongOrNull(23) ?: 0L,
owned = cursor.getBoolean(24),
previouslyOwned = cursor.getBoolean(25),
forTrade = cursor.getBoolean(26),
wantInTrade = cursor.getBoolean(27),
wantToBuy = cursor.getBoolean(28),
wantToPlay = cursor.getBoolean(29),
preordered = cursor.getBoolean(30),
wishlist = cursor.getBoolean(31),
wishlistPriority = cursor.getIntOrNull(32) ?: 3, // Like to Have
statusTimestamp = cursor.getLongOrNull(33) ?: 0L,
wishlistComment = cursor.getString(34),
wishlistCommentDirtyTimestamp = cursor.getLongOrNull(35) ?: 0L,
tradeCondition = cursor.getStringOrNull(36),
tradeConditionDirtyTimestamp = cursor.getLongOrNull(37) ?: 0L,
wantParts = cursor.getStringOrNull(38),
wantPartsDirtyTimestamp = cursor.getLongOrNull(39) ?: 0L,
hasParts = cursor.getStringOrNull(40),
hasPartsDirtyTimestamp = cursor.getLongOrNull(41) ?: 0L,
)
}
private fun fetchDeletedCollectionItems(): Cursor? {
return getCollectionItems(
isGreaterThanZero(Collection.Columns.COLLECTION_DELETE_TIMESTAMP),
R.plurals.sync_notification_collection_deleting
)
}
private fun fetchNewCollectionItems(): Cursor? {
val selection =
"(${getDirtyColumnSelection(isGreaterThanZero(Collection.Columns.COLLECTION_DIRTY_TIMESTAMP))}) AND ${Collection.Columns.COLLECTION_ID.whereNullOrBlank()}"
return getCollectionItems(selection, R.plurals.sync_notification_collection_adding)
}
private fun fetchDirtyCollectionItems(): Cursor? {
val selection = getDirtyColumnSelection("")
return getCollectionItems(selection, R.plurals.sync_notification_collection_uploading)
}
private fun getDirtyColumnSelection(existingSelection: String): String {
val sb = StringBuilder(existingSelection)
for (task in uploadTasks) {
if (sb.isNotEmpty()) sb.append(" OR ")
sb.append(isGreaterThanZero(task.timestampColumn))
}
return sb.toString()
}
private fun isGreaterThanZero(columnName: String): String {
return "$columnName>0"
}
private fun getCollectionItems(selection: String, @PluralsRes messageResId: Int): Cursor? {
val cursor = context.contentResolver.query(
Collection.CONTENT_URI,
PROJECTION,
selection, null, null
)
val count = cursor?.count ?: 0
val detail = context.resources.getQuantityString(messageResId, count, count)
Timber.i(detail)
if (count > 0) updateProgressNotification(detail)
return cursor
}
private fun processDeletedCollectionItem(item: CollectionItemForUploadEntity) {
val deleteTask = CollectionDeleteTask(okHttpClient, item)
deleteTask.post()
if (processResponseForError(deleteTask)) {
return
}
context.contentResolver.delete(Collection.buildUri(item.internalId), null, null)
notifySuccess(item, item.collectionId, R.string.sync_notification_collection_deleted)
}
private fun processNewCollectionItem(item: CollectionItemForUploadEntity) {
val addTask = CollectionAddTask(okHttpClient, item)
addTask.post()
if (processResponseForError(addTask)) {
return
}
val contentValues = ContentValues()
addTask.appendContentValues(contentValues)
context.contentResolver.update(Collection.buildUri(item.internalId), contentValues, null, null)
runBlocking {
repository.refreshCollectionItems(item.gameId)
}
notifySuccess(item, item.gameId * -1, R.string.sync_notification_collection_added)
}
private fun processDirtyCollectionItem(item: CollectionItemForUploadEntity) {
if (item.collectionId != INVALID_ID) {
val contentValues = ContentValues()
for (task in uploadTasks) {
if (processUploadTask(task, item, contentValues)) return
}
if (contentValues.size() > 0) {
context.contentResolver.update(Collection.buildUri(item.internalId), contentValues, null, null)
notifySuccess(item, item.collectionId, R.string.sync_notification_collection_updated)
}
} else {
Timber.d("Invalid collectionItem ID for internal ID %1\$s; game ID %2\$s", item.internalId, item.gameId)
}
}
private fun processUploadTask(
task: CollectionUploadTask,
collectionItem: CollectionItemForUploadEntity,
contentValues: ContentValues
): Boolean {
task.addCollectionItem(collectionItem)
if (task.isDirty) {
task.post()
if (processResponseForError(task)) {
return true
}
task.appendContentValues(contentValues)
}
return false
}
private fun notifySuccess(item: CollectionItemForUploadEntity, id: Int, @StringRes messageResId: Int) {
syncResult.stats.numUpdates++
currentGameId = item.gameId
currentGameName = item.collectionName
currentGameHeroImageUrl = item.heroImageUrl
currentGameThumbnailUrl = item.thumbnailUrl
notifyUser(
item.collectionName,
context.getString(messageResId),
id,
item.heroImageUrl,
item.thumbnailUrl,
item.imageUrl,
)
}
private fun processResponseForError(response: CollectionTask): Boolean {
return when {
response.hasAuthError() -> {
Timber.w("Auth error; clearing password")
syncResult.stats.numAuthExceptions++
Authenticator.clearPassword(context)
true
}
!response.errorMessage.isNullOrBlank() -> {
syncResult.stats.numIoExceptions++
notifyUploadError(response.errorMessage)
true
}
else -> false
}
}
companion object {
val PROJECTION = arrayOf(
BaseColumns._ID,
Collection.Columns.COLLECTION_ID,
Games.Columns.GAME_ID,
Collection.Columns.COLLECTION_NAME,
Collection.Columns.COLLECTION_IMAGE_URL,
Collection.Columns.COLLECTION_THUMBNAIL_URL, // 5
Collection.Columns.COLLECTION_HERO_IMAGE_URL,
Games.Columns.IMAGE_URL,
Games.Columns.THUMBNAIL_URL,
Games.Columns.HERO_IMAGE_URL,
Collection.Columns.RATING, // 10
Collection.Columns.RATING_DIRTY_TIMESTAMP,
Collection.Columns.COMMENT,
Collection.Columns.COMMENT_DIRTY_TIMESTAMP,
Collection.Columns.PRIVATE_INFO_ACQUIRED_FROM,
Collection.Columns.PRIVATE_INFO_ACQUISITION_DATE, // 15
Collection.Columns.PRIVATE_INFO_COMMENT,
Collection.Columns.PRIVATE_INFO_CURRENT_VALUE,
Collection.Columns.PRIVATE_INFO_CURRENT_VALUE_CURRENCY,
Collection.Columns.PRIVATE_INFO_PRICE_PAID,
Collection.Columns.PRIVATE_INFO_PRICE_PAID_CURRENCY, // 20
Collection.Columns.PRIVATE_INFO_QUANTITY,
Collection.Columns.PRIVATE_INFO_INVENTORY_LOCATION,
Collection.Columns.PRIVATE_INFO_DIRTY_TIMESTAMP,
Collection.Columns.STATUS_OWN,
Collection.Columns.STATUS_PREVIOUSLY_OWNED, // 25
Collection.Columns.STATUS_FOR_TRADE,
Collection.Columns.STATUS_WANT,
Collection.Columns.STATUS_WANT_TO_BUY,
Collection.Columns.STATUS_WANT_TO_PLAY,
Collection.Columns.STATUS_PREORDERED, // 30
Collection.Columns.STATUS_WISHLIST,
Collection.Columns.STATUS_WISHLIST_PRIORITY,
Collection.Columns.STATUS_DIRTY_TIMESTAMP,
Collection.Columns.WISHLIST_COMMENT,
Collection.Columns.WISHLIST_COMMENT_DIRTY_TIMESTAMP, // 35
Collection.Columns.CONDITION,
Collection.Columns.TRADE_CONDITION_DIRTY_TIMESTAMP,
Collection.Columns.WANTPARTS_LIST,
Collection.Columns.WANT_PARTS_DIRTY_TIMESTAMP,
Collection.Columns.HASPARTS_LIST, // 40
Collection.Columns.HAS_PARTS_DIRTY_TIMESTAMP,
)
}
}
| app/src/main/java/com/boardgamegeek/service/SyncCollectionUpload.kt | 864240166 |
package com.boardgamegeek.provider
import android.content.ContentValues
import android.net.Uri
import com.boardgamegeek.provider.BggContract.Buddies
import com.boardgamegeek.provider.BggContract.Companion.PATH_BUDDIES
import com.boardgamegeek.provider.BggDatabase.Tables
class BuddiesProvider : BasicProvider() {
override fun getType(uri: Uri) = Buddies.CONTENT_TYPE
override val path: String = PATH_BUDDIES
override val table = Tables.BUDDIES
override val defaultSortOrder = Buddies.DEFAULT_SORT
override fun insertedUri(values: ContentValues?, rowId: Long): Uri? {
val buddyName = values?.getAsString(Buddies.Columns.BUDDY_NAME)
return if (buddyName.isNullOrBlank()) null else Buddies.buildBuddyUri(buddyName)
}
}
| app/src/main/java/com/boardgamegeek/provider/BuddiesProvider.kt | 864404740 |
package kotlinx.serialization.json
import com.google.gson.*
import kotlinx.serialization.*
import org.junit.Test
import kotlin.test.*
class GsonCompatibilityTest {
@Serializable
data class Box(val d: Double, val f: Float)
@Test
fun testNaN() {
checkCompatibility(Box(Double.NaN, 1.0f))
checkCompatibility(Box(1.0, Float.NaN))
checkCompatibility(Box(Double.NaN, Float.NaN))
}
@Test
fun testInfinity() {
checkCompatibility(Box(Double.POSITIVE_INFINITY, 1.0f))
checkCompatibility(Box(1.0, Float.POSITIVE_INFINITY))
checkCompatibility(Box(Double.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY))
}
@Test
fun testNumber() {
checkCompatibility(Box(23.9, 23.9f))
}
private fun checkCompatibility(box: Box) {
checkCompatibility(box, Gson(), Json)
checkCompatibility(box, GsonBuilder().serializeSpecialFloatingPointValues().create(), Json { allowSpecialFloatingPointValues = true })
}
private fun checkCompatibility(box: Box, gson: Gson, json: Json) {
val jsonResult = resultOrNull { json.encodeToString(box) }
val gsonResult = resultOrNull { gson.toJson(box) }
assertEquals(gsonResult, jsonResult)
if (jsonResult != null && gsonResult != null) {
val jsonDeserialized: Box = json.decodeFromString(jsonResult)
val gsonDeserialized: Box = gson.fromJson(gsonResult, Box::class.java)
assertEquals(gsonDeserialized, jsonDeserialized)
}
}
private fun resultOrNull(function: () -> String): String? {
return try {
function()
} catch (t: Throwable) {
null
}
}
}
| formats/json-tests/jvmTest/src/kotlinx/serialization/json/GsonCompatibilityTest.kt | 1559504990 |
package mediathek.tool
import mediathek.daten.DatenDownload
import mediathek.daten.DatenFilm
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.apache.commons.text.WordUtils
import org.apache.logging.log4j.LogManager
import java.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
open class MVInfoFile {
private fun formatFilmAsString(film: DatenFilm?, url: HttpUrl?): String {
if (null == film || url == null)
return ""
//calculate file size based on actual used URL
val fileSize = FileSize.getFileSizeFromUrl(url)
val formatString = String.format("%%-%ds %%s", MAX_HEADER_LENGTH)
var sb = StringBuilder()
sb = appendFormattedTableLine(sb, formatString, FILM_SENDER, film.sender)
sb = appendFormattedTableLine(sb, formatString, FILM_THEMA, film.thema).append(System.lineSeparator())
sb = appendFormattedTableLine(sb, formatString, FILM_TITEL, film.title).append(System.lineSeparator())
sb = appendFormattedTableLine(sb, formatString, FILM_DATUM, film.sendeDatum)
sb = appendFormattedTableLine(sb, formatString, FILM_ZEIT, film.sendeZeit)
sb = appendFormattedTableLine(sb, formatString, FILM_DAUER, film.dauer)
if (fileSize > FileSize.INVALID_SIZE)
sb = appendFormattedTableLine(sb, formatString, FILM_GROESSE, FileUtils.humanReadableByteCountBinary(fileSize))
else
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
sb.append("Website")
sb.append(System.lineSeparator())
sb.append(film.websiteLink)
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
sb.append(FILM_URL)
sb.append(System.lineSeparator())
sb.append(url)
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
sb.append(splitStringIntoMaxFixedLengthLines(film.description, MAX_LINE_LENGTH))
sb.append(System.lineSeparator())
sb.append(System.lineSeparator())
return sb.toString()
}
protected fun appendFormattedTableLine(sb: StringBuilder, formatString: String?, keyTitle: String?, value: String?): StringBuilder {
return sb.append(String.format(formatString!!, String.format("%s:", keyTitle), value))
.append(System.lineSeparator())
}
protected fun splitStringIntoMaxFixedLengthLines(input: String?, lineLength: Int): String {
return Optional.ofNullable(input)
.map { s: String? -> WordUtils.wrap(s, lineLength) }
.orElse("")
}
@Throws(IOException::class)
fun writeInfoFile(film: DatenFilm?, path: Path, url: HttpUrl?) {
logger.info("Infofile schreiben nach: {}", path.toAbsolutePath().toString())
path.toFile().parentFile.mkdirs()
Files.newOutputStream(path).use { os ->
DataOutputStream(os).use { dos ->
OutputStreamWriter(dos).use { osw ->
BufferedWriter(osw).use { br ->
br.write(formatFilmAsString(film, url))
br.flush()
}
}
}
}
logger.info("Infodatei geschrieben")
}
@Throws(IOException::class)
fun writeInfoFile(datenDownload: DatenDownload) {
File(datenDownload.arr[DatenDownload.DOWNLOAD_ZIEL_PFAD]).mkdirs()
val path = Paths.get(datenDownload.fileNameWithoutSuffix + ".txt")
val film = datenDownload.film
// this is the URL that will be used during download.
// write this into info file and calculate size from it
val url = datenDownload.arr[DatenDownload.DOWNLOAD_URL].toHttpUrl()
film?.let { writeInfoFile(it, path, url) }
}
private companion object {
private val logger = LogManager.getLogger(MVInfoFile::class.java)
private const val FILM_GROESSE = "Größe"
private const val FILM_SENDER = "Sender"
private const val FILM_THEMA = "Thema"
private const val FILM_TITEL = "Titel"
private const val FILM_DATUM = "Datum"
private const val FILM_ZEIT = "Zeit"
private const val FILM_DAUER = "Dauer"
private const val FILM_URL = "URL"
private const val MAX_HEADER_LENGTH = 12
private const val MAX_LINE_LENGTH = 62
}
} | src/main/java/mediathek/tool/MVInfoFile.kt | 1694011634 |
@file:JvmName("Debug")
package io.rover.sdk.debug
import android.content.Context
import io.rover.sdk.core.Rover
import io.rover.sdk.core.container.Assembler
import io.rover.sdk.core.container.Container
import io.rover.sdk.core.container.Resolver
import io.rover.sdk.core.container.Scope
import io.rover.sdk.core.events.EventQueueServiceInterface
import io.rover.sdk.core.platform.DeviceIdentificationInterface
import io.rover.sdk.core.routing.Router
import io.rover.sdk.debug.routes.DebugRoute
/**
* The Debug module adds certain useful bits of debug functionality to the Rover SDK, namely a
* new `isTestDevice` boolean to each event that is tracked through the EventQueue and a hidden
* activity for managing its value.
*
* Note that it may safely be used in production as well as dev builds of your app, but it is
* optional should you want to be extra sure that debug functionality cannot be inadvertently
* exposed.
*/
class DebugAssembler : Assembler {
override fun assemble(container: Container) {
container.register(
Scope.Singleton,
DebugPreferences::class.java
) { resolver ->
DebugPreferences(
resolver.resolveSingletonOrFail(Context::class.java),
resolver.resolveSingletonOrFail(DeviceIdentificationInterface::class.java)
)
}
}
override fun afterAssembly(resolver: Resolver) {
resolver.resolveSingletonOrFail(Router::class.java).apply {
registerRoute(
DebugRoute(
resolver.resolveSingletonOrFail(Context::class.java)
)
)
}
resolver.resolveSingletonOrFail(EventQueueServiceInterface::class.java)
.addContextProvider(
TestDeviceContextProvider(
resolver.resolveSingletonOrFail(DebugPreferences::class.java)
)
)
}
}
@Deprecated("Use .resolve(DebugPreferences::class.java)")
val Rover.debugPreferences: DebugPreferences
get() = this.resolve(DebugPreferences::class.java) ?: throw missingDependencyError("DebugPreferences")
private fun missingDependencyError(name: String): Throwable {
throw RuntimeException("Dependency not registered: $name. Did you include DebugAssembler() in the assembler list?")
}
| debug/src/main/kotlin/io/rover/sdk/debug/DebugAssembler.kt | 3434502180 |
package net.torvald.terranvm.runtime.compiler.cflat
import net.torvald.terranvm.VMOpcodesRISC
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
/**
* A compiler for C-flat language that compiles into TerranVM Terra Instruction Set.
*
* # Disclaimer
*
* 0. This compiler, BY NO MEANS, guarantees to implement standard C language; c'mon, $100+ for a standard document?
* 1. I suck at code and test. Please report bugs!
* 2. Please move along with my terrible sense of humour.
*
* # About C-flat
*
* C-flat is a stupid version of C. Everything is global and a word (or byte if it's array).
*
* ## New Features
*
* - Typeless (everything is a word), non-zero is truthy and zero is falsy
* - Infinite loop using ```forever``` block. You can still use ```for (;;)```, ```while (true)```
* - Counted simple loop (without loop counter ref) using ```repeat``` block
*
*
* ## Important Changes from C
*
* - All function definition must specify return type, even if the type is ```void```.
* - ```float``` is IEEE 754 Binary32.
* - Everything is global
* - Everything is a word (32-bit)
* - Everything is ```int```, ```float``` and ```pointer``` at the same time. You decide.
* - Unary pre- and post- increments/decrements are considered _evil_ and thus prohibited.
* - Unsigned types are also considered _evil_ and thus prohibited.
* - Everything except function's local variable is ```extern```, any usage of the keyword will throw error.
* - Function cannot have non-local variable defined inside, as ```static``` keyword is illegal.
* - And thus, following keywords will throw error:
* - auto, register, volatile (not supported)
* - signed, unsigned (prohibited)
* - static (no global inside function)
* - extern (everything is global)
* - Assignment does not return shit.
*
*
* ## Issues
* - FIXME arithmetic ops will not work with integers, need to autodetect types and slap in ADDINT instead of just ADD
*
*
* Created by minjaesong on 2017-06-04.
*/
object Cflat {
private val structOpen = '{'
private val structClose = '}'
private val parenOpen = '('
private val parenClose = ')'
private val preprocessorTokenSep = Regex("""[ \t]+""")
private val nullchar = 0.toChar()
private val infiniteLoops = arrayListOf<Regex>(
Regex("""while\(true\)"""), // whitespaces are filtered on preprocess
Regex("""for\([\s]*;[\s]*;[\s]*\)""")
) // more types of infinite loops are must be dealt with (e.g. while (0xFFFFFFFF < 0x7FFFFFFF))
private val regexRegisterLiteral = Regex("""^[Rr][0-9]+$""") // same as the assembler
private val regexBooleanWhole = Regex("""^(true|false)$""")
private val regexHexWhole = Regex("""^(0[Xx][0-9A-Fa-f_]+?)$""") // DIFFERENT FROM the assembler
private val regexOctWhole = Regex("""^(0[0-7_]+)$""")
private val regexBinWhole = Regex("""^(0[Bb][01_]+)$""") // DIFFERENT FROM the assembler
private val regexFPWhole = Regex("""^([-+]?[0-9]*[.][0-9]+[eE]*[-+0-9]*[fF]*|[-+]?[0-9]+[.eEfF][0-9+-]*[fF]?)$""") // same as the assembler
private val regexIntWhole = Regex("""^([-+]?[0-9_]+[Ll]?)$""") // DIFFERENT FROM the assembler
private fun String.matchesNumberLiteral() = this.matches(regexHexWhole) || this.matches(regexOctWhole) || this.matches(regexBinWhole) || this.matches(regexIntWhole) || this.matches(regexFPWhole)
private fun String.matchesFloatLiteral() = this.matches(regexFPWhole)
private fun String.matchesStringLiteral() = this.endsWith(0.toChar())
private fun generateTemporaryVarName(inst: String, arg1: String, arg2: String) = "$$${inst}_${arg1}_$arg2"
private fun generateSuperTemporaryVarName(lineNum: Int, inst: String, arg1: String, arg2: String) = "$$${inst}_${arg1}_${arg2}_\$l$lineNum"
private val regexVarNameWhole = Regex("""^([A-Za-z_][A-Za-z0-9_]*)$""")
private val regexWhitespaceNoSP = Regex("""[\t\r\n\v\f]""")
private val regexIndents = Regex("""^ +|^\t+|(?<=\n) +|(?<=\n)\t+""")
private val digraphs = hashMapOf(
"<:" to '[',
":>" to ']',
"<%" to '{',
"%>" to '}',
"%:" to '#'
)
private val trigraphs = hashMapOf(
"??=" to "#",
"??/" to "'",
"??'" to "^",
"??(" to "[",
"??)" to "]",
"??!" to "|",
"??<" to "{",
"??>" to "}",
"??-" to "~"
)
private val keywords = hashSetOf(
// classic C
"auto","break","case","char","const","continue","default","do","double","else","enum","extern","float",
"for","goto","if","int","long","register","return","short","signed","static","struct","switch","sizeof", // is an operator
"typedef","union","unsigned","void","volatile","while",
// C-flat code blocks
"forever","repeat"
// C-flat dropped keywords (keywords that won't do anything/behave differently than C95, etc.):
// - auto, register, signed, unsigned, volatile, static: not implemented; WILL THROW ERROR
// - float: will act same as double
// - extern: everthing is global, anyway; WILL THROW ERROR
// C-flat exclusive keywords:
// - bool, true, false: bool algebra
)
private val unsupportedKeywords = hashSetOf(
"auto","register","signed","unsigned","volatile","static",
"extern",
"long", "short", "double", "bool"
)
private val operatorsHierarchyInternal = arrayOf(
// opirator precedence in internal format (#_nameinlowercase) PUT NO PARENS HERE! TODO [ ] are allowed? pls chk
// most important
hashSetOf("++","--","[", "]",".","->"),
hashSetOf("#_preinc","#_predec","#_unaryplus","#_unaryminus","!","~","#_ptrderef","#_addressof","sizeof","(char *)","(short *)","(int *)","(long *)","(float *)","(double *)","(bool *)","(void *)", "(char)","(short)","(int)","(long)","(float)","(double)","(bool)"),
hashSetOf("*","/","%"),
hashSetOf("+","-"),
hashSetOf("<<",">>",">>>"),
hashSetOf("<","<=",">",">="),
hashSetOf("==","!="),
hashSetOf("&"),
hashSetOf("^"),
hashSetOf("|"),
hashSetOf("&&"),
hashSetOf("||"),
hashSetOf("?",":"),
hashSetOf("=","+=","-=","*=","/=","%=","<<=",">>=","&=","^=","|="),
hashSetOf(",")
// least important
).reversedArray() // this makes op with highest precedence have bigger number
// operators must return value when TREE is evaluated -- with NO EXCEPTION; '=' must return value too! (not just because of C standard, but design of #_assignvar)
private val unaryOps = hashSetOf(
"++","--",
"#_preinc","#_predec","#_unaryplus","#_unaryminus","!","~","#_ptrderef","#_addressof","sizeof","(char *)","(short *)","(int *)","(long *)","(float *)","(double *)","(bool *)","(void *)", "(char)","(short)","(int)","(long)","(float)","(double)","(bool)"
)
private val operatorsHierarchyRTL = arrayOf(
false,
true,
false,false,false,false,false,false,false,false,false,false,
true,true,
false
)
private val operatorsNoOrder = HashSet<String>()
init {
operatorsHierarchyInternal.forEach { array ->
array.forEach { word -> operatorsNoOrder.add(word) }
}
}
private val splittableTokens = arrayOf( // order is important!
"<<=",">>=","...",
"++","--","&&","||","<<",">>","->","<=",">=","==","!=","+=","-=","*=","/=","%=","&=","^=","|=",
"<",">","^","|","?",":","=",",",".","+","-","!","~","*","&","/","%","(",")",
" "
)
private val argumentDefBadTokens = splittableTokens.toMutableList().minus(",").minus("*").minus("...").toHashSet()
private val evilOperators = hashSetOf(
"++","--"
)
private val funcAnnotations = hashSetOf(
"auto", // does nothing; useless even in C (it's derived from B language, actually)
"extern" // not used in C-flat
)
private val funcTypes = hashSetOf(
"char", "short", "int", "long", "float", "double", "bool", "void"
)
private val varAnnotations = hashSetOf(
"auto", // does nothing; useless even in C (it's derived from B language, actually)
"extern", // not used in C-flat
"const",
"register" // not used in C-flat
)
private val varTypes = hashSetOf(
"struct", "char", "short", "int", "long", "float", "double", "bool", "var", "val"
)
private val validFuncPreword = (funcAnnotations + funcTypes).toHashSet()
private val validVariablePreword = (varAnnotations + varTypes).toHashSet()
private val codeBlockKeywords = hashSetOf(
"do", "else", "enum", "for", "if", "struct", "switch", "union", "while", "forever", "repeat"
)
private val functionalKeywordsWithOneArg = hashSetOf(
"goto", "return"
)
private val functionalKeywordsNoArg = hashSetOf(
"break", "continue",
"return" // return nothing
)
private val preprocessorKeywords = hashSetOf(
"#include","#ifndef","#ifdef","#define","#if","#else","#elif","#endif","#undef","#pragma"
)
private val escapeSequences = hashMapOf<String, Char>(
"""\a""" to 0x07.toChar(), // Alert (Beep, Bell)
"""\b""" to 0x08.toChar(), // Backspace
"""\f""" to 0x0C.toChar(), // Formfeed
"""\n""" to 0x0A.toChar(), // Newline (Line Feed)
"""\r""" to 0x0D.toChar(), // Carriage Return
"""\t""" to 0x09.toChar(), // Horizontal Tab
"""\v""" to 0x0B.toChar(), // Vertical Tab
"""\\""" to 0x5C.toChar(), // Backslash
"""\'""" to 0x27.toChar(), // Single quotation mark
"""\"""" to 0x22.toChar(), // Double quotation mark
"""\?""" to 0x3F.toChar() // uestion mark (used to avoid trigraphs)
)
private val builtinFunctions = hashSetOf(
"#_declarevar" // #_declarevar(SyntaxTreeNode<RawString> varname, SyntaxTreeNode<RawString> vartype)
)
private val functionWithSingleArgNoParen = hashSetOf(
"return", "goto", "comefrom"
)
private val compilerInternalFuncArgsCount = hashMapOf(
"#_declarevar" to 2,
"endfuncdef" to 1,
"=" to 2,
"endif" to 0,
"endelse" to 0
)
/* Error messages */
val errorUndeclaredVariable = "Undeclared variable"
val errorIncompatibleType = "Incompatible type(s)"
val errorRedeclaration = "Redeclaration"
fun sizeofPrimitive(type: String) = when (type) {
"char" -> 1
"short" -> 2
"int" -> 4
"long" -> 8
"float" -> 4
"double" -> 8
"bool" -> 1
"void" -> 1 // GCC feature
else -> throw IllegalArgumentException("Unknown primitive type: $type")
}
private val functionsImplicitEnd = hashSetOf(
"if", "else", "for", "while", "switch"
)
private val exprToIR = hashMapOf(
"#_declarevar" to "DECLARE",
"return" to "RETURN",
"+" to "ADD",
"-" to "SUB",
"*" to "MUL",
"/" to "DIV",
"^" to "POW",
"%" to "MOD",
"<<" to "SHL",
">>" to "SHR",
">>>" to "USHR",
"and" to "AND",
"or" to "OR",
"xor" to "XOR",
"not" to "NOT",
"=" to "ASSIGN",
"==" to "ISEQ",
"!=" to "ISNEQ",
">" to "ISGT",
"<" to "ISLS",
">=" to "ISGTEQ",
"<=" to "ISLSEQ",
"if" to "IF",
"endif" to "ENDIF",
"else" to "ELSE",
"endelse" to "ENDELSE",
"goto" to "GOTOLABEL",
"comefrom" to "DEFLABEL",
"asm" to "INLINEASM",
"funcdef" to "FUNCDEF",
"endfuncdef" to "ENDFUNCDEF",
"stackpush" to "STACKPUSH"
)
private val irCmpInst = hashSetOf(
"ISEQ_II", "ISEQ_IF", "ISEQ_FI", "ISEQ_FF",
"ISNEQ_II", "ISNEQ_IF", "ISNEQ_FI", "ISNEQ_FF",
"ISGT_II", "ISGT_IF", "ISGT_FI", "ISGT_FF",
"ISLS_II", "ISLS_IF", "ISLS_FI", "ISLS_FF",
"ISGTEQ_II", "ISGTEQ_IF", "ISGTEQ_FI", "ISGTEQ_FF",
"ISLSEQ_II", "ISLSEQ_IF", "ISLSEQ_FI", "ISLSEQ_FF"
)
private val jmpCommands = hashSetOf(
"JMP", "JZ", "JNZ", "JGT", "JLS"
)
// compiler options
var useDigraph = true
var useTrigraph = false
var errorIncompatibles = true
operator fun invoke(
program: String,
// options
useDigraph: Boolean = false,
useTrigraph: Boolean = false,
errorIncompatible: Boolean = true
) {
this.useDigraph = useDigraph
this.useTrigraph = useTrigraph
this.errorIncompatibles = errorIncompatible
//val tree = tokenise(preprocess(program))
TODO()
}
private val structDict = ArrayList<CStruct>()
private val structNameDict = ArrayList<String>()
private val funcDict = ArrayList<CFunction>()
private val funcNameDict = ArrayList<String>()
private val varDict = HashSet<CData>()
private val varNameDict = HashSet<String>()
private val includesUser = HashSet<String>()
private val includesLib = HashSet<String>()
private fun getFuncByName(name: String): CFunction? {
funcDict.forEach {
if (it.name == name) return it
}
return null
}
private fun structSearchByName(name: String): CStruct? {
structDict.forEach {
if (it.name == name) return it
}
return null
}
fun preprocess(program: String): String {
var program = program
//.replace(regexIndents, "") // must come before regexWhitespaceNoSP
//.replace(regexWhitespaceNoSP, "")
var out = StringBuilder()
if (useTrigraph) {
trigraphs.forEach { from, to ->
program = program.replace(from, to)
}
}
val rules = PreprocessorRules()
// Scan thru line by line (assuming single command per line...?)
program.lines().forEach {
if (it.startsWith('#')) {
val tokens = it.split(preprocessorTokenSep)
val cmd = tokens[0].drop(1).toLowerCase()
when (cmd) {
"include" -> TODO("Preprocessor keyword 'include'")
"define" -> rules.addDefinition(tokens[1], tokens.subList(2, tokens.size).joinToString(" "))
"undef" -> rules.removeDefinition(tokens[1])
else -> throw UndefinedStatement("Preprocessor macro '$cmd' is not supported.")
}
}
else {
// process each line according to rules
var line = it
rules.forEachKeywordForTokens { replaceRegex, replaceWord ->
line = line.replace(replaceRegex, " $replaceWord ")
}
out.append("$line\n")
}
}
println(out.toString())
return out.toString()
}
/** No preprocessor should exist at this stage! */
fun tokenise(program: String): ArrayList<LineStructure> {
fun debug1(any: Any) { if (true) println(any) }
///////////////////////////////////
// STEP 0. Divide things cleanly //
///////////////////////////////////
// a.k.a. tokenise properly e.g. {extern int foo ( int initSize , SomeStruct strut , )} or {int foo = getch ( ) * ( ( num1 + num3 % 16 ) - 1 )}
val lineStructures = ArrayList<LineStructure>()
var currentProgramLineNumber = 1
var currentLine = LineStructure(currentProgramLineNumber, 0, ArrayList<String>())
// put things to lineStructure, kill any whitespace
val sb = StringBuilder()
var charCtr = 0
var structureDepth = 0
fun splitAndMoveAlong() {
if (sb.isNotEmpty()) {
if (errorIncompatibles && unsupportedKeywords.contains(sb.toString())) {
throw IllegalTokenException("at line $currentProgramLineNumber with token '$sb'")
}
debug1("!! split: depth $structureDepth, word '$sb'")
currentLine.depth = structureDepth // !important
currentLine.tokens.add(sb.toString())
sb.setLength(0)
}
}
fun gotoNewline() {
if (currentLine.tokens.isNotEmpty()) {
lineStructures.add(currentLine)
sb.setLength(0)
currentLine = LineStructure(currentProgramLineNumber, -1337, ArrayList<String>())
}
}
var forStatementEngaged = false // to filter FOR range semicolon from statement-end semicolon
var isLiteralMode = false // "" ''
var isCharLiteral = false
var isLineComment = false
var isBlockComment = false
while (charCtr < program.length) {
var char = program[charCtr]
var lookahead4 = program.substring(charCtr, minOf(charCtr + 4, program.length)) // charOfIndex {0, 1, 2, 3}
var lookahead3 = program.substring(charCtr, minOf(charCtr + 3, program.length)) // charOfIndex {0, 1, 2}
var lookahead2 = program.substring(charCtr, minOf(charCtr + 2, program.length)) // charOfIndex {0, 1}
var lookbehind2 = program.substring(maxOf(charCtr - 1, 0), charCtr + 1) // charOfIndex {-1, 0}
// count up line num
if (char == '\n' && !isCharLiteral && !isLiteralMode) {
currentProgramLineNumber += 1
currentLine.lineNum = currentProgramLineNumber
if (isLineComment) isLineComment = false
}
else if (char == '\n' && isLiteralMode) {
//throw SyntaxError("at line $currentProgramLineNumber -- line break used inside of string literal")
// ignore \n by doing nothing
}
else if (lookahead2 == "//" && !isLineComment) {
isLineComment = true
charCtr += 1
}
else if (!isBlockComment && lookahead2 == "/*") {
isBlockComment = true
charCtr += 1
}
else if (!isBlockComment && lookahead2 == "*/") {
isBlockComment = false
charCtr += 1
}
else if (!isLiteralMode && !isCharLiteral && !isBlockComment && !isLineComment && char.toString().matches(regexWhitespaceNoSP)) {
// do nothing
}
else if (!isLiteralMode && !isCharLiteral && !isBlockComment && !isLineComment) {
// replace digraphs
if (useDigraph && digraphs.containsKey(lookahead2)) { // replace digraphs
char = digraphs[lookahead2]!!
lookahead4 = char + lookahead4.substring(0..lookahead4.lastIndex)
lookahead3 = char + lookahead3.substring(0..lookahead3.lastIndex)
lookahead2 = char + lookahead2.substring(0..lookahead2.lastIndex)
lookbehind2 = lookbehind2.substring(0..lookahead2.lastIndex - 1) + char
charCtr += 1
}
// filter shits
if (lookahead2 == "//" || lookahead2 == "/*" || lookahead2 == "*/") {
throw SyntaxError("at line $currentProgramLineNumber -- illegal token '$lookahead2'")
}
// do the real jobs
if (char == structOpen) {
debug1("!! met structOpen at line $currentProgramLineNumber")
splitAndMoveAlong()
gotoNewline()
structureDepth += 1 // must go last, because of quirks with 'codeblock{' and 'codeblock {'
}
else if (char == structClose) {
debug1("!! met structClose at line $currentProgramLineNumber")
structureDepth -= 1 // must go first
splitAndMoveAlong()
gotoNewline()
}
// double quotes
else if (char == '"' && lookbehind2[0] != '\\') {
isLiteralMode = !isLiteralMode
sb.append(char)
}
// char literal
else if (!isCharLiteral && char == '\'' && lookbehind2[0] != '\'') {
if ((lookahead4[1] == '\\' && lookahead4[3] != '\'') || (lookahead4[1] != '\\' && lookahead4[2] != '\''))
throw SyntaxError("Illegal usage of char literal")
isCharLiteral = !isCharLiteral
}
// -- TODO -- FOR statement is now a special case
else if (!forStatementEngaged && char == ';') {
splitAndMoveAlong()
gotoNewline()
}
else {
if (splittableTokens.contains(lookahead3)) { // three-char operator
splitAndMoveAlong() // split previously accumulated word
sb.append(lookahead3)
splitAndMoveAlong()
charCtr += 2
}
else if (splittableTokens.contains(lookahead2)) { // two-char operator
splitAndMoveAlong() // split previously accumulated word
if (evilOperators.contains(lookahead2)) {
throw IllegalTokenException("at line $currentProgramLineNumber -- evil operator '$lookahead2'")
}
sb.append(lookahead2)
splitAndMoveAlong()
charCtr += 1
}
else if (splittableTokens.contains(char.toString())) { // operator and ' '
if (char == '.') { // struct reference or decimal point, depending on the context
// it's decimal if:
// .[number]
// \.e[+-]?[0-9]+ (exponent)
// [number].[ fF]?
// spaces around decimal points are NOT ALLOWED
if (lookahead2.matches(Regex("""\.[0-9]""")) or
lookahead4.matches(Regex("""\.e[+-]?[0-9]+""")) or
(lookbehind2.matches(Regex("""[0-9]+\.""")) and lookahead2.matches(Regex("""\.[ Ff,)]""")))
) {
// get match length
var charHolder: Char
// we don't need travel back because 'else' clause on the far bottom have been already putting numbers into the stringBuilder
var travelForth = 0
do {
travelForth += 1
charHolder = program[charCtr + travelForth]
} while (charHolder in '0'..'9' || charHolder.toString().matches(Regex("""[-+eEfF]""")))
val numberWord = program.substring(charCtr..charCtr + travelForth - 1)
debug1("[C-flat.tokenise] decimal number token: $sb$numberWord, on line $currentProgramLineNumber")
sb.append(numberWord)
splitAndMoveAlong()
charCtr += travelForth - 1
}
else { // reference call
splitAndMoveAlong() // split previously accumulated word
debug1("[C-flat.tokenise] splittable token: $char, on line $currentProgramLineNumber")
sb.append(char)
splitAndMoveAlong()
}
}
else if (char != ' ') {
splitAndMoveAlong() // split previously accumulated word
debug1("[C-flat.tokenise] splittable token: $char, on line $currentProgramLineNumber")
sb.append(char)
splitAndMoveAlong()
}
else { // space detected, split only
splitAndMoveAlong()
}
}
else {
sb.append(char)
}
}
}
else if (isCharLiteral && !isLiteralMode) {
if (char == '\\') { // escape sequence of char literal
sb.append(escapeSequences[lookahead2]!!.toInt())
charCtr += 1
}
else {
sb.append(char.toInt())
}
}
else if (isLiteralMode && !isCharLiteral) {
if (char == '"' && lookbehind2[0] != '\\') {
isLiteralMode = !isLiteralMode
}
sb.append(char)
}
else {
// do nothing
}
charCtr += 1
}
return lineStructures
}
val rootNodeName = "cflat_node_root"
fun buildTree(lineStructures: List<LineStructure>): SyntaxTreeNode {
fun debug1(any: Any) { if (true) println(any) }
///////////////////////////
// STEP 1. Create a tree //
///////////////////////////
// In this step, we build tree from the line structures parsed by the parser. //
val ASTroot = SyntaxTreeNode(ExpressionType.FUNCTION_DEF, ReturnType.NOTHING, name = rootNodeName, isRoot = true, lineNumber = 1)
val workingNodes = Stack<SyntaxTreeNode>()
workingNodes.push(ASTroot)
fun getWorkingNode() = workingNodes.peek()
fun printStackDebug(): String {
val sb = StringBuilder()
sb.append("Node stack: [")
workingNodes.forEachIndexed { index, it ->
if (index > 0) { sb.append(", ") }
sb.append("l"); sb.append(it.lineNumber)
}
sb.append("]")
return sb.toString()
}
lineStructures.forEachIndexed { index, it -> val (lineNum, depth, tokens) = it
val nextLineDepth = if (index != lineStructures.lastIndex) lineStructures[index + 1].depth else null
debug1("buildtree!! tokens: $tokens")
debug1("call #$index from buildTree()")
val nodeBuilt = asTreeNode(lineNum, tokens)
getWorkingNode().addStatement(nodeBuilt)
debug1("end call #$index from buildTree()")
if (nextLineDepth != null) {
// has code block
if (nextLineDepth > depth) {
workingNodes.push(nodeBuilt)
}
// code block escape
else if (nextLineDepth < depth) {
repeat(depth - nextLineDepth) { workingNodes.pop() }
}
}
}
/////////////////////////////////
// STEP 1-1. Simplify the tree //
/////////////////////////////////
// In this step, we modify the tree so translating to IR2 be easier. //
// More specifically, we do: //
// 1. "If" (cond) {stmt1} "Else" {stmt2} -> "IfElse" (cond) {stmt1, stmt2} //
ASTroot.traversePreorderStatements { node, _ ->
// JOB #1
val ifNodeIndex = node.statements.findAllToIndices { it.name == "if" }
var deletionCount = 0
ifNodeIndex.forEach {
// as we do online-delete, precalculated numbers will go off
// deletionCount will compensate it.
val it = it - deletionCount
val ifNode = node.statements[it]
val elseNode = node.statements.getOrNull(it + 1)
// if filtered IF node has ELSE node appended...
if (elseNode != null && elseNode.name == "else") {
val newNode = SyntaxTreeNode(
ifNode.expressionType, ifNode.returnType,
"ifelse",
ifNode.lineNumber,
ifNode.isRoot, ifNode.isPartOfArgumentsNode
)
if (ifNode.statements.size > 1) throw InternalError("If node contains 2 or more statements!\n[NODE START]\n$node\n[NODE END]")
if (elseNode.statements.size > 1) throw InternalError("Else node contains 2 or more statements!\n[NODE START]\n$node\n[NODE END]")
ifNode.arguments.forEach { newNode.addArgument(it) } // should contain only 1 arg but oh well
newNode.addStatement(ifNode.statements[0])
newNode.addStatement(elseNode.statements[0])
node.statements[it] = newNode
node.statements.removeAt(it + 1)
deletionCount += 1
}
}
}
return ASTroot
}
/**
* @param type "variable", "literal_i", "literal_f"
* @param value string for variable name, int for integer and float literals
*/
private data class VirtualStackItem(val type: String, val value: String)
fun String.isVariable() = this.startsWith('$')
fun String.isRegister() = this.matches(regexRegisterLiteral)
fun ArrayList<String>.append(str: String) = if (str.endsWith(';'))
this.add(str)
else
throw IllegalArgumentException("You missed a semicolon for: $str")
///////////////////////////////////////////////////
// publicising things so that they can be tested //
///////////////////////////////////////////////////
fun resolveTypeString(type: String, isPointer: Boolean = false): ReturnType {
/*val isPointer = type.endsWith('*') or type.endsWith("_ptr") or isPointer
return when (type) {
"void" -> if (isPointer) ReturnType.NOTHING_PTR else ReturnType.NOTHING
"char" -> if (isPointer) ReturnType.CHAR_PTR else ReturnType.CHAR
"short" -> if (isPointer) ReturnType.SHORT_PTR else ReturnType.SHORT
"int" -> if (isPointer) ReturnType.INT_PTR else ReturnType.INT
"long" -> if (isPointer) ReturnType.LONG_PTR else ReturnType.LONG
"float" -> if (isPointer) ReturnType.FLOAT_PTR else ReturnType.FLOAT
"double" -> if (isPointer) ReturnType.DOUBLE_PTR else ReturnType.DOUBLE
"bool" -> if (isPointer) ReturnType.BOOL_PTR else ReturnType.BOOL
else -> if (isPointer) ReturnType.STRUCT_PTR else ReturnType.STRUCT
}*/
return when (type.toLowerCase()) {
"void" -> ReturnType.NOTHING
"int" -> ReturnType.INT
"float" -> ReturnType.FLOAT
else -> throw SyntaxError("Unknown type: $type")
}
}
fun asTreeNode(lineNumber: Int, tokens: List<String>): SyntaxTreeNode {
fun splitContainsValidVariablePreword(split: List<String>): Int {
var ret = -1
for (stage in 0..minOf(3, split.lastIndex)) {
if (validVariablePreword.contains(split[stage])) ret += 1
}
return ret
}
fun debug1(any: Any?) { if (true) println(any) }
// contradiction: auto AND extern
debug1("[asTreeNode] tokens: $tokens")
val firstAssignIndex = tokens.indexOf("=")
val firstLeftParenIndex = tokens.indexOf("(")
val lastRightParenIndex = tokens.lastIndexOf(")")
// special case for FOR :
// int i = 0 // i must be declared beforehand !!; think of C < 99
// for (i = 2 + (3 * 4), i <= 10, i = i + 2) { // separated by comma, parens are mandatory
// dosometing();
// }
if (tokens[0] == "for") {
// for tokens inside of firstLeftParen..lastRightParen,
// split tokens by ',' (will result in 3 tokens, may or may not empty)
// recurse call those three
// e.g. forNode.arguments[0] = asTreeNode( ... )
// forNode.arguments[1] = asTreeNode( ... )
// forNode.arguments[2] = asTreeNode( ... )
val forNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, null, "for", lineNumber)
val subTokens = tokens.subList(firstLeftParenIndex, lastRightParenIndex)
val commas = listOf(0, subTokens.indexOf(","), subTokens.lastIndexOf(","), subTokens.size)
val forArgs = (0..2).map { subTokens.subList(1 + commas[it], commas[it + 1]) }.map { asTreeNode(lineNumber, it) }
forArgs.forEach {
forNode.addArgument(it)
}
debug1("[asTreeNode] for tree: \n$forNode")
return forNode
}
val functionCallTokens: List<String>? =
if (firstLeftParenIndex == -1)
null
else if (firstAssignIndex == -1)
tokens.subList(0, firstLeftParenIndex)
else
tokens.subList(firstAssignIndex + 1, firstLeftParenIndex)
val functionCallTokensContainsTokens = if (functionCallTokens == null) false else
(functionCallTokens.map { if (splittableTokens.contains(it)) 1 else 0 }.sum() > 0)
// if TRUE, it's not a function call/def (e.g. foobar = funccall ( arg arg arg )
debug1("!!##[asTreeNode] line $lineNumber; functionCallTokens: $functionCallTokens; contains tokens?: $functionCallTokensContainsTokens")
/////////////////////////////
// unwrap (((((parens))))) //
/////////////////////////////
// FIXME ( asrtra ) + ( feinov ) forms are errenously stripped its paren away
/*if (tokens.first() == "(" && tokens.last() == ")") {
var wrapSize = 1
while (tokens[wrapSize] == "(" && tokens[tokens.lastIndex - wrapSize] == ")") {
wrapSize++
}
return asTreeNode(lineNumber, tokens.subList(wrapSize, tokens.lastIndex - wrapSize + 1))
}*/
debug1("!!##[asTreeNode] input token: $tokens")
////////////////////////////
// as Function Definition //
////////////////////////////
if (!functionCallTokensContainsTokens && functionCallTokens != null && functionCallTokens.size >= 2 && functionCallTokens.size <= 4) { // e.g. int main , StructName fooo , extern void doSomething , extern unsigned StructName uwwse
val actualFuncType = functionCallTokens[functionCallTokens.lastIndex - 1]
val returnType = resolveTypeString(actualFuncType)
val funcName = functionCallTokens.last()
// get arguments
// int * index , bool * * isSomething , double someNumber , ...
val argumentsDef = tokens.subList(firstLeftParenIndex + 1, lastRightParenIndex)
val argTypeNamePair = ArrayList<Pair<ReturnType, String?>>()
debug1("!! func def args")
debug1("!! <- $argumentsDef")
// chew it down to more understandable format
var typeHolder: ReturnType? = null
var nameHolder: String? = null
argumentsDef.forEachIndexed { index, token ->
if (argumentDefBadTokens.contains(token)) {
throw IllegalTokenException("at line $lineNumber -- illegal token '$token' used on function argument definition")
}
if (token == ",") {
if (typeHolder == null) throw SyntaxError("at line $lineNumber -- type not specified")
argTypeNamePair.add(typeHolder!! to nameHolder)
typeHolder = null
nameHolder = null
}
else if (token == "*") {
if (typeHolder == null) throw SyntaxError("at line $lineNumber -- type not specified")
typeHolder = resolveTypeString(typeHolder.toString().toLowerCase(), true)
}
else if (typeHolder == null) {
typeHolder = resolveTypeString(token)
}
else if (typeHolder != null) {
nameHolder = token
if (index == argumentsDef.lastIndex) {
argTypeNamePair.add(typeHolder!! to nameHolder)
}
}
else {
throw InternalError("uncaught shit right there")
}
}
debug1("!! -> $argTypeNamePair")
debug1("================================")
val funcDefNode = SyntaxTreeNode(ExpressionType.FUNCTION_DEF, returnType, funcName, lineNumber)
//if (returnType == ReturnType.STRUCT || returnType == ReturnType.STRUCT_PTR) {
// funcDefNode.structName = actualFuncType
//}
argTypeNamePair.forEach { val (type, name) = it
// TODO struct and structName
val funcDefArgNode = SyntaxTreeNode(ExpressionType.FUNC_ARGUMENT_DEF, type, name, lineNumber, isPartOfArgumentsNode = true)
funcDefNode.addArgument(funcDefArgNode)
}
return funcDefNode
}
//////////////////////
// as Function Call // (also works as keyworded code block (e.g. if, for, while))
//////////////////////
else if (tokens.size >= 3 /* foo, (, ); guaranteed to be at least three */ && tokens[1] == "(" &&
!functionCallTokensContainsTokens && functionCallTokens != null && functionCallTokens.size == 1) { // e.g. if ( , while ( ,
val funcName = functionCallTokens.last()
// get arguments
// complex_statements , ( value = funccall ( arg ) ) , "string,arg" , 42f
val argumentsDef = tokens.subList(firstLeftParenIndex + 1, lastRightParenIndex)
debug1("!! func call args:")
debug1("!! <- $argumentsDef")
// split into tokens list, splitted by ','
val functionCallArguments = ArrayList<ArrayList<String>>() // double array is intended (e.g. [["tsrasrat"], ["42"], [callff, (, "wut", )]] for input ("tsrasrat", "42", callff("wut"))
var tokensHolder = ArrayList<String>()
argumentsDef.forEachIndexed { index, token ->
if (index == argumentsDef.lastIndex) {
tokensHolder.add(token)
functionCallArguments.add(tokensHolder)
tokensHolder = ArrayList<String>() // can't reuse; must make new one
}
else if (token == ",") {
if (tokensHolder.isEmpty()) {
throw SyntaxError("at line $lineNumber -- misplaced comma")
}
else {
functionCallArguments.add(tokensHolder)
tokensHolder = ArrayList<String>() // can't reuse; must make new one
}
}
else {
tokensHolder.add(token)
}
}
debug1("!! -> $functionCallArguments")
val funcCallNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, null, funcName, lineNumber)
functionCallArguments.forEach {
debug1("!! forEach $it")
debug1("call from asTreeNode().asFunctionCall")
val argNodeLeaf = asTreeNode(lineNumber, it); argNodeLeaf.isPartOfArgumentsNode = true
funcCallNode.addArgument(argNodeLeaf)
}
debug1("================================")
return funcCallNode
}
////////////////////////
// as Var Call / etc. //
////////////////////////
else {
// filter illegal lines (absurd keyword usage)
tokens.forEach {
if (codeBlockKeywords.contains(it)) {
// code block without argumenets; give it proper parens and redirect
val newTokens = tokens.toMutableList()
if (newTokens.size != 1) {
throw SyntaxError("Number of tokens is not 1 (got size of ${newTokens.size}): ${newTokens}")
}
newTokens.add("("); newTokens.add(")")
debug1("call from asTreeNode().filterIllegalLines")
return asTreeNode(lineNumber, newTokens)
}
}
///////////////////////
// Bunch of literals //
///////////////////////
if (tokens.size == 1) {
val word = tokens[0]
debug1("!! literal, token: '$word'")
//debug1("================================")
// filtered String literals
if (word.startsWith('"') && word.endsWith('"')) {
val leafNode = SyntaxTreeNode(ExpressionType.LITERAL_LEAF, ReturnType.DATABASE, null, lineNumber)
leafNode.literalValue = tokens[0].substring(1, tokens[0].lastIndex) + nullchar
return leafNode
}
// bool literals
else if (word.matches(regexBooleanWhole)) {
val leafNode = SyntaxTreeNode(ExpressionType.LITERAL_LEAF, ReturnType.INT, null, lineNumber)
leafNode.literalValue = word == "true"
return leafNode
}
// hexadecimal literals
else if (word.matches(regexHexWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^0-9A-Fa-f]"""), "").toLong(16).and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// octal literals
else if (word.matches(regexOctWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^0-7]"""), "").toLong(8).and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// binary literals
else if (word.matches(regexBinWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^01]"""), "").toLong(2).and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// int literals
else if (word.matches(regexIntWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.INT,
null, lineNumber
)
try {
leafNode.literalValue =
word.replace(Regex("""[^0-9]"""), "").toLong().and(0xFFFFFFFFL).toInt()
}
catch (e: NumberFormatException) {
throw IllegalTokenException("at line $lineNumber -- $word is too large to be represented as ${leafNode.returnType?.toString()?.toLowerCase()}")
}
return leafNode
}
// floating point literals
else if (word.matches(regexFPWhole)) {
val leafNode = SyntaxTreeNode(
ExpressionType.LITERAL_LEAF,
ReturnType.FLOAT,
null, lineNumber
)
try {
leafNode.literalValue = if (word.endsWith('F', true))
word.slice(0..word.lastIndex - 1).toDouble() // DOUBLE when C-flat; replace it with 'toFloat()' if you're standard C
else
word.toDouble()
}
catch (e: NumberFormatException) {
throw InternalError("at line $lineNumber, while parsing '$word' as Double")
}
return leafNode
}
//////////////////////////////////////
// variable literal (VARIABLE_LEAF) // usually function call arguments
//////////////////////////////////////
else if (word.matches(regexVarNameWhole)) {
val leafNode = SyntaxTreeNode(ExpressionType.VARIABLE_READ, null, word, lineNumber)
return leafNode
}
}
else {
/////////////////////////////////////////////////
// return something; goto somewhere (keywords) //
/////////////////////////////////////////////////
if (tokens[0] == "goto" || tokens[0] == "comefrom") {
val nnode = SyntaxTreeNode(
ExpressionType.FUNCTION_CALL,
null,
tokens[0],
lineNumber
)
val rawTreeNode = tokens[1].toRawTreeNode(lineNumber); rawTreeNode.isPartOfArgumentsNode = true
nnode.addArgument(rawTreeNode)
return nnode
}
else if (tokens[0] == "return") {
val returnNode = SyntaxTreeNode(
ExpressionType.FUNCTION_CALL,
null,
"return",
lineNumber
)
val node = turnInfixTokensIntoTree(lineNumber, tokens.subList(1, tokens.lastIndex + 1)); node.isPartOfArgumentsNode = true
returnNode.addArgument(node)
return returnNode
}
//////////////////////////
// variable declaration //
//////////////////////////
// extern auto struct STRUCTID foobarbaz
// extern auto int foobarlulz
else if (splitContainsValidVariablePreword(tokens) != -1) {
val prewordIndex = splitContainsValidVariablePreword(tokens)
val realType = tokens[prewordIndex]
try {
val hasAssignment: Boolean
if (realType == "struct")
hasAssignment = tokens.lastIndex > prewordIndex + 2
else
hasAssignment = tokens.lastIndex > prewordIndex + 1
// deal with assignment
if (hasAssignment) {
// TODO support type_ptr_ptr_ptr...
// use turnInfixTokensIntoTree and inject it to assignment node
val isPtrType = tokens[1] == "*"
val typeStr = tokens[0] + if (isPtrType) "_ptr" else ""
val tokensWithoutType = if (isPtrType)
tokens.subList(2, tokens.size)
else
tokens.subList(1, tokens.size)
val infixNode = turnInfixTokensIntoTree(lineNumber, tokensWithoutType)
//#_assignvar(SyntaxTreeNode<RawString> varname, SyntaxTreeNode<RawString> vartype, SyntaxTreeNode value)
val returnNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, ReturnType.NOTHING, "#_assignvar", lineNumber)
val nameNode = tokensWithoutType.first().toRawTreeNode(lineNumber); nameNode.isPartOfArgumentsNode = true
returnNode.addArgument(nameNode)
val typeNode = typeStr.toRawTreeNode(lineNumber); typeNode.isPartOfArgumentsNode = true
returnNode.addArgument(typeNode)
infixNode.isPartOfArgumentsNode = true
returnNode.addArgument(infixNode)
return returnNode
}
else {
// #_declarevar(SyntaxTreeNode<RawString> varname, SyntaxTreeNode<RawString> vartype)
val leafNode = SyntaxTreeNode(ExpressionType.INTERNAL_FUNCTION_CALL, ReturnType.NOTHING, "#_declarevar", lineNumber)
val valueNode = tokens[1].toRawTreeNode(lineNumber); valueNode.isPartOfArgumentsNode = true
leafNode.addArgument(valueNode)
val typeNode = tokens[0].toRawTreeNode(lineNumber); typeNode.isPartOfArgumentsNode = true
leafNode.addArgument(typeNode)
return leafNode
}
}
catch (syntaxFuck: ArrayIndexOutOfBoundsException) {
throw SyntaxError("at line $lineNumber -- missing statement(s)")
}
}
else {
debug1("!! infix in: $tokens")
// infix notation
return turnInfixTokensIntoTree(lineNumber, tokens)
}
TODO()
} // end if (tokens.size == 1)
TODO()
}
}
fun turnInfixTokensIntoTree(lineNumber: Int, tokens: List<String>): SyntaxTreeNode {
// based on https://stackoverflow.com/questions/1946896/conversion-from-infix-to-prefix
// FIXME: differentiate parens for function call from grouping
fun debug(any: Any) { if (true) println(any) }
fun precedenceOf(token: String): Int {
if (token == "(" || token == ")") return -1
operatorsHierarchyInternal.forEachIndexed { index, hashSet ->
if (hashSet.contains(token)) return index
}
throw SyntaxError("[infix-to-tree] at $lineNumber -- unknown operator '$token'")
}
val tokens = tokens.reversed()
val stack = Stack<String>()
val treeArgsStack = Stack<Any>()
fun addToTree(token: String) {
debug("[infix-to-tree] adding '$token'")
fun argsCountOf(operator: String) = if (unaryOps.contains(operator)) 1 else 2
fun popAsTree(): SyntaxTreeNode {
val rawElem = treeArgsStack.pop()
if (rawElem is String) {
debug("[infix-to-tree] call from turnInfixTokensIntoTree().addToTree().popAsTree()")
return asTreeNode(lineNumber, listOf(rawElem))
}
else if (rawElem is SyntaxTreeNode)
return rawElem
else
throw InternalError("I said you to put String or SyntaxTreeNode only; what's this? ${rawElem.javaClass.simpleName}?")
}
if (!operatorsNoOrder.contains(token)) {
debug("-> not a operator; pushing to args stack")
treeArgsStack.push(token)
}
else {
debug("-> taking ${argsCountOf(token)} value(s) from stack")
val treeNode = SyntaxTreeNode(ExpressionType.FUNCTION_CALL, null, token, lineNumber)
repeat(argsCountOf(token)) {
val poppedTree = popAsTree(); poppedTree.isPartOfArgumentsNode = true
treeNode.addArgument(poppedTree)
}
treeArgsStack.push(treeNode)
}
}
debug("[infix-to-tree] reversed tokens: $tokens")
tokens.forEachIndexed { index, rawToken ->
// contextually decide what is real token
val token =
// if prev token is operator (used '+' as token list is reversed)
if (index == tokens.lastIndex || operatorsNoOrder.contains(tokens[index + 1])) {
if (rawToken == "+") "#_unaryplus"
else if (rawToken == "-") "#_unaryminus"
else if (rawToken == "&") "#_addressof"
else if (rawToken == "*") "#_ptrderef"
else if (rawToken == "++") "#_preinc"
else if (rawToken == "--") "#_predec"
else rawToken
}
else rawToken
if (token == ")") {
stack.push(token)
}
else if (token == "(") {
while (stack.isNotEmpty()) {
val t = stack.pop()
if (t == ")") break
addToTree(t)
}
}
else if (!operatorsNoOrder.contains(token)) {
addToTree(token)
}
else {
// XXX: associativity should be considered here
// https://en.wikipedia.org/wiki/Operator_associativity
while (stack.isNotEmpty() && precedenceOf(stack.peek()) > precedenceOf(token)) {
addToTree(stack.pop())
}
stack.add(token)
}
}
while (stack.isNotEmpty()) {
addToTree(stack.pop())
}
if (treeArgsStack.size != 1) {
throw InternalError("Stack size is wrong -- supposed to be 1, but it's ${treeArgsStack.size}\nstack: $treeArgsStack")
}
debug("[infix-to-tree] finalised tree:\n${treeArgsStack.peek()}")
return if (treeArgsStack.peek() is SyntaxTreeNode)
treeArgsStack.peek() as SyntaxTreeNode
else {
debug("[infix-to-tree] call from turnInfixTokensIntoTree().if (treeArgsStack.peek() is SyntaxTreeNode).else")
asTreeNode(lineNumber, listOf(treeArgsStack.peek() as String))
}
}
data class LineStructure(var lineNum: Int, var depth: Int, val tokens: MutableList<String>)
class SyntaxTreeNode(
val expressionType: ExpressionType,
val returnType: ReturnType?, // STATEMENT, LITERAL_LEAF: valid ReturnType; VAREABLE_LEAF: always null
var name: String?,
val lineNumber: Int, // used to generate error message
val isRoot: Boolean = false,
//val derefDepth: Int = 0 // how many ***s are there for pointer
var isPartOfArgumentsNode: Boolean = false
) {
var literalValue: Any? = null // for LITERALs only
var structName: String? = null // for STRUCT return type
val arguments = ArrayList<SyntaxTreeNode>() // for FUNCTION, CODE_BLOCK
val statements = ArrayList<SyntaxTreeNode>()
var depth: Int? = null
fun addArgument(node: SyntaxTreeNode) {
arguments.add(node)
}
fun addStatement(node: SyntaxTreeNode) {
statements.add(node)
}
fun updateDepth() {
if (!isRoot) throw Error("Updating depth only make sense when used as root")
this.depth = 0
arguments.forEach { it._updateDepth(1) }
statements.forEach { it._updateDepth(1) }
}
private fun _updateDepth(recursiveDepth: Int) {
this.depth = recursiveDepth
arguments.forEach { it._updateDepth(recursiveDepth + 1) }
statements.forEach { it._updateDepth(recursiveDepth + 1) }
}
fun expandImplicitEnds() {
if (!isRoot) throw Error("Expanding implicit 'end's only make sense when used as root")
// fixme no nested ifs
statements.forEach { it.statements.forEach { it._expandImplicitEnds() } } // root level if OF FUNCDEF
statements.forEach { it._expandImplicitEnds() } // root level if
}
private fun _expandImplicitEnds() {
if (this.name in functionsImplicitEnd) {
this.statements.add(SyntaxTreeNode(
ExpressionType.INTERNAL_FUNCTION_CALL, null, "end${this.name}", this.lineNumber, this.isRoot
))
}
else if (this.expressionType == ExpressionType.FUNCTION_DEF) {
val endfuncdef = SyntaxTreeNode(
ExpressionType.INTERNAL_FUNCTION_CALL, null, "endfuncdef", this.lineNumber, this.isRoot
)
endfuncdef.addArgument(SyntaxTreeNode(ExpressionType.FUNC_ARGUMENT_DEF, null, this.name!!, this.lineNumber, isPartOfArgumentsNode = true))
this.statements.add(endfuncdef)
}
}
val isLeaf: Boolean
get() = expressionType.toString().endsWith("_LEAF") ||
(arguments.isEmpty() && statements.isEmpty())
override fun toString() = toStringRepresentation(0)
private fun toStringRepresentation(depth: Int): String {
val header = "│ ".repeat(depth) + if (isRoot) "⧫AST (name: $name)" else if (isLeaf) "◊AST$depth (name: $name)" else "☐AST$depth (name: $name)"
val lines = arrayListOf(
header,
"│ ".repeat(depth+1) + "ExprType : $expressionType",
"│ ".repeat(depth+1) + "RetnType : $returnType",
"│ ".repeat(depth+1) + "LiteralV : '$literalValue'",
"│ ".repeat(depth+1) + "isArgNod : $isPartOfArgumentsNode"
)
if (!isLeaf) {
lines.add("│ ".repeat(depth+1) + "# of arguments: ${arguments.size}")
arguments.forEach { lines.add(it.toStringRepresentation(depth + 1)) }
lines.add("│ ".repeat(depth+1) + "# of statements: ${statements.size}")
statements.forEach { lines.add(it.toStringRepresentation(depth + 1)) }
}
lines.add("│ ".repeat(depth) + "╘" + "═".repeat(header.length - 1 - 2*depth))
val sb = StringBuilder()
lines.forEachIndexed { index, line ->
sb.append(line)
if (index < lines.lastIndex) { sb.append("\n") }
}
return sb.toString()
}
private fun traverseStmtOnly(node: SyntaxTreeNode, action: (SyntaxTreeNode, Int) -> Unit, depth: Int = 0) {
//if (node == null) return
action(node, depth)
node.statements.forEach { traverseStmtOnly(it, action, depth + 1) }
}
fun traversePreorderStatements(action: (SyntaxTreeNode, Int) -> Unit) {
this.traverseStmtOnly(this, action)
}
}
private fun String.toRawTreeNode(lineNumber: Int): SyntaxTreeNode {
val node = SyntaxTreeNode(ExpressionType.LITERAL_LEAF, ReturnType.DATABASE, null, lineNumber)
node.literalValue = this
return node
}
inline fun <T> Iterable<T>.findAllToIndices(predicate: (T) -> Boolean): IntArray {
val indices = ArrayList<Int>()
this.forEachIndexed { index, t ->
if (predicate(t))
indices.add(index)
}
return indices.toIntArray()
}
enum class ExpressionType {
FUNCTION_DEF, FUNC_ARGUMENT_DEF, // expect Arguments and Statements
INTERNAL_FUNCTION_CALL,
FUNCTION_CALL, // expect Arguments and Statements
// the case of OPERATOR CALL //
// returnType: variable type; name: "="; TODO add description for STRUCT
// arg0: name of the variable (String)
// arg1: (optional) assigned value, either LITERAL or FUNCTION_CALL or another OPERATOR CALL
// arg2: (if STRUCT) struct identifier (String)
LITERAL_LEAF, // literals, also act as a leaf of the tree; has returnType of null
VARIABLE_WRITE, // CodeL; loads memory address to be written onto
VARIABLE_READ // CodeR; the actual value stored in its memory address
}
enum class ReturnType {
INT, FLOAT,
NOTHING, // null
DATABASE // array of bytes, also could be String
}
class PreprocessorRules {
private val kwdRetPair = HashMap<String, String>()
fun addDefinition(keyword: String, ret: String) {
kwdRetPair[keyword] = ret
}
fun removeDefinition(keyword: String) {
kwdRetPair.remove(keyword)
}
fun forEachKeywordForTokens(action: (String, String) -> Unit) {
kwdRetPair.forEach { key, value ->
action("""[ \t\n]+""" + key + """(?=[ \t\n;]+)""", value)
}
}
}
/**
* Notation rules:
* - Variable: prepend with '$' (e.g. $duplicantsCount) // totally not a Oxygen Not Included reference
* - Register: prepend with 'r' (e.g. r3)
*/
data class IntermediateRepresentation(
var lineNum: Int,
var instruction: String = "DUMMY",
var arg1: String? = null,
var arg2: String? = null,
var arg3: String? = null,
var arg4: String? = null,
var arg5: String? = null
) {
constructor(other: IntermediateRepresentation) : this(
other.lineNum,
other.instruction,
other.arg1,
other.arg2,
other.arg3,
other.arg4,
other.arg5
)
override fun toString(): String {
val sb = StringBuilder()
sb.append(instruction)
arg1?.let { sb.append(" $it") }
arg2?.let { sb.append(", $it") }
arg3?.let { sb.append(", $it") }
arg4?.let { sb.append(", $it") }
arg5?.let { sb.append(", $it") }
sb.append("; (at line $lineNum)")
return sb.toString()
}
}
}
open class SyntaxError(msg: String? = null) : Exception(msg)
class IllegalTokenException(msg: String? = null) : SyntaxError(msg)
class UnresolvedReference(msg: String? = null) : SyntaxError(msg)
class UndefinedStatement(msg: String? = null) : SyntaxError(msg)
class DuplicateDefinition(msg: String? = null) : SyntaxError(msg)
class PreprocessorErrorMessage(msg: String) : SyntaxError(msg)
| src/net/torvald/terranvm/runtime/compiler/cflat/Compiler.kt | 604203426 |
package nl.hannahsten.texifyidea.structure.filter
import com.intellij.ide.util.treeView.smartTree.ActionPresentation
import com.intellij.ide.util.treeView.smartTree.Filter
import com.intellij.ide.util.treeView.smartTree.TreeElement
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.structure.latex.LatexStructureViewCommandElement
import nl.hannahsten.texifyidea.util.labels.getLabelDefinitionCommands
import javax.swing.Icon
/**
* @author Hannah Schellekens
*/
class LabelFilter : Filter {
override fun isVisible(treeElement: TreeElement): Boolean {
if (treeElement !is LatexStructureViewCommandElement) {
return true
}
return !getLabelDefinitionCommands().contains(treeElement.commandName)
}
override fun isReverted(): Boolean = true
override fun getPresentation(): ActionPresentation = LatexLabelFilterPresentation.INSTANCE
override fun getName(): String = "latex.texify.filter.label"
/**
* @author Hannah Schellekens
*/
private class LatexLabelFilterPresentation : ActionPresentation {
override fun getText(): String = "Show Labels"
override fun getDescription(): String = "Show Labels"
override fun getIcon(): Icon = TexifyIcons.DOT_LABEL
companion object {
val INSTANCE = LatexLabelFilterPresentation()
}
}
} | src/nl/hannahsten/texifyidea/structure/filter/LabelFilter.kt | 2362361268 |
/**
* Created by menion on 29/08/2016.
* This code is part of Locus project from Asamm Software, s. r. o.
*/
package com.asamm.locus.api.sample.pages
import android.app.AlertDialog
import android.content.Intent
import android.widget.Toast
import com.asamm.locus.api.sample.ActivityDashboard
import com.asamm.locus.api.sample.BuildConfig
import com.asamm.locus.api.sample.utils.BasicAdapterItem
import com.asamm.locus.api.sample.utils.SampleCalls
import locus.api.android.ActionBasics
import locus.api.android.ActionFiles
import locus.api.android.features.geocaching.fieldNotes.FieldNotesHelper
import locus.api.android.objects.LocusVersion
import locus.api.android.utils.LocusConst
import java.util.*
class PageUtilsFragment : ABasePageFragment() {
override val items: List<BasicAdapterItem>
get() {
val items = ArrayList<BasicAdapterItem>()
items.add(BasicAdapterItem(-1,
"Get basic info about Locus app",
"Basic checks on installed Locus apps."))
items.add(BasicAdapterItem(1,
"Send GPX file to system",
"Send existing GPX file to system. This should invoke selection of an app that will handle this request."))
items.add(BasicAdapterItem(2,
"Send GPX file directly to Locus",
"You may also send intent (with a link to a file) directly to Locus app."))
items.add(BasicAdapterItem(3,
"Pick location from Locus",
"If you need 'location' in your application, this call allows you to use Locus 'GetLocation' screen. Result is handled in MainActivity as 'LocusUtils.isIntentGetLocation()'"))
items.add(BasicAdapterItem(4,
"Pick file",
"Allows to use Locus internal file picker and choose a file from the file system. You may also specify a filter on requested file. Request is sent as 'Activity.startActivityForResult()', so you have to handle the result in your own activity."))
items.add(BasicAdapterItem(5,
"Pick directory",
"Same as previous sample, just for picking directories instead of files."))
items.add(BasicAdapterItem(6,
"Get ROOT directory",
"Allows to get current active ROOT directory of installed Locus."))
items.add(BasicAdapterItem(7,
"Add WMS map",
"Allows to add WMS map directly to the list of WMS services."))
items.add(BasicAdapterItem(11,
"Dashboard",
"Very nice example that shows how your app may create its own dashboard filled with data received by Locus 'Periodic updates'"))
items.add(BasicAdapterItem(17,
"Get fresh UpdateContainer",
"Simple method how to get fresh UpdateContainer with new data ( no need for PeriodicUpdates )"))
items.add(BasicAdapterItem(12,
"Show circles",
"Small function that allows to draw circles on Locus map. This function is called as broadcast so check result in running Locus!"))
items.add(BasicAdapterItem(13,
"Is Periodic update enabled",
"Because periodic updates are useful in many cases, not just for the dashboard, this function allows to check if 'Periodic updates' are enabled in Locus."))
items.add(BasicAdapterItem(14,
"Request available Geocaching field notes",
"Simple method of getting number of existing field notes in Locus Map application"))
items.add(BasicAdapterItem(15,
"Check item purchase state",
"This function allows to check state of purchase of a certain item (with known ID) in Locus Store"))
items.add(BasicAdapterItem(16,
"Display detail of Store item",
"Display detail of a certain Locus Store item (with known ID)"))
items.add(BasicAdapterItem(19,
"Take a 'screenshot'",
"Take a bitmap screenshot of certain place in app"))
items.add(BasicAdapterItem(20,
"New 'Action tasks' API",
"Suggest to test in split screen mode with active Locus Map"))
// TEMPORARY TEST ITEMS
if (BuildConfig.DEBUG) {
// nothing to test
}
return items
}
@Throws(Exception::class)
override fun onItemClicked(itemId: Int, activeLocus: LocusVersion) {
// handle action
when (itemId) {
-1 -> SampleCalls.callDisplayLocusMapInfo(act)
1 -> SampleCalls.callSendFileToSystem(act)
2 -> SampleCalls.callSendFileToLocus(act, activeLocus)
3 -> SampleCalls.pickLocation(act)
4 ->
// filter data so only visible will be GPX and KML files
ActionFiles.actionPickFile(act,
0, "Give me a FILE!!",
arrayOf(".gpx", ".kml"))
5 -> ActionFiles.actionPickDir(act, 1)
6 -> AlertDialog.Builder(act)
.setTitle("Locus Root directory")
.setMessage("dir:" + SampleCalls.getRootDirectory(act, activeLocus) +
"\n\n'null' means no required version installed or different problem")
.setPositiveButton("Close") { _, _ -> }
.show()
7 -> ActionBasics.callAddNewWmsMap(act,
"http://mapy.geology.cz/arcgis/services/Inspire/GM500K/MapServer/WMSServer")
11 -> startActivity(Intent(act, ActivityDashboard::class.java))
12 -> SampleCalls.showCircles(act)
13 -> AlertDialog.Builder(act).setTitle("Periodic update")
.setMessage("enabled:" + SampleCalls.isPeriodicUpdateEnabled(act, activeLocus))
.setPositiveButton("Close") { _, _ -> }
.show()
14 -> {
val count = FieldNotesHelper.getCount(act, activeLocus)
Toast.makeText(act,
"Available field notes:$count", Toast.LENGTH_LONG).show()
}
15 -> {
// We test here if user has purchased "Add-on Field Notes Pro. Unique ID is defined on our Store
// so it needs to be known for you before asking.
val purchaseId = ActionBasics.getItemPurchaseState(
act, activeLocus, 5943264947470336L)
when (purchaseId) {
LocusConst.PURCHASE_STATE_PURCHASED -> Toast.makeText(act,
"Purchase item state: purchased", Toast.LENGTH_LONG).show()
LocusConst.PURCHASE_STATE_NOT_PURCHASED -> Toast.makeText(act,
"Purchase item state: not purchased", Toast.LENGTH_LONG).show()
else -> // this usually means that user profile is not loaded. Best what to do is call
// "displayLocusStoreItemDetail" to display item detail which also loads users
// profile
Toast.makeText(act,
"Purchase item state: $purchaseId", Toast.LENGTH_LONG).show()
}
}
16 ->
// We display here Locus Store with certain item. In this case it is "Add-on Field Notes Pro.
// Unique ID is defined on our Store so it needs to be known for you before asking.
ActionBasics.displayLocusStoreItemDetail(
act, activeLocus, 5943264947470336L)
17 -> {
val uc = ActionBasics.getUpdateContainer(act, activeLocus)
if (uc != null) {
AlertDialog.Builder(act)
.setTitle("Fresh UpdateContainer")
.setMessage("UC: $uc")
.setPositiveButton("Close") { _, _ -> }
.show()
} else {
Toast.makeText(act,
"Unable to obtain UpdateContainer from $activeLocus", Toast.LENGTH_LONG).show()
}
}
19 -> {
@Suppress("ReplaceSingleLineLet")
act.supportFragmentManager
.beginTransaction()
.add(MapFragment(), "MAP_FRAGMENT")
.commit()
}
20 -> {
@Suppress("ReplaceSingleLineLet")
act.supportFragmentManager
.beginTransaction()
.add(PageBroadcastApiSamples(), "BROADCAST_API_FRAGMENT")
.commit()
}
}
}
}
| locus-api-android-sample/src/main/java/com/asamm/locus/api/sample/pages/PageUtilsFragment.kt | 3877400891 |
package com.matchr
import ca.allanwang.kau.utils.postDelayed
import com.google.firebase.database.*
import com.matchr.data.*
import com.matchr.utils.L
import org.jetbrains.anko.doAsync
import java.util.*
/**
* Created by Allan Wang on 2017-10-21.
*/
object Firebase {
const val TYPE = "type"
const val DATA = "data"
const val QUESTION = "question"
const val OPTIONS = "options"
const val USER_ID = "user_id"
const val RESPONSE_ID = "response_id"
const val WEIGHT = "weight"
const val NAME = "name"
const val EMAIL = "email"
lateinit var question_pool_key: String
val database: FirebaseDatabase by lazy { FirebaseDatabase.getInstance() }
val users
get() = database.getReference("test")
fun getFirstQuestion(callback: (Int) -> Unit) {
users.genericGet("startId") { data ->
L.v(data?.key)
L.v(data?.value?.toString())
callback(data.intValueOr(-1))
}
}
fun init(callback: () -> Unit) {
users.ref.genericGet("data_pool") {
question_pool_key = it?.value?.toString() ?: QUESTION_DATA_TUTORING
callback()
}
}
private fun DataSnapshot?.intValueOr(default: Int) = this?.value?.toString()?.toIntOrNull() ?: default
private fun DataSnapshot?.floatValueOr(default: Float) = this?.value?.toString()?.toFloatOrNull() ?: default
fun getQuestion(id: Int, callback: (Question?) -> Unit) {
users.genericGet(Endpoints.QUESTIONS.pathWith("$question_pool_key/$id")) { data ->
if (data == null) return@genericGet callback(null)
val question = data.child(QUESTION).value.toString()
val options = data.child(OPTIONS).children.filterNotNull().map { d ->
d.key to d.intValueOr(-1)
}
if (options.isEmpty()) return@genericGet callback(null)
val type = data.child(TYPE).intValueOr(0)
callback(Question(id, question, options, if (type >= QuestionType.values.size) 0 else type))
}
}
fun saveQuestion(poolKey: String, question: Question) {
val data = mutableListOf<Pair<String, Any>>().apply {
add(TYPE to question.type)
add(QUESTION to question.question)
question.options.forEach { (k, v) ->
add("$OPTIONS/$k" to v)
}
}
Endpoints.QUESTIONS.saveData(poolKey, question.id, *data.toTypedArray())
}
private fun DatabaseReference.genericGet(path: String, callback: (DataSnapshot?) -> Unit) {
L.v("Getting data for path $path")
child(path).ref.orderByPriority().addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
callback(null)
}
override fun onDataChange(p0: DataSnapshot) {
callback(p0)
}
})
}
fun saveResponse(response: Response) {
Endpoints.RESPONSES.saveData("$question_pool_key/${response.userId}", response.qOrdinal,
DATA to response.data)
}
fun getResponse(id: String, qId: Int, callback: (Response?) -> Unit) {
users.genericGet(Endpoints.RESPONSES.pathWith("$question_pool_key/$id")) { data ->
if (data == null) return@genericGet callback(null)
val response = data.child(DATA).children.filterNotNull().map { d -> d.value.toString() }
if (response.isEmpty()) return@genericGet callback(null)
callback(Response(id, qId, response))
}
}
fun getResponses(id: String, callback: (List<Response>) -> Unit) {
users.genericGet(Endpoints.RESPONSES.pathWith("$question_pool_key/$id")) { data ->
if (data == null) return@genericGet callback(emptyList())
val responses = data.children.map {
Response(id, it.key.toInt(), it.child(DATA).children.filterNotNull().map { d ->
d.value.toString()
})
}
callback(responses)
}
}
fun matchData(userId: String, callback: (List<Pair<User, Float>>) -> Unit) {
doAsync {
users.genericGet(Endpoints.RESPONSES.pathWith(question_pool_key)) { data ->
if (data == null) return@genericGet callback(emptyList())
var self: Pair<User, Map<Int, List<String>>>? = null
getUsers { users ->
if (users.isEmpty()) return@getUsers callback(emptyList())
val candidates: List<Pair<User, Map<Int, List<String>>>> = data.children.mapNotNull {
L.d("K ${it.key}")
val candidate = users[it.key] ?: return@mapNotNull null
val responses = it.children.map { r ->
val response = r.child(DATA).children.filterNotNull().map { d -> d.value.toString() }
r.key.toInt() to response
}.filter { it.second.isNotEmpty() }.toMap()
if (candidate.id == userId)
self = candidate to responses
candidate to responses
}.filter { (user, responses) -> user.id != "null" && user.id != userId && responses.isNotEmpty() }
L.d("Self $self")
L.d("Match candidates $candidates")
if (candidates.isEmpty() || self == null) return@getUsers callback(emptyList())
getMatchrs { m ->
if (m.isEmpty()) return@getMatchrs callback(emptyList())
callback(match(m, self!!.second, candidates))
}
}
}
}
}
private fun match(matchrs: List<Matchr>, selfResponses: Map<Int,
List<String>>, candidates: List<Pair<User, Map<Int, List<String>>>>): List<Pair<User, Float>> {
return candidates.map { c ->
val score = matchrs.map { m ->
match(m, selfResponses, c)
}.sum()
val u = c.first to score
L.v("UUU $u")
u
}
}
private fun match(matchr: Matchr, selfResponses: Map<Int, List<String>>,
candidate: Pair<User, Map<Int, List<String>>>): Float {
val data1 = selfResponses[matchr.rId1] ?: return 0f
val data2 = candidate.second[matchr.rId2] ?: return 0f
//compute intersect, divide by average data size, multiply be weight
return data1.intersect(data2).size.toFloat() * 2 / (data1.size + data2.size) * matchr.weight
}
fun saveUser(user: User) {
val child = database.reference.child(Endpoints.USERS.pathWith(user.id))
child.child(NAME).setValue(user.name)
child.child(EMAIL).setValue(user.email)
}
fun getUsers(callback: (Map<String, User>) -> Unit) {
database.reference.genericGet(Endpoints.USERS.pathWith("")) { data ->
data ?: return@genericGet callback(emptyMap())
callback(data.children.map { it.key to User(it.key, it.child(NAME).value.toString(), it.child(EMAIL).value.toString()) }.toMap())
}
}
fun saveMatchr(poolKey: String, rId1: Int, rId2: Int, weight: Float)
= saveMatchr(poolKey, Matchr(rId1, rId2, weight))
fun saveMatchr(poolKey: String, matchr: Matchr) {
Endpoints.MATCHR.saveData(poolKey, matchr.rId1,
RESPONSE_ID to matchr.rId2, WEIGHT to matchr.weight)
}
fun getMatchrs(callback: (List<Matchr>) -> Unit) {
users.genericGet(Endpoints.MATCHR.pathWith(question_pool_key)) { data ->
data ?: return@genericGet callback(emptyList())
callback(data.children.map {
val children = it.children
Matchr(it.key.toInt(), it.child(RESPONSE_ID).intValueOr(-1),
it.child(WEIGHT).floatValueOr(0f))
}.filter { it.rId1 >= 0 && it.rId2 >= 0 && it.weight != 0f })
}
}
}
enum class Endpoints {
RESPONSES, QUESTIONS, MATCHR, USERS;
fun saveData(userId: String, childId: Int, vararg data: Pair<String, Any>)
= saveDataImpl(pathWith(userId), childId, *data)
fun pathWith(post: String) = "${name.toLowerCase(Locale.US)}/$post"
}
fun saveDataImpl(path: String, childId: Int, vararg data: Pair<String, Any>) {
val child = Firebase.users.child("$path/$childId")
data.forEachIndexed { i, (k, v) ->
child.child(k).setValue(v)
child.child(k).setPriority(i)
}
} | app/src/main/java/com/matchr/Firebase.kt | 519597486 |
package com.gdgnantes.devfest.android.graphics
import android.graphics.*
import com.squareup.picasso.Transformation
class RoundedTransformation : Transformation {
private val paint: Paint = Paint()
override fun transform(source: Bitmap): Bitmap {
paint.isAntiAlias = true
paint.shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
val radius = Math.min(source.width, source.height) / 2
val output = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(output)
canvas.drawRoundRect(0f, 0f, source.width.toFloat(), source.height.toFloat(), radius.toFloat(), radius.toFloat(), paint)
if (source != output) {
source.recycle()
}
return output
}
override fun key(): String {
return "rounded"
}
}
| app/src/main/kotlin/com/gdgnantes/devfest/android/graphics/RoundedTransformation.kt | 2849775174 |
package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.MultiRule
import io.gitlab.arturbosch.detekt.api.Rule
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtConstructor
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtVariableDeclaration
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
/**
* @author Artur Bosch
*/
class NamingRules(config: Config = Config.empty) : MultiRule() {
private val variableNamingRule = VariableNaming(config)
private val variableMinNameLengthRule = VariableMinLength(config)
private val variableMaxNameLengthRule = VariableMaxLength(config)
private val topLevelPropertyRule = TopLevelPropertyNaming(config)
private val objectConstantNamingRule = ObjectPropertyNaming(config)
private val packageNamingRule = PackageNaming(config)
private val classOrObjectNamingRule = ClassNaming(config)
private val enumEntryNamingRule = EnumNaming(config)
private val functionNamingRule = FunctionNaming(config)
private val functionMaxNameLengthRule = FunctionMaxLength(config)
private val functionMinNameLengthRule = FunctionMinLength(config)
private val forbiddenClassNameRule = ForbiddenClassName(config)
private val constructorParameterNamingRule = ConstructorParameterNaming(config)
private val functionParameterNamingRule = FunctionParameterNaming(config)
override val rules: List<Rule> = listOf(
variableNamingRule,
variableMinNameLengthRule,
variableMaxNameLengthRule,
topLevelPropertyRule,
objectConstantNamingRule,
packageNamingRule,
classOrObjectNamingRule,
enumEntryNamingRule,
functionNamingRule,
functionMaxNameLengthRule,
functionMinNameLengthRule,
forbiddenClassNameRule,
constructorParameterNamingRule,
functionParameterNamingRule
)
override fun visitPackageDirective(directive: KtPackageDirective) {
super.visitPackageDirective(directive)
packageNamingRule.runIfActive { visitPackageDirective(directive) }
}
override fun visitNamedDeclaration(declaration: KtNamedDeclaration) {
if (declaration.nameAsSafeName.isSpecial) {
return
}
declaration.nameIdentifier?.parent?.javaClass?.let {
when (declaration) {
is KtProperty -> handleVariable(declaration)
is KtNamedFunction -> handleFunction(declaration)
is KtEnumEntry -> enumEntryNamingRule.runIfActive { visitEnumEntry(declaration) }
is KtClassOrObject -> handleClassOrObject(declaration)
is KtParameter -> handleParameter(declaration)
}
}
super.visitNamedDeclaration(declaration)
}
private fun handleClassOrObject(declaration: KtClassOrObject) {
classOrObjectNamingRule.runIfActive { visitClassOrObject(declaration) }
forbiddenClassNameRule.runIfActive { visitClassOrObject(declaration) }
}
private fun handleFunction(declaration: KtNamedFunction) {
functionNamingRule.runIfActive { visitNamedFunction(declaration) }
functionMaxNameLengthRule.runIfActive { visitNamedFunction(declaration) }
functionMinNameLengthRule.runIfActive { visitNamedFunction(declaration) }
}
private fun handleVariable(declaration: KtProperty) {
variableMaxNameLengthRule.runIfActive { visitProperty(declaration) }
variableMinNameLengthRule.runIfActive { visitProperty(declaration) }
when {
declaration.isTopLevel -> topLevelPropertyRule.runIfActive { visitProperty(declaration) }
declaration.withinObjectDeclaration() -> objectConstantNamingRule.runIfActive { visitProperty(declaration) }
else -> variableNamingRule.runIfActive { visitProperty(declaration) }
}
}
private fun handleParameter(declaration: KtParameter) {
when (declaration.ownerFunction) {
is KtConstructor<*> -> constructorParameterNamingRule.runIfActive { visitParameter(declaration) }
is KtNamedFunction -> functionParameterNamingRule.runIfActive { visitParameter(declaration) }
}
}
private fun KtVariableDeclaration.withinObjectDeclaration(): Boolean =
this.getNonStrictParentOfType(KtObjectDeclaration::class.java) != null
}
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/NamingRules.kt | 1884935454 |
/*
* Copyright 2016-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.kotlin.mybatis3.custom.render
data class KJsonTestRecord(
var id: Int,
var description: String,
var info: String
)
| src/test/kotlin/examples/kotlin/mybatis3/custom/render/KJsonTestRecord.kt | 435573051 |
package ir.toolki.ganmaz.classification
import com.google.common.collect.HashMultiset
import com.google.common.collect.Multiset
import com.google.common.collect.Multisets
import java.util.*
class DataSet(documents: List<Document>) {
private val digestedDocs: MutableList<DigestedDoc> = arrayListOf()
private var df: Multiset<String> = HashMultiset.create()
init {
documents.forEach { TextUtils.tokenizeAndNormalize(it.body()).toSet().forEach { df.add(it) } }
df = Multisets.copyHighestCountFirst(df)
documents.forEach { digestedDocs.add(DigestedDoc(it, df)) }
}
fun size() = digestedDocs.size
fun score(doc: Document): List<Pair<DigestedDoc, Double>> {
val map: MutableMap<DigestedDoc, Double> = hashMapOf()
val digested = DigestedDoc(doc, df)
val digestedLen = Math.sqrt(digested.termScore.values.map { it -> it * it }.sum())
digestedDocs.forEach {
var sumScore = 0.0
digested.termScore.forEach { term, score ->
if (it.termScore.containsKey(term))
sumScore += score * it.termScore.get(term)!!.toDouble()
}
val itLen = Math.sqrt(it.termScore.values.map { it -> it * it }.sum())
sumScore /= (digestedLen * itLen)
map.put(it, sumScore)
}
return map.map { it -> Pair(it.key, it.value) }.sortedBy { it -> it.second }.reversed().toList()
}
fun classify(doc: Document, k: Int): String {
val ranked = score(doc)
var labels = ranked.map { it -> it.first.doc.label }.toList()
labels = labels.subList(0, Math.min(k, labels.size))
val map = labels.groupBy { it }
return Collections.max(map.entries, compareBy { it.value.size }).key
}
companion object {
fun evaluate(train: List<Document>, test: List<Document>): Double {
val dataset = DataSet(train)
var corrects = 0
test.forEach {
val klass = dataset.classify(it, 5)
if (klass == it.label)
corrects++
}
return corrects.toDouble() / test.size
}
}
}
| src/main/java/ir/toolki/ganmaz/classification/DataSet.kt | 1919241376 |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.modernstorage.storage
import android.net.Uri
import okio.Path
import okio.Path.Companion.toPath
fun Path.toUri(): Uri {
val str = this.toString()
if (str.startsWith("content:/")) {
return Uri.parse(str.replace("content:/", "content://"))
}
return Uri.parse(str)
}
fun Uri.toOkioPath(): Path {
return this.toString().toPath(false)
}
@Deprecated(
"Use the Uri.toOkioPath() method instead",
ReplaceWith("toOkioPath()"),
DeprecationLevel.WARNING
)
fun Uri.toPath() = this.toOkioPath()
| storage/src/main/java/com/google/modernstorage/storage/PathUtils.kt | 3288348542 |
/*
* 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.testFramework
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.idea.IdeaTestApplication
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.project.stateStore
import com.intellij.util.SmartList
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.io.systemIndependentPath
import org.junit.rules.ExternalResource
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.nio.file.Files
import java.util.concurrent.atomic.AtomicBoolean
private var sharedModule: Module? = null
open class ApplicationRule : ExternalResource() {
companion object {
init {
Logger.setFactory(TestLoggerFactory::class.java)
}
}
override public final fun before() {
IdeaTestApplication.getInstance()
TestRunnerUtil.replaceIdeEventQueueSafely()
(PersistentFS.getInstance() as PersistentFSImpl).cleanPersistedContents()
}
}
/**
* Project created on request, so, could be used as a bare (only application).
*/
class ProjectRule : ApplicationRule() {
companion object {
private var sharedProject: ProjectEx? = null
private val projectOpened = AtomicBoolean()
private fun createLightProject(): ProjectEx {
(PersistentFS.getInstance() as PersistentFSImpl).cleanPersistedContents()
val projectFile = generateTemporaryPath("light_temp_shared_project${ProjectFileType.DOT_DEFAULT_EXTENSION}")
val projectPath = projectFile.systemIndependentPath
val buffer = ByteArrayOutputStream()
Throwable(projectPath, null).printStackTrace(PrintStream(buffer))
val project = PlatformTestCase.createProject(projectPath, "Light project: $buffer") as ProjectEx
Disposer.register(ApplicationManager.getApplication(), Disposable {
try {
disposeProject()
}
finally {
Files.deleteIfExists(projectFile)
}
})
(VirtualFilePointerManager.getInstance() as VirtualFilePointerManagerImpl).storePointers()
return project
}
private fun disposeProject() {
val project = sharedProject ?: return
sharedProject = null
sharedModule = null
Disposer.dispose(project)
}
}
override public fun after() {
if (projectOpened.compareAndSet(true, false)) {
sharedProject?.let { runInEdtAndWait { (ProjectManager.getInstance() as ProjectManagerImpl).forceCloseProject(it, false) } }
}
}
val projectIfOpened: ProjectEx?
get() = if (projectOpened.get()) sharedProject else null
val project: ProjectEx
get() {
var result = sharedProject
if (result == null) {
synchronized(IdeaTestApplication.getInstance()) {
result = sharedProject
if (result == null) {
result = createLightProject()
sharedProject = result
}
}
}
if (projectOpened.compareAndSet(false, true)) {
runInEdtAndWait { ProjectManagerEx.getInstanceEx().openTestProject(project) }
}
return result!!
}
val module: Module
get() {
var result = sharedModule
if (result == null) {
runInEdtAndWait {
LightProjectDescriptor().setUpProject(project, object : LightProjectDescriptor.SetupHandler {
override fun moduleCreated(module: Module) {
result = module
sharedModule = module
}
})
}
}
return result!!
}
}
/**
* rules: outer, middle, inner
* out:
* starting outer rule
* starting middle rule
* starting inner rule
* finished inner rule
* finished middle rule
* finished outer rule
*/
class RuleChain(vararg val rules: TestRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
var statement = base
for (i in (rules.size - 1) downTo 0) {
statement = rules[i].apply(statement, description)
}
return statement
}
}
private fun <T : Annotation> Description.getOwnOrClassAnnotation(annotationClass: Class<T>) = getAnnotation(annotationClass) ?: testClass?.getAnnotation(annotationClass)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class RunsInEdt
class EdtRule : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return if (description.getOwnOrClassAnnotation(RunsInEdt::class.java) == null) {
base
}
else {
statement { runInEdtAndWait { base.evaluate() } }
}
}
}
class InitInspectionRule : TestRule {
override fun apply(base: Statement, description: Description) = statement { runInInitMode { base.evaluate() } }
}
inline fun statement(crossinline runnable: () -> Unit) = object : Statement() {
override fun evaluate() {
runnable()
}
}
/**
* Do not optimise test load speed.
* @see IProjectStore.setOptimiseTestLoadSpeed
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class RunsInActiveStoreMode
class ActiveStoreRule(private val projectRule: ProjectRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return if (description.getOwnOrClassAnnotation(RunsInActiveStoreMode::class.java) == null) {
base
}
else {
statement { projectRule.project.runInLoadComponentStateMode { base.evaluate() } }
}
}
}
/**
* In test mode component state is not loaded. Project or module store will load component state if project/module file exists.
* So must be a strong reason to explicitly use this method.
*/
inline fun <T> Project.runInLoadComponentStateMode(task: () -> T): T {
val store = stateStore
val isModeDisabled = store.isOptimiseTestLoadSpeed
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = false
}
try {
return task()
}
finally {
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = true
}
}
}
fun createHeavyProject(path: String, useDefaultProjectSettings: Boolean = false) = ProjectManagerEx.getInstanceEx().newProject(null, path, useDefaultProjectSettings, false)!!
fun Project.use(task: (Project) -> Unit) {
val projectManager = ProjectManagerEx.getInstanceEx() as ProjectManagerImpl
try {
runInEdtAndWait { projectManager.openTestProject(this) }
task(this)
}
finally {
runInEdtAndWait { projectManager.forceCloseProject(this, true) }
}
}
class DisposeNonLightProjectsRule : ExternalResource() {
override fun after() {
val projectManager = if (ApplicationManager.getApplication().isDisposed) null else ProjectManager.getInstance() as ProjectManagerImpl
projectManager?.openProjects?.forEachGuaranteed {
if (!ProjectManagerImpl.isLight(it)) {
runInEdtAndWait { projectManager.forceCloseProject(it, true) }
}
}
}
}
class DisposeModulesRule(private val projectRule: ProjectRule) : ExternalResource() {
override fun after() {
projectRule.projectIfOpened?.let {
val moduleManager = ModuleManager.getInstance(it)
runInEdtAndWait {
moduleManager.modules.forEachGuaranteed {
if (!it.isDisposed && it !== sharedModule) {
moduleManager.disposeModule(it)
}
}
}
}
}
}
/**
* Only and only if "before" logic in case of exception doesn't require "after" logic - must be no side effects if "before" finished abnormally.
* So, should be one task per rule.
*/
class WrapRule(private val before: () -> () -> Unit) : TestRule {
override fun apply(base: Statement, description: Description) = statement {
val after = before()
try {
base.evaluate()
}
finally {
after()
}
}
}
fun createProjectAndUseInLoadComponentStateMode(tempDirManager: TemporaryDirectory, directoryBased: Boolean = false, task: (Project) -> Unit) {
createOrLoadProject(tempDirManager, task, directoryBased = directoryBased)
}
fun loadAndUseProject(tempDirManager: TemporaryDirectory, projectCreator: ((VirtualFile) -> String), task: (Project) -> Unit) {
createOrLoadProject(tempDirManager, task, projectCreator, false)
}
private fun createOrLoadProject(tempDirManager: TemporaryDirectory, task: (Project) -> Unit, projectCreator: ((VirtualFile) -> String)? = null, directoryBased: Boolean) {
runInEdtAndWait {
val filePath: String
if (projectCreator == null) {
filePath = tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}").systemIndependentPath
}
else {
filePath = runUndoTransparentWriteAction { projectCreator(tempDirManager.newVirtualDirectory()) }
}
val project = if (projectCreator == null) createHeavyProject(filePath, true) else ProjectManagerEx.getInstanceEx().loadProject(filePath)!!
project.runInLoadComponentStateMode {
project.use(task)
}
}
}
fun ComponentManager.saveStore() {
stateStore.save(SmartList())
} | platform/testFramework/src/com/intellij/testFramework/FixtureRule.kt | 2776949001 |
package com.lasthopesoftware.bluewater.client.connection.builder.GivenServerIsFoundViaLookup.AndTheUserNameIsAnEmptyString
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.builder.PassThroughBase64Encoder
import com.lasthopesoftware.bluewater.client.connection.builder.UrlScanner
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.LookupServers
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerInfo
import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory
import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.testing.TestConnections
import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
class WhenScanningForUrls {
companion object {
private var urlProvider: IUrlProvider? = null
@BeforeClass
@JvmStatic
fun before() {
val connectionTester = mockk<TestConnections>()
every { connectionTester.promiseIsConnectionPossible(any()) } returns false.toPromise()
every { connectionTester.promiseIsConnectionPossible(match { a ->
"http://1.2.3.4:143/MCWS/v1/" == a.urlProvider.baseUrl.toString() && a.urlProvider.authCode == null
}) } returns true.toPromise()
val serverLookup = mockk<LookupServers>()
every { serverLookup.promiseServerInformation(LibraryId(44)) } returns Promise(
ServerInfo(
143,
null,
"1.2.3.4", emptyList(), emptyList(),
null
)
)
val connectionSettingsLookup = mockk<LookupConnectionSettings>()
every { connectionSettingsLookup.lookupConnectionSettings(LibraryId(44)) } returns ConnectionSettings(accessCode = "gooPc", userName = "", password = "").toPromise()
val urlScanner = UrlScanner(
PassThroughBase64Encoder,
connectionTester,
serverLookup,
connectionSettingsLookup,
OkHttpFactory
)
urlProvider = urlScanner.promiseBuiltUrlProvider(LibraryId(44)).toFuture().get()
}
}
@Test
fun thenTheUrlProviderIsReturned() {
assertThat(urlProvider).isNotNull
}
@Test
fun thenTheBaseUrlIsCorrect() {
assertThat(urlProvider?.baseUrl.toString()).isEqualTo("http://1.2.3.4:143/MCWS/v1/")
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/builder/GivenServerIsFoundViaLookup/AndTheUserNameIsAnEmptyString/WhenScanningForUrls.kt | 2758782862 |
package com.linroid.vulkan.sample
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.linroid.vulkan.sample.R
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Example of a call to a native method
sample_text.text = stringFromJNI()
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
}
| vulkan/android_sample/app/src/main/java/com/linroid/vulkan/sample/MainActivity.kt | 1463593540 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.flipper.plugins.uidebugger.descriptors
import android.os.Build
import android.widget.TextView
import com.facebook.flipper.plugins.uidebugger.model.Color
import com.facebook.flipper.plugins.uidebugger.model.Inspectable
import com.facebook.flipper.plugins.uidebugger.model.InspectableObject
import com.facebook.flipper.plugins.uidebugger.model.InspectableValue
import com.facebook.flipper.plugins.uidebugger.model.MetadataId
object TextViewDescriptor : ChainedDescriptor<TextView>() {
private const val NAMESPACE = "TextView"
private var SectionId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, NAMESPACE)
private val TextAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "text")
private val TextSizeAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "textSize")
private val TextColorAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "textColor")
private val IsBoldAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "isBold")
private val IsItalicAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "isItalic")
private val WeightAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "weight")
private val TypefaceAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "typeface")
private val MinLinesAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "minLines")
private val MaxLinesAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "maxLines")
private val MinWidthAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "minWidth")
private val MaxWidthAttributeId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, "maxWidth")
override fun onGetName(node: TextView): String = node.javaClass.simpleName
override fun onGetData(
node: TextView,
attributeSections: MutableMap<MetadataId, InspectableObject>
) {
val props =
mutableMapOf<Int, Inspectable>(
TextAttributeId to InspectableValue.Text(node.text.toString()),
TextSizeAttributeId to InspectableValue.Number(node.textSize),
TextColorAttributeId to
InspectableValue.Color(Color.fromColor(node.textColors.defaultColor)))
val typeface = node.typeface
if (typeface != null) {
val typeFaceProp =
mutableMapOf<Int, InspectableValue>(
IsBoldAttributeId to InspectableValue.Boolean(typeface.isBold),
IsItalicAttributeId to InspectableValue.Boolean(typeface.isItalic),
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
typeFaceProp[WeightAttributeId] = InspectableValue.Number(typeface.weight)
}
props[TypefaceAttributeId] = InspectableObject(typeFaceProp)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
props[MinLinesAttributeId] = InspectableValue.Number(node.minLines)
props[MaxLinesAttributeId] = InspectableValue.Number(node.maxLines)
props[MinWidthAttributeId] = InspectableValue.Number(node.minWidth)
props[MaxWidthAttributeId] = InspectableValue.Number(node.maxWidth)
}
attributeSections[SectionId] = InspectableObject(props)
}
}
| android/src/main/java/com/facebook/flipper/plugins/uidebugger/descriptors/TextViewDescriptor.kt | 1265847701 |
package eu.scott.warehouse.lib
/**
* Created on 2018-07-27
*
* @author Andrew Berezovskyi ([email protected])
* @version $version-stub$
* @since 0.0.1
*/
object MqttTopics {
const val REGISTRATION_ANNOUNCE = "_scott/whc/registration/announce"
const val REGISTRATION_ACK = "_scott/whc/registration/ack"
const val WHC_PLANS = "_scott/whc/plans"
const val TWIN_SIM_REG_ANNOUNCE = "twins/registration/announce"
const val TWIN_SIM_REG_ACK = "twins/registration/handshake"
}
| lyo-services/lib-common/src/main/kotlin/eu/scott/warehouse/lib/MqttTopics.kt | 416578990 |
/*
* Copyright 2018 Andrei Heidelbacher <[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.
*/
@file:JvmName("Utils")
package org.chronolens.core.cli
import picocli.CommandLine
import picocli.CommandLine.ExecutionException
import picocli.CommandLine.HelpCommand
import picocli.CommandLine.RunLast
import picocli.CommandLine.defaultExceptionHandler
import java.util.ServiceLoader
import kotlin.system.exitProcess
/**
* Prints the given [message] to `stderr` and exits with status code `1`.
* code.
*
* Should be used to validate user input and initial state.
*/
public fun exit(message: String): Nothing {
System.err.println(message)
exitProcess(1)
}
/**
* Assembles all the provided subcommands, parses the given command-line [args]
* and runs the [mainCommand], exiting with status code `1` if any error occurs.
*
* A `help` subcommand is implicitly added.
*/
public fun run(mainCommand: MainCommand, vararg args: String) {
mainCommand.registerSubcommands(assembleSubcommands())
val cmd = CommandLine(mainCommand.command).apply {
addSubcommand("help", HelpCommand())
isCaseInsensitiveEnumValuesAllowed = true
}
val exceptionHandler = defaultExceptionHandler().andExit(1)
try {
cmd.parseWithHandlers(RunLast(), exceptionHandler, *args)
} catch (e: ExecutionException) {
System.err.println(e.message)
e.printStackTrace(System.err)
exitProcess(1)
}
}
/** Returns the list of provided subcommands. */
internal fun assembleSubcommands(): List<Subcommand> =
ServiceLoader.load(Subcommand::class.java)
.sortedBy(Subcommand::name)
internal fun String.paragraphs(): Array<String> {
val pars = arrayListOf<String>()
var par = StringBuilder()
var newPar = true
for (line in trimIndent().lines()) {
if (line.isBlank() && par.isNotBlank()) {
pars += par.toString()
par = StringBuilder()
newPar = true
} else if (line.isNotBlank()) {
if (!newPar) {
par.append(' ')
}
par.append(line)
newPar = false
}
}
if (par.isNotBlank()) {
pars += par.toString()
}
return pars.toTypedArray()
}
internal fun String.words(): List<String> {
val words = arrayListOf<String>()
var word = StringBuilder()
for (char in this.capitalize()) {
if (char.isUpperCase()) {
if (!word.isBlank()) {
words += word.toString()
word = StringBuilder()
}
word.append(char.toLowerCase())
} else {
word.append(char)
}
}
if (word.isNotBlank()) {
words += word.toString()
}
return words
}
internal fun getOptionName(propertyName: String): String =
propertyName.words().joinToString(separator = "-", prefix = "--")
| chronolens-core/src/main/kotlin/org/chronolens/core/cli/Utils.kt | 4109939398 |
package cc.aoeiuv020.panovel.util
import cc.aoeiuv020.gson.type
import cc.aoeiuv020.panovel.report.Reporter
/**
* Created by AoEiuV020 on 2018.05.24-12:22:17.
*/
inline fun <reified T> T?.notNullOrReport(): T =
notNullOrReport(type<T>().toString())
fun <T> T?.notNullOrReport(value: String): T =
Reporter.notNullOrReport(this, value)
| app/src/main/java/cc/aoeiuv020/panovel/util/ext.kt | 2177473636 |
package org.tasks.data
import androidx.room.*
import com.todoroo.astrid.data.Task
@Dao
abstract class TagDao {
@Query("UPDATE tags SET name = :name WHERE tag_uid = :tagUid")
abstract suspend fun rename(tagUid: String, name: String)
@Insert
abstract suspend fun insert(tag: Tag)
@Insert
abstract suspend fun insert(tags: Iterable<Tag>)
@Query("DELETE FROM tags WHERE task = :taskId AND tag_uid in (:tagUids)")
internal abstract suspend fun deleteTags(taskId: Long, tagUids: List<String>)
@Query("SELECT * FROM tags WHERE tag_uid = :tagUid")
abstract suspend fun getByTagUid(tagUid: String): List<Tag>
@Query("SELECT * FROM tags WHERE task = :taskId")
abstract suspend fun getTagsForTask(taskId: Long): List<Tag>
@Query("SELECT * FROM tags WHERE task = :taskId AND tag_uid = :tagUid")
abstract suspend fun getTagByTaskAndTagUid(taskId: Long, tagUid: String): Tag?
@Delete
abstract suspend fun delete(tags: List<Tag>)
@Transaction
open suspend fun applyTags(task: Task, tagDataDao: TagDataDao, current: List<TagData>) {
val taskId = task.id
val existing = HashSet(tagDataDao.getTagDataForTask(taskId))
val selected = HashSet<TagData>(current)
val added = selected subtract existing
val removed = existing subtract selected
deleteTags(taskId, removed.map { td -> td.remoteId!! })
insert(task, added)
}
suspend fun insert(task: Task, tags: Collection<TagData>) {
if (!tags.isEmpty()) {
insert(tags.map { Tag(task, it) })
}
}
} | app/src/main/java/org/tasks/data/TagDao.kt | 1182253820 |
package com.chibatching.kotpref.pref
import android.annotation.SuppressLint
import android.content.SharedPreferences
import com.chibatching.kotpref.KotprefModel
import com.chibatching.kotpref.execute
import kotlin.reflect.KProperty
/**
* Delegate long shared preferences property.
* @param default default long value
* @param key custom preferences key
* @param commitByDefault commit this property instead of apply
*/
public fun KotprefModel.longPref(
default: Long = 0L,
key: String? = null,
commitByDefault: Boolean = commitAllPropertiesByDefault
): AbstractPref<Long> = LongPref(default, key, commitByDefault)
/**
* Delegate long shared preferences property.
* @param default default long value
* @param key custom preferences key resource id
* @param commitByDefault commit this property instead of apply
*/
public fun KotprefModel.longPref(
default: Long = 0L,
key: Int,
commitByDefault: Boolean = commitAllPropertiesByDefault
): AbstractPref<Long> = longPref(default, context.getString(key), commitByDefault)
internal class LongPref(
val default: Long,
override val key: String?,
private val commitByDefault: Boolean
) : AbstractPref<Long>() {
override fun getFromPreference(property: KProperty<*>, preference: SharedPreferences): Long {
return preference.getLong(preferenceKey, default)
}
@SuppressLint("CommitPrefEdits")
override fun setToPreference(
property: KProperty<*>,
value: Long,
preference: SharedPreferences
) {
preference.edit().putLong(preferenceKey, value).execute(commitByDefault)
}
override fun setToEditor(
property: KProperty<*>,
value: Long,
editor: SharedPreferences.Editor
) {
editor.putLong(preferenceKey, value)
}
}
| kotpref/src/main/kotlin/com/chibatching/kotpref/pref/LongPref.kt | 3516729040 |
package net.nemerosa.ontrack.extension.av.config
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.graphql.support.ListRef
/**
* Subscription to an auto versioning event.
*
* @property scope List of events to listen to
* @property channel ID of the channel to listen to
* @property config JSON configuration for the subscription
*/
data class AutoVersioningNotification(
val channel: String,
val config: JsonNode,
@ListRef
val scope: List<AutoVersioningNotificationScope> = listOf(AutoVersioningNotificationScope.ALL),
) {
companion object {
/**
* Origin of the notifications which are set by the auto versioning
*/
const val ORIGIN = "auto-versioning"
}
}
| ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/config/AutoVersioningNotification.kt | 2943531333 |
package net.nemerosa.ontrack.extension.indicators.stats
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class IndicatorStatsTest {
@Test
fun checks() {
assertFailsWith<IllegalStateException> {
stats(
total = -1,
count = 0
)
}
assertFailsWith<IllegalStateException> {
stats(
total = 0,
count = -1
)
}
assertFailsWith<IllegalStateException> {
stats(
total = 1,
count = 2
)
}
}
@Test
fun percent() {
assertEquals(
0,
stats(
total = 0,
count = 0
).percent
)
assertEquals(
0,
stats(
total = 10,
count = 0
).percent
)
assertEquals(
20,
stats(
total = 10,
count = 2
).percent
)
assertEquals(
100,
stats(
total = 10,
count = 10
).percent
)
}
private fun stats(
total: Int,
count: Int
) = IndicatorStats(
total = total,
count = count,
min = null,
avg = null,
max = null,
minCount = 0,
maxCount = 0
)
} | ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/stats/IndicatorStatsTest.kt | 265629454 |
package net.nemerosa.ontrack.extension.license.remote.stripe
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component
@ConfigurationProperties(prefix = "ontrack.config.license.stripe")
@Component
class StripeLicenseConfigurationProperties {
/**
* API authentication token.
*/
var token: String? = null
/**
* Subscription ID
*/
var subscription: String? = null
} | ontrack-extension-license/src/main/java/net/nemerosa/ontrack/extension/license/remote/stripe/StripeLicenseConfigurationProperties.kt | 721896898 |
/*
* Copyright (c) 2015 - 2022
*
* Maximilian Hille <[email protected]>
* Juliane Lehmann <[email protected]>
*
* This file is part of Watch Later.
*
* Watch Later 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.
*
* Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lambdasoup.watchlater.test
import android.accounts.Account
import android.accounts.AccountManager
import android.accounts.AccountManagerFuture
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.content.pm.verify.domain.DomainVerificationManager
import android.content.pm.verify.domain.DomainVerificationUserState
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createEmptyComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
import androidx.test.espresso.intent.matcher.IntentMatchers.hasData
import androidx.test.espresso.intent.matcher.IntentMatchers.hasPackage
import com.lambdasoup.tea.testing.TeaIdlingResource
import com.lambdasoup.watchlater.R
import com.lambdasoup.watchlater.onNodeWithTextRes
import com.lambdasoup.watchlater.ui.add.AddActivity
import com.lambdasoup.watchlater.ui.launcher.LauncherActivity
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.cucumber.java.After
import io.cucumber.java.Before
import io.cucumber.java.en.Given
import io.cucumber.java.en.Then
import io.cucumber.java.en.When
import io.cucumber.junit.CucumberOptions
import io.cucumber.junit.WithJunitRule
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.hamcrest.Matchers.allOf
import org.junit.Rule
import java.util.concurrent.TimeUnit
@CucumberOptions(
features = ["features"],
strict = true,
name = [".*"],
)
@WithJunitRule
class CucumberTest {
@get:Rule
val rule = createEmptyComposeRule()
private var scenario: ActivityScenario<ComponentActivity>? = null
private val packageManager: PackageManager = com.lambdasoup.watchlater.packageManager
private val domainVerificationManager: DomainVerificationManager =
com.lambdasoup.watchlater.domainVerificationManager
private val accountManager = com.lambdasoup.watchlater.accountManager
private val sharedPreferences = com.lambdasoup.watchlater.sharedPreferences
private val server = MockWebServer()
private val idlingResource = TeaIdlingResource()
@Before
fun before() {
server.start(port = 8080)
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest) =
when (request.path) {
"/videos?part=snippet,contentDetails&maxResults=1&id=dGFSjKuJfrI" ->
MockResponse()
.setResponseCode(200)
.setBody(VIDEO_INFO_JSON)
else -> MockResponse()
.setResponseCode(404)
.setBody("unhandled path + ${request.path}")
}
}
Intents.init()
Intents.intending(hasAction(Intent.ACTION_VIEW))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, Intent()))
whenever(domainVerificationManager.getDomainVerificationUserState(any())).thenReturn(
mock()
)
rule.registerIdlingResource(idlingResource.composeIdlingResource)
}
@After
fun after() {
rule.unregisterIdlingResource(idlingResource.composeIdlingResource)
Intents.release()
server.shutdown()
}
@When("I open the Launcher")
fun openLauncher() {
val intent = Intent(
ApplicationProvider.getApplicationContext(),
LauncherActivity::class.java
)
scenario = ActivityScenario.launch(intent)
}
@When("click on the demo button")
fun clickDemoButton() {
rule.onNodeWithTextRes(R.string.launcher_example_button, ignoreCase = true)
.performClick()
}
@Given("Watch Later is not set as default")
fun watchLaterIsNotDefault() {
whenever(packageManager.resolveActivity(any(), eq(PackageManager.MATCH_DEFAULT_ONLY)))
.thenReturn(null)
}
@Given("Watch Later is set as default")
fun watchLaterIsDefault() {
val resolveInfo: ResolveInfo = ResolveInfo().apply {
activityInfo = ActivityInfo().apply {
name = "com.lambdasoup.watchlater.ui.add.AddActivity"
}
}
whenever(packageManager.resolveActivity(any(), eq(PackageManager.MATCH_DEFAULT_ONLY)))
.thenReturn(resolveInfo)
}
@Given("Watch Later is not missing any hostname verifications")
fun isNotMissingVerifications() {
val state: DomainVerificationUserState = mock()
whenever(state.hostToStateMap).thenReturn(
mapOf(
"test.domain.1" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
"test.domain.2" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
"test.domain.3" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
)
)
whenever(domainVerificationManager.getDomainVerificationUserState(any()))
.thenReturn(state)
}
@Given("Watch Later is missing some hostname verifications")
fun isMissingVerifications() {
val state: DomainVerificationUserState = mock()
whenever(state.hostToStateMap).thenReturn(
mapOf(
"test.domain.1" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
"test.domain.2" to DomainVerificationUserState.DOMAIN_STATE_NONE,
"test.domain.3" to DomainVerificationUserState.DOMAIN_STATE_VERIFIED,
)
)
whenever(domainVerificationManager.getDomainVerificationUserState(any()))
.thenReturn(state)
}
@Then("I see the Launcher")
fun launcherIsOpen() {
rule.onNodeWithTextRes(R.string.launcher_example_title)
.assertIsDisplayed()
}
@Then("I see the setup instructions")
fun setupInstructionsVisible() {
rule.onNodeWithTextRes(R.string.launcher_action_title)
.assertIsDisplayed()
}
@Then("I do not see the setup instructions")
fun setupInstructionsNotVisible() {
rule.onNodeWithTextRes(R.string.launcher_action_title)
.assertDoesNotExist()
}
@Then("the video is opened")
fun videoIsOpened() {
Intents.intended(allOf(hasData("https://www.youtube.com/watch?v=dGFSjKuJfrI")))
}
@Given("the Google account is set")
fun googleAccountSet() {
whenever(sharedPreferences.getString("pref_key_default_account_name", null))
.thenReturn("[email protected]")
val account = Account("[email protected]", "com.google")
whenever(accountManager.getAccountsByType("com.google"))
.thenReturn(
arrayOf(account)
)
whenever(
accountManager.getAuthToken(
account,
"oauth2:https://www.googleapis.com/auth/youtube",
null,
false,
null,
null
)
)
.thenReturn(object : AccountManagerFuture<Bundle> {
override fun cancel(p0: Boolean) = throw NotImplementedError()
override fun isCancelled() = throw NotImplementedError()
override fun isDone() = throw NotImplementedError()
override fun getResult() = Bundle().apply {
putString(AccountManager.KEY_AUTHTOKEN, "test-auth-token")
}
override fun getResult(p0: Long, p1: TimeUnit?) = throw NotImplementedError()
})
}
@Given("a playlist has been selected")
fun playlistSet() {
whenever(sharedPreferences.getString("playlist-id", null))
.thenReturn("test-playlist-id")
whenever(sharedPreferences.getString("playlist-title", null))
.thenReturn("Test playlist title")
}
@When("I open Watch Later via a YouTube URL")
fun watchLaterOpensFromUrl() {
val intent = Intent(
ApplicationProvider.getApplicationContext(),
AddActivity::class.java
)
intent.action = Intent.ACTION_VIEW
intent.data = Uri.parse("https://www.youtube.com/watch?v=dGFSjKuJfrI")
scenario = ActivityScenario.launch(intent)
}
@When("the user clicks on 'Watch now'")
fun userClicksWatchNow() {
rule.onNodeWithTextRes(R.string.action_watchnow, ignoreCase = true)
.performClick()
}
@Then("the YouTube app is opened with the video URL")
fun youtubeOpened() {
Intents.intended(
allOf(
hasData("https://www.youtube.com/watch?v=dGFSjKuJfrI"),
hasAction(Intent.ACTION_VIEW),
hasPackage("com.google.android.youtube"),
)
)
}
@Then("I see the video info")
fun videoInfoDisplayed() {
rule.onNodeWithText("Test video title")
.assertIsDisplayed()
}
companion object {
const val VIDEO_INFO_JSON = """
{
"items": [
{
"id": "dGFSjKuJfrI",
"snippet": {
"title": "Test video title",
"description": "Test video description",
"thumbnails": {
"medium": {
"url": "http://localhost:8080/test-thumbnail"
}
}
},
"contentDetails": {
"duration": "1m35s"
}
}
]
}
"""
}
}
| app/src/androidTest/java/com/lambdasoup/watchlater/test/CucumberTest.kt | 2964578873 |
package com.jraska.analytics
data class AnalyticsEvent(
val name: String,
val properties: Map<String, Any?>
)
| plugins/src/main/java/com/jraska/analytics/AnalyticsEvent.kt | 2227133160 |
package org.rust.lang.core.psi.ext
interface RsStructOrEnumItemElement : RsQualifiedNamedElement, RsTypeBearingItemElement, RsGenericDeclaration
| src/main/kotlin/org/rust/lang/core/psi/ext/RsStructOrEnumItemElement.kt | 127963000 |
package usbbot.config
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.newFixedThreadPoolContext
import org.apache.commons.collections4.CollectionUtils
import org.apache.commons.collections4.queue.CircularFifoQueue
import org.apache.commons.dbutils.ResultSetHandler
import usbbot.modules.music.Music
import usbbot.modules.music.MyData
import util.getLogger
import java.sql.Timestamp
import java.util.*
import kotlin.collections.ArrayList
data class DBMusicQueueEntry(val id: Int, val forGuild: Long, val youtubeId: String, val requetedBy: Long, val addedAt: Timestamp) {
fun getAudioTrack() : AudioTrack? {
var retTrack : AudioTrack? = null
Music.playerManager.loadItem(youtubeId, object : AudioLoadResultHandler {
override fun loadFailed(exception: FriendlyException) {
DBMusicQueue.logger.warn("This is awkward... there was a video in the DB that won't load: $youtubeId")
}
override fun trackLoaded(track: AudioTrack) {
retTrack = track
}
override fun noMatches() {
DBMusicQueue.logger.warn("This is awkward... there was a video in the DB that no longer exists: $youtubeId")
}
override fun playlistLoaded(playlist: AudioPlaylist) {
throw IllegalStateException("There should never be a playlist loaded from the database backend!")
}
}).get()
retTrack?.userData = MyData(requetedBy, id, forGuild, youtubeId)
return retTrack
}
}
fun getSongsFromDB(guildID: Long, limit: Int, offset: Int = 0) : List<DBMusicQueueEntry> =
DatabaseConnection.queryRunner
.query("SELECT * FROM music_queue WHERE forGuild = ? ORDER BY addedAt ASC LIMIT ? OFFSET ?",
DBMusicQueue.songDBEntryCreator,
guildID, limit, offset)
fun getMusicQueueForGuild(guildID: Long) : DBMusicQueue {
val result = getSongsFromDB(guildID, 10)
val queue = CircularFifoQueue<AudioTrack>(10)
result.forEach {
val tmp = it.getAudioTrack()
if (tmp != null) {
queue.add(tmp)
} else {
DatabaseConnection.queryRunner.update("DELETE FROM music_queue WHERE id = ?", it.id)
}
}
val rsh = ResultSetHandler {
if (it.next()) it.getInt(1)
else 0
}
val size = DatabaseConnection.queryRunner.query("SELECT COUNT(*) FROM music_queue WHERE forGuild = ?",
rsh,
guildID)
return DBMusicQueue(guildID, queue, size)
}
class DBMusicQueue(val guildID: Long, val queue : Queue<AudioTrack>, var size: Int) {
companion object {
val logger = DBMusicQueue.getLogger()
val songDBEntryCreator = ResultSetHandler <List<DBMusicQueueEntry>> {
val output = mutableListOf<DBMusicQueueEntry>()
while (it.next()) {
output.add(DBMusicQueueEntry(
it.getInt("id"),
it.getLong("forGuild"),
it.getString("youtubeId"),
it.getLong("requestedBy"),
it.getTimestamp("addedAt")))
}
output
}
val musicQueueWorker = newFixedThreadPoolContext(2, "Music Queue Worker")
}
fun removeFromDB(track: AudioTrack) = launch(musicQueueWorker) {
DatabaseConnection.queryRunner.update("DELETE FROM music_queue WHERE id = ?", (track.userData as MyData).id)
}
fun add(track: AudioTrack) {
val data = (track.userData as MyData)
DatabaseConnection.queryRunner
.update("INSERT INTO music_queue (forGuild, youtubeId, requestedBy) VALUES (?, ?, ?)",
data.forGuild, data.youtubeId, data.requestedBy)
synchronized(size) {
if (size < 10) {
synchronized(queue) {
val musicQueueEntry = DatabaseConnection.queryRunner
.query("SELECT * FROM music_queue WHERE forGuild = ? AND youtubeId = ? AND requestedBy = ?",
DBMusicQueue.songDBEntryCreator,
data.forGuild, data.youtubeId, data.requestedBy)
(track.userData as MyData).id = musicQueueEntry.first().id
queue.add(track)
}
}
size++
}
}
fun hasNext() : Boolean = queue.isNotEmpty()
fun getNext() : AudioTrack? {
val out = synchronized(queue) {
queue.poll()
}
removeFromDB(out)
if (queue.size < 5) {
launch(musicQueueWorker) {
val size = synchronized(queue) {
queue.size
}
val songs = getSongsFromDB(guildID, 10 - size, size)
songs.forEach {
val audioTrack = it.getAudioTrack()
if (audioTrack != null) {
synchronized(queue) {
if (!queue.contains(audioTrack)) {
queue.add(audioTrack)
}
}
}
}
}
}
synchronized(size) {
size--
}
return out
}
} | src/main/kotlin/usbbot/config/DBMusicQueue.kt | 1500778621 |
package graphql.language
import java.util.ArrayList
class InterfaceTypeDefinition(override val name: String) : AbstractNode(), TypeDefinition {
val fieldDefinitions: MutableList<FieldDefinition> = ArrayList()
val directives: MutableList<Directive> = ArrayList()
override val children: List<Node>
get() {
val result = ArrayList<Node>()
result.addAll(fieldDefinitions)
result.addAll(directives)
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as InterfaceTypeDefinition
if (name != that.name) {
return false
}
return true
}
override fun toString(): String {
return "InterfaceTypeDefinition{" +
"name='" + name + '\'' +
", fieldDefinitions=" + fieldDefinitions +
", directives=" + directives +
'}'
}
}
| src/main/kotlin/graphql/language/InterfaceTypeDefinition.kt | 3468083923 |
package com.robyn.dayplus2.myUtils
import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.SoundPool
import com.robyn.dayplus2.R
//
//fun playSound(context: Context) {
// val soundPool = SoundPool(5, AudioManager.STREAM_MUSIC, 0)
//
// val soundId = soundPool.load(context, R.raw.noti, 1)
//
// soundPool.play(soundId, 1f, 1f, 0, 2, 1f)
//
// val mPlayer = MediaPlayer.create(context, R.raw.noti)
// mPlayer.start()
//} | app/src/main/java/com/robyn/dayplus2/myUtils/SoundUtils.kt | 424059180 |
package org.istbd.IST_Syllabus.db
import androidx.room.*
@Dao
abstract class CourseDao {
@Update
abstract suspend fun update(courseEntity: CourseEntity)
@Query("SELECT * FROM course")
abstract suspend fun getAll(): List<CourseEntity>
@Query("SELECT * FROM course WHERE department = :department order by major")
abstract suspend fun getAllByDepartment(department: String): List<CourseEntity>
} | app/src/main/java/org/istbd/IST_Syllabus/db/CourseDao.kt | 2115166917 |
package com.esorokin.lantector.presentation.view
import com.arellomobile.mvp.viewstate.strategy.OneExecutionStateStrategy
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType
import com.esorokin.lantector.presentation.navigation.AppScreen
@StateStrategyType(OneExecutionStateStrategy::class)
interface MainView : BaseView {
fun openDrawer()
fun closeDrawer()
companion object TabScreens {
val DETECT_LANGUAGE_SCREEN_NAME: String = AppScreen.DetectLanguage::class.java.simpleName
val HISTORY_SCREEN_NAME: String = AppScreen.History::class.java.simpleName
}
} | app/src/main/java/com/esorokin/lantector/presentation/view/MainView.kt | 3519408046 |
package com.soywiz.korfl.as3swf
object ActionValueType {
val STRING: Int = 0
val FLOAT: Int = 1
val NIL: Int = 2
val UNDEFINED: Int = 3
val REGISTER: Int = 4
val BOOLEAN: Int = 5
val DOUBLE: Int = 6
val INTEGER: Int = 7
val CONSTANT_8: Int = 8
val CONSTANT_16: Int = 9
fun toString(bitmapFormat: Int) = when (bitmapFormat) {
STRING -> "string"
FLOAT -> "float"
NIL -> "null"
UNDEFINED -> "undefined"
REGISTER -> "register"
BOOLEAN -> "boolean"
DOUBLE -> "double"
INTEGER -> "integer"
CONSTANT_8 -> "constant8"
CONSTANT_16 -> "constant16"
else -> "unknown"
}
}
enum class BitmapFormat(val id: Int) {
BIT_8(3), BIT_15(4), BIT_24_32(5), UNKNOWN(-1);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: UNKNOWN
}
}
object BitmapType {
const val JPEG = 1
const val GIF89A = 2
const val PNG = 3
fun toString(bitmapFormat: Int): String = when (bitmapFormat) {
JPEG -> "JPEG"
GIF89A -> "GIF89a"
PNG -> "PNG"
else -> "unknown"
}
}
object BlendMode {
const val NORMAL_0 = 0
const val NORMAL_1 = 1
const val LAYER = 2
const val MULTIPLY = 3
const val SCREEN = 4
const val LIGHTEN = 5
const val DARKEN = 6
const val DIFFERENCE = 7
const val ADD = 8
const val SUBTRACT = 9
const val INVERT = 10
const val ALPHA = 11
const val ERASE = 12
const val OVERLAY = 13
const val HARDLIGHT = 14
fun toString(blendMode: Int): String = when (blendMode) {
NORMAL_0, NORMAL_1 -> "normal"
LAYER -> "layer"
MULTIPLY -> "multiply"
SCREEN -> "screen"
LIGHTEN -> "lighten"
DARKEN -> "darken"
DIFFERENCE -> "difference"
ADD -> "add"
SUBTRACT -> "subtract"
INVERT -> "invert"
ALPHA -> "alpha"
ERASE -> "erase"
OVERLAY -> "overlay"
HARDLIGHT -> "hardlight"
else -> "unknown"
}
}
object CSMTableHint {
const val THIN = 0
const val MEDIUM = 1
const val THICK = 2
fun toString(csmTableHint: Int): String = when (csmTableHint) {
THIN -> "thin"
MEDIUM -> "medium"
THICK -> "thick"
else -> "unknown"
}
}
enum class GradientInterpolationMode(val id: Int) {
NORMAL(0), LINEAR(1);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: NORMAL
}
}
enum class GradientSpreadMode(val id: Int) {
PAD(0), REFLECT(1), REPEAT(2);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: PAD
}
}
enum class ScaleMode(val id: Int) {
NONE(0), HORIZONTAL(1), VERTICAL(2), NORMAL(3);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: NORMAL
}
}
enum class LineCapsStyle(val id: Int) {
ROUND(0), NO(1), SQUARE(2);
companion object {
val BY_ID = values().map { it.id to it }.toMap()
operator fun get(index: Int) = BY_ID[index] ?: LineCapsStyle.ROUND
}
}
object LineJointStyle {
const val ROUND = 0
const val BEVEL = 1
const val MITER = 2
fun toString(lineJointStyle: Int) = when (lineJointStyle) {
ROUND -> "round"
BEVEL -> "bevel"
MITER -> "miter"
else -> "null"
}
}
object SoundCompression {
const val UNCOMPRESSED_NATIVE_ENDIAN = 0
const val ADPCM = 1
const val MP3 = 2
const val UNCOMPRESSED_LITTLE_ENDIAN = 3
const val NELLYMOSER_16_KHZ = 4
const val NELLYMOSER_8_KHZ = 5
const val NELLYMOSER = 6
const val SPEEX = 11
fun toString(soundCompression: Int): String {
return when (soundCompression) {
UNCOMPRESSED_NATIVE_ENDIAN -> "Uncompressed Native Endian"
ADPCM -> "ADPCM"
MP3 -> "MP3"
UNCOMPRESSED_LITTLE_ENDIAN -> "Uncompressed Little Endian"
NELLYMOSER_16_KHZ -> "Nellymoser 16kHz"
NELLYMOSER_8_KHZ -> "Nellymoser 8kHz"
NELLYMOSER -> "Nellymoser"
SPEEX -> "Speex"
else -> return "unknown"
}
}
}
object SoundRate {
const val KHZ_5 = 0
const val KHZ_11 = 1
const val KHZ_22 = 2
const val KHZ_44 = 3
fun toString(soundRate: Int): String {
return when (soundRate) {
KHZ_5 -> "5.5kHz"
KHZ_11 -> "11kHz"
KHZ_22 -> "22kHz"
KHZ_44 -> "44kHz"
else -> "unknown"
}
}
}
object SoundSize {
const val BIT_8 = 0
const val BIT_16 = 1
fun toString(soundSize: Int): String {
return when (soundSize) {
BIT_8 -> "8bit"
BIT_16 -> "16bit"
else -> "unknown"
}
}
}
object SoundType {
const val MONO = 0
const val STEREO = 1
fun toString(soundType: Int): String {
return when (soundType) {
MONO -> "mono"
STEREO -> "stereo"
else -> "unknown"
}
}
}
object VideoCodecID {
const val H263 = 2
const val SCREEN = 3
const val VP6 = 4
const val VP6ALPHA = 5
const val SCREENV2 = 6
fun toString(codecId: Int): String {
return when (codecId) {
H263 -> "H.263"
SCREEN -> "Screen Video"
VP6 -> "VP6"
VP6ALPHA -> "VP6 With Alpha"
SCREENV2 -> "Screen Video V2"
else -> "unknown"
}
}
}
object VideoDeblockingType {
const val VIDEOPACKET = 0
const val OFF = 1
const val LEVEL1 = 2
const val LEVEL2 = 3
const val LEVEL3 = 4
const val LEVEL4 = 5
fun toString(deblockingType: Int): String {
return when (deblockingType) {
VIDEOPACKET -> "videopacket"
OFF -> "off"
LEVEL1 -> "level 1"
LEVEL2 -> "level 2"
LEVEL3 -> "level 3"
LEVEL4 -> "level 4"
else -> "unknown"
}
}
}
| korge-swf/src/commonMain/kotlin/com/soywiz/korfl/as3swf/consts.kt | 3020278582 |
package com.example.sqldelight.hockey.data
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
import com.example.sqldelight.hockey.HockeyDb
import kotlin.native.concurrent.AtomicReference
import kotlin.native.concurrent.freeze
object Db {
private val driverRef = AtomicReference<SqlDriver?>(null)
private val dbRef = AtomicReference<HockeyDb?>(null)
internal fun dbSetup(driver: SqlDriver) {
val db = createQueryWrapper(driver)
driverRef.value = driver.freeze()
dbRef.value = db.freeze()
}
internal fun dbClear() {
driverRef.value!!.close()
dbRef.value = null
driverRef.value = null
}
// Called from Swift
@Suppress("unused")
fun defaultDriver() {
Db.dbSetup(NativeSqliteDriver(Schema, "sampledb"))
}
val instance: HockeyDb
get() = dbRef.value!!
}
| sample/common/src/iosMain/kotlin/com/example/sqldelight/hockey/data/Db.kt | 1994051148 |
package org.jetbrains.protocolReader
private val BASE_VALUE_PREFIX = "baseMessage"
internal class ExistingSubtypeAspect(private val jsonSuperClass: TypeRef<*>) {
private var subtypeCaster: SubtypeCaster? = null
fun setSubtypeCaster(subtypeCaster: SubtypeCaster) {
this.subtypeCaster = subtypeCaster
}
fun writeGetSuperMethodJava(out: TextOutput) {
out.newLine().append("override fun getBase() = ").append(BASE_VALUE_PREFIX)
}
fun writeSuperFieldJava(out: TextOutput) {
out.append(", private val ").append(BASE_VALUE_PREFIX).append(": ").append(jsonSuperClass.type!!.typeClass.canonicalName)
}
fun writeParseMethod(scope: ClassScope, out: TextOutput) {
out.newLine().append("companion object").block {
out.append("fun parse").append('(').append(JSON_READER_PARAMETER_DEF).append(", name: String?").append(") = ")
jsonSuperClass.type!!.writeInstantiateCode(scope, out)
out.append('(').append(READER_NAME).append(", name)").append('.')
subtypeCaster!!.writeJava(out)
}
out.newLine()
}
fun writeInstantiateCode(className: String, out: TextOutput) {
out.append(className).append(".parse")
}
}
| platform/script-debugger/protocol/protocol-reader/src/ExistingSubtypeAspect.kt | 370117691 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.