content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* KOTLIN LEARN
*
* MIT License (MIT)
* Copyright (c) 2015-2020 Alessio Saltarin
*
*/
package net.littlelite.kotlinlearn
/**
* A data class is a short-hand for a class that holds
* just data. It automatically gets:
* - equals
* - hashCode
* - toString
* - copy
* - componentN
*/
data class UserDataClass(val name: String,
val surname: String,
val age: Int)
| src/main/kotlin/UserDataClass.kt | 2331234011 |
package chat.rocket.android.suggestions.ui
import android.content.Context
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.view.WindowManager
import androidx.recyclerview.widget.RecyclerView
import chat.rocket.android.suggestions.R
internal class PopupRecyclerView : RecyclerView {
private var displayWidth: Int = 0
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
context,
attrs,
defStyle
) {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val size = DisplayMetrics()
display.getMetrics(size)
val screenWidth = size.widthPixels
displayWidth = screenWidth
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
val hSpec = MeasureSpec.makeMeasureSpec(
resources.getDimensionPixelSize(
R.dimen.popup_max_height
), MeasureSpec.AT_MOST
)
val wSpec = MeasureSpec.makeMeasureSpec(displayWidth, MeasureSpec.EXACTLY)
super.onMeasure(wSpec, hSpec)
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l + 40, t, r - 40, b)
}
}
| suggestions/src/main/java/chat/rocket/android/suggestions/ui/PopupRecyclerView.kt | 115078328 |
package com.bubelov.coins.model
import java.time.LocalDateTime
data class User(
val id: String,
val email: String,
val emailConfirmed: Boolean,
val firstName: String,
val lastName: String,
val avatarUrl: String,
val createdAt: LocalDateTime,
val updatedAt: LocalDateTime
) | app/src/main/java/com/bubelov/coins/model/User.kt | 2743709790 |
package permissions.dispatcher.processor.exception
import permissions.dispatcher.processor.RuntimePermissionsElement
public class NoAnnotatedMethodsException(rpe: RuntimePermissionsElement, type: Class<*>): RuntimeException("Annotated class '${rpe.inputClassName}' doesn't have any method annotated with '@${type.simpleName}'") {
} | PermissionsDispatcher-master/processor/src/main/kotlin/permissions/dispatcher/processor/exception/NoAnnotatedMethodsException.kt | 41200441 |
/*
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kotlintest.provided
import com.hotels.styx.support.TestResultReporter
import io.kotlintest.AbstractProjectConfig
import io.kotlintest.extensions.TestListener
class ProjectConfig: AbstractProjectConfig() {
override fun listeners(): List<TestListener> = listOf(TestResultReporter)
}
| system-tests/ft-suite/src/test/kotlin/io/kotlintest/provided/ProjectConfig.kt | 3291289808 |
/*
* Copyright (c) 2018. Faruk Toptaş
*
* 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 me.toptas.fancyshowcase
/**
* Shape of animated focus
*/
enum class FocusShape {
CIRCLE,
ROUNDED_RECTANGLE
}
| fancyshowcaseview/src/main/java/me/toptas/fancyshowcase/FocusShape.kt | 3968957590 |
package com.github.premnirmal.ticker.base
import android.graphics.Color
import android.os.Build
import android.view.View
import androidx.core.content.ContextCompat
import androidx.viewbinding.ViewBinding
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.premnirmal.ticker.model.HistoryProvider.Range
import com.github.premnirmal.ticker.network.data.DataPoint
import com.github.premnirmal.ticker.network.data.Quote
import com.github.premnirmal.ticker.ui.DateAxisFormatter
import com.github.premnirmal.ticker.ui.HourAxisFormatter
import com.github.premnirmal.ticker.ui.MultilineXAxisRenderer
import com.github.premnirmal.ticker.ui.TextMarkerView
import com.github.premnirmal.ticker.ui.ValueAxisFormatter
import com.github.premnirmal.tickerwidget.R
abstract class BaseGraphActivity<T : ViewBinding> : BaseActivity<T>() {
protected var dataPoints: List<DataPoint>? = null
protected abstract var range: Range
protected fun setupGraphView() {
val graphView: LineChart = findViewById(R.id.graphView)
graphView.isDoubleTapToZoomEnabled = false
graphView.axisLeft.setDrawGridLines(false)
graphView.axisLeft.setDrawAxisLine(false)
graphView.axisLeft.isEnabled = false
graphView.axisRight.setDrawGridLines(false)
graphView.axisRight.setDrawAxisLine(true)
graphView.axisRight.isEnabled = true
graphView.xAxis.setDrawGridLines(false)
graphView.setXAxisRenderer(
MultilineXAxisRenderer(
graphView.viewPortHandler, graphView.xAxis,
graphView.getTransformer(YAxis.AxisDependency.RIGHT)
)
)
graphView.extraBottomOffset = resources.getDimension(R.dimen.graph_bottom_offset)
graphView.legend.isEnabled = false
graphView.description = null
val colorAccent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
ContextCompat.getColor(this, android.R.color.system_accent1_600)
} else {
ContextCompat.getColor(this, R.color.accent_fallback)
}
graphView.setNoDataText("")
graphView.setNoDataTextColor(colorAccent)
graphView.marker = TextMarkerView(this)
}
protected fun loadGraph(ticker: String, quote: Quote) {
val graphView: LineChart = findViewById(R.id.graphView)
if (dataPoints == null || dataPoints!!.isEmpty()) {
onNoGraphData(graphView)
graphView.setNoDataText(getString(R.string.no_data))
graphView.invalidate()
return
}
graphView.setNoDataText("")
graphView.lineData?.clearValues()
val series = LineDataSet(dataPoints, ticker)
series.setDrawHorizontalHighlightIndicator(false)
series.setDrawValues(false)
val colorAccent = if (quote.changeInPercent >= 0) {
ContextCompat.getColor(this, R.color.positive_green_dark)
} else {
ContextCompat.getColor(this, R.color.negative_red)
}
series.setDrawFilled(true)
series.color = colorAccent
series.fillColor = colorAccent
series.fillAlpha = 150
series.setDrawCircles(true)
series.mode = LineDataSet.Mode.CUBIC_BEZIER
series.cubicIntensity = 0.07f
series.lineWidth = 2f
series.setDrawCircles(false)
series.highLightColor = Color.GRAY
val lineData = LineData(series)
graphView.data = lineData
val xAxis: XAxis = graphView.xAxis
val yAxis: YAxis = graphView.axisRight
if (range == Range.ONE_DAY) {
xAxis.valueFormatter = HourAxisFormatter()
} else {
xAxis.valueFormatter = DateAxisFormatter()
}
yAxis.valueFormatter = ValueAxisFormatter()
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.textSize = 10f
yAxis.textSize = 10f
xAxis.textColor = Color.GRAY
yAxis.textColor = Color.GRAY
xAxis.setLabelCount(5, true)
yAxis.setLabelCount(5, true)
yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
xAxis.setDrawAxisLine(true)
yAxis.setDrawAxisLine(true)
xAxis.setDrawGridLines(false)
yAxis.setDrawGridLines(false)
graphView.invalidate()
onGraphDataAdded(graphView)
}
/**
* xml OnClick
* @param v
*/
fun updateRange(v: View) {
when (v.id) {
R.id.one_day -> range = Range.ONE_DAY
R.id.two_weeks -> range = Range.TWO_WEEKS
R.id.one_month -> range = Range.ONE_MONTH
R.id.three_month -> range = Range.THREE_MONTH
R.id.one_year -> range = Range.ONE_YEAR
R.id.five_years -> range = Range.FIVE_YEARS
R.id.max -> range = Range.MAX
}
fetchGraphData()
}
protected abstract fun fetchGraphData()
protected abstract fun onGraphDataAdded(graphView: LineChart)
protected abstract fun onNoGraphData(graphView: LineChart)
} | app/src/main/kotlin/com/github/premnirmal/ticker/base/BaseGraphActivity.kt | 3821845236 |
/*
* Copyright 2017 Alexey Shtanko
*
* 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.shtanko.picasagallery.extensions
import io.shtanko.picasagallery.data.entity.album.AlbumType
import io.shtanko.picasagallery.data.entity.internal.ContentType
import io.shtanko.picasagallery.data.entity.photo.PhotoType
typealias AlbumsList = List<AlbumType>
typealias PhotosList = List<PhotoType>
typealias ContentList = List<ContentType>
| app/src/main/kotlin/io/shtanko/picasagallery/extensions/Aliases.kt | 4162575015 |
/*
* Copyright 2020 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.samples.apps.sunflower.plantdetail
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ShareCompat
import androidx.core.widget.NestedScrollView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.google.samples.apps.sunflower.R
import com.google.samples.apps.sunflower.data.Plant
import com.google.samples.apps.sunflower.databinding.FragmentPlantDetailBinding
import com.google.samples.apps.sunflower.utilities.InjectorUtils
import com.google.samples.apps.sunflower.viewmodels.PlantDetailViewModel
/**
* A fragment representing a single Plant detail screen.
*/
class PlantDetailFragment : Fragment() {
private val args: PlantDetailFragmentArgs by navArgs()
private val plantDetailViewModel: PlantDetailViewModel by viewModels {
InjectorUtils.providePlantDetailViewModelFactory(requireActivity(), args.plantId)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(
inflater, R.layout.fragment_plant_detail, container, false
).apply {
viewModel = plantDetailViewModel
lifecycleOwner = viewLifecycleOwner
callback = object : Callback {
override fun add(plant: Plant?) {
plant?.let {
hideAppBarFab(fab)
plantDetailViewModel.addPlantToGarden()
Snackbar.make(root, R.string.added_plant_to_garden, Snackbar.LENGTH_LONG)
.show()
}
}
}
var isToolbarShown = false
// scroll change listener begins at Y = 0 when image is fully collapsed
plantDetailScrollview.setOnScrollChangeListener(
NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
// User scrolled past image to height of toolbar and the title text is
// underneath the toolbar, so the toolbar should be shown.
val shouldShowToolbar = scrollY > toolbar.height
// The new state of the toolbar differs from the previous state; update
// appbar and toolbar attributes.
if (isToolbarShown != shouldShowToolbar) {
isToolbarShown = shouldShowToolbar
// Use shadow animator to add elevation if toolbar is shown
appbar.isActivated = shouldShowToolbar
// Show the plant name if toolbar is shown
toolbarLayout.isTitleEnabled = shouldShowToolbar
}
}
)
toolbar.setNavigationOnClickListener { view ->
view.findNavController().navigateUp()
}
toolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_share -> {
createShareIntent()
true
}
else -> false
}
}
}
setHasOptionsMenu(true)
return binding.root
}
// Helper function for calling a share functionality.
// Should be used when user presses a share button/menu item.
@Suppress("DEPRECATION")
private fun createShareIntent() {
val shareText = plantDetailViewModel.plant.value.let { plant ->
if (plant == null) {
""
} else {
getString(R.string.share_text_plant, plant.name)
}
}
val shareIntent = ShareCompat.IntentBuilder.from(requireActivity())
.setText(shareText)
.setType("text/plain")
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
startActivity(shareIntent)
}
// FloatingActionButtons anchored to AppBarLayouts have their visibility controlled by the scroll position.
// We want to turn this behavior off to hide the FAB when it is clicked.
//
// This is adapted from Chris Banes' Stack Overflow answer: https://stackoverflow.com/a/41442923
private fun hideAppBarFab(fab: FloatingActionButton) {
val params = fab.layoutParams as CoordinatorLayout.LayoutParams
val behavior = params.behavior as FloatingActionButton.Behavior
behavior.isAutoHideEnabled = false
fab.hide()
}
interface Callback {
fun add(plant: Plant?)
}
}
| MigrationCodelab/app/src/main/java/com/google/samples/apps/sunflower/plantdetail/PlantDetailFragment.kt | 3487506523 |
package i_introduction._7_Nullable_Types
import org.junit.Assert.assertEquals
import org.junit.Test
class _07_Nullable_Types {
fun testSendMessageToClient(
client: Client?,
message: String?,
email: String? = null,
shouldBeInvoked: Boolean = false
) {
var invoked = false
sendMessageToClient(client, message, object : Mailer {
override fun sendMessage(actualEmail: String, actualMessage: String) {
invoked = true
assertEquals("The message is not as expected:",
message, actualMessage)
assertEquals("The email is not as expected:",
email, actualEmail)
}
})
assertEquals("The function 'sendMessage' should${if (shouldBeInvoked) "" else "n't"} be invoked",
shouldBeInvoked, invoked)
}
@Test fun everythingIsOk() {
testSendMessageToClient(Client(PersonalInfo("[email protected]")),
"Hi Bob! We have an awesome proposition for you...",
"[email protected]",
true)
}
@Test fun noMessage() {
testSendMessageToClient(Client(PersonalInfo("[email protected]")), null)
}
@Test fun noEmail() {
testSendMessageToClient(Client(PersonalInfo(null)), "Hi Bob! We have an awesome proposition for you...")
}
@Test fun noPersonalInfo() {
testSendMessageToClient(Client(null), "Hi Bob! We have an awesome proposition for you...")
}
@Test fun noClient() {
testSendMessageToClient(null, "Hi Bob! We have an awesome proposition for you...")
}
} | test/i_introduction/_7_Nullable_Types/_07_Nullable_Types.kt | 1952287532 |
package com.beust.kobalt.api
/**
* Base interface for affinity interfaces.
*/
interface IAffinity {
companion object {
/**
* The recommended default affinity if your plug-in can run this project. Use a higher
* number if you expect to compete against other actors and you'd like to win over them.
*/
const val DEFAULT_POSITIVE_AFFINITY = 100
}
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/api/IAffinity.kt | 1438042360 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.tabs
import javafx.application.Platform
import javafx.scene.Node
import javafx.scene.canvas.Canvas
import javafx.scene.input.MouseEvent
import javafx.scene.paint.Color
import javafx.scene.shape.StrokeLineCap
import org.joml.Matrix3x2d
import org.joml.Vector2d
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.AbstractParameter
import uk.co.nickthecoder.paratask.parameters.DoubleParameter
import uk.co.nickthecoder.paratask.parameters.fields.ParameterField
import uk.co.nickthecoder.tickle.Pose
import uk.co.nickthecoder.tickle.editor.util.AngleParameter
import uk.co.nickthecoder.tickle.editor.util.Vector2dParameter
import uk.co.nickthecoder.tickle.editor.util.cachedImage
import uk.co.nickthecoder.tickle.physics.BoxDef
import uk.co.nickthecoder.tickle.physics.CircleDef
import uk.co.nickthecoder.tickle.physics.PolygonDef
import uk.co.nickthecoder.tickle.physics.ShapeDef
class ShapeEditorParameter(name: String, val pose: Pose, val fixtureParameter: CostumeTab.PhysicsTask.FixtureParameter)
: AbstractParameter(name, label = "", description = "") {
override fun errorMessage(): String? = null
override fun copy() = ShapeEditorParameter(name, pose, fixtureParameter)
override fun isStretchy(): Boolean = true
private var field = ShapeEditorField(this)
override fun createField(): ParameterField {
field.build()
return field
}
fun update(shapedDef: ShapeDef?) {
field.update(shapedDef)
}
}
class ShapeEditorTask(pose: Pose, val fixtureParameter: CostumeTab.PhysicsTask.FixtureParameter)
: AbstractTask() {
val shapeEditorP = ShapeEditorParameter("shapeEditor", pose, fixtureParameter)
override val taskD = TaskDescription("editShape")
.addParameters(shapeEditorP)
override fun run() {}
}
class ShapeEditorField(shapeEditorParameter: ShapeEditorParameter) : ParameterField(shapeEditorParameter) {
val fixtureParameter = shapeEditorParameter.fixtureParameter
val pose = shapeEditorParameter.pose
val poseWidth = pose.rect.width
val poseHeight = pose.rect.height
val margin = 10.0
val borderColor = Color(0.0, 0.0, 0.0, 0.3)
val shapeColor = Color(1.0, 0.0, 0.0, 1.0)
val handleColor = Color(0.0, 0.0, 1.0, 1.0)
val currentHandleColor = Color(1.0, 1.0, 1.0, 1.0)
val canvas = Canvas(poseWidth.toDouble() + margin * 2, poseHeight.toDouble() + margin * 2)
val handles = mutableListOf<Handle>()
init {
//println("Creating SEP")
with(canvas) {
graphicsContext2D.transform(1.0, 0.0, 0.0, -1.0, 0.0, canvas.height)
addEventHandler(MouseEvent.MOUSE_PRESSED) { onMousePressed(it) }
addEventHandler(MouseEvent.MOUSE_MOVED) { onMouseMoved(it) }
addEventHandler(MouseEvent.MOUSE_DRAGGED) { onMouseDragged(it) }
addEventHandler(MouseEvent.MOUSE_RELEASED) { dragging = false }
}
}
override fun createControl(): Node {
return canvas
}
var dirty = false
set(v) {
if (v && !field) {
Platform.runLater {
redraw()
}
}
field = v
}
var currentHandle: Handle? = null
set(v) {
if (field != v) {
field = v
dirty = true
}
}
var dragging = false
var currentShapedDef: ShapeDef? = null
fun closestHandle(event: MouseEvent): Handle? {
val offsetX = event.x - margin - pose.offsetX
val offsetY = canvas.height - margin - event.y - pose.offsetY
var result: Handle? = null
var minDist = Double.MAX_VALUE
handles.forEach { handle ->
val position = handle.position()
val dx = Math.abs(position.x - offsetX)
val dy = Math.abs(position.y - offsetY)
if (dx <= 6.0 && dy <= 6) {
val dist = dx * dx + dy * dy
if (dist < minDist) {
minDist = dist
result = handle
}
}
}
return result
}
fun onMousePressed(event: MouseEvent) {
currentHandle = closestHandle(event)
dragging = currentHandle != null
}
fun onMouseMoved(event: MouseEvent) {
// println("onMouseMoved")
currentHandle = closestHandle(event)
}
fun onMouseDragged(event: MouseEvent) {
//println("onMouseDragged")
val offsetX = event.x - margin - pose.offsetX
val offsetY = canvas.height - margin - event.y - pose.offsetY
currentHandle?.moveTo(offsetX, offsetY)
}
fun update(shapeDef: ShapeDef?) {
//println("Update using : $shapeDef")
currentShapedDef = shapeDef
if (!dragging) {
//println("Creating drag handles")
handles.clear()
when (shapeDef) {
is CircleDef -> {
handles.add(RadiusHandle(fixtureParameter.circleCenterP.xP, fixtureParameter.circleCenterP.yP, fixtureParameter.circleRadiusP))
handles.add(PositionHandle(fixtureParameter.circleCenterP))
}
is BoxDef -> {
val corner1 = CornerHandle(fixtureParameter.boxCenterP, fixtureParameter.boxSizeP.xP, fixtureParameter.boxSizeP.yP, fixtureParameter.boxAngleP, null)
val corner2 = CornerHandle(fixtureParameter.boxCenterP, fixtureParameter.boxSizeP.xP, fixtureParameter.boxSizeP.yP, fixtureParameter.boxAngleP, corner1)
handles.add(corner1)
handles.add(corner2)
}
is PolygonDef -> {
fixtureParameter.polygonPointsP.innerParameters.forEach { pointP ->
handles.add(PositionHandle(pointP))
}
}
}
}
dirty = true
}
fun redraw() {
dirty = false
//println("Redraw")
val shapeDef = currentShapedDef
with(canvas.graphicsContext2D) {
save()
clearRect(0.0, 0.0, canvas.width, canvas.height)
lineWidth = 1.0
stroke = borderColor
translate(margin, margin)
strokeRect(0.0, 0.0, poseWidth.toDouble(), poseHeight.toDouble())
save()
translate(pose.offsetX, pose.offsetY)
save()
when (shapeDef) {
is CircleDef -> {
drawOutlined(shapeColor) {
strokeOval(shapeDef.center.x - shapeDef.radius, shapeDef.center.y - shapeDef.radius, shapeDef.radius * 2, shapeDef.radius * 2)
}
}
is BoxDef -> {
translate(shapeDef.center.x, shapeDef.center.y)
rotate(shapeDef.angle.degrees)
drawOutlined(shapeColor) {
strokeRect(-shapeDef.width / 2, -shapeDef.height / 2, shapeDef.width, shapeDef.height)
}
}
is PolygonDef -> {
lineCap = StrokeLineCap.ROUND
drawOutlined(shapeColor) {
val xs = DoubleArray(shapeDef.points.size, { i -> shapeDef.points.map { it.x }[i] })
val ys = DoubleArray(shapeDef.points.size, { i -> shapeDef.points.map { it.y }[i] })
strokePolygon(xs, ys, shapeDef.points.size)
}
}
}
restore()
handles.forEach { it.draw() }
restore()
this.globalAlpha = 0.5
drawImage(pose.texture.cachedImage(),
pose.rect.left.toDouble(), pose.rect.bottom.toDouble(), pose.rect.width.toDouble(), -pose.rect.height.toDouble(),
0.0, 0.0, pose.rect.width.toDouble(), pose.rect.height.toDouble())
this.globalAlpha = 1.0
restore()
}
}
fun drawOutlined(color: Color, shape: () -> Unit) {
with(canvas.graphicsContext2D) {
stroke = Color.BLACK
lineCap = StrokeLineCap.ROUND
lineWidth = 2.0
shape()
stroke = color
lineWidth = 1.0
shape()
}
}
inner abstract class Handle {
abstract fun position(): Vector2d
fun draw() {
with(canvas.graphicsContext2D) {
save()
val position = position()
translate(position.x, position.y)
drawOutlined(if (this@Handle == currentHandle) currentHandleColor else handleColor) {
strokeRect(-3.0, -3.0, 6.0, 6.0)
}
restore()
}
}
abstract fun moveTo(x: Double, y: Double)
}
inner class PositionHandle(val parameter: Vector2dParameter) : Handle() {
override fun position() = Vector2d(parameter.x ?: 0.0, parameter.y ?: 0.0)
override fun moveTo(x: Double, y: Double) {
parameter.xP.value = x
parameter.yP.value = y
}
}
inner class RadiusHandle(val centerXP: DoubleParameter, val centerYP: DoubleParameter, val radiusParameter: DoubleParameter) : Handle() {
override fun position() = Vector2d((centerXP.value ?: 0.0) + (radiusParameter.value ?: 0.0), (centerYP.value
?: 0.0))
override fun moveTo(x: Double, y: Double) {
radiusParameter.value = x - (centerXP.value ?: 0.0)
}
}
inner class CornerHandle(
val centerParameter: Vector2dParameter,
val widthParameter: DoubleParameter,
val heightParameter: DoubleParameter,
val angleParameter: AngleParameter,
other: CornerHandle?)
: Handle() {
lateinit var other: CornerHandle
var plusX: Boolean = true
var plusY: Boolean = true
init {
if (other != null) {
this.other = other
this.other.other = this
plusX = false
plusY = false
}
}
override fun position(): Vector2d {
with(canvas.graphicsContext2D) {
val scaleX = if (plusX) 0.5 else -0.5
val scaleY = if (plusY) 0.5 else -0.5
val width = widthParameter.value ?: 0.0
val height = heightParameter.value ?: 0.0
val cos = Math.cos(angleParameter.value.radians)
val sin = Math.sin(angleParameter.value.radians)
val dx = width * scaleX * cos - height * scaleY * sin
val dy = height * scaleY * cos + width * scaleX * sin
return Vector2d((centerParameter.x ?: 0.0) + dx, (centerParameter.y ?: 0.0) + dy)
}
}
override fun moveTo(x: Double, y: Double) {
val rotate = Matrix3x2d().rotate(-angleParameter.value.radians)
val rotated = Vector2d(x - (centerParameter.x ?: 0.0), y - (centerParameter.y ?: 0.0))
rotate.transformPosition(rotated)
val otherRotated = other.position()
otherRotated.x -= (centerParameter.x ?: 0.0)
otherRotated.y -= (centerParameter.y ?: 0.0)
rotate.transformPosition(otherRotated)
val oldWidth = widthParameter.value ?: 0.0
val oldHeight = heightParameter.value ?: 0.0
var width = Math.round(rotated.x - otherRotated.x).toDouble() * if (plusX) 1 else -1
var height = Math.round(rotated.y - otherRotated.y).toDouble() * if (plusY) 1 else -1
if (width < 0) {
width = -width
plusX = !plusX
other.plusX = !plusX
}
if (height < 0) {
height = -height
plusY = !plusY
other.plusY = !plusY
}
centerParameter.x = (centerParameter.x ?: 0.0) + (width - oldWidth) / 2 * if (plusX) 1 else -1
centerParameter.y = (centerParameter.y ?: 0.0) + (height - oldHeight) / 2 * if (plusY) 1 else -1
widthParameter.value = width
heightParameter.value = height
}
}
}
| tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/tabs/ShapeEditorParameter.kt | 306487695 |
package com.getbase.android.db.cursors
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import com.getbase.android.db.loaders.CursorLoaderBuilder
import com.getbase.android.db.test.AsyncTasksMonitor
import com.getbase.android.db.test.TestActivity
import com.getbase.android.db.test.TestContentProvider
import com.getbase.android.db.test.TestContract
import com.google.common.truth.Truth
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
@RunWith(AndroidJUnit4::class)
class ComposedCursorLoaderTest {
@Rule
@JvmField
val rule = ActivityTestRule(TestActivity::class.java)
private val asyncTasksMonitor = AsyncTasksMonitor()
@Test
fun shouldGracefullyHandleTransformationsYieldingTheSameInstance() {
val initialLoad = TransformData(1, pauseWhenExecuting = false)
val firstReload = TransformData(2)
val secondReload = TransformData(2)
// Check preconditions for this scenario: the reloads have to use the same
// instance of transformation output object and it has to be different than
// the result of initial load to trigger onNewDataDelivered callback.
Truth.assertThat(firstReload.result).isSameAs(secondReload.result)
Truth.assertThat(initialLoad.result).isNotSameAs(firstReload.result)
val results = LinkedBlockingDeque<Int>()
val transforms = LinkedList<TransformData>().apply {
add(initialLoad)
add(firstReload)
add(secondReload)
}
// Start the loader on TestContract.BASE_URI. The returned Cursor will be transformed using
// TransformData objects enqueued in transforms queue.
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(0, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<Int> {
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Int> =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transform { transforms.removeFirst().perform() }
.build(rule.activity)
override fun onLoadFinished(loader: Loader<Int>, data: Int) = results.putLast(data)
override fun onLoaderReset(loader: Loader<Int>) = Unit
})
}
// Wait until the initial load is completed. We do this to ensure the content observers
// are registered on TestContract.BASE_URI and we can trigger Loader reload with
// ContentResolver.notifyChange call.
Truth.assertThat(results.takeFirst()).isEqualTo(1)
// The reloads are scheduled on the main Looper.
scheduleLoaderReload()
// Let's wait until the async task used by our Loader is started.
firstReload.waitUntilStarted()
// Now the things get tricky. We have to switch to the main thread to properly
// orchestrate all threads.
rule.runOnUiThread {
// The first reload is paused. We schedule yet another reload on the main Looper. Note
// that we're on the main thread here, so the reload will be processed *after* everything
// we do in this runnable.
scheduleLoaderReload()
// We want to complete the second reload before the result of first reload are
// delivered and processed on the main thread. To do that, we schedule yet another
// task that will be processed on the main thread after the second reload trigger.
scheduleMainLooperTask {
// At this point we're after the second reload trigger. The first reload is still
// waiting in the cursor transformation. We synchronously wait until the task is
// started...
secondReload.waitUntilStarted()
// ...and finished.
secondReload.proceed()
asyncTasksMonitor.waitUntilIdle()
// Again, we synchronously wait for the task to finish. We want to be sure that
// the results of the first reload are not processed yet. At this point we'll have:
// - Two delivery tasks for both reloads enqueued in main Looper.
// - Two pending result entries for the same result in the ComposedCursorLoader
// internals.
// - The first reload results should be cancelled; the second reload results should be
// delivered to onLoadFinished callback.
}
// We resume the first reload execution on the background thread.
firstReload.proceed()
// We synchronously wait until the first reload on the background thread
// is completed, because we don't want the first reload task to be added as
// mCancellingTask in the guts of AsyncTaskLoader.onCancelLoad. Instead, we
// want the results from this task to go through the branch that "cancels"
// the results delivered from an old task.
asyncTasksMonitor.waitUntilIdle()
// At this point the background tasks are completed and we have the following
// queue on the main Looper:
// - reload triggered by ContentResolver.notifyChange call
// - a task that waits for a second reload
// - result delivery from first reload.
}
// The whole machinery is in motion right now, we just need to wait.
// If everything goes well, the first reload will be cancelled, and the
// second reload will be successfully delivered.
Truth.assertThat(results.takeFirst()).isEqualTo(2)
}
@Test
fun shouldNotInvokeTransformationWhenLoaderDestroyedDuringQuery() {
val asyncTaskIdleLatch = CountDownLatch(1)
//As throwing exception on background loader thread do not fail test we need flag to ensure
//that transformation was never invoked
val transformationInvoked = AtomicBoolean(false)
//Prepare TestContentProvider to wait when loader start query for data
TestContentProvider.blockOnQuery()
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(1, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<Nothing> {
override fun onCreateLoader(id: Int, args: Bundle?) =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transform {
transformationInvoked.set(true)
throw AssertionError("This transformation should never be invoked")
}
.build(rule.activity)
override fun onLoadFinished(loader: Loader<Nothing>, data: Nothing?) {
throw AssertionError("This loader should be cancelled so result should never be returned")
}
override fun onLoaderReset(loader: Loader<Nothing>) {}
})
}
//Now when loader is scheduled, test thread should wait until
//Loader is created and initialized by LoaderManager
TestContentProvider.waitUntilQueryStarted()
//As loader is busy querying for data we cancel load in background.
//Then we allow it to finish query and move forward. In the meantime
//test thread is waiting until asyncTaskMonitor will be idle.
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.destroyLoader(1)
TestContentProvider.proceedQuery()
asyncTasksMonitor.waitUntilIdle()
asyncTaskIdleLatch.countDown()
}
//After all background work is done and check if transformation will not be invoked
asyncTaskIdleLatch.await()
Truth.assertThat(transformationInvoked.get()).isFalse()
}
@Test
fun shouldNotInvokeSecondTransformationWhenLoaderDestroyedDuringFirstTransformation() {
val firstTransformation = TransformData(1)
val secondTransformationInvoked = AtomicBoolean(false)
val asyncTaskIdleLatch = CountDownLatch(1)
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(1, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<Nothing> {
override fun onCreateLoader(id: Int, args: Bundle?) =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transform { firstTransformation.perform() }
.transform {
secondTransformationInvoked.set(true)
throw AssertionError("This transformation should never be invoked")
}
.build(rule.activity)
override fun onLoadFinished(loader: Loader<Nothing>, data: Nothing?) {
throw AssertionError("This loader should be cancelled so result should never be returned")
}
override fun onLoaderReset(loader: Loader<Nothing>) {}
})
}
firstTransformation.waitUntilStarted()
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.destroyLoader(1)
firstTransformation.proceed()
asyncTasksMonitor.waitUntilIdle()
asyncTaskIdleLatch.countDown()
}
asyncTaskIdleLatch.await()
Truth.assertThat(secondTransformationInvoked.get()).isFalse()
}
interface RowTransformation {
fun transform(): Int;
}
@Test
fun shouldNotInvokeTransformationForSecondRowWhenLoaderDestroyedDuringTransformationOfFirstRow() {
val secondTransformationInvoked = AtomicBoolean(false)
val asyncTaskIdleLatch = CountDownLatch(1)
TestContentProvider.setDataForQuery(mutableListOf(1, 2))
val firstTransformation = TransformData(1)
val transformations = mutableListOf(
object : RowTransformation {
override fun transform(): Int = firstTransformation.perform()
},
object : RowTransformation {
override fun transform(): Int {
secondTransformationInvoked.set(true)
return 2
}
}
)
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(1, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<List<Int>> {
override fun onCreateLoader(id: Int, args: Bundle?) =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transformRow {
val transformation = transformations.first()
transformations.remove(transformation)
transformation.transform()
}
.build(rule.activity)
override fun onLoadFinished(loader: Loader<List<Int>>, data: List<Int>?) {
throw AssertionError("This loader should be cancelled so result should never be returned")
}
override fun onLoaderReset(loader: Loader<List<Int>>) {}
})
}
firstTransformation.waitUntilStarted()
//Data is loaded and loader is blocked on first row transformation
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.destroyLoader(1)
firstTransformation.proceed()
asyncTasksMonitor.waitUntilIdle()
asyncTaskIdleLatch.countDown()
}
asyncTaskIdleLatch.await()
Truth.assertThat(secondTransformationInvoked.get()).isFalse()
}
private fun scheduleMainLooperTask(task: () -> Unit) = Handler(Looper.getMainLooper()).post(task)
private fun scheduleLoaderReload() = rule.activity.contentResolver.notifyChange(TestContract.BASE_URI, null)
private fun AsyncTasksMonitor.waitUntilIdle() {
while (!isIdleNow) {
SystemClock.sleep(10)
}
}
class TransformData(val result: Int, pauseWhenExecuting: Boolean = true) {
private val startLatch = CountDownLatch(if (pauseWhenExecuting) 1 else 0)
private val proceedLatch = CountDownLatch(if (pauseWhenExecuting) 1 else 0)
fun perform(): Int {
startLatch.countDown()
proceedLatch.awaitOrFail()
return result
}
fun waitUntilStarted() = startLatch.awaitOrFail()
fun proceed() = proceedLatch.countDown()
private fun CountDownLatch.awaitOrFail(): Unit {
if (!await(3, TimeUnit.SECONDS)) {
Assert.fail()
}
}
}
}
| library/src/androidTest/java/com/getbase/android/db/cursors/ComposedCursorLoaderTest.kt | 696581472 |
package org.peercast.core.lib
import android.net.Uri
import kotlinx.serialization.json.*
import org.peercast.core.lib.internal.BaseJsonRpcConnection
import org.peercast.core.lib.rpc.*
import org.peercast.core.lib.rpc.io.*
import org.peercast.core.lib.rpc.io.JsonRpcResponse
import org.peercast.core.lib.rpc.io.decodeRpcResponse
import org.peercast.core.lib.rpc.io.decodeRpcResponseOnlyErrorCheck
import java.io.IOException
/**
* PeerCastController経由でRPCコマンドを実行する。
*
* @licenses Dual licensed under the MIT or GPL licenses.
* @author (c) 2019-2020, T Yoshizawa
* @see <a href=https://github.com/kumaryu/peercaststation/wiki/JSON-RPC-API-%E3%83%A1%E3%83%A2>JSON RPC API メモ</a>
* @version 4.0.0
*/
class PeerCastRpcClient(private val conn: BaseJsonRpcConnection) {
/**@param endPoint RPC接続へのURL*/
constructor(endPoint: String) : this(JsonRpcConnection(endPoint))
constructor(controller: PeerCastController) : this(controller.rpcEndPoint)
/**RPC接続へのURL*/
val rpcEndPoint: Uri get() = Uri.parse(conn.endPoint)
private suspend inline fun <reified T> JsonObject.sendCommand(): T {
return conn.post(this.toString()){
decodeRpcResponse(it)
}
}
//result=nullしか帰ってこない場合
private suspend fun JsonObject.sendVoidCommand() {
conn.post(this.toString()){
decodeRpcResponseOnlyErrorCheck(it)
}
}
/**
* 稼働時間、ポート開放状態、IPアドレスなどの情報の取得。
* @throws IOException
* **/
suspend fun getStatus(): Status {
return buildRpcRequest("getStatus").sendCommand()
}
/**
* チャンネルに再接続。
* @throws IOException
* @return なし
* */
suspend fun bumpChannel(channelId: String) {
return buildRpcRequest("bumpChannel", channelId).sendVoidCommand()
}
/**
* チャンネルを停止する。
* @throws IOException
* @return 成功か
* */
suspend fun stopChannel(channelId: String) {
buildRpcRequest("stopChannel", channelId)
.sendVoidCommand()
}
/**
* チャンネルに関して特定の接続を停止する。成功すれば true、失敗すれば false を返す。
* @throws IOException
* @return 成功か
* */
suspend fun stopChannelConnection(channelId: String, connectionId: Int): Boolean {
return buildRpcRequestArrayParams("stopChannelConnection") {
add(channelId)
add(connectionId)
}.sendCommand()
}
/**
* チャンネルの接続情報。
* @throws IOException
* */
suspend fun getChannelConnections(channelId: String): List<ChannelConnection> {
return buildRpcRequest("getChannelConnections", channelId).sendCommand()
}
/**
* リレーツリー情報。ルートは自分自身。
* @throws IOException
* */
suspend fun getChannelRelayTree(channelId: String): List<ChannelRelayTree> {
return buildRpcRequest("getChannelRelayTree", channelId)
.sendCommand()
}
suspend fun getChannelInfo(channelId: String): ChannelInfoResult {
return buildRpcRequest("getChannelInfo", channelId).sendCommand()
}
/**
* バージョン情報の取得。
* @throws IOException
* */
suspend fun getVersionInfo(): VersionInfo {
return buildRpcRequest("getVersionInfo").sendCommand()
}
/**
* 特定のチャンネルの情報。
* @throws IOException
* */
suspend fun getChannelStatus(channelId: String): ChannelStatus {
return buildRpcRequest("getChannelStatus", channelId).sendCommand()
}
/**
* すべてのチャンネルの情報。
* @throws IOException
* */
suspend fun getChannels(): List<Channel> {
return buildRpcRequest("getChannels").sendCommand()
}
/**
* リレーに関する設定の取得。
* @throws IOException
* */
suspend fun getSettings(): Settings {
return buildRpcRequest("getSettings").sendCommand()
}
/**
* リレーに関する設定を変更。
* @throws IOException
* */
suspend fun setSettings(settings: Settings) {
buildRpcRequestObjectParams("setSettings") {
put("settings", Json.encodeToJsonElement(settings))
}.sendVoidCommand()
}
/**
* ログをクリア。
* @throws IOException
* */
suspend fun clearLog() {
buildRpcRequest("clearLog").sendVoidCommand()
}
/**
* ログバッファーの内容の取得
* @throws IOException
* @since YT22
* */
suspend fun getLog(from: Int? = null, maxLines: Int? = null): List<Log> {
return buildRpcRequestObjectParams("getLog") {
put("from", from)
put("maxLines", maxLines)
}.sendCommand()
}
/**
* ログレベルの取得。
* @throws IOException
* @since YT22
* */
suspend fun getLogSettings(): LogSettings {
return buildRpcRequest("getLogSettings").sendCommand()
}
/**
* ログレベルの設定。
* @throws IOException
* @since YT22
* */
suspend fun setLogSettings(settings: LogSettings) {
buildRpcRequest("setLogSettings",
Json.encodeToJsonElement(settings)
).sendVoidCommand()
}
/**
* 外部サイトの index.txtから取得されたチャンネル一覧。YPブラウザでの表示用。
* @throws IOException
* */
suspend fun getYPChannels(): List<YpChannel> {
return buildRpcRequest("getYPChannels").sendCommand()
}
/**
* 登録されているイエローページの取得。
* @throws IOException
* */
suspend fun getYellowPages(): List<YellowPage> {
return buildRpcRequest("getYellowPages").sendCommand()
}
/**
* イエローページを追加。
* @throws IOException
* */
suspend fun addYellowPage(
protocol: String, name: String,
uri: String = "", announceUri: String = "", channelsUri: String = "",
) {
throw NotImplementedError("Not implemented yet in jrpc.cpp")
}
/**
* イエローページを削除。
* @throws IOException
* */
suspend fun removeYellowPage(yellowPageId: Int) {
buildRpcRequest("removeYellowPage", yellowPageId).sendVoidCommand()
}
/**
* YP から index.txt を取得する。
* @throws IOException
* */
suspend fun updateYPChannels() {
throw NotImplementedError("Not implemented yet in jrpc.cpp")
}
override fun hashCode(): Int {
return javaClass.hashCode() * 31 + conn.hashCode()
}
override fun equals(other: Any?): Boolean {
return other is PeerCastRpcClient &&
other.javaClass == javaClass &&
other.conn == conn
}
} | libpeercast/src/main/java/org/peercast/core/lib/PeerCastRpcClient.kt | 3906482322 |
package solution
import data.structure.ListNode
class LinkProblems {
/**
* https://leetcode-cn.com/problems/merge-k-sorted-lists/
*/
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
var currentNode = Array<ListNode?>(lists.size) { null }
var result: ListNode? = null
var current: ListNode? = null
lists.forEachIndexed { index, listNode ->
currentNode[index] = listNode
}
currentNode = currentNode.filterNotNull().toTypedArray()
while (currentNode.isNotEmpty()) {
var m = currentNode[0]
var minIndex = 0
currentNode.forEachIndexed { index, listNode ->
if (listNode!!.`val` < m!!.`val`) {
m = listNode
minIndex = index
}
}
if (current == null) {
result = m
current = result
} else {
current.next = m
current = current.next
}
currentNode[minIndex] = currentNode[minIndex]?.next
currentNode = currentNode.filterNotNull().toTypedArray()
current?.next = null
}
return result
}
/**
* https://leetcode-cn.com/problems/add-two-numbers-ii/
*/
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val h1 = ListNode(0)
h1.next = l1
val h2 = ListNode(0)
h2.next = l2
val reverseList: (ListNode) -> Unit = {
var current = it.next
it.next = null
while (current != null) {
val pointer = current
current = current.next
if (it.next == null) {
it.next = pointer
pointer.next = null
} else {
pointer.next = it.next
it.next = pointer
}
}
}
reverseList(h1)
reverseList(h2)
var n1 = h1.next
var n2 = h2.next
val ans = ListNode(0)
var cur: ListNode? = null
var carry = 0
while (n1 != null && n2 != null) {
val n = n1.`val` + n2.`val` + carry
carry = n / 10
if (ans.next == null) {
ans.next = ListNode(n % 10)
cur = ans.next
} else {
cur!!.next = ListNode(n % 10)
cur = cur.next
}
n1 = n1.next
n2 = n2.next
}
while (n1 != null) {
cur!!.next = ListNode((n1.`val` + carry) % 10)
carry = (n1.`val` + carry) / 10
cur = cur.next
n1 = n1.next
}
while (n2 != null) {
cur!!.next = ListNode((n2.`val` + carry) % 10)
carry = (n2.`val` + carry) / 10
cur = cur.next
n2 = n2.next
}
if (carry > 0) {
cur!!.next = ListNode(carry)
}
reverseList(ans)
return ans.next
}
/**
* https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
*/
fun deleteNode(head: ListNode?, `val`: Int): ListNode? {
val ans = ListNode(0)
ans.next = head
var before = ans
var current = ans.next
while (current != null) {
if (current.`val` == `val`) {
before.next = current.next
current.next = null
break
}
before = current
current = current.next
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer/
*/
fun getDecimalValue(head: ListNode?): Int {
var len = 0
var cur = head
var ans = 0
while (cur != null) {
len++
cur = cur.next
}
cur = head
var carry = (1).shl(len - 1)
while (cur != null) {
ans += carry * cur.`val`
carry = carry.shr(1)
cur = cur.next
}
return ans
}
/**
*
*/
fun addTwoNumbers2(l1: ListNode?, l2: ListNode?): ListNode? {
val h1 = ListNode(0)
h1.next = l1
val h2 = ListNode(0)
h2.next = l2
var n1 = h1.next
var n2 = h2.next
val ans = ListNode(0)
var cur: ListNode? = null
var carry = 0
while (n1 != null && n2 != null) {
val n = n1.`val` + n2.`val` + carry
carry = n / 10
if (ans.next == null) {
ans.next = ListNode(n % 10)
cur = ans.next
} else {
cur!!.next = ListNode(n % 10)
cur = cur.next
}
n1 = n1.next
n2 = n2.next
}
while (n1 != null) {
cur!!.next = ListNode((n1.`val` + carry) % 10)
carry = (n1.`val` + carry) / 10
cur = cur.next
n1 = n1.next
}
while (n2 != null) {
cur!!.next = ListNode((n2.`val` + carry) % 10)
carry = (n2.`val` + carry) / 10
cur = cur.next
n2 = n2.next
}
if (carry > 0) {
cur!!.next = ListNode(carry)
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/partition-list/
*/
fun partition(head: ListNode?, x: Int): ListNode? {
val littleList = ListNode(0)
val bigList = ListNode(0)
var current = head
var littleCurrent = littleList
var bigCurrent = bigList
while (current != null) {
val temp = current
current = current.next
temp.next = null
if (temp.`val` < x) {
littleCurrent.next = temp
littleCurrent = littleCurrent.next!!
} else {
bigCurrent.next = temp
bigCurrent = bigCurrent.next!!
}
}
littleCurrent.next = bigList.next
return littleList.next
}
/**
* https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
*/
fun reverseList(head: ListNode?): ListNode? {
val ans: ListNode = ListNode(0)
var current = head
while (current != null) {
val temp = current
current = current.next
temp.next = ans.next
ans.next = temp
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
*/
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
var cur1 = l1
var cur2 = l2
val ans = ListNode(0)
var cur: ListNode = ans
while (cur1 != null || cur2 != null) {
if (cur2 == null || (cur1 != null && cur1.`val` <= cur2.`val`)) {
cur.next = cur1
cur1 = cur1!!.next
cur = cur.next!!
cur.next = null
} else if (cur1 == null || cur1.`val` > cur2.`val`) {
cur.next = cur2
cur2 = cur2.next
cur = cur.next!!
cur.next = null
}
}
return ans.next
}
/**
<<<<<<< HEAD
* https://leetcode-cn.com/problems/palindrome-linked-list-lcci/
*/
fun isPalindrome(head: ListNode?): Boolean {
var cur = head
var listLength = 0
while (cur != null) {
listLength++
cur = cur.next
}
cur = head
var count = listLength / 2
val left = ListNode(0)
while (count > 0 && cur != null) {
count--
val temp = cur
cur = cur.next
temp.next = left.next
left.next = temp
}
var curLeft = left.next
var curRight = cur
if (listLength % 2 == 1) {
curRight = cur!!.next
}
while (curLeft != null && curRight != null) {
if (curLeft.`val` != curRight.`val`) {
return false
}
curLeft = curLeft.next
curRight = curRight.next
}
return true
}
/**
* https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
*/
fun kthToLast(head: ListNode?, k: Int): Int {
var cur = head
var listLength = 0
while (cur != null) {
listLength++
cur = cur.next
}
val pos = listLength - k + 1
cur = head
listLength = 0
while (cur != null) {
listLength++
if (listLength == pos) {
return cur.`val`
}
cur = cur.next
}
return 0
}
/**
* https://leetcode-cn.com/problems/middle-of-the-linked-list/
*/
fun middleNode(head: ListNode?): ListNode? {
var listLength = 0
var current = head
while (current != null) {
listLength++
current = current.next
}
val middle = listLength / 2 + 1
current = head
listLength = 0
while (current != null) {
listLength++
if (listLength == middle) {
return current
}
current = current.next
}
return null
}
/**
* https://leetcode-cn.com/problems/linked-list-components/
*/
fun numComponents(head: ListNode?, G: IntArray): Int {
var ans = 0
var current = head
var inList = false
while (current != null) {
if (current.`val` in G) {
if (!inList) {
inList = true
ans++
}
} else {
inList = false
}
current = current.next
}
return ans
}
/**
* https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
*/
fun removeDuplicateNodes(head: ListNode?): ListNode? {
val buffer = HashSet<Int>()
var current = head
var before: ListNode? = null
while (current != null) {
if (current.`val` in buffer) {
before!!.next = current.next
current = before
} else {
buffer.add(current.`val`)
}
before = current
current = current.next
}
return head
}
} | kotlin/problems/src/solution/LinkProblems.kt | 2552679982 |
package org.rust.lang.core.type
class RustEnumPatternTypeInferenceTest: RustTypificationTestBase() {
fun testEnumPattern() = testExpr("""
enum E {
X
}
fn main() {
let x = E::X;
x;
//^ E
}
""")
fun testEnumPatternWithUnnamedArgs() = testExpr("""
enum E {
X(i32, i16)
}
fn bar() -> E {}
fn main() {
let E::X(_, i) = bar();
i;
//^ i16
}
""")
fun testEnumPatternWithNamedArgs() = testExpr("""
enum E {
X { _1: i32, _2: i64 }
}
fn bar() -> E {}
fn main() {
let E::X(_, i) = bar();
i;
//^ <unknown>
}
""")
fun testEnumTupleOutOfBounds() = testExpr("""
enum E {
V(i32, i32)
}
fn main() {
let E::V(_, _, x): E = unimplemented!();
x
//^ <unknown>
}
""")
fun testStructTuple() = testExpr("""
struct Centimeters(f64);
struct Inches(i32);
impl Inches {
fn to_centimeters(&self) -> Centimeters {
let &Inches(inches) = self;
inches;
//^ i32
}
}
""")
fun testBindingWithPat() = testExpr("""
struct S { x: i32, y: i32 }
enum Result {
Ok(S),
Failure
}
fn foo(r: Result) {
let Result::Ok(s @ S { x, .. }) = r;
s
//^ S
}
""")
fun testBindingWithPatFailure1() = testExpr("""
struct S { x: i32, y: i32 }
enum Result {
Ok(S),
Failure
}
fn foo(r: Result) {
let Result::Ok(s @ S { j /* non-existing field */ }) = r;
s
//^ <unknown>
}
""")
fun testBindingWithPatFailure2() = testExpr("""
struct S { x: i32, y: i32 }
enum Result {
Ok(S),
Failure
}
fn foo(r: Result) {
let Result::Ok(s @ S { x /* missing fields */ }) = r;
s
//^ <unknown>
}
""")
}
| src/test/kotlin/org/rust/lang/core/type/RustEnumPatternTypeInferenceTest.kt | 259704091 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.ocr
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
class OCRSlashExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta), OCRExecutor {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val imageReference = imageReferenceOrAttachment("image")
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val image = args[options.imageReference].get(context)!! // Shouldn't be null here because it is required
context.deferChannelMessage()
handleOCRCommand(
loritta,
context,
false,
image.url
)
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/ocr/OCRSlashExecutor.kt | 819339316 |
package eu.kanade.tachiyomi.extension.it.hentaifantasy
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.*
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.regex.Pattern
class HentaiFantasy : ParsedHttpSource() {
override val name = "HentaiFantasy"
override val baseUrl = "http://www.hentaifantasy.it/index.php"
override val lang = "it"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
companion object {
val pagesUrlPattern by lazy {
Pattern.compile("""\"url\":\"(.*?)\"""")
}
val dateFormat by lazy {
SimpleDateFormat("yyyy.MM.dd")
}
}
override fun popularMangaSelector() = "div.list > div.group > div.title > a"
override fun popularMangaRequest(page: Int)
= GET("$baseUrl/most_downloaded/$page/", headers)
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.setUrlWithoutDomain(element.attr("href"))
manga.title = element.text().trim()
return manga
}
override fun popularMangaNextPageSelector() = "div.next > a.gbutton:contains(»):last-of-type"
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesRequest(page: Int)
= GET("$baseUrl/latest/$page/", headers)
override fun latestUpdatesFromElement(element: Element): SManga {
return popularMangaFromElement(element)
}
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
var tags = mutableListOf<String>()
var paths = mutableListOf<String>()
for (filter in if (filters.isEmpty()) getFilterList() else filters) {
when (filter) {
is TagList -> filter.state
.filter { it.state }
.map {
paths.add(it.name.toLowerCase().replace(" ", "_"));
it.id.toString()
}
.forEach { tags.add(it) }
}
}
var searchTags = tags.size > 0
if (!searchTags && query.length < 3) {
throw Exception("Inserisci almeno tre caratteri")
}
val form = FormBody.Builder().apply {
if (!searchTags) {
add("search", query)
} else {
tags.forEach {
add("tag[]", it)
}
}
}
var searchPath = if (!searchTags) {
"search"
} else if (paths.size == 1) {
"tag/${paths[0]}/${page}"
} else {
"search_tags"
}
return POST("${baseUrl}/${searchPath}", headers, form.build())
}
override fun searchMangaFromElement(element: Element): SManga {
return popularMangaFromElement(element)
}
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun mangaDetailsParse(document: Document): SManga {
val manga = SManga.create()
var genres = mutableListOf<String>()
document.select("div#tablelist > div.row").forEach { row ->
when (row.select("div.cell > b").first().text().trim()) {
"Autore" -> manga.author = row.select("div.cell > a").text().trim()
"Genere", "Tipo" -> row.select("div.cell > a > span.label").forEach {
genres.add(it.text().trim())
}
"Descrizione" -> manga.description = row.select("div.cell").last().text().trim()
}
}
manga.genre = genres.joinToString(", ")
manga.status = SManga.UNKNOWN
manga.thumbnail_url = document.select("div.thumbnail > img")?.attr("src")
return manga
}
override fun mangaDetailsRequest(manga: SManga) = POST(baseUrl + manga.url, headers)
override fun chapterListSelector() = "div.list > div.group div.element"
override fun chapterFromElement(element: Element): SChapter {
val chapter = SChapter.create()
element.select("div.title > a").let {
chapter.setUrlWithoutDomain(it.attr("href"))
chapter.name = it.text().trim()
}
chapter.date_upload = element.select("div.meta_r").first()?.ownText()?.substringAfterLast(", ")?.trim()?.let {
parseChapterDate(it)
} ?: 0L
return chapter
}
private fun parseChapterDate(date: String): Long {
return if (date == "Oggi") {
Calendar.getInstance().timeInMillis
} else if (date == "Ieri") {
Calendar.getInstance().apply {
add(Calendar.DAY_OF_YEAR, -1)
}.timeInMillis
} else {
try {
dateFormat.parse(date).time
} catch (e: ParseException) {
0L
}
}
}
override fun pageListRequest(chapter: SChapter) = POST(baseUrl + chapter.url, headers)
override fun pageListParse(response: Response): List<Page> {
val body = response.body()!!.string()
val pages = mutableListOf<Page>()
val p = pagesUrlPattern
val m = p.matcher(body)
var i = 0
while (m.find()) {
pages.add(Page(i++, "", m.group(1).replace("""\\""", "")))
}
return pages
}
override fun pageListParse(document: Document): List<Page> {
throw Exception("Not used")
}
override fun imageUrlRequest(page: Page) = GET(page.url)
override fun imageUrlParse(document: Document) = ""
private class Tag(name: String, val id: Int) : Filter.CheckBox(name)
private class TagList(title: String, tags: List<Tag>) : Filter.Group<Tag>(title, tags)
override fun getFilterList() = FilterList(
TagList("Generi", getTagList())
)
// Tags: 47
// $("select[name='tag[]']:eq(0) > option").map((i, el) => `Tag("${$(el).text().trim()}", ${$(el).attr("value")})`).get().sort().join(",\n")
// on http://www.hentaifantasy.it/search/
private fun getTagList() = listOf(
Tag("Ahegao", 56),
Tag("Anal", 28),
Tag("Ashikoki", 12),
Tag("Bestiality", 24),
Tag("Bizzare", 44),
Tag("Bondage", 30),
Tag("Cheating", 33),
Tag("Chubby", 57),
Tag("Dark Skin", 39),
Tag("Demon Girl", 43),
Tag("Femdom", 38),
Tag("Forced", 46),
Tag("Full color", 52),
Tag("Furry", 36),
Tag("Futanari", 18),
Tag("Group", 34),
Tag("Guro", 8),
Tag("Harem", 41),
Tag("Housewife", 51),
Tag("Incest", 11),
Tag("Lolicon", 20),
Tag("Maid", 55),
Tag("Milf", 31),
Tag("Monster Girl", 15),
Tag("Nurse", 49),
Tag("Oppai", 25),
Tag("Paizuri", 42),
Tag("Pettanko", 35),
Tag("Pissing", 32),
Tag("Public", 53),
Tag("Rape", 21),
Tag("Schoolgirl", 27),
Tag("Shotacon", 26),
Tag("Stockings", 40),
Tag("Swimsuit", 47),
Tag("Tanlines", 48),
Tag("Teacher", 50),
Tag("Tentacle", 23),
Tag("Toys", 45),
Tag("Trap", 29),
Tag("Tsundere", 54),
Tag("Uncensored", 59),
Tag("Vanilla", 19),
Tag("Yandere", 58),
Tag("Yaoi", 22),
Tag("Yuri", 14)
)
}
| src/it/hentaifantasy/src/eu/kanade/tachiyomi/extension/it/hentaifantasy/HentaiFantasy.kt | 1866828477 |
/*
* Copyright 2020 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.sample
import io.michaelrocks.lightsaber.Factory
import io.michaelrocks.lightsaber.sample.library.Droid
@Factory
internal interface DroidFactory {
@Factory.Return(R2D2::class)
fun produceR2D2(color: String): Droid
}
| samples/sample-android-kotlin/src/main/java/io/michaelrocks/lightsaber/sample/DroidFactory.kt | 3410803339 |
/*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.tls
import java.math.BigInteger
import java.net.InetAddress
import java.security.GeneralSecurityException
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.PrivateKey
import java.security.PublicKey
import java.security.SecureRandom
import java.security.Security
import java.security.Signature
import java.security.cert.X509Certificate
import java.security.interfaces.ECPublicKey
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.util.UUID
import java.util.concurrent.TimeUnit
import okhttp3.internal.canParseAsIpAddress
import okhttp3.tls.internal.der.AlgorithmIdentifier
import okhttp3.tls.internal.der.AttributeTypeAndValue
import okhttp3.tls.internal.der.BasicConstraints
import okhttp3.tls.internal.der.BitString
import okhttp3.tls.internal.der.Certificate
import okhttp3.tls.internal.der.CertificateAdapters
import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName
import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress
import okhttp3.tls.internal.der.Extension
import okhttp3.tls.internal.der.ObjectIdentifiers
import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints
import okhttp3.tls.internal.der.ObjectIdentifiers.organizationalUnitName
import okhttp3.tls.internal.der.ObjectIdentifiers.sha256WithRSAEncryption
import okhttp3.tls.internal.der.ObjectIdentifiers.sha256withEcdsa
import okhttp3.tls.internal.der.ObjectIdentifiers.subjectAlternativeName
import okhttp3.tls.internal.der.TbsCertificate
import okhttp3.tls.internal.der.Validity
import okio.ByteString
import okio.ByteString.Companion.decodeBase64
import okio.ByteString.Companion.toByteString
import org.bouncycastle.jce.provider.BouncyCastleProvider
/**
* A certificate and its private key. These are some properties of certificates that are used with
* TLS:
*
* * **A common name.** This is a string identifier for the certificate. It usually describes the
* purpose of the certificate like "Entrust Root Certification Authority - G2" or
* "www.squareup.com".
*
* * **A set of hostnames.** These are in the certificate's subject alternative name (SAN)
* extension. A subject alternative name is either a literal hostname (`squareup.com`), a literal
* IP address (`74.122.190.80`), or a hostname pattern (`*.api.squareup.com`).
*
* * **A validity interval.** A certificate should not be used before its validity interval starts
* or after it ends.
*
* * **A public key.** This cryptographic key is used for asymmetric encryption digital signatures.
* Note that the private key is not a part of the certificate!
*
* * **A signature issued by another certificate's private key.** This mechanism allows a trusted
* third-party to endorse a certificate. Third parties should only endorse certificates once
* they've confirmed that the owner of the private key is also the owner of the certificate's
* other properties.
*
* Certificates are signed by other certificates and a sequence of them is called a certificate
* chain. The chain terminates in a self-signed "root" certificate. Signing certificates in the
* middle of the chain are called "intermediates". Organizations that offer certificate signing are
* called certificate authorities (CAs).
*
* Browsers and other HTTP clients need a set of trusted root certificates to authenticate their
* peers. Sets of root certificates are managed by either the HTTP client (like Firefox), or the
* host platform (like Android). In July 2018 Android had 134 trusted root certificates for its HTTP
* clients to trust.
*
* For example, in order to establish a secure connection to `https://www.squareup.com/`,
* these three certificates are used.
*
* ```
* www.squareup.com certificate:
*
* Common Name: www.squareup.com
* Subject Alternative Names: www.squareup.com, squareup.com, account.squareup.com...
* Validity: 2018-07-03T20:18:17Z – 2019-08-01T20:48:15Z
* Public Key: d107beecc17325f55da976bcbab207ba4df68bd3f8fce7c3b5850311128264fd53e1baa342f58d93...
* Signature: 1fb0e66fac05322721fe3a3917f7c98dee1729af39c99eab415f22d8347b508acdf0bab91781c3720...
*
* signed by intermediate certificate:
*
* Common Name: Entrust Certification Authority - L1M
* Subject Alternative Names: none
* Validity: 2014-12-15T15:25:03Z – 2030-10-15T15:55:03Z
* Public Key: d081c13923c2b1d1ecf757dd55243691202248f7fcca520ab0ab3f33b5b08407f6df4e7ab0fb9822...
* Signature: b487c784221a29c0a478ecf54f1bb484976f77eed4cf59afa843962f1d58dea6f3155b2ed9439c4c4...
*
* signed by root certificate:
*
* Common Name: Entrust Root Certification Authority - G2
* Subject Alternative Names: none
* Validity: 2009-07-07T17:25:54Z – 2030-12-07T17:55:54Z
* Public Key: ba84b672db9e0c6be299e93001a776ea32b895411ac9da614e5872cffef68279bf7361060aa527d8...
* Self-signed Signature: 799f1d96c6b6793f228d87d3870304606a6b9a2e59897311ac43d1f513ff8d392bc0f...
* ```
*
* In this example the HTTP client already knows and trusts the last certificate, "Entrust Root
* Certification Authority - G2". That certificate is used to verify the signature of the
* intermediate certificate, "Entrust Certification Authority - L1M". The intermediate certificate
* is used to verify the signature of the "www.squareup.com" certificate.
*
* This roles are reversed for client authentication. In that case the client has a private key and
* a chain of certificates. The server uses a set of trusted root certificates to authenticate the
* client. Subject alternative names are not used for client authentication.
*/
@Suppress("DEPRECATION")
class HeldCertificate(
@get:JvmName("keyPair") val keyPair: KeyPair,
@get:JvmName("certificate") val certificate: X509Certificate
) {
@JvmName("-deprecated_certificate")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "certificate"),
level = DeprecationLevel.ERROR)
fun certificate(): X509Certificate = certificate
@JvmName("-deprecated_keyPair")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "keyPair"),
level = DeprecationLevel.ERROR)
fun keyPair(): KeyPair = keyPair
/**
* Returns the certificate encoded in [PEM format][rfc_7468].
*
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun certificatePem(): String = certificate.certificatePem()
/**
* Returns the RSA private key encoded in [PKCS #8][rfc_5208] [PEM format][rfc_7468].
*
* [rfc_5208]: https://tools.ietf.org/html/rfc5208
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun privateKeyPkcs8Pem(): String {
return buildString {
append("-----BEGIN PRIVATE KEY-----\n")
encodeBase64Lines(keyPair.private.encoded.toByteString())
append("-----END PRIVATE KEY-----\n")
}
}
/**
* Returns the RSA private key encoded in [PKCS #1][rfc_8017] [PEM format][rfc_7468].
*
* [rfc_8017]: https://tools.ietf.org/html/rfc8017
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun privateKeyPkcs1Pem(): String {
check(keyPair.private is RSAPrivateKey) { "PKCS1 only supports RSA keys" }
return buildString {
append("-----BEGIN RSA PRIVATE KEY-----\n")
encodeBase64Lines(pkcs1Bytes())
append("-----END RSA PRIVATE KEY-----\n")
}
}
private fun pkcs1Bytes(): ByteString {
val decoded = CertificateAdapters.privateKeyInfo.fromDer(keyPair.private.encoded.toByteString())
return decoded.privateKey
}
/** Build a held certificate with reasonable defaults. */
class Builder {
private var notBefore = -1L
private var notAfter = -1L
private var commonName: String? = null
private var organizationalUnit: String? = null
private val altNames = mutableListOf<String>()
private var serialNumber: BigInteger? = null
private var keyPair: KeyPair? = null
private var signedBy: HeldCertificate? = null
private var maxIntermediateCas = -1
private var keyAlgorithm: String? = null
private var keySize: Int = 0
init {
ecdsa256()
}
/**
* Sets the certificate to be valid in ```[notBefore..notAfter]```. Both endpoints are specified
* in the format of [System.currentTimeMillis]. Specify -1L for both values to use the default
* interval, 24 hours starting when the certificate is created.
*/
fun validityInterval(notBefore: Long, notAfter: Long) = apply {
require(notBefore <= notAfter && notBefore == -1L == (notAfter == -1L)) {
"invalid interval: $notBefore..$notAfter"
}
this.notBefore = notBefore
this.notAfter = notAfter
}
/**
* Sets the certificate to be valid immediately and until the specified duration has elapsed.
* The precision of this field is seconds; further precision will be truncated.
*/
fun duration(duration: Long, unit: TimeUnit) = apply {
val now = System.currentTimeMillis()
validityInterval(now, now + unit.toMillis(duration))
}
/**
* Adds a subject alternative name (SAN) to the certificate. This is usually a literal hostname,
* a literal IP address, or a hostname pattern. If no subject alternative names are added that
* extension will be omitted.
*/
fun addSubjectAlternativeName(altName: String) = apply {
altNames += altName
}
/**
* Set this certificate's common name (CN). Historically this held the hostname of TLS
* certificate, but that practice was deprecated by [RFC 2818][rfc_2818] and replaced with
* [addSubjectAlternativeName]. If unset a random string will be used.
*
* [rfc_2818]: https://tools.ietf.org/html/rfc2818
*/
fun commonName(cn: String) = apply {
this.commonName = cn
}
/** Sets the certificate's organizational unit (OU). If unset this field will be omitted. */
fun organizationalUnit(ou: String) = apply {
this.organizationalUnit = ou
}
/** Sets this certificate's serial number. If unset the serial number will be 1. */
fun serialNumber(serialNumber: BigInteger) = apply {
this.serialNumber = serialNumber
}
/** Sets this certificate's serial number. If unset the serial number will be 1. */
fun serialNumber(serialNumber: Long) = apply {
serialNumber(BigInteger.valueOf(serialNumber))
}
/**
* Sets the public/private key pair used for this certificate. If unset a key pair will be
* generated.
*/
fun keyPair(keyPair: KeyPair) = apply {
this.keyPair = keyPair
}
/**
* Sets the public/private key pair used for this certificate. If unset a key pair will be
* generated.
*/
fun keyPair(publicKey: PublicKey, privateKey: PrivateKey) = apply {
keyPair(KeyPair(publicKey, privateKey))
}
/**
* Set the certificate that will issue this certificate. If unset the certificate will be
* self-signed.
*/
fun signedBy(signedBy: HeldCertificate?) = apply {
this.signedBy = signedBy
}
/**
* Set this certificate to be a signing certificate, with up to `maxIntermediateCas`
* intermediate signing certificates beneath it.
*
* By default this certificate cannot not sign other certificates. Set this to 0 so this
* certificate can sign other certificates (but those certificates cannot themselves sign
* certificates). Set this to 1 so this certificate can sign intermediate certificates that can
* themselves sign certificates. Add one for each additional layer of intermediates to permit.
*/
fun certificateAuthority(maxIntermediateCas: Int) = apply {
require(maxIntermediateCas >= 0) {
"maxIntermediateCas < 0: $maxIntermediateCas"
}
this.maxIntermediateCas = maxIntermediateCas
}
/**
* Configure the certificate to generate a 256-bit ECDSA key, which provides about 128 bits of
* security. ECDSA keys are noticeably faster than RSA keys.
*
* This is the default configuration and has been since this API was introduced in OkHttp
* 3.11.0. Note that the default may change in future releases.
*/
fun ecdsa256() = apply {
keyAlgorithm = "EC"
keySize = 256
}
/**
* Configure the certificate to generate a 2048-bit RSA key, which provides about 112 bits of
* security. RSA keys are interoperable with very old clients that don't support ECDSA.
*/
fun rsa2048() = apply {
keyAlgorithm = "RSA"
keySize = 2048
}
fun build(): HeldCertificate {
// Subject keys & identity.
val subjectKeyPair = keyPair ?: generateKeyPair()
val subjectPublicKeyInfo = CertificateAdapters.subjectPublicKeyInfo.fromDer(
subjectKeyPair.public.encoded.toByteString()
)
val subject: List<List<AttributeTypeAndValue>> = subject()
// Issuer/signer keys & identity. May be the subject if it is self-signed.
val issuerKeyPair: KeyPair
val issuer: List<List<AttributeTypeAndValue>>
if (signedBy != null) {
issuerKeyPair = signedBy!!.keyPair
issuer = CertificateAdapters.rdnSequence.fromDer(
signedBy!!.certificate.subjectX500Principal.encoded.toByteString()
)
} else {
issuerKeyPair = subjectKeyPair
issuer = subject
}
val signatureAlgorithm = signatureAlgorithm(issuerKeyPair)
// Subset of certificate data that's covered by the signature.
val tbsCertificate = TbsCertificate(
version = 2L, // v3.
serialNumber = serialNumber ?: BigInteger.ONE,
signature = signatureAlgorithm,
issuer = issuer,
validity = validity(),
subject = subject,
subjectPublicKeyInfo = subjectPublicKeyInfo,
issuerUniqueID = null,
subjectUniqueID = null,
extensions = extensions()
)
// Signature.
val signature = Signature.getInstance(tbsCertificate.signatureAlgorithmName).run {
initSign(issuerKeyPair.private)
update(CertificateAdapters.tbsCertificate.toDer(tbsCertificate).toByteArray())
sign().toByteString()
}
// Complete signed certificate.
val certificate = Certificate(
tbsCertificate = tbsCertificate,
signatureAlgorithm = signatureAlgorithm,
signatureValue = BitString(
byteString = signature,
unusedBitsCount = 0
)
)
return HeldCertificate(subjectKeyPair, certificate.toX509Certificate())
}
private fun subject(): List<List<AttributeTypeAndValue>> {
val result = mutableListOf<List<AttributeTypeAndValue>>()
if (organizationalUnit != null) {
result += listOf(AttributeTypeAndValue(
type = organizationalUnitName,
value = organizationalUnit
))
}
result += listOf(AttributeTypeAndValue(
type = ObjectIdentifiers.commonName,
value = commonName ?: UUID.randomUUID().toString()
))
return result
}
private fun validity(): Validity {
val notBefore = if (notBefore != -1L) notBefore else System.currentTimeMillis()
val notAfter = if (notAfter != -1L) notAfter else notBefore + DEFAULT_DURATION_MILLIS
return Validity(
notBefore = notBefore,
notAfter = notAfter
)
}
private fun extensions(): MutableList<Extension> {
val result = mutableListOf<Extension>()
if (maxIntermediateCas != -1) {
result += Extension(
id = basicConstraints,
critical = true,
value = BasicConstraints(
ca = true,
maxIntermediateCas = maxIntermediateCas.toLong()
)
)
}
if (altNames.isNotEmpty()) {
val extensionValue = altNames.map {
when {
it.canParseAsIpAddress() -> {
generalNameIpAddress to InetAddress.getByName(it).address.toByteString()
}
else -> {
generalNameDnsName to it
}
}
}
result += Extension(
id = subjectAlternativeName,
critical = true,
value = extensionValue
)
}
return result
}
private fun signatureAlgorithm(signedByKeyPair: KeyPair): AlgorithmIdentifier {
return when (signedByKeyPair.private) {
is RSAPrivateKey -> AlgorithmIdentifier(
algorithm = sha256WithRSAEncryption,
parameters = null
)
else -> AlgorithmIdentifier(
algorithm = sha256withEcdsa,
parameters = ByteString.EMPTY
)
}
}
private fun generateKeyPair(): KeyPair {
return KeyPairGenerator.getInstance(keyAlgorithm).run {
initialize(keySize, SecureRandom())
generateKeyPair()
}
}
companion object {
private const val DEFAULT_DURATION_MILLIS = 1000L * 60 * 60 * 24 // 24 hours.
init {
Security.addProvider(BouncyCastleProvider())
}
}
}
companion object {
private val PEM_REGEX = Regex("""-----BEGIN ([!-,.-~ ]*)-----([^-]*)-----END \1-----""")
/**
* Decodes a multiline string that contains both a [certificate][certificatePem] and a
* [private key][privateKeyPkcs8Pem], both [PEM-encoded][rfc_7468]. A typical input string looks
* like this:
*
* ```
* -----BEGIN CERTIFICATE-----
* MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl
* cmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAwMTAx
* MDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2FzaC5h
* cHAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASda8ChkQXxGELnrV/oBnIAx3dD
* ocUOJfdz4pOJTP6dVQB9U3UBiW5uSX/MoOD0LL5zG3bVyL3Y6pDwKuYvfLNhoyAw
* HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF
* AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAtb9PYWO8bLmkcQIhAI2CfEZf3V/obmdT
* yyaoEufLKVXhrTQhRfodTeigi4RX
* -----END CERTIFICATE-----
* -----BEGIN PRIVATE KEY-----
* MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA7ODT0xhGSNn4ESj6J
* lu/GJQZoU9lDrCPeUcQ28tzOWw==
* -----END PRIVATE KEY-----
* ```
*
* The string should contain exactly one certificate and one private key in [PKCS #8][rfc_5208]
* format. It should not contain any other PEM-encoded blocks, but it may contain other text
* which will be ignored.
*
* Encode a held certificate into this format by concatenating the results of
* [certificatePem()][certificatePem] and [privateKeyPkcs8Pem()][privateKeyPkcs8Pem].
*
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
* [rfc_5208]: https://tools.ietf.org/html/rfc5208
*/
@JvmStatic
fun decode(certificateAndPrivateKeyPem: String): HeldCertificate {
var certificatePem: String? = null
var pkcs8Base64: String? = null
for (match in PEM_REGEX.findAll(certificateAndPrivateKeyPem)) {
when (val label = match.groups[1]!!.value) {
"CERTIFICATE" -> {
require(certificatePem == null) { "string includes multiple certificates" }
certificatePem = match.groups[0]!!.value // Keep --BEGIN-- and --END-- for certificates.
}
"PRIVATE KEY" -> {
require(pkcs8Base64 == null) { "string includes multiple private keys" }
pkcs8Base64 = match.groups[2]!!.value // Include the contents only for PKCS8.
}
else -> {
throw IllegalArgumentException("unexpected type: $label")
}
}
}
require(certificatePem != null) { "string does not include a certificate" }
require(pkcs8Base64 != null) { "string does not include a private key" }
return decode(certificatePem, pkcs8Base64)
}
private fun decode(certificatePem: String, pkcs8Base64Text: String): HeldCertificate {
val certificate = certificatePem.decodeCertificatePem()
val pkcs8Bytes = pkcs8Base64Text.decodeBase64()
?: throw IllegalArgumentException("failed to decode private key")
// The private key doesn't tell us its type but it's okay because the certificate knows!
val keyType = when (certificate.publicKey) {
is ECPublicKey -> "EC"
is RSAPublicKey -> "RSA"
else -> throw IllegalArgumentException("unexpected key type: ${certificate.publicKey}")
}
val privateKey = decodePkcs8(pkcs8Bytes, keyType)
val keyPair = KeyPair(certificate.publicKey, privateKey)
return HeldCertificate(keyPair, certificate)
}
private fun decodePkcs8(data: ByteString, keyAlgorithm: String): PrivateKey {
try {
val keyFactory = KeyFactory.getInstance(keyAlgorithm)
return keyFactory.generatePrivate(PKCS8EncodedKeySpec(data.toByteArray()))
} catch (e: GeneralSecurityException) {
throw IllegalArgumentException("failed to decode private key", e)
}
}
}
}
| okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt | 1428044451 |
package org.datadozer.index
import org.datadozer.SingleInstancePerThreadObjectPool
import org.datadozer.models.Document
import org.datadozer.models.FieldValue
import org.datadozer.models.TransactionLogEntryType
import org.datadozer.threadPoolExecutorProvider
import org.junit.AfterClass
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.nio.file.Files
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicLong
/*
* Licensed to DataDozer under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. DataDozer licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
class TransactionLogTests {
private val settings = WriterSettings(syncFlush = true)
private val threadPool = threadPoolExecutorProvider()
private val path = Files.createTempDirectory(null)
private val pool = SingleInstancePerThreadObjectPool({ TransactionWriter(path.toFile(), settings) })
private var transactionId = AtomicLong(1)
@Test
fun `Can read write transactions using multiple threads`() {
val runnable = Runnable {
val value = pool.borrowObject()
val doc = Document.newBuilder()
.setId(FieldValue.newBuilder().setStringValue("1"))
.setIndexName("index1")
.build()
val txEntry = transactionLogEntryFactory(1, transactionId.getAndIncrement(),
TransactionLogEntryType.DOC_DELETE, doc)
value.appendEntry(txEntry, 1)
pool.returnObject(value)
}
val tasks = List(999, { _ -> Executors.callable(runnable) })
val result = threadPool.invokeAll(tasks)
for (res in result) {
res.get()
}
val sut = TransactionReader(0L, path.toAbsolutePath().toString())
var txId = 1L
for (t in sut.replayTransactionsByIndex(1)) {
assertEquals(txId, t.modifyIndex)
txId++
}
// We started with x transactions so we should get back x transactions
assertEquals(999, sut.totalTransactionsCount)
}
@Test
fun `Can read back the data from a transaction`() {
val path = Files.createTempDirectory(null)
val sut = TransactionWriter(path.toFile(), settings)
for (i in 1 until 100) {
val doc = Document.newBuilder()
.setId(FieldValue.newBuilder().setIntegerValue(i))
.setIndexName("index1")
.build()
val entry = transactionLogEntryFactory(1, i.toLong(),
TransactionLogEntryType.DOC_DELETE, doc)
sut.appendEntry(entry, 1)
}
// Let read all the data from the transactions
var txId = 1L
val tr = TransactionReader(1, path.toAbsolutePath().toString())
for (t in tr.replayTransactionsByIndex(1)) {
val data = tr.getDataForEntry(t)
assertEquals(txId, data.id.longValue)
assertEquals("index1", data.indexName)
txId++
}
}
@AfterClass
fun cleanup() {
Files.delete(path)
}
} | core/src/test/kotlin/org/datadozer/index/TransactionLogTests.kt | 2897544495 |
package net.yested.core.utils
/**
* A list that can be operated upon to clarify what kinds of animations should happen when updating it in a UI.
* @author Eric Pabst ([email protected])
* Date: 4/4/2017
* Time: 11:49 PM
*/
interface OperableList<T> {
fun size(): Int
fun get(index: Int): T
fun add(index: Int, item: T)
fun removeAt(index: Int): T
fun move(fromIndex: Int, toIndex: Int)
fun indexOf(item: T): Int {
var index = size() - 1
while (index >= 0 && get(index) != item) {
index--
}
return index
}
fun contains(item: T): Boolean = indexOf(item) >= 0
}
fun <T> OperableList<T>.toList(): List<T> = range().map { get(it) }
fun <T> OperableList<T>.range() = (0..(size() - 1))
fun <T> OperableList<T>.reconcileTo(desiredList: List<T>) {
// delete anything that isn't in desiredList
range().reversed().forEach { if (!desiredList.contains(get(it))) removeAt(it) }
val (desiredListWithoutNew, newItems) = desiredList.partition { contains(it) }
var countMovingRight = 0
var countMovingLeft = 0
range().forEach { index ->
val desiredIndex = desiredListWithoutNew.indexOf(get(index))
if (desiredIndex > index) {
countMovingRight++
} else if (desiredIndex < index) {
countMovingLeft++
}
}
val desiredIndices = if (countMovingLeft <= countMovingRight) {
0..(desiredListWithoutNew.size - 1)
} else {
(0..(desiredListWithoutNew.size - 1)).reversed()
}
desiredIndices.forEach { desiredIndex ->
val desiredItem = desiredListWithoutNew[desiredIndex]
val indexToMove = indexOf(desiredItem)
if (indexToMove != desiredIndex) {
move(indexToMove, desiredIndex)
}
}
for (newItem in newItems) {
add(desiredList.indexOf(newItem), newItem)
}
}
open class InMemoryOperableList<T>(val list: MutableList<T>) : OperableList<T> {
var modificationCount = 0
override fun size(): Int = list.size
override fun get(index: Int): T = list[index]
override fun add(index: Int, item: T) {
modificationCount++
list.add(index, item)
}
override fun removeAt(index: Int): T {
modificationCount++
return list.removeAt(index)
}
override fun move(fromIndex: Int, toIndex: Int) {
modificationCount++
val item = list.removeAt(fromIndex)
list.add(toIndex, item)
}
}
| src/commonMain/kotlin/net/yested/core/utils/OperableList.kt | 4138781274 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vanniktech.emoji.twitter.category
import com.vanniktech.emoji.EmojiCategory
import com.vanniktech.emoji.twitter.TwitterEmoji
internal class FlagsCategory : EmojiCategory {
override val categoryNames: Map<String, String>
get() = mapOf(
"en" to "Flags",
"de" to "Flaggen",
)
override val emojis = ALL_EMOJIS
private companion object {
val ALL_EMOJIS: List<TwitterEmoji> = FlagsCategoryChunk0.EMOJIS + FlagsCategoryChunk1.EMOJIS + FlagsCategoryChunk2.EMOJIS
}
}
| emoji-twitter/src/commonMain/kotlin/com/vanniktech/emoji/twitter/category/FlagsCategory.kt | 2167574881 |
/**
* 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 ExtensionClassContainerImpl1links (
val self: Link? = null,
val propertyClass: kotlin.String? = null
) {
}
| clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/ExtensionClassContainerImpl1links.kt | 2683688767 |
/**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.rx
import android.view.View
import android.widget.ListView
import android.widget.TextView
import fr.cph.chicago.R
import fr.cph.chicago.core.activity.map.BusMapActivity
import fr.cph.chicago.core.adapter.BusMapSnippetAdapter
import fr.cph.chicago.core.model.BusArrival
import fr.cph.chicago.util.Util
import io.reactivex.rxjava3.core.SingleObserver
import io.reactivex.rxjava3.disposables.Disposable
import org.apache.commons.lang3.StringUtils
import timber.log.Timber
import java.util.Date
class BusFollowObserver(private val activity: BusMapActivity, private val layout: View, private val view: View, private val loadAll: Boolean) : SingleObserver<List<BusArrival>> {
companion object {
private val util = Util
}
override fun onSubscribe(d: Disposable) {}
override fun onSuccess(busArrivalsParam: List<BusArrival>) {
var busArrivals = busArrivalsParam.toMutableList()
if (!loadAll && busArrivals.size > 7) {
busArrivals = busArrivals.subList(0, 6)
val busArrival = BusArrival(Date(), "added bus", view.context.getString(R.string.bus_all_results), 0, 0, StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY, Date(), false)
busArrivals.add(busArrival)
}
val arrivals = view.findViewById<ListView>(R.id.arrivalsTextView)
val error = view.findViewById<TextView>(R.id.error)
if (busArrivals.isNotEmpty()) {
val ada = BusMapSnippetAdapter(busArrivals)
arrivals.adapter = ada
arrivals.visibility = ListView.VISIBLE
error.visibility = TextView.GONE
} else {
arrivals.visibility = ListView.GONE
error.visibility = TextView.VISIBLE
}
activity.refreshInfoWindow()
}
override fun onError(throwable: Throwable) {
util.handleConnectOrParserException(throwable, layout)
Timber.e(throwable, "Error while loading bus follow")
}
}
| android-app/src/googleplay/kotlin/fr/cph/chicago/rx/BusFollowObserver.kt | 1366982162 |
package com.lasthopesoftware.bluewater.shared.resilience.GivenATwoSecondTwoTriggersTimedCountdownLatch
import com.lasthopesoftware.bluewater.shared.resilience.TimedCountdownLatch
import org.assertj.core.api.Assertions.assertThat
import org.joda.time.Duration
import org.junit.BeforeClass
import org.junit.Test
class WhenTriggeringTheLatch {
companion object {
private var isClosed = false
@JvmStatic
@BeforeClass
fun setup() {
val timedLatch = TimedCountdownLatch(2, Duration.standardSeconds(2))
isClosed = timedLatch.trigger()
}
}
@Test
fun thenTheLatchIsNotClosed() {
assertThat(isClosed).isFalse
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/shared/resilience/GivenATwoSecondTwoTriggersTimedCountdownLatch/WhenTriggeringTheLatch.kt | 2930078439 |
package net.pterodactylus.sone.text
import net.pterodactylus.sone.data.Sone
import net.pterodactylus.sone.test.*
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Test
/**
* Unit test for [SonePart].
*/
class SonePartTest {
private val sone = mock<Sone>()
init {
whenever(sone.profile).thenReturn(mock())
whenever(sone.name).thenReturn("sone")
}
private val part = SonePart(sone)
@Test
fun textIsConstructedFromSonesNiceName() {
assertThat<String>(part.text, equalTo<String>("sone"))
}
}
| src/test/kotlin/net/pterodactylus/sone/text/SonePartTest.kt | 33773260 |
/*
* Copyright 2017 Thomas Volk
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package net.t53k.alkali
import java.util.concurrent.*
object PoisonPill
object Terminated
object Watch
data class Forward(val message: Any)
data class DeadLetter(val message: Any)
internal class AskingActor(private val returnChannel: LinkedBlockingQueue<Any>, private val target: ActorReference, val message: Any): Actor() {
override fun receive(message: Any) = returnChannel.put(message)
override fun before() {
target send message
}
}
class AskTimeoutException(msg: String): RuntimeException(msg)
internal class NameSpace(val name: String) {
companion object {
val system = NameSpace("_system")
}
fun name(actorName: String) = "$name/$actorName"
fun hasNameSpace(actorName: String) = actorName.startsWith(name)
}
class ActorSystemBuilder {
private var defaultActorHandler: ActorSystem.(Any) -> Unit = {}
private var deadLetterHandler: (Any) -> Unit = {}
fun onDefaultActorMessage(defaultActorHandler: ActorSystem.(Any) -> Unit): ActorSystemBuilder {
this.defaultActorHandler = defaultActorHandler
return this
}
fun onDeadLetterMessage(deadLetterHandler: (Any) -> Unit): ActorSystemBuilder {
this.deadLetterHandler = deadLetterHandler
return this
}
fun build(): ActorSystem = ActorSystem(defaultActorHandler, deadLetterHandler)
}
class ActorSystem(defaultActorHandler: ActorSystem.(Any) -> Unit = {}, deadLetterHandler: (Any) -> Unit = {}): ActorFactory {
private class DefaultActor(val defaultActorHandler: ActorSystem.(Any) -> Unit): Actor() {
override fun receive(message: Any) {
defaultActorHandler(system(), message)
}
}
private class DeadLetterActor(val deadLetterHandler: (Any) -> Unit): Actor() {
override fun receive(message: Any) {
deadLetterHandler((message as DeadLetter).message)
}
}
private data class ActorWrapper(val reference: ActorReference, private val actor: Actor){
fun waitForShutdown() {
actor.waitForShutdown()
}
}
private val _actors = mutableMapOf<String, ActorWrapper>()
private val _currentActor = ThreadLocal<ActorReference>()
private var _active = true
private var _deadLetterActor: ActorWrapper
private val MAIN_ACTOR_NAME = NameSpace.system.name("main")
private val DEAD_LETTER_ACTOR_NAME = NameSpace.system.name("deadLetter")
private val WAIT_FOR_SHUTDOWN_INTERVALL = 10L
init {
currentActor(_actor(MAIN_ACTOR_NAME, DefaultActor(defaultActorHandler)))
val deadLetterActor = DeadLetterActor(deadLetterHandler)
_deadLetterActor = ActorWrapper(_start(DEAD_LETTER_ACTOR_NAME, deadLetterActor), deadLetterActor)
}
@Synchronized
override fun <T> actor(name: String, actor: T): ActorReference where T : Actor {
require(!NameSpace.system.hasNameSpace(name)) { "actor name can not start with '${NameSpace.system.name}' !" }
return _actor(name, actor)
}
@Synchronized
private fun <T> _actor(name: String, actor: T): ActorReference where T : Actor {
require (!_actors.contains(name)) { "actor '$name' already exists" }
val actorRef = _start(name, actor)
_actors.put(name, ActorWrapper(actorRef, actor))
return actorRef
}
private fun <T> _start(name: String, actor: T): ActorReference where T : Actor {
passIfActive()
return actor.start(name, this)
}
@Synchronized
internal fun <T> actor(actor: T): ActorReference where T : Actor {
return _start(NameSpace.system.name("anonymous"), actor)
}
@Synchronized
fun find(name: String): ActorReference? = _actors[name]?.reference
internal fun ask(target: ActorReference, message: Any, timeout: Long): Any {
val returnChannel = LinkedBlockingQueue<Any>()
val askingActor = actor(AskingActor(returnChannel, target, message))
try {
return returnChannel.poll(timeout, TimeUnit.MILLISECONDS) ?: throw AskTimeoutException("timeout $timeout ms reached!")
}
finally {
askingActor send PoisonPill
}
}
fun currentActor(): ActorReference = _currentActor.get()
internal fun currentActor(actor: ActorReference) {
_currentActor.set(actor)
}
fun waitForShutdown() {
if(currentActor().name != MAIN_ACTOR_NAME) { throw IllegalStateException("an actor from the same system can not wait system shutdown")}
while (isActive()) {
Thread.sleep(WAIT_FOR_SHUTDOWN_INTERVALL)
}
_actors.forEach { it.value.waitForShutdown() }
_deadLetterActor.waitForShutdown()
}
@Synchronized
fun shutdown() {
passIfActive()
_actors.forEach { it.value.reference send PoisonPill }
_deadLetterActor.reference send PoisonPill
_active = false
}
private fun passIfActive() {
if(!isActive()) { throw IllegalStateException("ActorSystem is not active!") }
}
fun isActive() = _active
internal fun deadLetter(message: Any) {
if(message !is DeadLetter) {
_deadLetterActor.reference send DeadLetter(message)
}
}
}
| src/main/kotlin/net/t53k/alkali/ActorSystem.kt | 2725643423 |
package furhatos.app.demo.flow
import furhatos.app.demo.flow.modes.Parent
import furhatos.flow.kotlin.Utterance
import furhatos.flow.kotlin.furhat
import furhatos.flow.kotlin.state
import furhatos.flow.kotlin.utterance
fun Return(bridge: Utterance = utterance { +"alright" }) = state(Parent) {
onEntry {
furhat.say(utterance = bridge)
goto(Active(returning = true))
}
} | demo-skill/src/main/kotlin/furhatos/app/demo/flow/transitions/return.kt | 1747651272 |
package com.idapgroup.android.rx_mvp
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.idapgroup.android.mvp.impl.Action
import com.idapgroup.android.mvp.impl.BasePresenter
import io.reactivex.*
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.internal.functions.Functions
import io.reactivex.subjects.CompletableSubject
import java.util.*
open class RxBasePresenter<V> : BasePresenter<V>() {
// Optimization for safe subscribe
private val ERROR_CONSUMER: (Throwable) -> Unit = { Functions.ERROR_CONSUMER.accept(it) }
private val EMPTY_ACTION: Action = {}
private val mainHandler = Handler(Looper.getMainLooper())
private val activeTasks = LinkedHashMap<String, Task>()
private val resetTaskStateActionMap = LinkedHashMap<String, Action>()
private var isSavedState = false
private val onDetachViewActionList = mutableListOf<Action>()
private val onSaveStateActionList = mutableListOf<Action>()
inner class Task(val key: String) {
private val subTaskList = ArrayList<Disposable>()
private var subTaskCount = 0
private var cancelled = false
private var completable = CompletableSubject.create()
fun safeAddSubTask(subTask: Disposable) {
runOnUiThread { addSubTask(subTask) }
}
private fun addSubTask(subTask: Disposable) {
checkMainThread()
subTaskList.add(subTask)
++subTaskCount
if(cancelled) subTask.dispose()
}
fun removeSubTask() {
checkMainThread()
--subTaskCount
if(subTaskCount == 0) {
activeTasks.remove(key)
completable.onComplete()
}
}
fun cancel(): Completable {
checkMainThread()
val activeSubTaskList = subTaskList.filter { !it.isDisposed }
val awaitState = await(activeSubTaskList)
activeSubTaskList.forEach { it.dispose() }
cancelled = true
return awaitState
}
fun await(): Completable {
val activeSubTaskList = subTaskList.filter { !it.isDisposed }
return await(activeSubTaskList)
}
fun await(activeSubTaskList: List<Disposable>): Completable {
return if(activeSubTaskList.isEmpty()) Completable.complete() else completable
}
}
override fun onSaveState(savedState: Bundle) {
super.onSaveState(savedState)
onSaveStateActionList.forEach { it() }
onSaveStateActionList.clear()
savedState.putStringArrayList("task_keys", ArrayList(activeTasks.keys))
isSavedState = true
}
override fun onRestoreState(savedState: Bundle) {
super.onRestoreState(savedState)
// Reset tasks only if presenter was destroyed
if(!isSavedState) {
val taskKeyList = savedState.getStringArrayList("task_keys")
taskKeyList.forEach { resetTaskState(it) }
}
isSavedState = false
}
override fun onDetachedView() {
super.onDetachedView()
onDetachViewActionList.forEach { it() }
onDetachViewActionList.clear()
}
/** Preserves link for task by key while it's running */
protected fun <T> taskTracker(taskKey: String): ObservableTransformer<T, T> {
return ObservableTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun <T> Observable<T>.taskTracker(taskKey: String): Observable<T> {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
/** Preserves link for task by key while it's running */
protected fun <T> singleTaskTracker(taskKey: String): SingleTransformer<T, T> {
return SingleTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun <T> Single<T>.taskTracker(taskKey: String): Single<T> {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
/** Preserves link for task by key while it's running */
protected fun completableTaskTracker(taskKey: String): CompletableTransformer {
return CompletableTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun Completable.taskTracker(taskKey: String): Completable {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
/** Preserves link for task by key while it's running */
protected fun <T> maybeTaskTracker(taskKey: String): MaybeTransformer<T, T> {
return MaybeTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun <T> Maybe<T>.taskTracker(taskKey: String): Maybe<T> {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
private fun addTask(taskKey: String): Task {
checkMainThread()
if(activeTasks.containsKey(taskKey)) {
throw IllegalStateException("'$taskKey' is already tracked")
}
val task = Task(taskKey)
activeTasks[taskKey] = task
return task
}
protected fun setResetTaskStateAction(key: String, resetAction: Action) {
resetTaskStateActionMap.put(key, resetAction)
}
protected fun cancelTask(taskKey: String): Completable {
checkMainThread()
val task = activeTasks[taskKey] ?: return Completable.complete()
activeTasks.remove(taskKey)
val completable = task.cancel()
resetTaskState(taskKey)
return completable
}
protected fun awaitTask(taskKey: String): Completable {
return activeTasks[taskKey]?.await() ?: return Completable.complete()
}
protected fun isTaskActive(taskKey: String): Boolean {
checkMainThread()
return activeTasks[taskKey] != null
}
/** Calls preliminarily set a reset task state action */
private fun resetTaskState(taskKey: String) {
val resetTaskAction = resetTaskStateActionMap[taskKey]
if (resetTaskAction == null) {
Log.w(javaClass.simpleName, "Reset task action is not set for task key: " + taskKey)
} else {
execute(resetTaskAction)
}
}
fun <T> Observable<T>.safeSubscribe(
onNext: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER,
onComplete: Action = EMPTY_ACTION
): Disposable {
return subscribe(safeOnItem(onNext), safeOnError(onError), safeOnComplete(onComplete))
}
fun <T> Flowable<T>.safeSubscribe(
onNext: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER,
onComplete: Action = EMPTY_ACTION
): Disposable {
return subscribe(safeOnItem(onNext), safeOnError(onError), safeOnComplete(onComplete))
}
fun <T> Single<T>.safeSubscribe(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER
): Disposable {
return subscribe(safeOnItem(onSuccess), safeOnError(onError))
}
fun Completable.safeSubscribe(
onComplete: Action,
onError: (Throwable) -> Unit = ERROR_CONSUMER
): Disposable {
return subscribe({ execute(onComplete) }, safeOnError(onError))
}
fun <T> Maybe<T>.safeSubscribe(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER,
onComplete: Action = EMPTY_ACTION
): Disposable {
return subscribe(safeOnItem(onSuccess), safeOnError(onError), safeOnComplete(onComplete))
}
fun <T> safeOnItem(onItem: (T) -> Unit): (T) -> Unit {
return { item -> execute { onItem(item) } }
}
fun safeOnComplete(onComplete: Action): () -> Unit {
if(onComplete == EMPTY_ACTION) {
return EMPTY_ACTION
} else {
return { execute(onComplete) }
}
}
fun safeOnError(onError: (Throwable) -> Unit): (Throwable) -> Unit {
if(onError == ERROR_CONSUMER) {
return ERROR_CONSUMER
} else {
return { error: Throwable -> execute { onError(error) } }
}
}
fun <T> Observable<T>.cancelOnDetachView(onSaveState: Boolean = false): Observable<T> {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
fun <T> Flowable<T>.cancelOnDetachView(onSaveState: Boolean = false): Flowable<T> {
return doOnSubscribe {
cancelOnDetachView(object : Disposable {
override fun isDisposed() = throw RuntimeException("Unsupported")
override fun dispose() = it.cancel()
}, onSaveState)
}
}
fun <T> Single<T>.cancelOnDetachView(onSaveState: Boolean = false): Single<T> {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
fun <T> Maybe<T>.cancelOnDetachView(onSaveState: Boolean = false): Maybe<T> {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
fun Completable.cancelOnDetachView(onSaveState: Boolean = false): Completable {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
private fun cancelOnDetachView(disposable: Disposable, onSaveState: Boolean) {
runOnUiThread {
if(view == null || (onSaveState && isSavedState)) {
disposable.dispose()
} else {
if(onSaveState) {
onSaveStateActionList.add({
disposable.dispose()
})
}
onDetachViewActionList.add({
disposable.dispose()
})
}
}
}
private fun checkMainThread(message: String = "Must be call after observeOn(AndroidSchedulers.mainThread())") {
if(!isMainThread()) {
throw IllegalStateException(message)
}
}
private fun runOnUiThread(action: Action) {
if(isMainThread()) {
action()
} else {
mainHandler.post(action)
}
}
private fun isMainThread() = Looper.myLooper() == Looper.getMainLooper()
}
| mvp-utils/src/main/java/com/idapgroup/android/rx_mvp/RxBasePresenter.kt | 2525340355 |
package projects
import configurations.FunctionalTest
import configurations.PerformanceTestCoordinator
import configurations.SanityCheck
import configurations.buildReportTab
import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2018_2.FailureAction
import jetbrains.buildServer.configs.kotlin.v2018_2.IdOwner
import jetbrains.buildServer.configs.kotlin.v2018_2.Project
import model.BuildTypeBucket
import model.CIBuildModel
import model.SpecificBuild
import model.Stage
import model.TestType
class StageProject(model: CIBuildModel, stage: Stage, containsDeferredTests: Boolean, rootProjectUuid: String) : Project({
this.uuid = "${model.projectPrefix}Stage_${stage.stageName.uuid}"
this.id = AbsoluteId("${model.projectPrefix}Stage_${stage.stageName.id}")
this.name = stage.stageName.stageName
this.description = stage.stageName.description
features {
if (stage.specificBuilds.contains(SpecificBuild.SanityCheck)) {
buildReportTab("API Compatibility Report", "report-distributions-binary-compatibility-report.html")
buildReportTab("Incubating APIs Report", "incubation-reports/all-incubating.html")
}
if (!stage.performanceTests.isEmpty()) {
buildReportTab("Performance", "report-performance-performance-tests.zip!report/index.html")
}
}
val specificBuildTypes = stage.specificBuilds.map {
it.create(model, stage)
}
specificBuildTypes.forEach { buildType(it) }
stage.performanceTests.forEach {
buildType(PerformanceTestCoordinator(model, it, stage))
}
stage.functionalTests.forEach { testCoverage ->
val isSoakTest = testCoverage.testType == TestType.soak
if (isSoakTest) {
buildType(FunctionalTest(model, testCoverage, stage = stage))
} else {
val functionalTests = FunctionalTestProject(model, testCoverage, stage)
subProject(functionalTests)
if (stage.functionalTestsDependOnSpecificBuilds) {
specificBuildTypes.forEach { specificBuildType ->
functionalTests.addDependencyForAllBuildTypes(specificBuildType)
}
}
if (!(stage.functionalTestsDependOnSpecificBuilds && stage.specificBuilds.contains(SpecificBuild.SanityCheck)) && stage.dependsOnSanityCheck) {
functionalTests.addDependencyForAllBuildTypes(AbsoluteId(SanityCheck.buildTypeId(model)))
}
}
}
if (containsDeferredTests) {
val deferredTestsProject = Project {
uuid = "${rootProjectUuid}_deferred_tests"
id = AbsoluteId(uuid)
name = "Test coverage deferred from Quick Feedback and Ready for Merge"
model.buildTypeBuckets
.filter(BuildTypeBucket::containsSlowTests)
.forEach { bucket ->
FunctionalTestProject.missingTestCoverage
.filter { testConfig ->
bucket.hasTestsOf(testConfig.testType)
}
.forEach { testConfig ->
bucket.forTestType(testConfig.testType).forEach {
buildType(FunctionalTest(model, testConfig, it.getSubprojectNames(), stage, it.name))
}
}
}
}
subProject(deferredTestsProject)
}
})
private fun Project.addDependencyForAllBuildTypes(dependency: IdOwner) {
buildTypes.forEach { functionalTestBuildType ->
functionalTestBuildType.dependencies {
dependency(dependency) {
snapshot {
onDependencyFailure = FailureAction.CANCEL
onDependencyCancel = FailureAction.CANCEL
}
}
}
}
}
| .teamcity/Gradle_Check/projects/StageProject.kt | 676342194 |
package jp.toastkid.yobidashi.main
import androidx.fragment.app.FragmentManager
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.mockk
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.yobidashi.browser.BrowserFragment
import jp.toastkid.yobidashi.browser.floating.FloatingPreview
import jp.toastkid.yobidashi.browser.page_search.PageSearcherModule
import jp.toastkid.yobidashi.menu.MenuViewModel
import jp.toastkid.yobidashi.tab.TabAdapter
import org.junit.After
import org.junit.Before
import org.junit.Test
/**
* @author toastkidjp
*/
class OnBackPressedUseCaseTest {
private lateinit var onBackPressedUseCase: OnBackPressedUseCase
@MockK
private lateinit var tabListUseCase: TabListUseCase
@MockK
private lateinit var menuVisibility: () -> Boolean
@MockK
private lateinit var menuViewModel: MenuViewModel
@MockK
private lateinit var pageSearcherModule: PageSearcherModule
@MockK
private lateinit var floatingPreview: FloatingPreview
@MockK
private lateinit var tabs: TabAdapter
@MockK
private lateinit var onEmptyTabs: () -> Unit
@MockK
private lateinit var replaceToCurrentTab: TabReplacingUseCase
@MockK
private lateinit var supportFragmentManager: FragmentManager
@Before
fun setUp() {
MockKAnnotations.init(this)
onBackPressedUseCase = OnBackPressedUseCase(
tabListUseCase,
menuVisibility,
menuViewModel,
pageSearcherModule,
{ floatingPreview },
tabs,
onEmptyTabs,
replaceToCurrentTab,
supportFragmentManager
)
every { menuViewModel.close() }.just(Runs)
}
@Test
fun testTabListUseCaseIsTrue() {
every { tabListUseCase.onBackPressed() }.returns(true)
every { menuVisibility.invoke() }.returns(true)
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 0) { menuVisibility.invoke() }
verify (exactly = 0) { menuViewModel.close() }
}
@Test
fun testMenuIsVisible() {
every { tabListUseCase.onBackPressed() }.returns(false)
every { menuVisibility.invoke() }.returns(true)
every { pageSearcherModule.isVisible() }.returns(false)
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 1) { menuVisibility.invoke() }
verify (exactly = 1) { menuViewModel.close() }
verify (exactly = 0) { pageSearcherModule.isVisible() }
}
@Test
fun testPageSearcherModuleIsVisible() {
every { tabListUseCase.onBackPressed() }.returns(false)
every { menuVisibility.invoke() }.returns(false)
every { pageSearcherModule.isVisible() }.returns(true)
every { pageSearcherModule.hide() }.just(Runs)
every { floatingPreview.onBackPressed() }.answers { true }
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 1) { menuVisibility.invoke() }
verify (exactly = 0) { menuViewModel.close() }
verify (exactly = 1) { pageSearcherModule.isVisible() }
verify (exactly = 1) { pageSearcherModule.hide() }
verify (exactly = 0) { floatingPreview.onBackPressed() }
}
@Test
fun testFloatingPreviewIsVisible() {
every { tabListUseCase.onBackPressed() }.returns(false)
every { menuVisibility.invoke() }.returns(false)
every { pageSearcherModule.isVisible() }.returns(false)
every { pageSearcherModule.hide() }.just(Runs)
every { floatingPreview.onBackPressed() }.answers { false }
every { floatingPreview.hide() }.just(Runs)
val fragment = mockk<BrowserFragment>()
every { supportFragmentManager.findFragmentById(any()) }.answers { fragment }
every { fragment.pressBack() }.returns(true)
every { tabs.closeTab(any()) }.just(Runs)
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 1) { menuVisibility.invoke() }
verify (exactly = 0) { menuViewModel.close() }
verify (exactly = 1) { pageSearcherModule.isVisible() }
verify (exactly = 0) { pageSearcherModule.hide() }
verify (exactly = 1) { floatingPreview.onBackPressed() }
verify (exactly = 0) { floatingPreview.hide() }
verify (exactly = 1) { supportFragmentManager.findFragmentById(any()) }
verify (exactly = 1) { fragment.pressBack() }
verify (exactly = 0) { tabs.closeTab(any()) }
}
@After
fun tearDown() {
unmockkAll()
}
} | app/src/test/java/jp/toastkid/yobidashi/main/OnBackPressedUseCaseTest.kt | 2347232340 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import org.rust.lang.core.psi.RsUseGroup
import org.rust.lang.core.psi.RsUseSpeck
val RsUseGroup.parentUseSpeck: RsUseSpeck get() = parent as RsUseSpeck
| src/main/kotlin/org/rust/lang/core/psi/ext/RsUseGroup.kt | 2575803188 |
package eu.kanade.tachiyomi.source.model
import android.net.Uri
import eu.kanade.tachiyomi.network.ProgressListener
import rx.subjects.Subject
import tachiyomi.source.model.PageUrl
open class Page(
val index: Int,
val url: String = "",
var imageUrl: String? = null,
@Transient var uri: Uri? = null // Deprecated but can't be deleted due to extensions
) : ProgressListener {
val number: Int
get() = index + 1
@Transient
@Volatile
var status: Int = 0
set(value) {
field = value
statusSubject?.onNext(value)
statusCallback?.invoke(this)
}
@Transient
@Volatile
var progress: Int = 0
set(value) {
field = value
statusCallback?.invoke(this)
}
@Transient
private var statusSubject: Subject<Int, Int>? = null
@Transient
private var statusCallback: ((Page) -> Unit)? = null
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
progress = if (contentLength > 0) {
(100 * bytesRead / contentLength).toInt()
} else {
-1
}
}
fun setStatusSubject(subject: Subject<Int, Int>?) {
this.statusSubject = subject
}
fun setStatusCallback(f: ((Page) -> Unit)?) {
statusCallback = f
}
companion object {
const val QUEUE = 0
const val LOAD_PAGE = 1
const val DOWNLOAD_IMAGE = 2
const val READY = 3
const val ERROR = 4
}
}
fun Page.toPageUrl(): PageUrl {
return PageUrl(
url = this.imageUrl ?: this.url
)
}
fun PageUrl.toPage(index: Int): Page {
return Page(
index = index,
imageUrl = this.url
)
}
| app/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt | 308125051 |
//@file:Suppress("unused")
//
//package net.xpece.android.app
//
//import android.content.Context
//import android.support.annotation.RequiresApi
//import java.lang.ref.WeakReference
//import java.util.*
//import kotlin.reflect.KProperty
//
//private val systemServiceDelegates = object :
// ThreadLocal<WeakHashMap<Context, SystemServiceDelegate>>() {
// override fun initialValue() = WeakHashMap<Context, SystemServiceDelegate>()
//}
//
//val Context.systemServiceDelegate: SystemServiceDelegate
// get() {
// val delegates = systemServiceDelegates.get()
// var delegate = delegates[this]
// if (delegate == null) {
// delegate = SystemServiceDelegate(this)
// delegates[this] = delegate
// }
// return delegate
// }
//
//class SystemServiceDelegate internal constructor(context: Context) {
// private val contextRef = WeakReference(context)
// val context = contextRef.get()!!
//
// @RequiresApi(23)
// inline operator fun <reified S> getValue(thisRef: Any?, property: KProperty<*>): S {
// return context.getSystemServiceOrThrow()
// }
//}
| commons-services/src/main/java/net/xpece/android/app/SystemServiceDelegates.kt | 4073293237 |
package verseczi.intervaltimer
import android.app.Activity
import android.app.AlertDialog
import android.content.*
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.text.SpannableStringBuilder
import android.view.MotionEvent
import android.view.View
import android.view.View.OnClickListener
import android.widget.*
import java.util.concurrent.TimeUnit
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.CompoundButton
import android.widget.CompoundButton.OnCheckedChangeListener
import verseczi.intervaltimer.backgroundTask.appChooser
import verseczi.intervaltimer.backgroundTask.rootAccess
import verseczi.intervaltimer.data.Database
import verseczi.intervaltimer.helpers.bindView
class Main : AppCompatActivity() {
// Views
// @content_main_timelapse_calc.xml
private val etImgQty: EditText by bindView(R.id.etIMG_NUM)
private val etFPS: EditText by bindView(R.id.etFPS)
private val etInterval: EditText by bindView(R.id.etInterval)
// @content_main_infocard
private val tvImgQty: TextView by bindView(R.id.tvImg_num)
private val tvClipLength: TextView by bindView(R.id.tvCliplength)
private val tvDuration: TextView by bindView(R.id.tvDuration)
// @content_main_coordinate
private val tvCoordX: TextView by bindView(R.id.tv_CoordX)
private val tvCoordY: TextView by bindView(R.id.tv_CoordY)
// @content_main_delay
private val etDelay: EditText by bindView(R.id.etDelay)
private val swDelay: Switch by bindView(R.id.delayed_switch)
// @content_main_repeat
private val swEndlessrepeat: Switch by bindView(R.id.endless_switch)
// @content_main_app_chooser
private val ivAppIcon: ImageView by bindView(R.id.app_icon_n)
private val tvAppName: TextView by bindView(R.id.app_name_n)
private val tvAppPackageName: TextView by bindView(R.id.package_name_n)
// Buttons
private val bnStart: Button by bindView(R.id.start_button)
private val bnCoordinates: Button by bindView(R.id.getcoordinates)
private val bnChooseApp: Button by bindView(R.id.choose_app)
private val bnDelayMinus: Button by bindView(R.id.delay_minus)
private val bnDelayPlus: Button by bindView(R.id.delay_plus)
// Text of the views
var _ImgQty: Int
get() = etImgQty.text.toString().toInt()
set(value) {
etImgQty.text = SpannableStringBuilder("$value")
}
var _Interval: Int
get() = etInterval.text.toString().toInt()
set(value) {
etInterval.text = SpannableStringBuilder("$value")
}
var _FPS: Int
get() = etFPS.text.toString().toInt()
set(value) {
etFPS.text = SpannableStringBuilder("$value")
}
var _tvImgQty: Int
get() = tvImgQty.text.toString().toInt()
set(value) {
tvImgQty.text = value.toString()
}
var _ClipLength: Int
get() {
val durationRegex = tvClipLength.text.toString().split(":".toRegex())
return durationRegex[0].toInt() * 3600 + durationRegex[1].toInt() * 60 + durationRegex[2].toInt()
}
set(value) {
tvClipLength.text = formatTime(value)
}
var _Duration: Int
get() {
val durationRegex = tvDuration.text.toString().split(":".toRegex())
return durationRegex[0].toInt() * 3600 + durationRegex[1].toInt() * 60 + durationRegex[2].toInt()
}
set(value) {
tvDuration.text = formatTime(value)
}
var _coordX: Int
get() = tvCoordX.text.toString().toInt()
set(value) {
tvCoordX.text = SpannableStringBuilder("$value")
}
var _coordY: Int
get() = tvCoordY.text.toString().toInt()
set(value) {
tvCoordY.text = SpannableStringBuilder("$value")
}
var _delay: Int
get() = etDelay.text.toString().toInt()
set(value) {
etDelay.text = SpannableStringBuilder("$value")
}
var _delayed: Boolean
get() = swDelay.isChecked
set(value) {
swDelay.isChecked = value
}
var _endlessRepeat: Boolean
get() = swEndlessrepeat.isChecked
set(value) {
swEndlessrepeat.isChecked = value
}
var _appIcon: Drawable
get() = ivAppIcon.drawable
set(value) {
ivAppIcon.setImageDrawable(value)
}
var _appName: String
get() = tvAppName.text.toString()
set(value) {
tvAppName.text = value
}
var _appPackageName: String
get() = tvAppPackageName.text.toString()
set(value) {
tvAppPackageName.text = value
}
// Database
private lateinit var db: Database
// PackageManager
private lateinit var pm:PackageManager
// Context @Main
private lateinit var mContext: Context
private lateinit var _intentService: Intent
private var _clickingService: clickingService? = null
private var isCancelled: Boolean = false
private var currentProgressstate: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolbar) as Toolbar)
db = Database(this)
pm = packageManager
mContext = this
// Init
_ImgQty = db.imgQty
_Interval = db.interval
_coordX = db.coordinateX
_coordY = db.coordinateY
_delay = db.delay
_delayed = db.delayed
if(!db.delayed) {
_delay = 0
etDelay.isEnabled = false
bnDelayMinus.isEnabled = false
bnDelayPlus.isEnabled = false
bnDelayMinus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
bnDelayPlus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
}
_tvImgQty = db.imgQty
_FPS = db.FPS
_ClipLength = db.imgQty / db.FPS
_Duration = db.interval * db.imgQty
_endlessRepeat = db.endlessRepeat
try {
val appinfo: ApplicationInfo = pm.getApplicationInfo(db.packageName, 0)
_appIcon = pm.getApplicationIcon(appinfo)
_appName = pm.getApplicationLabel(appinfo).toString()
_appPackageName = db.packageName
} catch (e: PackageManager.NameNotFoundException) {
// :(
}
val clickListener: OnClickListener = OnClickListener { v ->
when (v.id) {
R.id.start_button -> startClickingService()
R.id.getcoordinates -> {
val intent = Intent(mContext, GetCoordinates::class.java)
startActivityForResult(intent, 1)
}
R.id.choose_app -> appChooser(this@Main, ivAppIcon, tvAppName, tvAppPackageName).execute()
}
}
class GenericTextWatcher(val view: View) : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
when (view) {
etImgQty -> {
if (etImgQty.text.toString() == "")
_ImgQty = 0
db.imgQty = _ImgQty
updateInfoBox(db.imgQty, db.FPS, db.interval)
}
etFPS -> {
if (etFPS.text.toString() == "")
_FPS = 0
db.FPS = _FPS
updateInfoBox(db.imgQty, db.FPS, db.interval)
}
etInterval -> {
if (etInterval.text.toString() == "")
_Interval = 0
db.interval = _Interval
updateInfoBox(db.imgQty, db.FPS, db.interval)
}
etDelay -> {
if (etDelay.text.toString() == "")
_delay = 0
if(_delay == 0) {
_delayed = false
db.delayed = false
db.delay = 0
} else
db.delay = _delay
}
}
}
}
class isCheckedListener(val view: View) : OnCheckedChangeListener {
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
when (view) {
swDelay -> {
if (isChecked) {
db.delayed = true
if(_delay == 0)
db.delay = db.defaultValue(db._DELAY) as Int
_delay = db.delay
etDelay.isEnabled = true
bnDelayMinus.isEnabled = true
bnDelayPlus.isEnabled = true
bnDelayMinus.background.clearColorFilter()
bnDelayPlus.background.clearColorFilter()
} else {
db.delayed = false
_delay = 0
etDelay.isEnabled = false
bnDelayMinus.isEnabled = false
bnDelayPlus.isEnabled = false
bnDelayMinus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
bnDelayPlus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
}
}
}
}
}
etImgQty.addTextChangedListener(GenericTextWatcher(etImgQty))
etFPS.addTextChangedListener(GenericTextWatcher(etFPS))
etInterval.addTextChangedListener(GenericTextWatcher(etInterval))
etDelay.addTextChangedListener(GenericTextWatcher(etDelay))
swDelay.setOnCheckedChangeListener(isCheckedListener(swDelay))
swEndlessrepeat.setOnCheckedChangeListener(isCheckedListener(swEndlessrepeat))
bnStart.setOnClickListener(clickListener)
bnCoordinates.setOnClickListener(clickListener)
bnChooseApp.setOnClickListener(clickListener)
_intentService = Intent(this@Main, clickingService::class.java)
bindService(_intentService, mConnection, 0)
if (savedInstanceState == null) {
val extras = intent.extras
if (extras == null) {
isCancelled = false
} else {
isCancelled = extras.getBoolean("cancelled")
}
} else {
isCancelled = savedInstanceState.getSerializable("cancalled") as Boolean
}
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
val v: View = currentFocus
if ((ev.action == MotionEvent.ACTION_UP || ev.action == MotionEvent.ACTION_MOVE) && v is EditText && !v.javaClass.name.startsWith("android.webkit.")) {
val scrcoords: IntArray = IntArray(2)
v.getLocationOnScreen(scrcoords)
val x: Float = ev.rawX + v.getLeft() - scrcoords[0]
val y: Float = ev.rawY + v.getTop() - scrcoords[1]
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
v.clearFocus()
hideKeyboard((this))
}
}
return super.dispatchTouchEvent(ev)
}
fun hideKeyboard(activity: Activity) {
if (activity.window != null && activity.window.decorView != null) {
val imm: InputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(activity.window.decorView.windowToken, 0)
}
}
val mConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName) {
_clickingService = null
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val mLocalBinder = service as clickingService.LocalBinder
_clickingService = mLocalBinder.getServerInstance()
if(!isCancelled)
_clickingService?.startClicking()
if (isCancelled) {
db.cancelled = false
isCancelled = false
currentProgressstate = _clickingService?.getProgress() as Int
_clickingService?.stopClicking()
val builder = AlertDialog.Builder(mContext)
builder.setTitle("Result")
builder.setMessage("Progress: " + currentProgressstate + " / " + db.imgQty + "\n " +
"Do you want to continue?")
builder.setPositiveButton("Yes") { dialog, id ->
_clickingService?.resumeClicking()
startChoosedApp()
}
builder.setNegativeButton("No") { dialog, id ->
_clickingService?.stopService()
dialog.cancel()
}
builder.setOnCancelListener {
_clickingService?.stopService()
}
val dialog = builder.create()
dialog.show()
}
}
}
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
context.unregisterReceiver(this)
val access = intent.getBooleanExtra("accessGranted", false)
if (access) {
if(isCancelled)
startClickingService(db.imgQty - currentProgressstate, false, true)
else
startClickingService(db.imgQty, db.delayed, true)
} else {
rootDenied()
}
}
}
fun rootDenied() {
val builder = AlertDialog.Builder(mContext)
builder.setTitle("Root access denied!")
builder.setMessage("You need to have root access for your device!")
builder.setPositiveButton("Ok") { dialog, id -> dialog.cancel() }
builder.create().show()
}
fun didntChooseApp() {
val builder = AlertDialog.Builder(mContext)
builder.setTitle("Wrong settings!")
builder.setMessage("You didn't choose any app!")
builder.setPositiveButton("Ok") { dialog, id -> dialog.cancel() }
builder.create().show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
if (requestCode == 1) {
if (resultCode == 1) {
db.coordinateX = data.getIntExtra("coordx", 0)
db.coordinateY = data.getIntExtra("coordy", 0)
tvCoordX.text = Integer.toString(db.coordinateX)
tvCoordY.text = Integer.toString(db.coordinateY)
}
}
}//onActivityResult
fun startClickingService(_imqty: Int = db.imgQty, delayed: Boolean = db.delayed, rootGranted: Boolean = false) {
if(pm.getLaunchIntentForPackage(db.packageName) != null) {
// Getting root access
if (!rootGranted) {
val rootaccess = rootAccess(this@Main)
val filtera = IntentFilter()
filtera.addAction(rootaccess.rootaccess)
registerReceiver(receiver, filtera)
rootaccess.execute()
}
// Start and bind service if we have root access
if (rootGranted) {
bindService(_intentService, mConnection, 0)
_intentService.putExtra("imgqty", _imqty)
_intentService.putExtra("delayed", delayed)
startService(_intentService)
startChoosedApp()
}
} else
didntChooseApp()
}
fun startChoosedApp () {
try {
pm = packageManager
var LaunchIntent: Intent = pm.getLaunchIntentForPackage(db.packageName)
startActivity( LaunchIntent )
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
fun updateInfoBox(imgQty: Int, fps: Int, interval: Int) {
_tvImgQty = imgQty
_ClipLength = imgQty / fps
_Duration = interval * imgQty
}
fun formatTime(value: Int): String {
val durationS = value.toLong()
return String.format("%02d:%02d:%02d", TimeUnit.SECONDS.toHours(durationS),
TimeUnit.SECONDS.toMinutes(durationS) - TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(durationS)),
durationS - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(durationS)))
}
fun increaseInteger(view: View) {
var tv: TextView = findViewById(view.labelFor) as TextView
tv.text = (tv.text.toString().toInt() + 1).toString()
}
fun decreaseInteger(view: View) {
var tv: TextView = findViewById(view.labelFor) as TextView
tv.text = (tv.text.toString().toInt() - 1).toString()
}
} | app/src/main/java/verseczi/intervaltimer/Main.kt | 2518671295 |
package org.jetbrains.dokka.gradle
import org.jetbrains.dokka.DokkaException
import java.io.File
/**
* @see DokkaMultiModuleFileLayout.targetChildOutputDirectory
* @see NoCopy
* @see CompactInParent
*/
fun interface DokkaMultiModuleFileLayout {
/**
* @param parent: The [DokkaMultiModuleTask] that is initiating a composite documentation run
* @param child: Some child task registered in [parent]
* @return The target output directory of the [child] dokka task referenced by [parent]. This should
* be unique for all registered child tasks.
*/
fun targetChildOutputDirectory(parent: DokkaMultiModuleTask, child: AbstractDokkaTask): File
/**
* Will link to the original [AbstractDokkaTask.outputDirectory]. This requires no copying of the output files.
*/
object NoCopy : DokkaMultiModuleFileLayout {
override fun targetChildOutputDirectory(parent: DokkaMultiModuleTask, child: AbstractDokkaTask): File =
child.outputDirectory.getSafe()
}
/**
* Will point to a subfolder inside the output directory of the parent.
* The subfolder will follow the structure of the gradle project structure
* e.g.
* :parentProject:firstAncestor:secondAncestor will be be resolved to
* {parent output directory}/firstAncestor/secondAncestor
*/
object CompactInParent : DokkaMultiModuleFileLayout {
override fun targetChildOutputDirectory(parent: DokkaMultiModuleTask, child: AbstractDokkaTask): File {
val relativeProjectPath = parent.project.relativeProjectPath(child.project.path)
val relativeFilePath = relativeProjectPath.replace(":", File.separator)
check(!File(relativeFilePath).isAbsolute) { "Unexpected absolute path $relativeFilePath" }
return parent.outputDirectory.getSafe().resolve(relativeFilePath)
}
}
}
internal fun DokkaMultiModuleTask.targetChildOutputDirectory(
child: AbstractDokkaTask
): File = fileLayout.get().targetChildOutputDirectory(this, child)
internal fun DokkaMultiModuleTask.copyChildOutputDirectories() {
childDokkaTasks.forEach { child ->
this.copyChildOutputDirectory(child)
}
}
internal fun DokkaMultiModuleTask.copyChildOutputDirectory(child: AbstractDokkaTask) {
val targetChildOutputDirectory = project.file(fileLayout.get().targetChildOutputDirectory(this, child))
val sourceChildOutputDirectory = child.outputDirectory.getSafe()
/* Pointing to the same directory -> No copy necessary */
if (sourceChildOutputDirectory.absoluteFile == targetChildOutputDirectory.absoluteFile) {
return
}
/* Cannot target *inside* the original folder */
if (targetChildOutputDirectory.absoluteFile.startsWith(sourceChildOutputDirectory.absoluteFile)) {
throw DokkaException(
"Cannot re-locate output directory into itself.\n" +
"sourceChildOutputDirectory=${sourceChildOutputDirectory.path}\n" +
"targetChildOutputDirectory=${targetChildOutputDirectory.path}"
)
}
/* Source output directory is empty -> No copy necessary */
if (!sourceChildOutputDirectory.exists()) {
return
}
sourceChildOutputDirectory.copyRecursively(targetChildOutputDirectory, overwrite = true)
}
| runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/DokkaMultiModuleFileLayout.kt | 3414043838 |
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.config
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.migration.SerializationMigrator
import com.netflix.spinnaker.q.redis.RedisClusterDeadMessageHandler
import com.netflix.spinnaker.q.redis.RedisClusterQueue
import com.netflix.spinnaker.q.redis.RedisDeadMessageHandler
import com.netflix.spinnaker.q.redis.RedisQueue
import java.net.URI
import java.time.Clock
import java.time.Duration
import java.util.Optional
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import redis.clients.jedis.HostAndPort
import redis.clients.jedis.Jedis
import redis.clients.jedis.JedisCluster
import redis.clients.jedis.JedisPool
import redis.clients.jedis.Protocol
import redis.clients.jedis.util.Pool
@Configuration
@EnableConfigurationProperties(RedisQueueProperties::class)
@ConditionalOnProperty(
value = ["keiko.queue.redis.enabled"],
havingValue = "true",
matchIfMissing = true
)
class RedisQueueConfiguration {
@Bean
@ConditionalOnMissingBean(GenericObjectPoolConfig::class)
fun redisPoolConfig() = GenericObjectPoolConfig<Any>().apply {
blockWhenExhausted = false
maxWaitMillis = 2000
}
@Bean
@ConditionalOnMissingBean(name = ["queueRedisPool"])
@ConditionalOnProperty(
value = ["redis.cluster-enabled"],
havingValue = "false",
matchIfMissing = true
)
fun queueRedisPool(
@Value("\${redis.connection:redis://localhost:6379}") connection: String,
@Value("\${redis.timeout:2000}") timeout: Int,
redisPoolConfig: GenericObjectPoolConfig<Any>
) =
URI.create(connection).let { cx ->
val port = if (cx.port == -1) Protocol.DEFAULT_PORT else cx.port
val db = if (cx.path.isNullOrEmpty()) {
Protocol.DEFAULT_DATABASE
} else {
cx.path.substringAfter("/").toInt()
}
val password = cx.userInfo?.substringAfter(":")
JedisPool(redisPoolConfig, cx.host, port, timeout, password, db)
}
@Bean
@ConditionalOnMissingBean(name = ["queue"])
@ConditionalOnProperty(
value = ["redis.cluster-enabled"],
havingValue = "false",
matchIfMissing = true
)
fun queue(
@Qualifier("queueRedisPool") redisPool: Pool<Jedis>,
redisQueueProperties: RedisQueueProperties,
clock: Clock,
deadMessageHandler: RedisDeadMessageHandler,
publisher: EventPublisher,
redisQueueObjectMapper: ObjectMapper,
serializationMigrator: Optional<SerializationMigrator>
) =
RedisQueue(
queueName = redisQueueProperties.queueName,
pool = redisPool,
clock = clock,
mapper = redisQueueObjectMapper,
deadMessageHandlers = listOf(deadMessageHandler),
publisher = publisher,
ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()),
serializationMigrator = serializationMigrator
)
@Bean
@ConditionalOnMissingBean(name = ["redisDeadMessageHandler"])
@ConditionalOnProperty(
value = ["redis.cluster-enabled"],
havingValue = "false",
matchIfMissing = true
)
fun redisDeadMessageHandler(
@Qualifier("queueRedisPool") redisPool: Pool<Jedis>,
redisQueueProperties: RedisQueueProperties,
clock: Clock
) =
RedisDeadMessageHandler(
deadLetterQueueName = redisQueueProperties.deadLetterQueueName,
pool = redisPool,
clock = clock
)
@Bean
@ConditionalOnMissingBean(name = ["queueRedisCluster"])
@ConditionalOnProperty(value = ["redis.cluster-enabled"])
fun queueRedisCluster(
@Value("\${redis.connection:redis://localhost:6379}") connection: String,
@Value("\${redis.timeout:2000}") timeout: Int,
@Value("\${redis.maxattempts:4}") maxAttempts: Int,
redisPoolConfig: GenericObjectPoolConfig<Any>
): JedisCluster {
URI.create(connection).let { cx ->
val port = if (cx.port == -1) Protocol.DEFAULT_PORT else cx.port
val password = cx.userInfo?.substringAfter(":")
return JedisCluster(
HostAndPort(cx.host, port),
timeout,
timeout,
maxAttempts,
password,
redisPoolConfig
)
}
}
@Bean
@ConditionalOnMissingBean(name = ["queue", "clusterQueue"])
@ConditionalOnProperty(value = ["redis.cluster-enabled"])
fun clusterQueue(
@Qualifier("queueRedisCluster") cluster: JedisCluster,
redisQueueProperties: RedisQueueProperties,
clock: Clock,
deadMessageHandler: RedisClusterDeadMessageHandler,
publisher: EventPublisher,
redisQueueObjectMapper: ObjectMapper,
serializationMigrator: Optional<SerializationMigrator>
) =
RedisClusterQueue(
queueName = redisQueueProperties.queueName,
jedisCluster = cluster,
clock = clock,
mapper = redisQueueObjectMapper,
deadMessageHandlers = listOf(deadMessageHandler),
publisher = publisher,
ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()),
serializationMigrator = serializationMigrator
)
@Bean
@ConditionalOnMissingBean(name = ["redisClusterDeadMessageHandler"])
@ConditionalOnProperty(value = ["redis.cluster-enabled"])
fun redisClusterDeadMessageHandler(
@Qualifier("queueRedisCluster") cluster: JedisCluster,
redisQueueProperties: RedisQueueProperties,
clock: Clock
) = RedisClusterDeadMessageHandler(
deadLetterQueueName = redisQueueProperties.deadLetterQueueName,
jedisCluster = cluster,
clock = clock
)
@Bean
@ConditionalOnMissingBean
fun redisQueueObjectMapper(properties: Optional<ObjectMapperSubtypeProperties>): ObjectMapper =
ObjectMapper().apply {
registerModule(KotlinModule())
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
SpringObjectMapperConfigurer(
properties.orElse(ObjectMapperSubtypeProperties())
).registerSubtypes(this)
}
}
| keiko-redis-spring/src/main/kotlin/com/netflix/spinnaker/config/RedisQueueConfiguration.kt | 2730905012 |
package common.view
import android.view.View
import android.widget.FrameLayout
import common.robolectric
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class RecyclerViewTest {
@Test fun testClicks() {
var clicks = 0
val v = View(robolectric)
val a = RecyclerViewAdapter({ 1 },
{ 1 },
{ p, type -> v },
{ vh, pos -> },
{ clicks++ })
a.onCreateViewHolder(FrameLayout(robolectric), 1)
v.performClick()
assertThat(clicks).isEqualTo(1)
v.performClick()
v.performClick()
assertThat(clicks).isEqualTo(3)
}
@Test fun testBinds() {
var binds = 0
val a = RecyclerViewAdapter({ 1 },
{ 1 },
{ p, type -> View(robolectric) },
{ vh, pos -> binds++ },
{ })
val vh = a.onCreateViewHolder(FrameLayout(robolectric), 1)
a.onBindViewHolder(vh, 1)
assertThat(binds).isEqualTo(1)
a.onBindViewHolder(vh, 2)
a.onBindViewHolder(vh, 3)
assertThat(binds).isEqualTo(3)
}
@Test fun testInflates() {
}
} | app/src/test/kotlin/common/view/RecyclerViewTest.kt | 3572457902 |
/*
* 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.
*/
// TEST PROCESSOR: ResolveJavaTypeProcessor
// EXPECTED:
// C<*kotlin.Any?>
// C.<init>.X?
// C<*kotlin.Any?>
// kotlin.Int
// kotlin.String?
// kotlin.collections.MutableSet<*kotlin.Any?>?
// kotlin.Unit
// kotlin.IntArray?
// C.T?
// C.PFun.P?
// kotlin.collections.MutableList<out kotlin.collections.MutableSet<kotlin.Double?>?>?
// kotlin.collections.MutableList<in kotlin.collections.MutableList<out kotlin.Double?>?>?
// Bar?
// kotlin.Array<Bar?>?
// Foo<Base.T?, Base.Inner.P?>?
// Bar<Base.Inner.P?, Base.T?>?
// kotlin.collections.MutableList<Base.T?>?
// kotlin.Unit
// Base.T?
// kotlin.Unit
// kotlin.Array<Base.T?>?
// kotlin.Unit
// kotlin.Array<Base.T?>?
// kotlin.Unit
// kotlin.collections.MutableList<Base.T?>?
// kotlin.Unit
// Base.T?
// kotlin.Unit
// kotlin.Array<Base.T?>?
// kotlin.Unit
// kotlin.Array<Base.T?>?
// kotlin.Unit
// Base<Another.T?, Another.T?>?
// kotlin.Int
// kotlin.Int
// JavaEnum
// kotlin.Unit
// kotlin.Array<JavaEnum?>?
// kotlin.String?
// JavaEnum?
// END
// FILE: a.kt
annotation class Test
@Test
class Foo<P>: C<P>() {
}
class Bar
// FILE: C.java
import java.util.List;
import java.util.Set;
public class C<T> {
public C() {}
// to reproduce the case where type reference is owned by a constructor
public <X> C(X x) {}
public int intFun() {}
public String strFun() {}
public void wildcardParam(Set<?> param1) {}
public int[] intArrayFun() {}
public T TFoo() {}
public <P> P PFun() {}
public List<? extends Set<Double>> extendsSetFun() {}
public List<? super List<? extends Double>> extendsListTFun() {}
public Bar BarFun() {}
public Bar[] BarArryFun() {}
}
// FILE: Base.java
import java.util.List;
class Foo<T1,T2> {}
class Bar<T1, T2> {}
class Base<T,P> {
void genericT(List<T> t){};
void singleT(T t){};
void varargT(T... t){};
void arrayT(T[] t){};
class Inner<P> {
void genericT(List<T> t){};
void singleT(T t){};
void varargT(T... t){};
void arrayT(T[] t){};
Foo<T, P> foo;
Bar<P, T> bar;
}
}
class Another<T> {
Base<T, T> base;
}
public enum JavaEnum {
VAL1(1),
VAL2(2);
private int x;
JavaEnum(int x) {
this.x = x;
}
void enumMethod() {}
}
| test-utils/testData/api/resolveJavaType.kt | 3684854275 |
package com.automation.remarks.kirk
import org.aeonbits.owner.Config
import org.aeonbits.owner.Config.*
import java.io.File
/**
* Created by sergey on 25.06.17.
*/
@Sources("classpath:kirk.properties")
interface Configuration : Config {
@Key("kirk.browser")
@DefaultValue("chrome")
fun browserName(): String
@Key("kirk.timeout")
@DefaultValue("4000")
fun timeout(): Int
@Key("kirk.poolingInterval")
@DefaultValue("0.1")
fun poolingInterval(): Double
@Key("kirk.autoClose")
@DefaultValue("true")
fun autoClose(): Boolean
@DefaultValue("")
@Key("kirk.screenSize")
fun screenSize(): List<Int>
@Key("kirk.baseUrl")
fun baseUrl(): String?
/**
* For use <headless> chrome options, set property "kirk.startMaximized=false"
* */
@Separator(",")
@DefaultValue("")
@Key("kirk.chrome.args")
fun chromeArgs(): List<String>
/**
* Chrome binary property example: -Dkirk.chrome.bin="path/to/your/chrome/bin"
* */
@Key("kirk.chrome.binary")
fun chromeBin(): String
@Separator(",")
@DefaultValue("")
@Key("kirk.chrome.extensions")
fun chromeExtensions(): List<File>
@Key("kirk.report.dir")
fun reportDir(): String
/**
* Highlight Element style
* */
@Key("kirk.highlight.border")
@DefaultValue("true")
fun highlightBorder(): Boolean
@Key("kirk.highlight.style")
@DefaultValue("dotted")
fun highlightStyle(): String
@Key("kirk.highlight.size")
@DefaultValue("2px")
fun highlightSize(): String
@Key("kirk.highlight.color")
@DefaultValue("red")
fun highlightColor(): String
@Separator(",")
@DefaultValue("")
@Key("kirk.desired.capabilities")
fun capabilities(): List<String>
@Key("kirk.remote.url")
@DefaultValue("")
fun remoteUrl(): String
@Key("kirk.listener")
@DefaultValue("")
fun listenerClass(): String
} | kirk-core/src/main/kotlin/com/automation/remarks/kirk/Configuration.kt | 2136782302 |
package com.telesoftas.core.common
import com.nhaarman.mockito_kotlin.given
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals("Simple math does not work", 4, 2 + 2)
}
/**
* Should not work without mockito-inline in before Mockito releases an in-built system.
*/
@Test
fun finalClasses_canBeMocked() {
val finalClass = mock<FinalClass>()
given(finalClass.doNothing()).will { }
tryFinal(finalClass)
verify(finalClass).doNothing()
}
private fun tryFinal(bundle: FinalClass) {
bundle.doNothing()
}
class FinalClass {
fun doNothing() {
// Do nothing
}
}
} | telesoftas-common/src/test/kotlin/com/telesoftas/core/common/ExampleUnitTest.kt | 4093938514 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.toml.lang
import com.intellij.openapi.fileTypes.ExactFileNameMatcher
import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher
import com.intellij.openapi.fileTypes.FileTypeConsumer
import com.intellij.openapi.fileTypes.FileTypeFactory
class TomlFileTypeFactory : FileTypeFactory() {
override fun createFileTypes(consumer: FileTypeConsumer) {
consumer.consume(TomlFileType,
ExactFileNameMatcher("Cargo.lock"),
ExtensionFileNameMatcher(TomlFileType.DEFAULTS.EXTENSION))
}
}
| toml/src/main/kotlin/org/toml/lang/TomlFileTypeFactory.kt | 159277695 |
package net.cad
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
open class Application
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
} | src/main/kotlin/net/cad/Application.kt | 1472399567 |
/*
* 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.manager
interface ChangelogManager {
data class CumulativeChangelog(
val added: List<String>,
val improved: List<String>,
val fixed: List<String>
)
/**
* Returns true if the app has benn updated since the last time this method was called
*/
fun didUpdate(): Boolean
suspend fun getChangelog(): CumulativeChangelog
fun markChangelogSeen()
}
| domain/src/main/java/com/moez/QKSMS/manager/ChangelogManager.kt | 546652455 |
/*
* Copyright 2017-2019 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.vertx.gradle
import org.gradle.api.Project
/**
* Vertx Gradle extension.
*
* @author [Julien Ponge](https://julien.ponge.org/)
*/
open class VertxExtension(private val project: Project) {
var vertxVersion = "4.1.2"
var launcher = "io.vertx.core.Launcher"
var mainVerticle = ""
var args = listOf<String>()
var config = ""
var workDirectory = project.projectDir.absolutePath
var jvmArgs = listOf<String>()
var redeploy = true
var watch = listOf("${project.projectDir.absolutePath}/src/**/*")
var onRedeploy = listOf("classes")
var redeployScanPeriod = 1000L
var redeployGracePeriod = 1000L
var redeployTerminationPeriod = 1000L
var debugPort = 5005L
var debugSuspend = false
override fun toString(): String {
return "VertxExtension(project=$project, vertxVersion='$vertxVersion', launcher='$launcher', mainVerticle='$mainVerticle', args=$args, config='$config', workDirectory='$workDirectory', jvmArgs=$jvmArgs, redeploy=$redeploy, watch=$watch, onRedeploy='$onRedeploy', redeployScanPeriod=$redeployScanPeriod, redeployGracePeriod=$redeployGracePeriod, redeployTerminationPeriod=$redeployTerminationPeriod, debugPort=$debugPort, debugSuspend=$debugSuspend)"
}
}
/**
* Extension method to make easier the configuration of the plugin when used with the Gradle Kotlin DSL
*/
fun Project.vertx(configure: VertxExtension.() -> Unit) =
extensions.configure(VertxExtension::class.java, configure)
| src/main/kotlin/io/vertx/gradle/VertxExtension.kt | 2951511437 |
package org.http4k.serverless
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.servlet.FakeHttpServletRequest
import org.http4k.servlet.FakeHttpServletResponse
import org.junit.jupiter.api.Test
class AlibabaCloudHttpFunctionTest {
@Test
fun `calls the handler and returns proper body`() {
val app = { req: Request -> Response(OK).body(req.bodyString()) }
val request = FakeHttpServletRequest(Request(GET, "").body("hello alibaba"))
val response = FakeHttpServletResponse()
object : AlibabaCloudHttpFunction(AppLoader { app }) {}.handleRequest(request, response, null)
assertThat(response.http4k.bodyString(), equalTo("hello alibaba"))
}
}
| http4k-serverless/alibaba/src/test/kotlin/org/http4k/serverless/AlibabaCloudHttpFunctionTest.kt | 304195091 |
package net.milosvasic.dispatcher.response
interface ResponseAction {
fun onAction()
}
| Dispatcher/src/main/kotlin/net/milosvasic/dispatcher/response/ResponseAction.kt | 2862852005 |
package de.tutao.tutanota.push
import android.annotation.TargetApi
import android.app.*
import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.AudioAttributes
import android.media.RingtoneManager
import android.os.Build
import android.util.Log
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import de.tutao.tutanota.*
import java.io.File
import java.util.concurrent.ConcurrentHashMap
const val NOTIFICATION_DISMISSED_ADDR_EXTRA = "notificationDismissed"
private const val EMAIL_NOTIFICATION_CHANNEL_ID = "notifications"
private val VIBRATION_PATTERN = longArrayOf(100, 200, 100, 200)
private const val NOTIFICATION_EMAIL_GROUP = "de.tutao.tutanota.email"
private const val SUMMARY_NOTIFICATION_ID = 45
private const val PERSISTENT_NOTIFICATION_CHANNEL_ID = "service_intent"
private const val ALARM_NOTIFICATION_CHANNEL_ID = "alarms"
private const val DOWNLOAD_NOTIFICATION_CHANNEL_ID = "downloads"
class LocalNotificationsFacade(private val context: Context) {
private val notificationManager: NotificationManager
get() = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
private val aliasNotification: MutableMap<String, LocalNotificationInfo> = ConcurrentHashMap()
fun makeConnectionNotification(): Notification {
return NotificationCompat.Builder(context, PERSISTENT_NOTIFICATION_CHANNEL_ID)
.setContentTitle("Notification service")
.setContentText("Syncing notifications")
.setSmallIcon(R.drawable.ic_status)
.setProgress(0, 0, true)
.build()
}
fun notificationDismissed(dismissAdders: List<String>?, isSummary: Boolean) {
if (isSummary) {
// If the user clicked on summary directly, reset counter for all notifications
aliasNotification.clear()
} else {
if (dismissAdders != null) {
for (addr in dismissAdders) {
aliasNotification.remove(addr)
notificationManager.cancel(makeNotificationId(addr))
}
}
}
if (aliasNotification.isEmpty()) {
notificationManager.cancel(SUMMARY_NOTIFICATION_ID)
} else {
var allAreZero = true
for (info in aliasNotification.values) {
if (info.counter > 0) {
allAreZero = false
break
}
}
if (allAreZero) {
notificationManager.cancel(SUMMARY_NOTIFICATION_ID)
} else {
for (info in aliasNotification.values) {
if (info.counter > 0) {
sendSummaryNotification(
notificationManager,
info.message, info.notificationInfo, false
)
break
}
}
}
}
}
fun sendEmailNotifications(notificationInfos: List<NotificationInfo>) {
if (notificationInfos.isEmpty()) {
return
}
val title = context.getString(R.string.pushNewMail_msg)
for (notificationInfo in notificationInfos) {
val counterPerAlias = aliasNotification[notificationInfo.mailAddress]?.incremented(notificationInfo.counter)
?: LocalNotificationInfo(
title,
notificationInfo.counter, notificationInfo
)
aliasNotification[notificationInfo.mailAddress] = counterPerAlias
val notificationId = makeNotificationId(notificationInfo.mailAddress)
@ColorInt val redColor = context.resources.getColor(R.color.red, context.theme)
val notificationBuilder = NotificationCompat.Builder(context, EMAIL_NOTIFICATION_CHANNEL_ID)
.setLights(redColor, 1000, 1000)
notificationBuilder.setContentTitle(title)
.setColor(redColor)
.setContentText(notificationContent(notificationInfo.mailAddress))
.setNumber(counterPerAlias.counter)
.setSmallIcon(R.drawable.ic_status)
.setDeleteIntent(intentForDelete(arrayListOf(notificationInfo.mailAddress)))
.setContentIntent(intentOpenMailbox(notificationInfo, false))
.setGroup(NOTIFICATION_EMAIL_GROUP)
.setAutoCancel(true)
.setGroupAlertBehavior(if (atLeastNougat()) NotificationCompat.GROUP_ALERT_CHILDREN else NotificationCompat.GROUP_ALERT_SUMMARY)
.setDefaults(Notification.DEFAULT_ALL)
notificationManager.notify(notificationId, notificationBuilder.build())
}
sendSummaryNotification(
notificationManager, title,
notificationInfos[0], true
)
}
@TargetApi(Build.VERSION_CODES.Q)
fun sendDownloadFinishedNotification(fileName: String?) {
val notificationManager = NotificationManagerCompat.from(context)
val channel = NotificationChannel(
"downloads",
"Downloads",
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
val pendingIntent = PendingIntent.getActivity(
context,
1,
Intent(DownloadManager.ACTION_VIEW_DOWNLOADS),
PendingIntent.FLAG_IMMUTABLE
)
val notification = Notification.Builder(context, channel.id)
.setContentIntent(pendingIntent)
.setContentTitle(fileName)
.setContentText(context.getText(R.string.downloadCompleted_msg))
.setSmallIcon(R.drawable.ic_download)
.setAutoCancel(true)
.build()
notificationManager.notify(makeNotificationId("downloads"), notification)
}
private fun sendSummaryNotification(
notificationManager: NotificationManager,
title: String,
notificationInfo: NotificationInfo,
sound: Boolean,
) {
var summaryCounter = 0
val addresses = arrayListOf<String>()
val inboxStyle = NotificationCompat.InboxStyle()
for ((key, value) in aliasNotification) {
val count = value.counter
if (count > 0) {
summaryCounter += count
inboxStyle.addLine(notificationContent(key))
addresses.add(key)
}
}
val builder = NotificationCompat.Builder(context, EMAIL_NOTIFICATION_CHANNEL_ID)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
@ColorInt val red = context.resources.getColor(R.color.red, context.theme)
val notification = builder.setContentTitle(title)
.setContentText(notificationContent(notificationInfo.mailAddress))
.setSmallIcon(R.drawable.ic_status)
.setGroup(NOTIFICATION_EMAIL_GROUP)
.setGroupSummary(true)
.setColor(red)
.setNumber(summaryCounter)
.setStyle(inboxStyle)
.setContentIntent(intentOpenMailbox(notificationInfo, true))
.setDeleteIntent(intentForDelete(addresses))
.setAutoCancel(true) // We need to update summary without sound when one of the alarms is cancelled
// but we need to use sound if it's API < N because GROUP_ALERT_CHILDREN doesn't
// work with sound there (pehaps summary consumes it somehow?) and we must do
// summary with sound instead on the old versions.
.setDefaults(if (sound) NotificationCompat.DEFAULT_SOUND or NotificationCompat.DEFAULT_VIBRATE else 0)
.setGroupAlertBehavior(if (atLeastNougat()) NotificationCompat.GROUP_ALERT_CHILDREN else NotificationCompat.GROUP_ALERT_SUMMARY)
.build()
notificationManager.notify(SUMMARY_NOTIFICATION_ID, notification)
}
fun showErrorNotification(@StringRes message: Int, exception: Throwable?) {
val intent = Intent(context, MainActivity::class.java)
.setAction(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_SUBJECT, "Alarm error v" + BuildConfig.VERSION_NAME)
if (exception != null) {
val stackTrace = Log.getStackTraceString(exception)
val errorString = "${exception.message}\n$stackTrace"
intent.clipData = ClipData.newPlainText("error", errorString)
}
val notification: Notification =
NotificationCompat.Builder(context, ALARM_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_status)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(message))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setStyle(NotificationCompat.BigTextStyle())
.setContentIntent(
PendingIntent.getActivity(
context,
(Math.random() * 20000).toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
)
.setAutoCancel(true)
.build()
notificationManager.notify(1000, notification)
}
@TargetApi(Build.VERSION_CODES.O)
fun createNotificationChannels() {
val mailNotificationChannel = NotificationChannel(
EMAIL_NOTIFICATION_CHANNEL_ID,
context.getString(R.string.pushNewMail_msg),
NotificationManager.IMPORTANCE_DEFAULT
).default()
notificationManager.createNotificationChannel(mailNotificationChannel)
val serviceNotificationChannel = NotificationChannel(
PERSISTENT_NOTIFICATION_CHANNEL_ID, context.getString(R.string.notificationSync_msg),
NotificationManager.IMPORTANCE_LOW
)
notificationManager.createNotificationChannel(serviceNotificationChannel)
val alarmNotificationsChannel = NotificationChannel(
ALARM_NOTIFICATION_CHANNEL_ID,
context.getString(R.string.reminder_label),
NotificationManager.IMPORTANCE_HIGH
).default()
notificationManager.createNotificationChannel(alarmNotificationsChannel)
val downloadNotificationsChannel = NotificationChannel(
DOWNLOAD_NOTIFICATION_CHANNEL_ID,
context.getString(R.string.downloadCompleted_msg),
NotificationManager.IMPORTANCE_DEFAULT
)
downloadNotificationsChannel.setShowBadge(false)
notificationManager.createNotificationChannel(downloadNotificationsChannel)
}
@TargetApi(Build.VERSION_CODES.O)
private fun NotificationChannel.default(): NotificationChannel {
val ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val att = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.build()
setShowBadge(true)
setSound(ringtoneUri, att)
enableLights(true)
vibrationPattern = VIBRATION_PATTERN
lightColor = Color.RED
return this
}
private fun notificationContent(address: String): String {
return aliasNotification[address]!!.counter.toString() + " " + address
}
private fun makeNotificationId(address: String): Int {
return Math.abs(1 + address.hashCode())
}
private fun intentForDelete(addresses: ArrayList<String>): PendingIntent {
val deleteIntent = Intent(context, PushNotificationService::class.java)
deleteIntent.putStringArrayListExtra(NOTIFICATION_DISMISSED_ADDR_EXTRA, addresses)
return PendingIntent.getService(
context.applicationContext,
makeNotificationId("dismiss${addresses.joinToString("+")}"),
deleteIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
private fun intentOpenMailbox(
notificationInfo: NotificationInfo,
isSummary: Boolean,
): PendingIntent {
val openMailboxIntent = Intent(context, MainActivity::class.java)
openMailboxIntent.action = MainActivity.OPEN_USER_MAILBOX_ACTION
openMailboxIntent.putExtra(
MainActivity.OPEN_USER_MAILBOX_MAIL_ADDRESS_KEY,
notificationInfo.mailAddress
)
openMailboxIntent.putExtra(
MainActivity.OPEN_USER_MAILBOX_USERID_KEY,
notificationInfo.userId
)
openMailboxIntent.putExtra(MainActivity.IS_SUMMARY_EXTRA, isSummary)
return PendingIntent.getActivity(
context.applicationContext,
makeNotificationId(notificationInfo.mailAddress + "@isSummary" + isSummary),
openMailboxIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
}
fun notificationDismissedIntent(
context: Context,
emailAddresses: ArrayList<String>,
sender: String,
isSummary: Boolean,
): Intent {
val deleteIntent = Intent(context, PushNotificationService::class.java)
deleteIntent.putStringArrayListExtra(NOTIFICATION_DISMISSED_ADDR_EXTRA, emailAddresses)
deleteIntent.putExtra("sender", sender)
deleteIntent.putExtra(MainActivity.IS_SUMMARY_EXTRA, isSummary)
return deleteIntent
}
fun showAlarmNotification(context: Context, timestamp: Long, summary: String, intent: Intent) {
val contentText = String.format("%tR %s", timestamp, summary)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
@ColorInt val red = context.resources.getColor(R.color.red, context.theme)
notificationManager.notify(
System.currentTimeMillis().toInt(),
NotificationCompat.Builder(context, ALARM_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_status)
.setContentTitle(context.getString(R.string.reminder_label))
.setContentText(contentText)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(red)
.setContentIntent(openCalendarIntent(context, intent))
.setAutoCancel(true)
.build()
)
}
private fun openCalendarIntent(context: Context, alarmIntent: Intent): PendingIntent {
val userId = alarmIntent.getStringExtra(MainActivity.OPEN_USER_MAILBOX_USERID_KEY)
val openCalendarEventIntent = Intent(context, MainActivity::class.java)
openCalendarEventIntent.action = MainActivity.OPEN_CALENDAR_ACTION
openCalendarEventIntent.putExtra(MainActivity.OPEN_USER_MAILBOX_USERID_KEY, userId)
return PendingIntent.getActivity(
context,
alarmIntent.data.toString().hashCode(),
openCalendarEventIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
/**
* create a notification that starts a new task and gives it access to the downloaded file
* to view it.
*/
fun showDownloadNotification(context: Context, file: File) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val uri = FileProvider.getUriForFile(context, BuildConfig.FILE_PROVIDER_AUTHORITY, file)
val mimeType = getMimeType(file.toUri(), context)
val intent = Intent(Intent.ACTION_VIEW).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
setDataAndType(uri, mimeType)
}
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
notificationManager.notify(System.currentTimeMillis().toInt(),
NotificationCompat.Builder(context, DOWNLOAD_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_download)
.setContentTitle(context.getString(R.string.downloadCompleted_msg))
.setContentText(file.name)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build()
)
} | app-android/app/src/main/java/de/tutao/tutanota/push/LocalNotificationsFacade.kt | 495599368 |
package jpm.android.robot
/**
* Created by jm on 17/01/17.
*
*
* see drawings:
* /opt/docs/ARDUINO/myStufs/robot/openscad/robot_diagram.dxf
* /opt/docs/ARDUINO/myStufs/robot/openscad/robot_diagram_symbols.dxf
* /opt/docs/ARDUINO/myStufs/robot/openscad/trignometria.dxf
*
* resume:
* - Y axis aligned with length positive angle to front
* - X axis aligned with width positive angle to right
* - 0 º angle aligned with front, rotate clockwise
*/
object RobotDimensions {
data class SonarInfo(val angleDeg: Int, val angleRad: Double, val x: Double, val y: Double)
// units meters:
//
val robotCircleRadius = 0.07 // BW / 2
val robotRectLength = 0.056 // BSd
val bodyWidth = 2 * robotCircleRadius // BW
val bodyTotalLength = 2 * robotCircleRadius + robotRectLength // Bl
val wheelBodyDistance = 0.005 //
val wheelRadius = 0.0325 // Wd / 2
val wheelWidth = 0.026 // Ww
val distanceWheel = bodyWidth + wheelWidth + 2 * wheelBodyDistance // BWw
val wheelAxisLenght = 0.075 // BWl
val robotTotalWidth = bodyWidth + 2 * (wheelBodyDistance + wheelWidth)
val sonarAngle = 30 // usDelta
val wheelSensorTicksPerRotation = 100
val sonarSensors = Array(12) { i ->
val angleDeg = i * sonarAngle
val angleRad = Math.toRadians(angleDeg.toDouble())
val (x,y) = when(i) {
9 -> Pair(-robotCircleRadius, 0.0) // left
3 -> Pair( robotCircleRadius, 0.0) // right
0 -> Pair(0.0, robotRectLength / 2.0 + robotCircleRadius) // front
6 -> Pair(0.0, -robotRectLength / 2.0 - robotCircleRadius) // back
4,5,7,8 -> Pair(robotCircleRadius * Math.sin(angleRad), -robotRectLength / 2.0 + robotCircleRadius * Math.cos(angleRad)) // negative Y
else -> Pair(robotCircleRadius * Math.sin(angleRad), robotRectLength / 2.0 + robotCircleRadius * Math.cos(angleRad)) // positive Y (1,2,10,11)
}
SonarInfo(angleDeg, angleRad, x, y)
}
/*
init {
var i = 0
sonarSensors.forEach { s ->
println("Sendor($i) \t= $s\n")
i += 1
}
}
*/
} | android/app/src/main/java/jpm/android/robot/RobotDimensions.kt | 1466975548 |
package ch.empros.kmap
interface Query {
val pagedQuery: String
val pageSize: Int
val startPage: Int
fun nextPage(): Query
}
/**
* A [SqlQuery] object can be used to create pageable data sources, see [KMap.pageObservableFrom].
* Note: [startPage] is zero-based, ie. the first page is at index 0.
*/
data class SqlQuery(private val query: String, override val pageSize: Int = 50, override val startPage: Int = 0) : Query {
init {
require(pageSize > 0, { "PageSize must be > 0, but got: $pageSize" })
require(startPage > -1, { "StartPage must >= 0, but got: $startPage" })
}
override val pagedQuery = "$query LIMIT $pageSize OFFSET ${startPage * pageSize}"
override fun nextPage() = copy(startPage = startPage + 1)
}
| data/src/main/kotlin/ch/empros/kmap/Query.kt | 1423546542 |
package me.sweetll.tucao.business.home.fragment
import android.annotation.TargetApi
import androidx.databinding.DataBindingUtil
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import android.transition.ArcMotion
import android.transition.ChangeBounds
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.transition.TransitionManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseFragment
import me.sweetll.tucao.business.channel.ChannelDetailActivity
import me.sweetll.tucao.business.home.adapter.AnimationAdapter
import me.sweetll.tucao.business.home.viewmodel.AnimationViewModel
import me.sweetll.tucao.business.video.VideoActivity
import me.sweetll.tucao.databinding.FragmentAnimationBinding
import me.sweetll.tucao.databinding.HeaderAnimationBinding
import me.sweetll.tucao.model.raw.Animation
class AnimationFragment : BaseFragment() {
lateinit var binding: FragmentAnimationBinding
val viewModel = AnimationViewModel(this)
val animationAdapter = AnimationAdapter(null)
var isLoad = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_animation, container, false)
binding.viewModel = viewModel
binding.loading.show()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.swipeRefresh.isEnabled = false
binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
binding.swipeRefresh.setOnRefreshListener {
viewModel.loadData()
}
binding.errorStub.setOnInflateListener {
_, inflated ->
inflated.setOnClickListener {
viewModel.loadData()
}
}
setupRecyclerView()
loadWhenNeed()
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
initTransition()
}
}
fun setupRecyclerView() {
val headerBinding: HeaderAnimationBinding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.header_animation, binding.root as ViewGroup, false)
headerBinding.viewModel = viewModel
animationAdapter.addHeaderView(headerBinding.root)
binding.animationRecycler.layoutManager = LinearLayoutManager(activity)
binding.animationRecycler.adapter = animationAdapter
binding.animationRecycler.addOnItemTouchListener(object: OnItemChildClickListener() {
override fun onSimpleItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
when (view.id) {
R.id.card_more -> {
ChannelDetailActivity.intentTo(activity!!, view.tag as Int)
}
R.id.card1, R.id.card2, R.id.card3, R.id.card4 -> {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val coverImg = (((view as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0)
val titleText = (view.getChildAt(0) as ViewGroup).getChildAt(1)
val p1: Pair<View, String> = Pair.create(coverImg, "cover")
val p2: Pair<View, String> = Pair.create(titleText, "bg")
val cover = titleText.tag as String
val options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity!!, p1, p2)
VideoActivity.intentTo(activity!!, view.tag as String, cover, options.toBundle())
} else {
VideoActivity.intentTo(activity!!, view.tag as String)
}
}
}
}
})
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun initTransition() {
val changeBounds = ChangeBounds()
val arcMotion = ArcMotion()
changeBounds.pathMotion = arcMotion
activity!!.window.sharedElementExitTransition = changeBounds
activity!!.window.sharedElementReenterTransition = null
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
loadWhenNeed()
}
fun loadWhenNeed() {
if (isVisible && userVisibleHint && !isLoad && !binding.swipeRefresh.isRefreshing) {
viewModel.loadData()
}
}
fun loadAnimation(animation: Animation) {
if (!isLoad) {
isLoad = true
TransitionManager.beginDelayedTransition(binding.swipeRefresh)
binding.swipeRefresh.isEnabled = true
binding.loading.visibility = View.GONE
if (binding.errorStub.isInflated) {
binding.errorStub.root.visibility = View.GONE
}
binding.animationRecycler.visibility = View.VISIBLE
}
animationAdapter.setNewData(animation.recommends)
}
fun loadError() {
if (!isLoad) {
TransitionManager.beginDelayedTransition(binding.swipeRefresh)
binding.loading.visibility = View.GONE
if (!binding.errorStub.isInflated) {
binding.errorStub.viewStub!!.visibility = View.VISIBLE
} else {
binding.errorStub.root.visibility = View.VISIBLE
}
}
}
fun setRefreshing(isRefreshing: Boolean) {
if (isLoad) {
binding.swipeRefresh.isRefreshing = isRefreshing
} else {
TransitionManager.beginDelayedTransition(binding.swipeRefresh)
binding.loading.visibility = if (isRefreshing) View.VISIBLE else View.GONE
if (isRefreshing) {
if (!binding.errorStub.isInflated) {
binding.errorStub.viewStub!!.visibility = View.GONE
} else {
binding.errorStub.root.visibility = View.GONE
}
}
}
}
} | app/src/main/kotlin/me/sweetll/tucao/business/home/fragment/AnimationFragment.kt | 2172834239 |
package pw.janyo.whatanime.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.flow.MutableStateFlow
import pw.janyo.whatanime.config.Configure
import pw.janyo.whatanime.model.entity.NightMode
private val DarkColorPalette = darkColorScheme()
private val LightColorPalette = lightColorScheme()
@Composable
fun isDarkMode(): Boolean {
val mode by Theme.nightMode.collectAsState()
return when (mode) {
NightMode.AUTO -> isSystemInDarkTheme()
NightMode.ON -> true
NightMode.OFF -> false
NightMode.MATERIAL_YOU -> isSystemInDarkTheme()
}
}
@Composable
fun WhatAnimeTheme(
content: @Composable() () -> Unit
) {
val isDark = isDarkMode()
val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val colorScheme = if (dynamicColor) {
val context = LocalContext.current
if (isDark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
} else {
if (isDarkMode()) DarkColorPalette else LightColorPalette
}
MaterialTheme(
colorScheme = colorScheme,
content = content
)
}
object Theme {
val nightMode = MutableStateFlow(Configure.nightMode)
} | app/src/main/java/pw/janyo/whatanime/ui/theme/Theme.kt | 3044730331 |
package com.darichey.discord.kommands.limiters
import com.darichey.discord.kommands.CommandFunction
import com.darichey.discord.kommands.Limiter
import sx.blah.discord.handle.obj.IChannel
/**
* A [Limiter] limiting the use of a command to certain [IChannel]s.
* Will pass a command executed in **ANY** of the given channels.
*/
class ChannelLimiter(vararg channels: String, onFail: CommandFunction = {}) :
Limiter({ channels.contains(channel.id) }, onFail) {
constructor(vararg channels: IChannel, onFail: CommandFunction = {}):
this(*channels.map(IChannel::getID).toTypedArray(), onFail = onFail)
} | src/main/kotlin/com/darichey/discord/kommands/limiters/ChannelLimiter.kt | 353955233 |
package kodando.rxjs
fun subscription(handler: () -> Unit) =
Subscription(handler)
inline fun <T> createObserverLike(): ObserverLike<T> {
return ObserverLikeImpl()
}
| kodando-rxjs/src/main/kotlin/kodando/rxjs/Helpers.kt | 134544371 |
package kodando.rxjs.operators
import kodando.rxjs.JsFunction
import kodando.rxjs.Observable
import kodando.rxjs.fromModule
import kodando.rxjs.import
private val catchError_: JsFunction =
fromModule("rxjs/operators") import "catchError"
fun <T> Observable<T>.catchError(transformer: (Any) -> Observable<T>): Observable<T> {
return pipe(catchError_.call(this, transformer))
}
| kodando-rxjs/src/main/kotlin/kodando/rxjs/operators/CatchError.kt | 2583509712 |
package components.menuBar.child
import components.progressBar.MenuBarImpl
import java.awt.event.ActionEvent
import java.util.*
import javax.swing.JMenuItem
/**
* Created by vicboma on 12/12/16.
*/
public fun MenuBarImpl.Companion.MenuBarFile(): Map<String, Map<String, (ActionEvent) -> Unit>> {
return object : LinkedHashMap<String, Map<String, (ActionEvent) -> Unit>>() {
init {
put("File",
object : LinkedHashMap<String, (ActionEvent) -> Unit>() {
init {
put("New", { clickAction (it) })
put("Open", { clickAction (it) })
put("Open Url", { clickAction (it) })
put("Open Recent", { clickAction (it) })
put("Close Project", { clickAction (it) })
put("---", { clickAction (it) })
put("Power Save Mode", { })
}
}
)
}
}
}
private fun clickAction(it: ActionEvent) {
var item = (it.source as JMenuItem)
item.text = it.actionCommand.plus(" - (Clicked!)")
item.removeActionListener(item.actionListeners.get(0))
} | 08-start-async-fileChooser-application/src/main/kotlin/components/menuBar/child/MenuBarFile.kt | 3249192251 |
/*
* 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.android.codelabs.paging.ui
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.example.android.codelabs.paging.Injection
import com.example.android.codelabs.paging.databinding.ActivitySearchRepositoriesBinding
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
class SearchRepositoriesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivitySearchRepositoriesBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// get the view model
val viewModel = ViewModelProvider(
this, Injection.provideViewModelFactory(
context = this,
owner = this
)
)
.get(SearchRepositoriesViewModel::class.java)
// add dividers between RecyclerView's row items
val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
binding.list.addItemDecoration(decoration)
// bind the state
binding.bindState(
uiState = viewModel.state,
pagingData = viewModel.pagingDataFlow,
uiActions = viewModel.accept
)
}
/**
* Binds the [UiState] provided by the [SearchRepositoriesViewModel] to the UI,
* and allows the UI to feed back user actions to it.
*/
private fun ActivitySearchRepositoriesBinding.bindState(
uiState: StateFlow<UiState>,
pagingData: Flow<PagingData<UiModel>>,
uiActions: (UiAction) -> Unit
) {
val repoAdapter = ReposAdapter()
val header = ReposLoadStateAdapter { repoAdapter.retry() }
list.adapter = repoAdapter.withLoadStateHeaderAndFooter(
header = header,
footer = ReposLoadStateAdapter { repoAdapter.retry() }
)
bindSearch(
uiState = uiState,
onQueryChanged = uiActions
)
bindList(
header = header,
repoAdapter = repoAdapter,
uiState = uiState,
pagingData = pagingData,
onScrollChanged = uiActions
)
}
private fun ActivitySearchRepositoriesBinding.bindSearch(
uiState: StateFlow<UiState>,
onQueryChanged: (UiAction.Search) -> Unit
) {
searchRepo.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO) {
updateRepoListFromInput(onQueryChanged)
true
} else {
false
}
}
searchRepo.setOnKeyListener { _, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
updateRepoListFromInput(onQueryChanged)
true
} else {
false
}
}
lifecycleScope.launch {
uiState
.map { it.query }
.distinctUntilChanged()
.collect(searchRepo::setText)
}
}
private fun ActivitySearchRepositoriesBinding.updateRepoListFromInput(onQueryChanged: (UiAction.Search) -> Unit) {
searchRepo.text.trim().let {
if (it.isNotEmpty()) {
list.scrollToPosition(0)
onQueryChanged(UiAction.Search(query = it.toString()))
}
}
}
private fun ActivitySearchRepositoriesBinding.bindList(
header: ReposLoadStateAdapter,
repoAdapter: ReposAdapter,
uiState: StateFlow<UiState>,
pagingData: Flow<PagingData<UiModel>>,
onScrollChanged: (UiAction.Scroll) -> Unit
) {
retryButton.setOnClickListener { repoAdapter.retry() }
list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy != 0) onScrollChanged(UiAction.Scroll(currentQuery = uiState.value.query))
}
})
val notLoading = repoAdapter.loadStateFlow
.asRemotePresentationState()
.map { it == RemotePresentationState.PRESENTED }
val hasNotScrolledForCurrentSearch = uiState
.map { it.hasNotScrolledForCurrentSearch }
.distinctUntilChanged()
val shouldScrollToTop = combine(
notLoading,
hasNotScrolledForCurrentSearch,
Boolean::and
)
.distinctUntilChanged()
lifecycleScope.launch {
pagingData.collectLatest(repoAdapter::submitData)
}
lifecycleScope.launch {
shouldScrollToTop.collect { shouldScroll ->
if (shouldScroll) list.scrollToPosition(0)
}
}
lifecycleScope.launch {
repoAdapter.loadStateFlow.collect { loadState ->
// Show a retry header if there was an error refreshing, and items were previously
// cached OR default to the default prepend state
header.loadState = loadState.mediator
?.refresh
?.takeIf { it is LoadState.Error && repoAdapter.itemCount > 0 }
?: loadState.prepend
val isListEmpty = loadState.refresh is LoadState.NotLoading && repoAdapter.itemCount == 0
// show empty list
emptyList.isVisible = isListEmpty
// Only show the list if refresh succeeds, either from the the local db or the remote.
list.isVisible = loadState.source.refresh is LoadState.NotLoading || loadState.mediator?.refresh is LoadState.NotLoading
// Show loading spinner during initial load or refresh.
progressBar.isVisible = loadState.mediator?.refresh is LoadState.Loading
// Show the retry state if initial load or refresh fails.
retryButton.isVisible = loadState.mediator?.refresh is LoadState.Error && repoAdapter.itemCount == 0
// Toast on any error, regardless of whether it came from RemoteMediator or PagingSource
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let {
Toast.makeText(
this@SearchRepositoriesActivity,
"\uD83D\uDE28 Wooops ${it.error}",
Toast.LENGTH_LONG
).show()
}
}
}
}
}
| advanced/end/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesActivity.kt | 3941648466 |
package fr.simonlebras.radiofrance.di.scopes
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope
| app/src/main/kotlin/fr/simonlebras/radiofrance/di/scopes/ActivityScope.kt | 1537028464 |
/****************************************************************************************
* Copyright (c) 2018 Mike Hardy <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.utils
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Message
import android.provider.OpenableColumns
import android.text.TextUtils
import android.webkit.MimeTypeMap
import androidx.annotation.CheckResult
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.AnkiActivity
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.CrashReportService
import com.ichi2.anki.R
import com.ichi2.anki.dialogs.DialogHandler
import com.ichi2.compat.CompatHelper
import org.apache.commons.compress.archivers.zip.ZipFile
import org.jetbrains.annotations.Contract
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.*
import java.util.zip.ZipException
import java.util.zip.ZipInputStream
import kotlin.collections.ArrayList
object ImportUtils {
/* A filename should be shortened if over this threshold */
private const val fileNameShorteningThreshold = 100
/**
* This code is used in multiple places to handle package imports
*
* @param context for use in resource resolution and path finding
* @param intent contains the file to import
* @return null if successful, otherwise error message
*/
fun handleFileImport(context: Context, intent: Intent): ImportResult {
return FileImporter().handleFileImport(context, intent)
}
/**
* Makes a cached copy of the file selected on [intent] and returns its path
*/
fun getFileCachedCopy(context: Context, intent: Intent): String? {
return FileImporter().getFileCachedCopy(context, intent)
}
fun showImportUnsuccessfulDialog(activity: Activity, errorMessage: String?, exitActivity: Boolean) {
FileImporter().showImportUnsuccessfulDialog(activity, errorMessage, exitActivity)
}
fun isCollectionPackage(filename: String?): Boolean {
return filename != null && (filename.lowercase(Locale.ROOT).endsWith(".colpkg") || "collection.apkg" == filename)
}
/** @return Whether the file is either a deck, or a collection package */
@Contract("null -> false")
fun isValidPackageName(filename: String?): Boolean {
return FileImporter.isDeckPackage(filename) || isCollectionPackage(filename)
}
/**
* Whether importUtils can handle the given intent
* Caused by #6312 - A launcher was sending ACTION_VIEW instead of ACTION_MAIN
*/
fun isInvalidViewIntent(intent: Intent): Boolean {
return intent.data == null && intent.clipData == null
}
fun isFileAValidDeck(fileName: String): Boolean {
return FileImporter.hasExtension(fileName, "apkg") || FileImporter.hasExtension(fileName, "colpkg")
}
@SuppressWarnings("WeakerAccess")
open class FileImporter {
/**
* This code is used in multiple places to handle package imports
*
* @param context for use in resource resolution and path finding
* @param intent contains the file to import
* @return null if successful, otherwise error message
*/
fun handleFileImport(context: Context, intent: Intent): ImportResult {
// This intent is used for opening apkg package files
// We want to go immediately to DeckPicker, clearing any history in the process
Timber.i("IntentHandler/ User requested to view a file")
val extras = if (intent.extras == null) "none" else TextUtils.join(", ", intent.extras!!.keySet())
Timber.i("Intent: %s. Data: %s", intent, extras)
return try {
handleFileImportInternal(context, intent)
} catch (e: Exception) {
CrashReportService.sendExceptionReport(e, "handleFileImport")
Timber.e(e, "failed to handle import intent")
ImportResult.fromErrorString(context.getString(R.string.import_error_handle_exception, e.localizedMessage))
}
}
private fun handleFileImportInternal(context: Context, intent: Intent): ImportResult {
val dataList = getUris(intent)
return if (dataList != null) {
handleContentProviderFile(context, intent, dataList)
} else {
ImportResult.fromErrorString(context.getString(R.string.import_error_handle_exception))
}
}
/**
* Makes a cached copy of the file selected on [intent] and returns its path
*/
fun getFileCachedCopy(context: Context, intent: Intent): String? {
val uri = getUris(intent)?.get(0) ?: return null
val filename = ensureValidLength(getFileNameFromContentProvider(context, uri) ?: return null)
val tempPath = Uri.fromFile(File(context.cacheDir, filename)).encodedPath!!
return if (copyFileToCache(context, uri, tempPath)) {
tempPath
} else {
null
}
}
private fun handleContentProviderFile(context: Context, intent: Intent, dataList: ArrayList<Uri>): ImportResult {
// Note: intent.getData() can be null. Use data instead.
validateImportTypes(context, dataList)?.let { errorMessage ->
return ImportResult.fromErrorString(errorMessage)
}
val tempOutDirList: ArrayList<String> = ArrayList()
for (data in dataList) {
// Get the original filename from the content provider URI
var filename = getFileNameFromContentProvider(context, data)
// Hack to fix bug where ContentResolver not returning filename correctly
if (filename == null) {
if (intent.type != null && ("application/apkg" == intent.type || hasValidZipFile(context, data))) {
// Set a dummy filename if MIME type provided or is a valid zip file
filename = "unknown_filename.apkg"
Timber.w("Could not retrieve filename from ContentProvider, but was valid zip file so we try to continue")
} else {
Timber.e("Could not retrieve filename from ContentProvider or read content as ZipFile")
CrashReportService.sendExceptionReport(RuntimeException("Could not import apkg from ContentProvider"), "IntentHandler.java", "apkg import failed")
return ImportResult.fromErrorString(AnkiDroidApp.appResources.getString(R.string.import_error_content_provider, AnkiDroidApp.manualUrl + "#importing"))
}
}
if (!isValidPackageName(filename)) {
return if (isAnkiDatabase(filename)) {
// .anki2 files aren't supported by Anki Desktop, we should eventually support them, because we can
// but for now, show a "nice" error.
ImportResult.fromErrorString(context.resources.getString(R.string.import_error_load_imported_database))
} else {
// Don't import if file doesn't have an Anki package extension
ImportResult.fromErrorString(context.resources.getString(R.string.import_error_not_apkg_extension, filename))
}
} else {
// Copy to temporary file
filename = ensureValidLength(filename)
val tempOutDir = Uri.fromFile(File(context.cacheDir, filename)).encodedPath!!
val errorMessage = if (copyFileToCache(context, data, tempOutDir)) null else context.getString(R.string.import_error_copy_to_cache)
// Show import dialog
if (errorMessage != null) {
CrashReportService.sendExceptionReport(RuntimeException("Error importing apkg file"), "IntentHandler.java", "apkg import failed")
return ImportResult.fromErrorString(errorMessage)
}
val validateZipResult = validateZipFile(context, tempOutDir)
if (validateZipResult != null) {
File(tempOutDir).delete()
return validateZipResult
}
tempOutDirList.add(tempOutDir)
}
sendShowImportFileDialogMsg(tempOutDirList)
}
return ImportResult.fromSuccess()
}
private fun validateZipFile(ctx: Context, filePath: String): ImportResult? {
val file = File(filePath)
var zf: ZipFile? = null
try {
zf = ZipFile(file)
} catch (e: Exception) {
Timber.w(e, "Failed to validate zip")
return ImportResult.fromInvalidZip(ctx, file, e)
} finally {
if (zf != null) {
try {
zf.close()
} catch (e: IOException) {
Timber.w(e, "Failed to close zip")
}
}
}
return null
}
private fun validateImportTypes(context: Context, dataList: ArrayList<Uri>): String? {
var apkgCount = 0
var colpkgCount = 0
for (data in dataList) {
var fileName = getFileNameFromContentProvider(context, data)
when {
isDeckPackage(fileName) -> {
apkgCount += 1
}
isCollectionPackage(fileName) -> {
colpkgCount += 1
}
}
}
if (apkgCount > 0 && colpkgCount > 0) {
Timber.i("Both apkg & colpkg selected.")
return context.resources.getString(R.string.import_error_colpkg_apkg)
} else if (colpkgCount > 1) {
Timber.i("Multiple colpkg files selected.")
return context.resources.getString(R.string.import_error_multiple_colpkg)
}
return null
}
private fun isAnkiDatabase(filename: String?): Boolean {
return filename != null && hasExtension(filename, "anki2")
}
private fun ensureValidLength(fileName: String): String {
// #6137 - filenames can be too long when URLEncoded
return try {
val encoded = URLEncoder.encode(fileName, "UTF-8")
if (encoded.length <= fileNameShorteningThreshold) {
Timber.d("No filename truncation necessary")
fileName
} else {
Timber.d("Filename was longer than %d, shortening", fileNameShorteningThreshold)
// take 90 instead of 100 so we don't get the extension
val substringLength = fileNameShorteningThreshold - 10
val shortenedFileName = encoded.substring(0, substringLength) + "..." + getExtension(fileName)
Timber.d("Shortened filename '%s' to '%s'", fileName, shortenedFileName)
// if we don't decode, % is double-encoded
URLDecoder.decode(shortenedFileName, "UTF-8")
}
} catch (e: Exception) {
Timber.w(e, "Failed to shorten file: %s", fileName)
fileName
}
}
@CheckResult
private fun getExtension(fileName: String): String {
val file = Uri.fromFile(File(fileName))
return MimeTypeMap.getFileExtensionFromUrl(file.toString())
}
protected open fun getFileNameFromContentProvider(context: Context, data: Uri): String? {
var filename: String? = null
context.contentResolver.query(data, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null).use { cursor ->
if (cursor != null && cursor.moveToFirst()) {
filename = cursor.getString(0)
Timber.d("handleFileImport() Importing from content provider: %s", filename)
}
}
return filename
}
fun showImportUnsuccessfulDialog(activity: Activity, errorMessage: String?, exitActivity: Boolean) {
Timber.e("showImportUnsuccessfulDialog() message %s", errorMessage)
val title = activity.resources.getString(R.string.import_title_error)
MaterialDialog(activity).show {
title(text = title)
message(text = errorMessage!!)
positiveButton(R.string.dialog_ok) {
if (exitActivity) {
AnkiActivity.finishActivityWithFade(activity)
}
}
}
}
/**
* Copy the data from the intent to a temporary file
* @param data intent from which to get input stream
* @param tempPath temporary path to store the cached file
* @return whether or not copy was successful
*/
protected open fun copyFileToCache(context: Context, data: Uri?, tempPath: String): Boolean {
// Get an input stream to the data in ContentProvider
val inputStream: InputStream? = try {
context.contentResolver.openInputStream(data!!)
} catch (e: FileNotFoundException) {
Timber.e(e, "Could not open input stream to intent data")
return false
}
// Check non-null
@Suppress("FoldInitializerAndIfToElvis")
if (inputStream == null) {
return false
}
try {
CompatHelper.compat.copyFile(inputStream, tempPath)
} catch (e: IOException) {
Timber.e(e, "Could not copy file to %s", tempPath)
return false
} finally {
try {
inputStream.close()
} catch (e: IOException) {
Timber.e(e, "Error closing input stream")
}
}
return true
}
companion object {
fun getUris(intent: Intent): ArrayList<Uri>? {
if (intent.data == null) {
Timber.i("No intent data. Attempting to read clip data.")
if (intent.clipData == null || intent.clipData!!.itemCount == 0) {
return null
}
val clipUriList: ArrayList<Uri> = ArrayList()
// Iterate over clipUri & create clipUriList
// Pass clipUri list.
for (i in 0 until intent.clipData!!.itemCount) {
intent.clipData?.getItemAt(i)?.let { clipUriList.add(it.uri) }
}
return clipUriList
}
// If Uri is of scheme which is supported by ContentResolver, read the contents
val intentUriScheme = intent.data!!.scheme
return if (intentUriScheme == ContentResolver.SCHEME_CONTENT || intentUriScheme == ContentResolver.SCHEME_FILE || intentUriScheme == ContentResolver.SCHEME_ANDROID_RESOURCE) {
Timber.i("Attempting to read content from intent.")
arrayListOf(intent.data!!)
} else {
null
}
}
/**
* Send a Message to AnkiDroidApp so that the DialogMessageHandler shows the Import apkg dialog.
* @param pathList list of path(s) to apkg file which will be imported
*/
private fun sendShowImportFileDialogMsg(pathList: ArrayList<String>) {
// Get the filename from the path
val f = File(pathList.first())
val filename = f.name
// Create a new message for DialogHandler so that we see the appropriate import dialog in DeckPicker
val handlerMessage = Message.obtain()
val msgData = Bundle()
msgData.putStringArrayList("importPath", pathList)
handlerMessage.data = msgData
if (isCollectionPackage(filename)) {
// Show confirmation dialog asking to confirm import with replace when file called "collection.apkg"
handlerMessage.what = DialogHandler.MSG_SHOW_COLLECTION_IMPORT_REPLACE_DIALOG
} else {
// Otherwise show confirmation dialog asking to confirm import with add
handlerMessage.what = DialogHandler.MSG_SHOW_COLLECTION_IMPORT_ADD_DIALOG
}
// Store the message in AnkiDroidApp message holder, which is loaded later in AnkiActivity.onResume
DialogHandler.storeMessage(handlerMessage)
}
internal fun isDeckPackage(filename: String?): Boolean {
return filename != null && filename.lowercase(Locale.ROOT).endsWith(".apkg") && "collection.apkg" != filename
}
fun hasExtension(filename: String, extension: String?): Boolean {
val fileParts = filename.split("\\.".toRegex()).toTypedArray()
if (fileParts.size < 2) {
return false
}
val extensionSegment = fileParts[fileParts.size - 1]
// either "apkg", or "apkg (1)".
// COULD_BE_BETTE: accepts .apkgaa"
return extensionSegment.lowercase(Locale.ROOT).startsWith(extension!!)
}
/**
* Check if the InputStream is to a valid non-empty zip file
* @param data uri from which to get input stream
* @return whether or not valid zip file
*/
private fun hasValidZipFile(context: Context, data: Uri?): Boolean {
// Get an input stream to the data in ContentProvider
var inputStream: InputStream? = null
try {
inputStream = context.contentResolver.openInputStream(data!!)
} catch (e: FileNotFoundException) {
Timber.e(e, "Could not open input stream to intent data")
}
// Make sure it's not null
if (inputStream == null) {
Timber.e("Could not open input stream to intent data")
return false
}
// Open zip input stream
val zis = ZipInputStream(inputStream)
var ok = false
try {
try {
val ze = zis.nextEntry
if (ze != null) {
// set ok flag to true if there are any valid entries in the zip file
ok = true
}
} catch (e: Exception) {
// don't set ok flag
Timber.d(e, "Error checking if provided file has a zip entry")
}
} finally {
// close the input streams
try {
zis.close()
inputStream.close()
} catch (e: Exception) {
Timber.d(e, "Error closing the InputStream")
}
}
return ok
}
}
}
class ImportResult(val humanReadableMessage: String?) {
val isSuccess: Boolean
get() = humanReadableMessage == null
companion object {
fun fromErrorString(message: String?): ImportResult {
return ImportResult(message)
}
fun fromSuccess(): ImportResult {
return ImportResult(null)
}
fun fromInvalidZip(ctx: Context, file: File, e: Exception): ImportResult {
return fromErrorString(getInvalidZipException(ctx, file, e))
}
private fun getInvalidZipException(ctx: Context, @Suppress("UNUSED_PARAMETER") file: File, e: Exception): String {
// This occurs when there is random corruption in a zip file
if (e is IOException && "central directory is empty, can't expand corrupt archive." == e.message) {
return ctx.getString(R.string.import_error_corrupt_zip, e.getLocalizedMessage())
}
// 7050 - this occurs when a file is truncated at the end (partial download/corrupt).
if (e is ZipException && "archive is not a ZIP archive" == e.message) {
return ctx.getString(R.string.import_error_corrupt_zip, e.getLocalizedMessage())
}
// If we don't have a good string, send a silent exception that we can better handle this in the future
CrashReportService.sendExceptionReport(e, "Import - invalid zip", "improve UI message here", true)
return ctx.getString(R.string.import_log_failed_unzip, e.localizedMessage)
}
}
}
}
| AnkiDroid/src/main/java/com/ichi2/utils/ImportUtils.kt | 4175607880 |
package de.christinecoenen.code.zapp.persistence
import androidx.room.TypeConverter
import org.joda.time.DateTime
class DateTimeConverter {
companion object {
@TypeConverter
@JvmStatic
fun fromDownloadStatus(value: DateTime?): Long {
return value?.toDateTimeISO()?.millis ?: 0L
}
@TypeConverter
@JvmStatic
fun toDownloadStatus(value: Long): DateTime? {
return if (value == 0L) null else DateTime(value)
}
}
}
| app/src/main/java/de/christinecoenen/code/zapp/persistence/DateTimeConverter.kt | 3318428599 |
/****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.wildplot.android.parsing
import java.lang.IllegalArgumentException
class ExpressionFormatException : IllegalArgumentException {
constructor() : super()
constructor(detailMessage: String?) : super(detailMessage)
}
| AnkiDroid/src/main/java/com/wildplot/android/parsing/ExpressionFormatException.kt | 249762208 |
package com.easternedgerobotics.rov.value
data class PortAftSpeedValue(override val speed: Float = 0f) : SpeedValue {
constructor() : this(0f)
}
| src/main/kotlin/com/easternedgerobotics/rov/value/PortAftSpeedValue.kt | 112049747 |
package com.sergey.spacegame.client.ui.scene2d
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.utils.ImmutableArray
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Matrix3
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack
import com.sergey.spacegame.common.ecs.component.PositionComponent
import com.sergey.spacegame.common.ecs.component.SizeComponent
import com.sergey.spacegame.common.ecs.component.Team1Component
import com.sergey.spacegame.common.ecs.component.Team2Component
import com.sergey.spacegame.common.ecs.component.VisualComponent
import com.sergey.spacegame.common.game.Level
/**
* A class that represents a drawable for a minimap
*
* @author sergeys
*
* @constructor Creates a new MinimapDrawable
* @property team1 - the texture region used to represent something from team 1
* @property team2 - the texture region used to represent something from team 2
* @property neutral - the texture region used to represent something not on a team
* @property white - a texture region representing a white pixel
* @property level - the level that this minimap should represent
* @property screen - a rectangle representing the area of the world that the screen covers
*/
class MinimapDrawable(val team1: TextureRegion, val team2: TextureRegion, val neutral: TextureRegion,
val white: TextureRegion,
val level: Level, val screen: Rectangle) : Drawable {
private var _minHeight: Float = 1f
private var _minWidth: Float = 1f
private var _rightWidth: Float = 0f
private var _leftWidth: Float = 0f
private var _bottomHeight: Float = 0f
private var _topHeight: Float = 0f
private val team1Entities = level.ecs.getEntitiesFor(Family.all(Team1Component::class.java, VisualComponent::class.java, PositionComponent::class.java).get())
private val team2Entities = level.ecs.getEntitiesFor(Family.all(Team2Component::class.java, VisualComponent::class.java, PositionComponent::class.java).get())
private val neutralEntities = level.ecs.getEntitiesFor(Family.all(VisualComponent::class.java, PositionComponent::class.java).exclude(Team1Component::class.java, Team2Component::class.java).get())
private val projection = Matrix3()
private val invProjection = Matrix3()
private val VEC = Vector2()
private var scaleX: Float = 1f
private var scaleY: Float = 1f
private var dragging: Boolean = false
override fun draw(batch: Batch, x: Float, y: Float, width: Float, height: Float) {
//Create our projection matrix
projection.setToTranslation(x - level.limits.minX, y - level.limits.minY)
scaleX = width / level.limits.width
scaleY = height / level.limits.height
projection.scale(scaleX, scaleY)
//Create the inverse of the projection matrix
invProjection.set(projection).inv()
//Calculate the position of the camera as of this frame
val x1 = VEC.set(screen.x - screen.width / 2, screen.y - screen.height / 2).mul(projection).x
val y1 = VEC.y
val x2 = VEC.set(screen.x + screen.width / 2, screen.y + screen.height / 2).mul(projection).x
val y2 = VEC.y
//Render the camera's position
batch.draw(white, x1, y1, x2 - x1, 1f) //Bottom
batch.draw(white, x1, y1, 1f, y2 - y1) //Left
batch.draw(white, x1, y2, x2 - x1, 1f) //Top
batch.draw(white, x2, y1, 1f, y2 - y1) //Right
//Border
batch.draw(white, x, y, width, 1f) //Bottom
batch.draw(white, x, y, 1f, height) //Left
batch.draw(white, x, y + height, width, 1f) //Top
batch.draw(white, x + width, y, 1f, height) //Right
//If it is controllable then allow the user to click to move the camera
if (level.viewport.viewportControllable) {
if (Gdx.input.justTouched() && Gdx.input.isTouched && Gdx.input.x in x..(x + width) && (Gdx.graphics.height - Gdx.input.y) in y..(y + height)) {
dragging = true
}
//Allow the user to drag around the position of the camera (invalid locaitons will be corrected in GameScreen#render
if (dragging && Gdx.input.isTouched && Gdx.input.x in x..(x + width) && (Gdx.graphics.height - Gdx.input.y) in y..(y + height)) {
VEC.set(Gdx.input.x.toFloat(), (Gdx.graphics.height - Gdx.input.y).toFloat()).mul(invProjection)
screen.x = VEC.x
screen.y = VEC.y
} else {
dragging = false
}
} else {
dragging = false
}
//Draw the previous things with clipping
batch.flush()
//Enable clipping
val pushed = ScissorStack.pushScissors(Rectangle(x, y, width, height))
//Draw all of the entities
drawEntities(neutralEntities, batch, neutral, scaleX, scaleY)
drawEntities(team2Entities, batch, team2, scaleX, scaleY)
drawEntities(team1Entities, batch, team1, scaleX, scaleY)
//Push it to the screen
batch.flush()
//Remove the clipping
if (pushed) ScissorStack.popScissors()
}
private fun drawEntities(array: ImmutableArray<Entity>,
batch: Batch,
region: TextureRegion, scaleX: Float, scaleY: Float) {
for (entity in array) {
PositionComponent.MAPPER.get(entity).setVector(VEC).mul(projection)
val sizeComponent = SizeComponent.MAPPER.get(entity)
if (sizeComponent == null) {
batch.draw(region, VEC.x - defaultWidth * scaleX / 2, VEC.y - defaultHeight * scaleY / 2, defaultWidth * scaleX, defaultWidth * scaleY)
} else {
batch.draw(region, VEC.x - sizeComponent.w * scaleX / 2, VEC.y - sizeComponent.h * scaleY / 2, sizeComponent.w * scaleX, sizeComponent.h * scaleY)
}
}
}
override fun setRightWidth(rightWidth: Float) {
_rightWidth = rightWidth
}
override fun getLeftWidth(): Float = _leftWidth
override fun setMinHeight(minHeight: Float) {
_minHeight = minHeight
}
override fun setBottomHeight(bottomHeight: Float) {
_bottomHeight = bottomHeight
}
override fun setTopHeight(topHeight: Float) {
_topHeight = topHeight
}
override fun getBottomHeight(): Float = _bottomHeight
override fun getRightWidth(): Float = _rightWidth
override fun getMinWidth(): Float = _minWidth
override fun getTopHeight(): Float = _topHeight
override fun setMinWidth(minWidth: Float) {
_minWidth = minWidth
}
override fun setLeftWidth(leftWidth: Float) {
_leftWidth = leftWidth
}
override fun getMinHeight(): Float = _minHeight
private companion object {
val defaultWidth = 10f
val defaultHeight = 10f
}
} | desktop/src/com/sergey/spacegame/client/ui/scene2d/MinimapDrawable.kt | 2931462141 |
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package uk.ac.bournemouth.darwin.html
import io.github.pdvrieze.darwin.servlet.support.ServletRequestInfo
import io.github.pdvrieze.darwin.servlet.support.darwinError
import io.github.pdvrieze.darwin.servlet.support.darwinResponse
import io.github.pdvrieze.darwin.servlet.support.htmlAccepted
import kotlinx.html.*
import net.devrieze.util.nullIfNot
import net.devrieze.util.overrideIf
import nl.adaptivity.xmlutil.XmlStreaming
import nl.adaptivity.xmlutil.XmlWriter
import nl.adaptivity.xmlutil.smartStartTag
import nl.adaptivity.xmlutil.writeAttribute
import uk.ac.bournemouth.darwin.accounts.*
import uk.ac.bournemouth.darwin.sharedhtml.darwinDialog
import uk.ac.bournemouth.darwin.sharedhtml.loginDialog
import uk.ac.bournemouth.darwin.sharedhtml.setAliasDialog
import java.net.URI
import java.net.URLEncoder
import java.security.MessageDigest
import java.security.Principal
import java.text.DateFormat
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
import javax.mail.Message
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import javax.servlet.ServletConfig
import javax.servlet.ServletException
import javax.servlet.annotation.MultipartConfig
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
//internal const val MAXTOKENLIFETIME = 864000 /* Ten days */
//internal const val MAXCHALLENGELIFETIME = 60 /* 60 seconds */
//internal const val MAX_RESET_VALIDITY = 1800 /* 12 hours */
/*
* This file contains the functionality needed for managing accounts on darwin. This includes the underlying database
* interaction through [AccountDb] as well as web interaction through [AccountController].
*/
/** Create a SHA1 digest of the source */
internal fun sha1(src: ByteArray): ByteArray = MessageDigest.getInstance("SHA1").digest(src)
const val DBRESOURCE = "java:comp/env/jdbc/webauthadm"
@MultipartConfig
class AccountController : HttpServlet() {
companion object {
private val log = Logger.getLogger(AccountController::class.java.name)
const val FIELD_USERNAME = "username"
const val FIELD_PASSWORD = "password"
const val FIELD_PUBKEY = "pubkey"
const val FIELD_REDIRECT = "redirect"
const val FIELD_KEYID = "keyid"
const val FIELD_ALIAS = "alias"
const val FIELD_APPNAME = "app"
const val FIELD_RESPONSE = "response"
const val FIELD_RESETTOKEN = "resettoken"
const val FIELD_NEWPASSWORD1 = "newpassword1"
const val FIELD_NEWPASSWORD2 = "newpassword2"
const val SC_UNPROCESSIBLE_ENTITY = 422
const val CHALLENGE_VERSION = "2"
const val HEADER_CHALLENGE_VERSION = "X-Challenge-version"
const val MIN_RESET_DELAY = 60 * 1000 // 60 seconds between reset requests
}
private inline fun <R> accountDb(block: AccountDb.() -> R): R = accountDb(DBRESOURCE, block)
private val logger = Logger.getLogger(AccountController::class.java.name)
override fun init(config: ServletConfig?) {
super.init(config)
logger.info("Initialising AccountController (ensuring that the required database tables are available)")
accountDb { this.ensureTables() }
}
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
val realPath = if (req.requestURI.startsWith(req.contextPath)) {
req.requestURI.substring(req.contextPath.length)
} else req.pathInfo
when (realPath) {
"/login" -> tryLogin(req, resp)
"/logout" -> logout(req, resp)
"/challenge" -> challenge(req, resp)
"/chpasswd" -> chpasswd(req, resp)
"/regkey" -> resp.darwinError(req, "HTTP method GET is not supported by this URL",
HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Get not supported")
"/forget" -> forgetKey(req, resp)
"/", null, "/myaccount" -> myAccount(req, resp)
"/setAliasForm" -> setAliasForm(req, resp)
"/resetpasswd" -> resetPassword(req, resp)
"/js/main.js" -> mainJs(req, resp)
else -> resp.darwinError(req, "The resource ${req.contextPath}${req.pathInfo
?: ""} was not found",
HttpServletResponse.SC_NOT_FOUND, "Not Found")
}
}
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
when (req.pathInfo) {
"/login" -> tryCredentials(req, resp)
"/challenge" -> challenge(req, resp)
"/chpasswd" -> chpasswd(req, resp)
"/regkey" -> registerkey(req, resp)
"/forget" -> forgetKey(req, resp)
else -> resp.darwinError(req, "The resource ${req.contextPath}${req.pathInfo} was not found",
HttpServletResponse.SC_NOT_FOUND, "Not Found")
}
}
private fun setAliasForm(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
val user: String = req.userPrincipal.name
val oldAlias: String? = req.getParameter(FIELD_ALIAS).nullIfNot { length > 0 }
val displayName: String = oldAlias.overrideIf { isBlank() } by user
resp.darwinResponse(req, "My Account", "My Account - $displayName") {
setAliasDialog(oldAlias)
}
}
}
private fun mainJs(req: HttpServletRequest, resp: HttpServletResponse) {
resp.contentType = "text/javascript"
resp.writer.use { out ->
out.println("""
require.config({
baseUrl:"/js",
paths: {
"accountmgr": "${req.contextPath}/js/accountmgr"
}
});
requirejs(['accountmgr'], function (accountmgr){
accountmgr.updateLinks()
})
""".trimIndent())
}
}
private data class AccountInfo(
val username: String,
val alias: String?,
val fullname: String?,
val isLocalPassword: Boolean,
val keys: List<KeyInfo>) {
fun toXmlWriter(writer: XmlWriter) {
writer.smartStartTag(null, "account") {
writeAttribute("username", username)
alias?.let { writeAttribute("alias", it) }
fullname?.let { writeAttribute("fullname", it) }
writeAttribute("isLocalPassword", if(isLocalPassword) "yes" else "no")
for (key in keys) {
key.toXmlWriter(writer)
}
}
}
}
private fun myAccount(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
val user: String = req.userPrincipal.name
val info = accountDb {
val alias = alias(user)
val fullname = fullname(user)
val isLocal = isLocalAccount(user)
val keys = keyInfo(user)
AccountInfo(user, alias, fullname, isLocal, keys)
}
if (req.htmlAccepted) {
val displayName = if (info.alias.isNullOrBlank()) (info.fullname ?: user) else info.alias
resp.darwinResponse(req, "My Account", "My Account - $displayName") {
section {
h1 { +"Account" }
p {
if (info.alias == null) {
val encodedDisplayName = URLEncoder.encode(displayName, "UTF-8")
a(href = "${context.accountMgrPath}setAliasForm?$FIELD_ALIAS=$encodedDisplayName") {
id = "accountmgr.setAlias"
attributes["alias"] = displayName
+"Set alias"
}
} else {
+"Alias: ${info.alias} "
a(href = "${context.accountMgrPath}setAliasForm?$FIELD_ALIAS=${info.alias}") {
id = "accountmgr.setAlias"
attributes["alias"] = info.alias
+"change"
}
}
}
if (info.isLocalPassword) p { a(href = "chpasswd") { +"change password" } }
}
val keys = info.keys
if (keys.isNotEmpty()) {
section {
h1 { +"Authorizations" }
table {
thead {
tr { th { +"Application" }; th { +"Last use" }; th {} }
}
tbody {
for (key in keys) {
tr {
classes += "authkey"
td { +(key.appname ?: "<unknown>") }
td {
+(key.lastUse?.let { DateFormat.getDateTimeInstance().format(it) }
?: "never")
}
td {
a(href = "${context.accountMgrPath}forget?$FIELD_KEYID=${key.keyId}",
classes = "forget_key_class") {
attributes["keyid"] = key.keyId.toString()
+"forget"
}
}
}
}
}
}
}
}
}
} else {
resp.contentType = "text/xml"
resp.characterEncoding="UTF8"
resp.outputStream.use {
XmlStreaming.newWriter(it, "UTF8").use { writer ->
writer.startDocument(null, null, null)
info.toXmlWriter(writer)
writer.endDocument()
}
}
}
}
}
private fun registerkey(req: HttpServletRequest, resp: HttpServletResponse) {
val username = req.getParameter(FIELD_USERNAME)
val password = req.getParameter(FIELD_PASSWORD)
val keyid = req.getParameter(FIELD_KEYID)
log.finer("registerkey called with username: $username password: ${"?".repeat(password.length)} keyid: $keyid")
if (username.isNullOrEmpty() || password.isNullOrEmpty()) {
resp.darwinError(req, "Missing credentials", HttpServletResponse.SC_FORBIDDEN, "Missing credentials")
log.warning("Missing credentials attempting to register key")
} else {
val pubkey = req.getParameter(FIELD_PUBKEY)
val appname: String? = req.getParameter(FIELD_APPNAME)
log.finer("registerkey: appname=$appname pubkey.length=${pubkey.length}")
accountDb(DBRESOURCE) {
if (verifyCredentials(username, password)) {
if (pubkey.isNullOrBlank()) {
resp.contentType = "text/plain"
resp.writer.use {
it.append("authenticated:").appendLine(username)
log.warning("registerkey: User authenticated but missing public key to register")
}
} else {
try {
val newKeyId = registerkey(username, pubkey, appname, keyid?.toInt())
resp.contentType = "text/plain"
resp.writer.use { it.append("key:").appendLine(newKeyId.toString()) }
log.fine("registerkey: registered key with id: $newKeyId")
} catch (e: NumberFormatException) {
resp.darwinError(
req, "Invalid key format", SC_UNPROCESSIBLE_ENTITY, "UNPROCESSIBLE ENTITY",
e
)
}
}
} else {
resp.darwinError(req, "Invalid credentials", HttpServletResponse.SC_FORBIDDEN,
"Invalid credentials")
log.info("Invalid authentication for user $username")
}
}
}
}
private fun forgetKey(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
val user = req.userPrincipal.name
val keyid: Int = try {
req.getParameter(FIELD_KEYID)?.toInt() ?: throw NumberFormatException("Missing keyId")
} catch (e: NumberFormatException) {
resp.darwinError(req,
"Invalid or missing key id (id:${req.getParameter(FIELD_KEYID)}, error:${e.message})",
SC_UNPROCESSIBLE_ENTITY, "UNPROCESSIBEL ENTITY")
return
}
try {
accountDb {
this.forgetKey(user, keyid)
}
} catch (e: IllegalArgumentException) {
resp.darwinError(req, "Key not owned", HttpServletResponse.SC_FORBIDDEN, "FORBIDDEN", e)
return
}
if (req.htmlAccepted) { // Just display the account manager dialog
resp.sendRedirect("${RequestServiceContext(ServletRequestInfo(req)).accountMgrPath}myaccount")
} else {
resp.status = HttpServletResponse.SC_NO_CONTENT
resp.writer.close()
}
}
}
private fun tryCredentials(req: HttpServletRequest, resp: HttpServletResponse) {
logger.info("Received username and password for login")
val username = req.getParameter(FIELD_USERNAME)
val password = req.getParameter(FIELD_PASSWORD)
val redirect = req.getParameter(FIELD_REDIRECT)
if (username == null || password == null) {
tryLogin(req, resp)
} else {
try {
if (req.authType != null || req.remoteUser != null || req.userPrincipal != null) {
// already authenticated
req.logout() // first log out. Then log in again
}
req.login(username, password) // this throws on failure
logger.fine("Login successful")
accountDb {
if (redirect != null) {
resp.sendRedirect(resp.encodeRedirectURL(redirect))
} else {
if (req.htmlAccepted) {
loginSuccess(req, resp)
} else {
resp.writer.use { it.append("login:").appendLine(username) }
}
}
}
} catch (e: ServletException) {
logger.log(Level.WARNING, "Failure in authentication", e)
invalidCredentials(req, resp)
}
}
}
private fun createAuthCookie(authtoken: String) = Cookie(DARWINCOOKIENAME,
authtoken).let { it.maxAge = MAXTOKENLIFETIME; it.path = "/"; it }
private fun HttpServletRequest.isAuthenticated(resp: HttpServletResponse): Boolean {
if (userPrincipal != null) {
return true
} else {
if (pathInfo != "/login") {
if (authenticate(resp)) {
if (userPrincipal != null) {
return true
}
}
}
}
return false
}
private inline fun authenticatedResponse(req: HttpServletRequest, resp: HttpServletResponse, block: () -> Unit) {
if (req.isAuthenticated(resp)) {
// if (req.userPrincipal!=null || (req.pathInfo!="/login" && req.authenticate(resp) && req.userPrincipal!=null)) {
block()
} else {
if (req.htmlAccepted) {
loginScreen(req, resp)
} else {
resp.status = HttpServletResponse.SC_UNAUTHORIZED
resp.writer.use { it.appendLine("error:Login is required\n") }
}
}
}
private inline fun authenticatedResponse(req: HttpServletRequest,
resp: HttpServletResponse,
condition: (HttpServletRequest) -> Boolean,
block: () -> Unit) {
if (req.isAuthenticated(resp) && condition(req)) {
block()
} else {
if (req.htmlAccepted) {
loginScreen(req, resp)
} else {
resp.status = HttpServletResponse.SC_UNAUTHORIZED
resp.writer.use { it.appendLine("error:Login is required\n") }
}
}
}
private fun tryLogin(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
accountDb {
val redirect = req.getParameter(FIELD_REDIRECT)
if (redirect != null) {
resp.sendRedirect(resp.encodeRedirectURL(redirect))
} else {
loginSuccess(req, resp)
}
}
}
}
private fun logout(req: HttpServletRequest, resp: HttpServletResponse) {
req.logout()
if (req.htmlAccepted) {
loginScreen(req, resp)
} else {
resp.contentType = "text/plain"
resp.writer.use { it.appendLine("logout") }
}
}
private fun challenge(req: HttpServletRequest, resp: HttpServletResponse) {
val keyId = req.getParameter(FIELD_KEYID)?.toInt()
if (keyId == null) {
resp.darwinError(req, "Insufficient credentials", 403, "Forbidden"); return
}
val responseParam = req.getParameter(FIELD_RESPONSE)
if (responseParam == null) {
issueChallenge(req, resp, keyId)
} else {
val response = try {
Base64.getUrlDecoder().decode(responseParam)
} catch (e: IllegalArgumentException) {
Base64.getDecoder().decode(responseParam)
}
handleResponse(req, resp, keyId, response)
}
}
private fun handleResponse(req: HttpServletRequest, resp: HttpServletResponse, keyId: Int, response: ByteArray) {
try {
accountDb {
val user = userFromChallengeResponse(keyId, req.remoteAddr, response)
if (user != null) {
val authtoken = createAuthtoken(user, req.remoteAddr, keyId)
resp.addHeader("Content-type", "text/plain")
resp.addCookie(createAuthCookie(authtoken))
resp.writer.use { it.append(authtoken) }
} else {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED)
}
}
} catch (e: AuthException) {
resp.darwinError(request = req, message = e.message, code = e.errorCode, cause = e)
}
}
private fun issueChallenge(req: HttpServletRequest, resp: HttpServletResponse, keyid: Int) {
accountDb {
cleanChallenges()
val challenge: String
try {
challenge = newChallenge(
keyid,
req.remoteAddr
) // This should fail on an incorrect keyid due to integrity constraints
} catch (e: AuthException) {
resp.contentType = "text/plain"
resp.status = e.errorCode
resp.writer.use { it.appendLine("INVALID REQUEST") }
if (e.errorCode == HttpServletResponse.SC_NOT_FOUND) { // missing code
return
}
throw e
}
resp.contentType = "text/plain"
resp.setHeader(HEADER_CHALLENGE_VERSION, CHALLENGE_VERSION)
resp.writer.use { it.appendLine(challenge) }
}
}
private class wrapUser(val req: HttpServletRequest, val username: String) : HttpServletRequest by req {
override fun getUserPrincipal(): Principal {
return Principal { username }
}
override fun isUserInRole(role: String): Boolean {
return accountDb { isUserInRole(username, role) }
}
override fun getAuthType() = HttpServletRequest.FORM_AUTH
}
private fun showChangeScreen(req: HttpServletRequest,
resp: HttpServletResponse,
message: String? = null,
resetToken: String? = null,
changedUser: String? = null) {
resp.darwinResponse(request = req, windowTitle = "Change password") {
darwinDialog("Change password") {
if (message != null) div("warning") { +message }
form(method = FormMethod.post) {
acceptCharset = "UTF-8"
if (resetToken != null) input(type = InputType.hidden) { value = resetToken }
table {
style = "border:none"
if (resetToken != null || req.isUserInRole("admin")) {
tr {
td { label { htmlFor = "#$FIELD_USERNAME"; +"Username:" } }
td {
input(name = FIELD_USERNAME, type = InputType.text) {
if (resetToken != null) {
disabled = true
}
if (changedUser != null) {
value = changedUser
}
}
}
}
} else {
tr {
td { label { htmlFor = "#$FIELD_PASSWORD"; +"Current password:" } }
td {
input(name = FIELD_PASSWORD, type = InputType.password)
}
}
}
tr {
td { label { htmlFor = "#$FIELD_NEWPASSWORD1"; +"New password:" } }
td { input(name = FIELD_NEWPASSWORD1, type = InputType.password) }
}
tr {
td { label { htmlFor = "#$FIELD_NEWPASSWORD2"; +"Repeat new password:" } }
td { input(name = FIELD_NEWPASSWORD2, type = InputType.password) }
}
}
span {
style = "margin-top: 1em; float:right"
input(type = InputType.submit) { value = "Change" }
}
}
}
}
}
private fun chpasswd(req: HttpServletRequest, resp: HttpServletResponse) {
val resetToken = req.getParameter(FIELD_RESETTOKEN).let { if (it.isNullOrBlank()) null else it }
if (req.userPrincipal == null && resetToken == null) {
// No user identification, require login first
resp.sendRedirect(resp.encodeRedirectURL("${req.servletPath}/login?redirect=${req.servletPath}/chpasswd"))
return
}
val changedUser: String? = req.getParameter(FIELD_USERNAME).let { if (it.isNullOrBlank()) null else it }
val origPasswd: String? = req.getParameter(FIELD_PASSWORD).let { if (it.isNullOrBlank()) null else it }
val newPasswd1: String? = req.getParameter(FIELD_NEWPASSWORD1).let { if (it.isNullOrBlank()) null else it }
val newPasswd2: String? = req.getParameter(FIELD_NEWPASSWORD2).let { if (it.isNullOrBlank()) null else it }
if (changedUser == null || newPasswd1 == null || newPasswd2 == null) {
showChangeScreen(req = req, resp = resp, resetToken = resetToken, changedUser = changedUser)
return
}
if (resetToken == null) req.login(changedUser,
origPasswd) // check the username/password again, if there is no reset token
if (newPasswd1 != newPasswd2) {
val message = if (origPasswd == null) {
"Please provide two identical copies of the new password"
} else {
"Please provide all of the current password and two copies of the new one"
}
showChangeScreen(req, resp, message = message, resetToken = resetToken)
return
}
if (newPasswd1.length < 6) {
showChangeScreen(req, resp, message = "The new passwords must be at lest 6 characters long",
resetToken = resetToken, changedUser = changedUser)
return
}
accountDb {
val requestingUser = req.userPrincipal?.name ?: changedUser
if (req.isUserInRole("admin")) {
if (updateCredentials(changedUser, newPasswd1)) {
resp.darwinResponse(req, "Password Changed") {
darwinDialog("Successs") { div { +"The password has been changed successfully" } }
}
} else {
resp.darwinError(req, "Failure updating password")
}
} else {
if (requestingUser == changedUser && resetToken != null && verifyResetToken(changedUser, resetToken)) {
if (updateCredentials(changedUser, newPasswd1)) {
resp.darwinResponse(req, "Password Changed") {
darwinDialog("Successs") { div { +"The password has been changed successfully" } }
}
} else {
resp.darwinError(req, "Failure updating password")
}
} else {
resp.darwinError(req, "The given reset token is invalid or expired")
}
}
}
}
private fun loginSuccess(req: HttpServletRequest, resp: HttpServletResponse) {
val userName = req.userPrincipal?.name
if (userName == null) {
loginScreen(req, resp)
} else {
if (req.htmlAccepted) {
resp.darwinResponse(request = req, windowTitle = "Welcome", pageTitle = "Welcome - Login successful") {
p { +"Congratulations with successfully authenticating on darwin." }
}
} else {
resp.writer.use { it.append("login:").appendLine(userName) }
}
}
}
private fun invalidCredentials(req: HttpServletRequest, resp: HttpServletResponse) {
resp.status = HttpServletResponse.SC_UNAUTHORIZED
if (req.htmlAccepted) {
loginScreen(req, resp, "Username or password not correct")
} else {
resp.writer.use { it.appendLine("invalid:Invalid credentials") }
}
}
private fun loginScreen(req: HttpServletRequest, resp: HttpServletResponse, errorMsg: String? = null) {
val redirect = req.getParameter("redirect") ?: if (req.pathInfo == "/login") null else req.requestURL.toString()
resp.darwinResponse(req, "Please log in") {
this.loginDialog(context, errorMsg, req.getParameter("username"), null, redirect, false)
/*
this.darwinDialog("Log in", positiveButton = null) {
if (errorMsg!=null) {
div("errorMsg") { +errorMsg }
}
form(action = "login", method = FormMethod.post, encType = FormEncType.applicationXWwwFormUrlEncoded) {
acceptCharset="utf8"
val redirect:String? = req.getParameter("redirect")
if(redirect!=null) {
input(name=FIELD_REDIRECT, type = InputType.hidden) { value = redirect }
}
val requestedUsername= req.getParameter("username")
table {
style = "border:none"
tr {
td {
label { for_='#'+FIELD_USERNAME
+"User name:"
}
}
td {
input(name=FIELD_USERNAME, type= InputType.text) {
if (requestedUsername!=null) { value=requestedUsername }
}
}
}
tr {
td {
label { for_='#'+FIELD_PASSWORD
+"Password:"
}
}
td {
input(name=FIELD_PASSWORD, type= InputType.password)
}
}
} // table
span {
style="margin-top: 1em; float: right;"
input(type= InputType.submit) {
value="Log in"
}
}
div { id="forgotpasswd"
a(href=req.contextPath+"/resetpasswd")
}
}
}
*/
}
}
private fun resetPassword(req: HttpServletRequest, resp: HttpServletResponse) {
val mailProperties = Properties()
val user = req.getParameter(FIELD_USERNAME)
if (user.isNullOrBlank()) {
requestResetDialog(req, resp)
} else {
accountDb {
if (!isUser(user)) throw AuthException("Unable to reset",
errorCode = HttpServletResponse.SC_BAD_REQUEST)
val lastReset = lastReset(user)?.time ?: 0
if (nowSeconds - lastReset < MIN_RESET_DELAY) throw AuthException("Too many reset attempts, try later",
errorCode = 429)
val resetToken = generateResetToken(user)
val mailSession = Session.getDefaultInstance(mailProperties)
val message = MimeMessage(mailSession)
val resetUrl = URI(req.scheme, null, req.serverName, req.serverPort, req.requestURI,
"?$FIELD_USERNAME=${URLEncoder.encode(user,
"UTF8")}&$FIELD_RESETTOKEN=${URLEncoder.encode(
resetToken, "UTF8")}", null).toString()
message.addRecipient(Message.RecipientType.TO, InternetAddress("[email protected]", user))
message.subject = "Darwin account password reset"
message.setContent("""
<html><head><title>Darwin account password reset</title></head><body>
<p>Please visit <a href="$resetUrl">$resetUrl</a> to reset your password.</p>
<p>This token will be valid for 30 minutes. If you didn't initiate the reset,
you can safely ignore this message</p>
</body></html>
""".trimIndent(), "text/html")
Transport.send(message)
}
resp.darwinResponse(req, "Reset request sent") {
darwinDialog("Reset request sent") {
p { +"A reset token has been sent to your email address. Please follow the instructions in the email." }
}
}
}
}
private fun requestResetDialog(req: HttpServletRequest,
resp: HttpServletResponse) {
resp.darwinResponse(req, "Provide username") {
darwinDialog("Give your username") {
p {
this.style = "width:22em"
+"Please provide your BU username such that a reset email can be sent to your email address."
}
form(action = "/resetpasswd", method = FormMethod.post) {
table {
tr {
th {
label { htmlFor = FIELD_USERNAME; +"User name:" }
}
td {
input(name = FIELD_USERNAME, type = InputType.text)
+"@bournemouth.ac.uk"
}
}
}
span {
style = "margin-top: 1em; float: right;"
input(type = InputType.reset) {
onClick = "window.location='/'"
}
input(type = InputType.submit) {
value = "Request reset"
}
}
}
}
}
}
}
| accountmgr/src/main/kotlin/uk/ac/bournemouth.darwin.html/AccountController.kt | 1171450283 |
package com.moviereel.utils.toolbox
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.util.*
/**
* @author lusinabrian on 27/07/17.
* @Notes Does diffing for adapters in class
* This is a utility that allows all adapters to update their data in a background thread and
* perform asynchronous updates
* @param oldItemList old items
* @param newItemList new item list
* @param adapter adapter to update
*/
class MovieReelDiffTool<T, VH : RecyclerView.ViewHolder>(
var oldItemList: ArrayList<T>,
var pendingUpdates: ArrayDeque<ArrayList<T>>,
var adapter: RecyclerView.Adapter<VH>) {
/**
* This performs a diff on the adapter
* */
fun performDiff(newItemList: ArrayList<T>) {
pendingUpdates.add(newItemList)
if (pendingUpdates.size > 1) {
return
}
updateItemsInternal(newItemList)
}
fun updateItemsInternal(newItemList: ArrayList<T>) {
doAsync {
val diff = MovieReelDiffUtilCallback(oldItemList, newItemList)
val diffResult = DiffUtil.calculateDiff(diff)
uiThread {
applyDiffResult(newItemList, diffResult)
}
}
// val handler = Handler()
// Thread(Runnable {
// val diff = MovieReelDiffUtilCallback(oldItemList, newItemList)
// val diffResult = DiffUtil.calculateDiff(diff)
//
// handler.post({
// applyDiffResult(newItemList, diffResult)
// })
// }).start()
}
/**
* Applyes the diff result to the new items which will apply th dispatch
* to the adapter
* @param newItemList
* @param diffResult, result from Diffing of new and old items
* */
fun applyDiffResult(newItemList: ArrayList<T>, diffResult: DiffUtil.DiffResult) {
pendingUpdates.remove()
// dispatch updates
dispatchUpdates(newItemList, diffResult)
if (pendingUpdates.size > 0) {
performDiff(pendingUpdates.peek())
}
}
/**
* Dispatches updates to adapter with new items and diff result
* @param newItems new items to add to adapter
* @param diffResult diff result from callback
* */
fun dispatchUpdates(newItems: ArrayList<T>, diffResult: DiffUtil.DiffResult) {
diffResult.dispatchUpdatesTo(adapter)
oldItemList.clear()
oldItemList.addAll(newItems)
}
} | app/src/main/kotlin/com/moviereel/utils/toolbox/MovieReelDiffTool.kt | 1866494038 |
package org.wordpress.android.fluxc.persistence
import com.wellsql.generated.PostSchedulingReminderTable
import com.yarolegovich.wellsql.WellSql
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.Table
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PostSchedulingNotificationSqlUtils
@Inject constructor() {
fun insert(
postId: Int,
scheduledTime: SchedulingReminderDbModel.Period
): Int? {
WellSql.insert(
PostSchedulingReminderBuilder(
postId = postId,
scheduledTime = scheduledTime.name
)
).execute()
return WellSql.select(PostSchedulingReminderBuilder::class.java)
.where()
.equals(PostSchedulingReminderTable.POST_ID, postId)
.equals(PostSchedulingReminderTable.SCHEDULED_TIME, scheduledTime.name)
.endWhere().asModel.firstOrNull()?.id
}
fun deleteSchedulingReminders(postId: Int) {
WellSql.delete(PostSchedulingReminderBuilder::class.java)
.where()
.equals(PostSchedulingReminderTable.POST_ID, postId)
.endWhere()
.execute()
}
fun getSchedulingReminderPeriodDbModel(
postId: Int
): SchedulingReminderDbModel.Period? {
return WellSql.select(PostSchedulingReminderBuilder::class.java)
.where()
.equals(PostSchedulingReminderTable.POST_ID, postId)
.endWhere().asModel.firstOrNull()?.scheduledTime?.let { SchedulingReminderDbModel.Period.valueOf(it) }
}
fun getSchedulingReminder(
notificationId: Int
): SchedulingReminderDbModel? {
return WellSql.select(PostSchedulingReminderBuilder::class.java)
.where()
.equals(PostSchedulingReminderTable.ID, notificationId)
.endWhere().asModel.firstOrNull()
?.let {
SchedulingReminderDbModel(
it.id,
it.postId,
SchedulingReminderDbModel.Period.valueOf(it.scheduledTime)
)
}
}
data class SchedulingReminderDbModel(val notificationId: Int, val postId: Int, val period: Period) {
enum class Period {
ONE_HOUR, TEN_MINUTES, WHEN_PUBLISHED
}
}
@Table(name = "PostSchedulingReminder")
data class PostSchedulingReminderBuilder(
@PrimaryKey @Column private var mId: Int = -1,
@Column var postId: Int,
@Column var scheduledTime: String
) : Identifiable {
constructor() : this(-1, -1, "")
override fun setId(id: Int) {
this.mId = id
}
override fun getId() = mId
}
}
| fluxc/src/main/java/org/wordpress/android/fluxc/persistence/PostSchedulingNotificationSqlUtils.kt | 330023258 |
package org.wordpress.android.fluxc.list
import com.nhaarman.mockitokotlin2.mock
import org.wordpress.android.fluxc.model.list.ListConfig
import org.wordpress.android.fluxc.model.list.ListDescriptor
import org.wordpress.android.fluxc.model.list.ListDescriptorTypeIdentifier
import org.wordpress.android.fluxc.model.list.ListDescriptorUniqueIdentifier
import org.wordpress.android.fluxc.model.list.datasource.InternalPagedListDataSource
import org.wordpress.android.fluxc.model.list.datasource.ListItemDataSourceInterface
internal typealias TestListIdentifier = Long
internal typealias TestPagedListResultType = String
internal typealias TestInternalPagedListDataSource =
InternalPagedListDataSource<TestListDescriptor, TestListIdentifier, TestPagedListResultType>
internal typealias TestListItemDataSource =
ListItemDataSourceInterface<TestListDescriptor, TestListIdentifier, TestPagedListResultType>
internal class TestListDescriptor(
override val uniqueIdentifier: ListDescriptorUniqueIdentifier = mock(),
override val typeIdentifier: ListDescriptorTypeIdentifier = mock(),
override val config: ListConfig = ListConfig.default
) : ListDescriptor
| example/src/test/java/org/wordpress/android/fluxc/list/TestListDescriptor.kt | 1705389640 |
package com.example.mercury.nearbysample
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.ObjectInput
import java.io.ObjectInputStream
import java.io.ObjectOutput
import java.io.ObjectOutputStream
import java.io.Serializable
class MessageModel(val who: String?, val text: String?) : Serializable {
override fun toString(): String {
return "MessageModel{" +
"who='" + who + '\''.toString() +
", text='" + text + '\''.toString() +
'}'.toString()
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || javaClass != o.javaClass) return false
val that = o as MessageModel?
if (if (who != null) who != that!!.who else that!!.who != null) return false
return if (text != null) text == that.text else that.text == null
}
override fun hashCode(): Int {
var result = who?.hashCode() ?: 0
result = 31 * result + (text?.hashCode() ?: 0)
return result
}
companion object {
fun empty(): MessageModel {
return MessageModel("", "")
}
@Throws(IOException::class)
fun convertToBytes(messageModel: MessageModel): ByteArray {
ByteArrayOutputStream().use { bos ->
ObjectOutputStream(bos).use { out ->
out.writeObject(messageModel)
return bos.toByteArray()
}
}
}
@Throws(IOException::class, ClassNotFoundException::class)
fun convertFromBytes(bytes: ByteArray): MessageModel {
ByteArrayInputStream(bytes).use { bis -> ObjectInputStream(bis).use { `in` -> return `in`.readObject() as MessageModel } }
}
}
}
| app/src/main/java/com/example/mercury/nearbysample/MessageModel.kt | 2101414355 |
package me.serce.franky.ui.flame
import me.serce.franky.Protocol.CallTraceSampleInfo
import java.util.*
fun CallTraceSampleInfo.validate() {
if (frameList.isEmpty()) {
throw IllegalArgumentException("Empty trace sample $this")
}
}
/**
* Represents tree of stack traces
*/
class FlameTree(sampleInfo: List<CallTraceSampleInfo>) {
val root: FlameNode = FlameNode(0, null)
init {
for (sample in sampleInfo) {
sample.validate()
addSampleToTree(sample)
}
}
private fun addSampleToTree(sample: CallTraceSampleInfo) {
val coef = sample.callCount
root.cost += coef
var node = root
for (frame in sample.frameList.reversed()) {
val methodId = frame.jMethodId
node = node.children.computeIfAbsent(methodId, {
FlameNode(frame.jMethodId, node)
})
node.cost += coef
}
}
}
class FlameNode(val methodId: Long, val parent: FlameNode?) {
var cost: Int = 0
val children: HashMap<Long, FlameNode> = hashMapOf()
}
| franky-intellij/src/main/kotlin/me/serce/franky/ui/flame/flameTree.kt | 160816959 |
package ch.difty.scipamato.core.sync.launcher
import ch.difty.scipamato.common.persistence.paging.Sort
import java.io.Serializable
import kotlin.math.min
/**
* The [SyncJobResult] collects log messages for one or more job steps
* and keeps track of the entire jobs result. If all steps succeed, the jobs
* result is success. If only one step fails, the job fails.
*/
class SyncJobResult {
private val logMessages: MutableList<LogMessage> = ArrayList()
private var result = JobResult.UNKNOWN
private var running = false
val isRunning get() = running
val isSuccessful: Boolean
get() = result == JobResult.SUCCESS
val isFailed: Boolean
get() = result == JobResult.FAILURE
val messages: List<LogMessage>
get() = ArrayList(logMessages)
fun messageCount() = messages.size.toLong()
fun setSuccess(msg: String) {
running = true
if (result != JobResult.FAILURE) result = JobResult.SUCCESS
logMessages.add(LogMessage(msg, MessageLevel.INFO))
}
fun setFailure(msg: String) {
running = true
result = JobResult.FAILURE
logMessages.add(LogMessage(msg, MessageLevel.ERROR))
}
fun setWarning(msg: String) {
running = true
logMessages.add(LogMessage(msg, MessageLevel.WARNING))
}
fun setDone() {
running = false
}
fun getPagedResultMessages(first: Int, count: Int, sortProp: String, dir: Sort.Direction): Iterator<LogMessage> {
fun <T, R : Comparable<R>> List<T>.sortMethod(selector: (T) -> R?): List<T> =
if (dir == Sort.Direction.ASC) this.sortedBy(selector)
else sortedByDescending(selector)
val sorted = when (sortProp) {
"messageLevel" -> messages.sortMethod { it.messageLevel }
else -> messages.sortMethod { it.message }
}
return sorted.subList(first, min(first + count, messages.size)).iterator()
}
fun clear() {
logMessages.clear()
result = JobResult.UNKNOWN
setDone()
}
private enum class JobResult {
UNKNOWN, SUCCESS, FAILURE
}
enum class MessageLevel {
INFO, WARNING, ERROR
}
data class LogMessage(
val message: String? = null,
val messageLevel: MessageLevel = MessageLevel.INFO,
) : Serializable {
companion object {
private const val serialVersionUID = 1L
}
}
}
| core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/launcher/SyncJobResult.kt | 2499423020 |
@file:JvmName("RPickMedia")
package pyxis.uzuki.live.richutilskt.utils
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import pyxis.uzuki.live.richutilskt.impl.F2
import pyxis.uzuki.live.richutilskt.module.image.OrientationFixer
class RPickMedia private constructor() {
private var mInternalStorage: Boolean = false
private var fixPhotoOrientation: Boolean = false
private val PERMISSION_ARRAY = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
private lateinit var title: String
private fun getActivity(context: Context): FragmentActivity? {
var c = context
while (c is ContextWrapper) {
if (c is FragmentActivity) {
return c
}
c = c.baseContext
}
return null
}
private fun Context.requestPermission(listener: (Boolean) -> Unit) {
RPermission.instance.checkPermission(this, PERMISSION_ARRAY) { code, _ ->
listener.invoke(code == RPermission.PERMISSION_GRANTED)
}
}
/**
* enable internal storage mode
*
* @param [isInternal] capture Image/Video in internal storage
*/
fun setInternalStorage(isInternal: Boolean) {
mInternalStorage = isInternal
}
/**
* enable fixing orientation
*
* @param [enable] fixing orientation
*/
fun setFixPhotoOrientation(enable: Boolean) {
this.fixPhotoOrientation = enable
}
/**
* set title of media when capture using PICK_FROM_CAMERA and PICK_FROM_CAMERA_VIDEO
*/
fun setTitle(title: String) {
this.title = title
}
/**
* pick image from Camera
*
* @param[callback] callback
*/
fun pickFromCamera(context: Context, callback: (Int, String) -> Unit) {
context.requestPermission {
if (!it) {
callback.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_CAMERA, callback)
}
}
/**
* pick image from Camera
*
* @param[callback] callback
*/
fun pickFromCamera(context: Context, callback: F2<Int, String>?) {
context.requestPermission {
if (!it) {
callback?.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_CAMERA) { code, uri -> callback?.invoke(code, uri) }
}
}
/**
* pick image from Gallery
*
* @param[callback] callback
*/
fun pickFromGallery(context: Context, callback: (Int, String) -> Unit) {
context.requestPermission {
if (!it) {
callback.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_GALLERY, callback)
}
}
/**
* pick image from Gallery
*
* @param[callback] callback
*/
fun pickFromGallery(context: Context, callback: F2<Int, String>?) {
context.requestPermission {
if (!it) {
callback?.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_GALLERY) { code, uri -> callback?.invoke(code, uri) }
}
}
/**
* pick image from Video
*
* @param[callback] callback
*/
fun pickFromVideo(context: Context, callback: (Int, String) -> Unit) {
context.requestPermission {
if (!it) {
callback.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_VIDEO, callback)
}
}
/**
* pick image from Video
*
* @param[callback] callback
*/
fun pickFromVideo(context: Context, callback: F2<Int, String>?) {
context.requestPermission {
if (!it) {
callback?.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_VIDEO, { code, uri -> callback?.invoke(code, uri) })
}
}
/**
* pick image from Camera (Video Mode)
*
* @param[callback] callback
*/
fun pickFromVideoCamera(context: Context, callback: (Int, String) -> Unit) {
context.requestPermission {
if (!it) {
callback.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_CAMERA_VIDEO, callback)
}
}
/**
* pick image from Camera (Video Mode)
*
* @param[callback] callback
*/
fun pickFromVideoCamera(context: Context, callback: F2<Int, String>?) {
context.requestPermission {
if (!it) {
callback?.invoke(PICK_FAILED, "")
return@requestPermission
}
requestPhotoPick(context, PICK_FROM_CAMERA_VIDEO, { code, uri -> callback?.invoke(code, uri) })
}
}
private var currentPhotoPath: String? = null
private var currentVideoPath: String? = null
@SuppressLint("ValidFragment")
private fun requestPhotoPick(context: Context, pickType: Int, callback: (Int, String) -> Unit) {
val fm = getActivity(context)?.supportFragmentManager
val intent = Intent()
if (!::title.isInitialized) {
title = nowDateString()
}
when (pickType) {
PICK_FROM_CAMERA -> {
intent.action = MediaStore.ACTION_IMAGE_CAPTURE
val captureUri = createUri(context, false, mInternalStorage, title)
currentPhotoPath = captureUri.toString()
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri)
}
PICK_FROM_GALLERY -> {
intent.action = Intent.ACTION_PICK
intent.type = android.provider.MediaStore.Images.Media.CONTENT_TYPE
}
PICK_FROM_VIDEO -> {
intent.action = Intent.ACTION_PICK
intent.type = android.provider.MediaStore.Video.Media.CONTENT_TYPE
}
PICK_FROM_CAMERA_VIDEO -> {
intent.action = MediaStore.ACTION_VIDEO_CAPTURE
val captureUri = createUri(context, true, mInternalStorage, title)
currentVideoPath = captureUri.toString()
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri)
}
}
val fragment = ResultFragment(fm as FragmentManager, callback, currentPhotoPath
?: "", currentVideoPath ?: "")
fragment.fixPhotoOrientation = fixPhotoOrientation
fm.beginTransaction().add(fragment, "FRAGMENT_TAG").commitAllowingStateLoss()
fm.executePendingTransactions()
fragment.startActivityForResult(intent, pickType)
}
@SuppressLint("ValidFragment")
class ResultFragment() : Fragment() {
var fm: FragmentManager? = null
var callback: ((Int, String) -> Unit)? = null
var currentPhotoPath = ""
var currentVideoPath = ""
var fixPhotoOrientation: Boolean = false
constructor(fm: FragmentManager, callback: (Int, String) -> Unit, currentPhotoPath: String, currentVideoPath: String) : this() {
this.fm = fm
this.callback = callback
this.currentPhotoPath = currentPhotoPath
this.currentVideoPath = currentVideoPath
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (callback == null) {
return
}
val callback = callback!! // implicit cast to non-null cause checking pre-processing
if (resultCode != Activity.RESULT_OK || context == null) {
callback.invoke(PICK_FAILED, "")
return
}
val context = context!! // implicit cast to non-null cause checking pre-processing
var realPath: String? = ""
if (requestCode == PICK_FROM_CAMERA) {
val uri = Uri.parse(currentPhotoPath)
realPath = uri getRealPath context
if (fixPhotoOrientation) {
realPath = OrientationFixer.execute(realPath, context)
}
} else if (requestCode == PICK_FROM_CAMERA_VIDEO && data != null && data.data != null) {
realPath = data.data.getRealPath(context)
if (realPath.isEmpty()) {
realPath = Uri.parse(currentVideoPath) getRealPath context
}
} else if (requestCode == PICK_FROM_CAMERA_VIDEO) {
realPath = Uri.parse(currentVideoPath) getRealPath context
} else if (data != null && data.data != null) {
realPath = data.data.getRealPath(context)
if (fixPhotoOrientation) {
realPath = OrientationFixer.execute(realPath, context)
}
}
if (realPath?.isEmpty() != false) {
callback.invoke(PICK_FAILED, "")
return
}
callback.invoke(PICK_SUCCESS, realPath)
fm?.beginTransaction()?.remove(this)?.commit()
}
}
companion object {
@JvmField
var instance: RPickMedia = RPickMedia()
val PICK_FROM_CAMERA = 0
val PICK_FROM_GALLERY = 1
val PICK_FROM_VIDEO = 2
val PICK_FROM_CAMERA_VIDEO = 3
@JvmField
val PICK_SUCCESS = 1
@JvmField
val PICK_FAILED = 0
}
} | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RPickMedia.kt | 3003312460 |
@file:Suppress("IllegalIdentifier")
package com.photoviewer.data.repository
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import com.photoviewer.data.entity.PhotoEntity
import com.photoviewer.data.repository.datastore.DatabasePhotoEntityStore
import com.photoviewer.data.repository.datastore.ServerPhotoEntityStore
import com.photoviewer.domain.usecases.SimpleSubscriber
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import rx.Observable.just
import java.util.*
class PhotoEntityDataSourceTest {
private val mDatabasePhotoEntityStore: DatabasePhotoEntityStore = mock()
private val mServerPhotoEntityStore: ServerPhotoEntityStore = mock()
private lateinit var mPhotoEntityDataSource: PhotoEntityDataSource
companion object {
private val FAKE_PHOTO_ID = 31
}
@Before fun setUp() {
mPhotoEntityDataSource = PhotoEntityDataSource(mDatabasePhotoEntityStore, mServerPhotoEntityStore)
}
@Test fun `should query database on getting photos`() {
val photosList = createPhotosList()
assumeDatabaseIsEmpty()
assumeServerHasRequestedContent(photosList)
mPhotoEntityDataSource.photos().subscribe(SimpleSubscriber<List<PhotoEntity>>())
verify(mDatabasePhotoEntityStore).queryForAll()
}
@Test fun `should query server on getting photos if database does not have them`() {
val photosList = createPhotosList()
assumeDatabaseIsEmpty()
assumeServerHasRequestedContent(photosList)
mPhotoEntityDataSource.photos().subscribe(SimpleSubscriber<List<PhotoEntity>>())
verify(mServerPhotoEntityStore).photoEntityList()
}
@Test fun `should save retrieved photos from server on getting photos`() {
val photosList = createPhotosList()
assumeDatabaseIsEmpty()
assumeServerHasRequestedContent(photosList)
mPhotoEntityDataSource.photos().subscribe(SimpleSubscriber<List<PhotoEntity>>())
verify(mDatabasePhotoEntityStore).saveAll(photosList)
}
private fun createPhotosList() = ArrayList<PhotoEntity>().apply {
add(PhotoEntity())
}
private fun assumeDatabaseIsEmpty() {
whenever(mDatabasePhotoEntityStore.queryForAll()).thenReturn(
just<List<PhotoEntity>>(ArrayList<PhotoEntity>()))
}
private fun assumeServerHasRequestedContent(photosList: List<PhotoEntity>) {
whenever(mServerPhotoEntityStore.photoEntityList()).thenReturn(just<List<PhotoEntity>>(photosList))
}
@Test fun `should not query server on getting photos if database has them`() {
val photoEntities = createPhotosList()
assumeDatabaseHasRequestesContent(photoEntities)
assumeServerHasRequestedContent(photoEntities)
mPhotoEntityDataSource.photos().subscribe()
verify(mDatabasePhotoEntityStore).queryForAll()
verifyZeroInteractions(mServerPhotoEntityStore)
}
private fun assumeDatabaseHasRequestesContent(photoEntities: List<PhotoEntity>) {
whenever(mDatabasePhotoEntityStore.queryForAll()).thenReturn(just<List<PhotoEntity>>(photoEntities))
}
@Test fun `should query only database on getting particular photo`() {
val photoEntity = PhotoEntity()
whenever(mDatabasePhotoEntityStore.queryForId(FAKE_PHOTO_ID)).thenReturn(
just(photoEntity))
mPhotoEntityDataSource.photo(FAKE_PHOTO_ID).subscribe()
verify(mDatabasePhotoEntityStore).queryForId(FAKE_PHOTO_ID)
}
}
| app/src/test/java/com/photoviewer/data/repository/PhotoEntityDataSourceTest.kt | 3710240013 |
package com.cypress.GameObjects.Enemies
import com.badlogic.gdx.graphics.g2d.Animation
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.utils.Array
import com.cypress.CGHelpers.AssetLoader
import com.cypress.GameObjects.*
/** */
class Warrior(public override val position : Vector2, private val player : Player) : Character() {
public override val isEnemy = true
public override val width = 115
public override val height = 180
public override val bounds = Rectangle(0f, 0f, width.toFloat(), height.toFloat())
public override val velocity = Vector2(4f, 12f)
public override val offsetY = 18f
public override val offsetX = 10f
public override var health = 50
public override var shouldGoToLeft = false
public override var delta = 0f
public override var shouldJump = false
public override var shouldGoToRight = false
public override var stayRight = false
public override var onGround = true
public override var gunType = "uzi"
public override var isDead = false
private val assets = AssetLoader.getInstance()
private val uziLeft = TextureRegion(assets.guns, 281, 95, 90, 58)
private var warriorGoesLeft = Animation(0.1f, Array<TextureRegion>())
private var warriorGoesRight = Animation(0.1f, Array<TextureRegion>())
private var warriorStayRight = TextureRegion(assets.warrior, 25, 11, width, height)
private var warriorStayLeft = TextureRegion(assets.warrior, 201, 11, width, height)
private var counter = 0
private var canShoot = false
private var startValue = 0f
init {
// setting animation
val posR = arrayOf(Pair( 28, 235), Pair(350, 237), Pair(674, 236), Pair( 30, 445), Pair(361, 445),
Pair(678, 445), Pair( 23, 662), Pair(349, 662), Pair(688, 663))
val posL = arrayOf(Pair(200, 236), Pair(529, 236), Pair(871, 236), Pair(199, 445), Pair(519, 442),
Pair(864, 442), Pair(204, 662), Pair(528, 661), Pair(853, 661))
val warriorsRight = Array<TextureRegion>()
val warriorsLeft = Array<TextureRegion>()
warriorsRight.addAll(
Array(9, {i -> TextureRegion(assets.warrior, posR[i].first, posR[i].second, width, height)}), 0, 8
)
warriorsLeft.addAll(
Array(9, {i -> TextureRegion(assets.warrior, posL[i].first, posL[i].second, width, height)}), 0, 8
)
warriorGoesRight = Animation(0.1f, warriorsRight, Animation.PlayMode.LOOP)
warriorGoesLeft = Animation(0.1f, warriorsLeft, Animation.PlayMode.LOOP)
}
/** Defines actions of warrior. */
public fun update(delta : Float) {
counter++
// movement of warrior
if (position.y <= 80f) {
onGround = true
position.y = 80f
velocity.y = 12f
}
// falling
else {
if (velocity.y < -9) velocity.y = -9f
position.y += velocity.y
velocity.y -= 0.2f
}
val distanceX = player.getX() - position.x
val distanceY = Math.abs(player.getY() - position.y)
if (counter % 50 == 0) {
canShoot = true
counter = 0
} else canShoot = false
// warrior pursues player
if (stayRight && distanceX > 0 && distanceX < 300f && distanceY < 500) {
shouldGoToRight = false
shouldGoToLeft = false
if (canShoot) {
assets.bulletsList.add(Bullet(this))
assets.shot[0]?.stop()
if (assets.musicOn) assets.shot[0]?.play()
}
}
else if (stayRight && distanceX >= 300f && distanceX < 500f) {
position.x += velocity.x
shouldGoToRight = true
shouldGoToLeft = false
}
else if (!stayRight && distanceX < 0 && distanceX > -300f && distanceY < 500) {
shouldGoToRight = false
shouldGoToLeft = false
if (canShoot) {
assets.bulletsList.add(Bullet(this))
assets.shot[0]?.stop()
if (assets.musicOn) assets.shot[0]?.play()
}
}
else if (!stayRight && distanceX <= -300f && distanceX > -500f) {
position.x -= velocity.x
shouldGoToRight = false
shouldGoToLeft = true
}
else if (distanceX == 0f) stayRight = !stayRight
// warrior can't find player and looks around
else {
shouldGoToRight = false
shouldGoToLeft = false
if (delta.hashCode() % 100 == 0) stayRight = !stayRight
}
}
/** Draws warrior. */
public fun draw(delta : Float, batcher : SpriteBatch) {
if (!isDead) startValue = delta
batcher.begin()
// warrior is dead
if (isDead) {
batcher.draw(death.getKeyFrame(delta - startValue), position.x, position.y, 155f, 155f)
if (delta - startValue > 0.5f) isDead = false
}
else {
if (shouldGoToLeft || !stayRight)
batcher.draw(uziLeft, position.x - 55, position.y + 25, 90f, 58f)
// warrior should stay still ...
if (!shouldGoToLeft && !shouldGoToRight) {
when (stayRight) {
// ... turning to the right side
true ->
batcher.draw(warriorStayRight, position.x, position.y, width.toFloat(), height.toFloat())
// ... turning to the left side
false ->
batcher.draw(warriorStayLeft, position.x, position.y, width.toFloat(), height.toFloat())
}
}
// warrior should go to left
else if (shouldGoToLeft) {
stayRight = false
batcher.draw(warriorGoesLeft.getKeyFrame(delta), position.x, position.y, width.toFloat(), height.toFloat())
}
// warrior should go to right
else if (shouldGoToRight) {
stayRight = true
batcher.draw(warriorGoesRight.getKeyFrame(delta), position.x, position.y, width.toFloat(), height.toFloat())
}
}
batcher.end()
}
/** Returns position of warrior on Ox axis. */
public override fun getX(): Float = position.x
/** Returns position of warrior on Oy axis. */
public override fun getY(): Float = position.y
/** Returns bounds of player. */
public fun getBound() : Rectangle = bounds
}
| core/src/com/cypress/GameObjects/Enemies/Warrior.kt | 780702013 |
package com.andreapivetta.blu.ui.timeline
import com.andreapivetta.blu.data.model.Tweet
import twitter4j.User
/**
* Created by andrea on 22/05/16.
*/
interface InteractionListener {
fun favorite(tweet: Tweet)
fun retweet(tweet: Tweet)
fun unfavorite(tweet: Tweet)
fun unretweet(tweet: Tweet)
fun reply(tweet: Tweet, user: User)
fun openTweet(tweet: Tweet)
fun showUser(user: User)
fun showImage(imageUrl: String)
fun showImages(imageUrls: List<String>, index: Int)
fun showVideo(videoUrl: String, videoType: String)
} | app/src/main/java/com/andreapivetta/blu/ui/timeline/InteractionListener.kt | 546820623 |
package me.ykrank.s1next.view.event
class RateEvent(val threadId: String, val postId: String)
| app/src/main/java/me/ykrank/s1next/view/event/RateEvent.kt | 728465070 |
package cases
@Suppress("unused", "UNUSED_VARIABLE")
fun preferToOverPairSyntaxPositive() {
val pair1 = Pair(1, 2)
val pair2: Pair<Int, Int> = Pair(1, 2)
val pair3 = Pair(Pair(1, 2), Pair(3, 4))
}
| detekt-rules/src/test/resources/cases/PreferToOverPairSyntaxPositive.kt | 2354313232 |
package com.pr0gramm.app.ui.fragments
import androidx.lifecycle.lifecycleScope
import com.pr0gramm.app.R
import com.pr0gramm.app.Settings
import com.pr0gramm.app.api.pr0gramm.Message
import com.pr0gramm.app.services.FavedCommentService
import com.pr0gramm.app.services.UserService
import com.pr0gramm.app.ui.MessageAdapter
import com.pr0gramm.app.ui.Pagination
import com.pr0gramm.app.ui.PaginationController
import com.pr0gramm.app.util.di.instance
/**
*/
class FavedCommentFragment : InboxFragment("FavedCommentFragment") {
private val favedCommentService: FavedCommentService by instance()
private val userService: UserService by instance()
override fun getContentAdapter(): Pair<MessageAdapter, Pagination<Message>> {
val loader = apiMessageLoader(requireContext()) { olderThan ->
val username = userService.name
if (username == null || !userService.isAuthorized) {
return@apiMessageLoader listOf()
}
favedCommentService.list(Settings.contentType, username, olderThan).map {
FavedCommentService.commentToMessage(it)
}
}
// create and initialize the adapter
val pagination = Pagination(lifecycleScope, loader)
val adapter = MessageAdapter(
R.layout.row_inbox_message, actionListener, null,
PaginationController(pagination))
return Pair(adapter, pagination)
}
}
| app/src/main/java/com/pr0gramm/app/ui/fragments/FavedCommentFragment.kt | 2445040319 |
package com.jamieadkins.gwent.domain.latest
data class GwentNewsArticle(
val id: Long,
val title: String,
val thumbnail: String,
val url: String
) | domain/src/main/java/com/jamieadkins/gwent/domain/latest/GwentNewsArticle.kt | 3086781115 |
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.gradle
interface Statement {
fun toGroovy(indentNumber: Int): String
}
data class StringStatement(val value: String) : Statement {
override fun toGroovy(indentNumber: Int): String = INDENT.repeat(indentNumber) + value
}
data class Expression(val left: String, val right: String) : Statement {
override fun toGroovy(indentNumber: Int): String = "${INDENT.repeat(indentNumber)}$left $right"
}
class Closure(val name: String, val statements: List<Statement>) : Statement {
override fun toGroovy(indentNumber: Int): String {
val indent = INDENT.repeat(indentNumber)
return """$indent$name {
${statements.joinToString(separator = "\n") { it.toGroovy(indentNumber + 1) }}
$indent}"""
}
}
data class Task(val name: String, val arguments: List<TaskParameter>, val statements: List<Statement>) : Statement {
override fun toGroovy(indentNumber: Int): String {
val indent = INDENT.repeat(indentNumber)
return """${indent}task $name(${arguments.joinToString { "${it.name}: ${it.value}" }}) {
${statements.joinToString(separator = "\n") { it.toGroovy(indentNumber + 1) }}
$indent}"""
}
}
data class TaskParameter(val name: String, val value: String)
private const val INDENT = " " | aspoet/src/main/kotlin/com/google/androidstudiopoet/gradle/GradleLang.kt | 427938327 |
/*
* 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.configurationStore.StreamProvider
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.options.*
import java.nio.file.Path
private val EMPTY = EmptySchemesManager()
class MockSchemeManagerFactory : SchemeManagerFactory() {
override fun <SCHEME : Scheme, MUTABLE_SCHEME : SCHEME> create(directoryName: String,
processor: SchemeProcessor<SCHEME, MUTABLE_SCHEME>,
presentableName: String?,
roamingType: RoamingType,
isUseOldFileNameSanitize: Boolean,
streamProvider: StreamProvider?,
directoryPath: Path?,
autoSave: Boolean): SchemeManager<SCHEME> {
@Suppress("UNCHECKED_CAST")
return EMPTY as SchemeManager<SCHEME>
}
}
| platform/testFramework/src/com/intellij/testFramework/MockSchemeManagerFactory.kt | 2811836602 |
package fernandocs.currencyconverter.view
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import fernandocs.currencyconverter.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.frag_container, RatesFragment()).commit()
}
}
}
| app/src/main/java/fernandocs/currencyconverter/view/MainActivity.kt | 3007426366 |
package com.github.pgutkowski.kgraphql.specification.language
import com.github.pgutkowski.kgraphql.Specification
import com.github.pgutkowski.kgraphql.assertNoErrors
import com.github.pgutkowski.kgraphql.expect
import com.github.pgutkowski.kgraphql.extract
import com.github.pgutkowski.kgraphql.integration.BaseSchemaTest
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
@Specification("2.10 Variables")
class VariablesSpecificationTest : BaseSchemaTest() {
@Test
fun `query with variables`(){
val map = execute(
query = "mutation(\$name: String!, \$age : Int!) {createActor(name: \$name, age: \$age){name, age}}",
variables = "{\"name\":\"Boguś Linda\", \"age\": 22}"
)
assertNoErrors(map)
assertThat(
map.extract<Map<String, Any>>("data/createActor"),
equalTo(mapOf("name" to "Boguś Linda", "age" to 22))
)
}
@Test
fun `query with boolean variable`(){
val map = execute(query = "query(\$big: Boolean!) {number(big: \$big)}", variables = "{\"big\": true}")
assertNoErrors(map)
assertThat(map.extract<Int>("data/number"), equalTo(10000))
}
@Test
fun `query with boolean variable default value`(){
val map = execute(query = "query(\$big: Boolean = true) {number(big: \$big)}")
assertNoErrors(map)
assertThat(map.extract<Int>("data/number"), equalTo(10000))
}
@Test
fun `query with variables and string default value`(){
val map = execute(
query = "mutation(\$name: String = \"Boguś Linda\", \$age : Int!) {createActor(name: \$name, age: \$age){name, age}}",
variables = "{\"age\": 22}"
)
assertNoErrors(map)
assertThat(
map.extract<Map<String, Any>>("data/createActor"),
equalTo(mapOf("name" to "Boguś Linda", "age" to 22))
)
}
@Test
fun `query with variables and default value pointing to another variable`(){
val map = execute(
query = "mutation(\$name: String = \"Boguś Linda\", \$age : Int = \$defaultAge, \$defaultAge : Int!) " +
"{createActor(name: \$name, age: \$age){name, age}}",
variables = "{\"defaultAge\": 22}"
)
assertNoErrors(map)
assertThat(
map.extract<Map<String, Any>>("data/createActor"),
equalTo(mapOf("name" to "Boguś Linda", "age" to 22))
)
}
@Test
fun `fragment with variable`(){
val map = execute(
query = "mutation(\$name: String = \"Boguś Linda\", \$age : Int!, \$big: Boolean!) {createActor(name: \$name, age: \$age){...Linda}}" +
"fragment Linda on Actor {picture(big: \$big)}",
variables = "{\"age\": 22, \"big\": true}"
)
assertNoErrors(map)
assertThat(
map.extract<String>("data/createActor/picture"),
equalTo("http://picture.server/pic/Boguś_Linda?big=true")
)
}
@Test
fun `fragment with missing variable`(){
expect<IllegalArgumentException>("Variable '\$big' was not declared for this operation"){
execute(
query = "mutation(\$name: String = \"Boguś Linda\", \$age : Int!) {createActor(name: \$name, age: \$age){...Linda}}" +
"fragment Linda on Actor {picture(big: \$big)}",
variables = "{\"age\": 22}"
)
}
}
} | src/test/kotlin/com/github/pgutkowski/kgraphql/specification/language/VariablesSpecificationTest.kt | 3347033696 |
package com.jereksel.libresubstratum
import android.arch.lifecycle.ViewModelProvider
import android.content.Context
import com.jereksel.libresubstratum.activities.installed.InstalledContract
import com.jereksel.libresubstratum.activities.priorities.PrioritiesContract
import com.jereksel.libresubstratum.activities.prioritiesdetail.PrioritiesDetailContract
import com.jereksel.libresubstratum.dagger.components.BaseComponent
import com.jereksel.libresubstratum.domain.Metrics
import com.jereksel.libresubstratum.domain.PrivacyPolicySettings
import com.jereksel.libresubstratum.domain.usecases.ICleanUnusedOverlays
import dagger.Component
import dagger.Module
import dagger.Provides
import io.kotlintest.mock.mock
import org.mockito.Mockito
import javax.inject.Named
import javax.inject.Singleton
class MockedApp : App() {
companion object {
@JvmStatic
val mockedInstalledPresenter: InstalledContract.Presenter = Mockito.mock(InstalledContract.Presenter::class.java)
@JvmStatic
val mockedPrioritiesPresenter: PrioritiesContract.Presenter = Mockito.mock(PrioritiesContract.Presenter::class.java)
@JvmStatic
val mockedPrioritiesDetailPresenter: PrioritiesDetailContract.Presenter = Mockito.mock(PrioritiesDetailContract.Presenter::class.java)
@JvmStatic
val viewModelFactory: ViewModelProvider.Factory = Mockito.mock(ViewModelProvider.Factory::class.java)
@Module
class TestModule {
@Provides
fun installed(): InstalledContract.Presenter = mockedInstalledPresenter
@Provides
fun priorities(): PrioritiesContract.Presenter = mockedPrioritiesPresenter
@Provides
fun proritiesDetail(): PrioritiesDetailContract.Presenter = mockedPrioritiesDetailPresenter
@Provides
@Named("persistent")
fun metrics(): Metrics = mock()
@Provides
fun factory() = viewModelFactory
@Provides
fun iCleanUnusedOverlays(): ICleanUnusedOverlays = mock()
@Provides
fun privacySettings(): PrivacyPolicySettings = object: PrivacyPolicySettings {
override fun isPrivacyPolicyRequired() = TODO()
}
@Provides
fun detailedPresenter(): com.jereksel.libresubstratum.activities.detailed.DetailedPresenter = mock()
}
@Singleton
@Component(modules = [TestModule::class])
interface TestComponent: BaseComponent
}
override fun getAppComponent(context: Context): BaseComponent {
return DaggerMockedApp_Companion_TestComponent.create()
}
}
| app/src/test/kotlin/com/jereksel/libresubstratum/MockedApp.kt | 507858932 |
package com.rssclient.model
import android.os.Parcelable
import com.aglushkov.taskmanager_http.image.Image
import kotlinx.android.parcel.Parcelize
import java.io.Serializable
import java.net.URL
@Parcelize
data class RssFeed(
var name: String,
var url: URL,
var image: Image? = null,
var items: List<RssItem> = ArrayList()) : Parcelable, Serializable {
companion object {
private const val serialVersionUID = 715000812082812655L
}
} | app_demo/src/main/java/com/rssclient/model/RssFeed.kt | 3229061844 |
package com.flexpoker.game.command.handlers
import com.flexpoker.framework.command.CommandHandler
import com.flexpoker.framework.event.EventPublisher
import com.flexpoker.game.command.aggregate.applyEvents
import com.flexpoker.game.command.aggregate.eventproducers.joinGame
import com.flexpoker.game.command.commands.JoinGameCommand
import com.flexpoker.game.command.events.GameEvent
import com.flexpoker.game.command.repository.GameEventRepository
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import javax.inject.Inject
@Component
class JoinGameCommandHandler @Inject constructor(
private val eventPublisher: EventPublisher<GameEvent>,
private val gameEventRepository: GameEventRepository
) : CommandHandler<JoinGameCommand> {
@Async
override fun handle(command: JoinGameCommand) {
val gameEvents = gameEventRepository.fetchAll(command.aggregateId)
val state = applyEvents(gameEvents)
val newEvents = joinGame(state, command.playerId)
val eventsWithVersions = gameEventRepository.setEventVersionsAndSave(gameEvents.size, newEvents)
eventsWithVersions.forEach { eventPublisher.publish(it) }
}
} | src/main/kotlin/com/flexpoker/game/command/handlers/JoinGameCommandHandler.kt | 3408425570 |
/*
* Copyright 2016-2019 Adrian Cotfas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.apps.adrcotfas.goodtime.util
import java.time.*
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.temporal.TemporalAdjusters
import java.util.*
import kotlin.math.roundToInt
object StringUtils {
private val backUpFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm")
private val dayOfWeekFormatter = DateTimeFormatter.ofPattern("E")
private val suffixes: NavigableMap<Long, String> = TreeMap()
/**
* Shortens a value in minutes to a easier to read format of maximum 4 characters
* Do not use this for anything else than the History chart before removing the extra left padding hack
* @param value the value in minutes to be formatted
* @return the formatted value
*/
fun formatLong(value: Long): String {
//Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return formatLong(Long.MIN_VALUE + 1)
if (value < 0) return "-" + formatLong(-value)
if (value < 1000) return value.toString() //deal with easy case
val e = suffixes.floorEntry(value)!!
val divideBy = e.key
val suffix = e.value
val truncated = value / (divideBy / 10) //the number part of the output times 10
val hasDecimal = truncated < 100 && truncated / 10.0 != (truncated / 10).toDouble()
return if (hasDecimal) (truncated / 10.0).toString() + suffix else (truncated / 10).toString() + suffix
}
fun formatDateAndTime(millis: Long): String {
return millis.toLocalDateTime().format(backUpFormatter)
}
@JvmStatic
fun formatTimeForStatistics(millis: Long?): String {
val date = LocalDateTime.ofInstant(
Instant.ofEpochMilli(
millis!!
), ZoneId.systemDefault()
)
return date.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))
}
@JvmStatic
fun formatDateForStatistics(millis: Long?): String {
val date = LocalDateTime.ofInstant(
Instant.ofEpochMilli(
millis!!
), ZoneId.systemDefault()
)
return "${date.format(DateTimeFormatter.ofPattern("EEEE"))} ${date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))}"
}
fun toPercentage(value: Float): String {
return (100 * value).roundToInt().toString() + "%"
}
fun toDayOfWeek(value: Int): String {
return LocalDateTime.now().with(TemporalAdjusters.next(DayOfWeek.of(value))).format(dayOfWeekFormatter)
}
fun toHourOfDay(hour: Int, is24HourFormat: Boolean): String {
val time = LocalTime.now().withHour(hour)
return time.format(
DateTimeFormatter.ofPattern(
if (is24HourFormat) "HH"
else "hh a"
)
).replace(" ", "\n")
}
init {
suffixes[1000L] = "k"
suffixes[1000000L] = "M"
suffixes[1000000000L] = "G"
suffixes[1000000000000L] = "T"
suffixes[1000000000000000L] = "P"
suffixes[1000000000000000000L] = "E"
}
fun formatMinutes(minutes: Long): String {
val days = minutes / 1440
val hours = minutes / 60 % 24
val remMin = minutes % 60
val result: String = if (minutes != 0L) {
((if (days != 0L) "${days}d\n" else "")
+ (if (hours != 0L) "" + hours.toString() + "h" else "")
+ if (remMin != 0L) " " + remMin.toString() + "m" else "")
} else {
"0m"
}
return result
}
} | app/src/main/java/com/apps/adrcotfas/goodtime/util/StringUtils.kt | 924517325 |
package net.nemerosa.ontrack.boot.graphql.actions
import net.nemerosa.ontrack.boot.ui.ProjectController
import net.nemerosa.ontrack.graphql.schema.ProjectMutations
import net.nemerosa.ontrack.graphql.schema.RootUser
import net.nemerosa.ontrack.graphql.schema.actions.UIAction
import net.nemerosa.ontrack.model.security.ProjectCreation
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.security.isGlobalFunctionGranted
import net.nemerosa.ontrack.ui.controller.EntityURIBuilder
import org.springframework.stereotype.Component
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on
@Component
class RootUserUIActions(
uriBuilder: EntityURIBuilder,
securityService: SecurityService
) : SimpleUIActionsProvider<RootUser>(RootUser::class, uriBuilder) {
override val actions: List<UIAction<RootUser>> = listOf(
mutationForm(ProjectMutations.CREATE_PROJECT, "Creating a project",
form = { on(ProjectController::class.java).newProjectForm() },
check = { securityService.isGlobalFunctionGranted<ProjectCreation>() }
)
)
} | ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/graphql/actions/RootUserUIActions.kt | 2407272150 |
package net.nemerosa.ontrack.extension.git.branching
import net.nemerosa.ontrack.model.support.NameValue
/**
* Branching model for a project.
*
* @property patterns Maps the _type_ of branch to a
* regular expressions.
*/
class BranchingModel(
val patterns: Map<String, String>
) {
constructor(patterns: List<NameValue>) : this(
patterns.associate { it.name to it.value }
)
companion object {
/**
* Default branching model to use
* when no model if defined globally or at
* project level.
*/
val DEFAULT = BranchingModel(
mapOf(
"Development" to "main|master|develop",
"Releases" to "release/.*"
)
)
}
/**
* Given this branching model, a list of Git branches, returns
* an indexed list of Git branches.
*
* @param branches List of Git branches to index
* @return Associates each type with a list of matching
* branches
*/
fun groupBranches(
branches: List<String>
): Map<String, List<String>> =
patterns.mapValues { (_, regex) ->
val pattern = regex.toRegex()
branches.filter { pattern.matches(it) }
}
/**
* Checks if the given branch matches at least one pattern in the model.
*/
fun matches(branchName: String): Boolean {
return patterns.values.any {
it.toRegex().matches(branchName)
}
}
} | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/branching/BranchingModel.kt | 347228250 |
package net.nemerosa.ontrack.boot.ui
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.security.*
import net.nemerosa.ontrack.model.structure.ID
import net.nemerosa.ontrack.ui.controller.AbstractResourceController
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
/**
* REST API to create & delete group mappings
*/
@RestController
@RequestMapping("/rest/group-mappings")
class AccountGroupMappingController(
private val accountGroupMappingService: AccountGroupMappingService,
private val providedGroupsService: ProvidedGroupsService,
private val authenticationSourceRepository: AuthenticationSourceRepository
) : AbstractResourceController() {
/**
* Gets the list of mappings for a provider and a source
*/
@GetMapping("{provider}/{source}")
fun getMappings(@PathVariable provider: String, @PathVariable source: String): ResponseEntity<List<AccountGroupMapping>> {
val authenticationSource = authenticationSourceRepository.getRequiredAuthenticationSource(provider, source)
return ResponseEntity.ok(accountGroupMappingService.getMappings(authenticationSource))
}
/**
* Creates a mapping
*/
@PostMapping("{provider}/{source}")
fun createMapping(@PathVariable provider: String, @PathVariable source: String, @RequestBody input: AccountGroupMappingInput): ResponseEntity<AccountGroupMapping> {
val authenticationSource = authenticationSourceRepository.getRequiredAuthenticationSource(provider, source)
return ResponseEntity.ok(accountGroupMappingService.newMapping(authenticationSource, input))
}
/**
* Deletes a mapping
*/
@DeleteMapping("{provider}/{source}/{id}")
fun deleteMapping(@PathVariable provider: String, @PathVariable source: String, @PathVariable id: ID): ResponseEntity<Ack> {
val authenticationSource = authenticationSourceRepository.getRequiredAuthenticationSource(provider, source)
return ResponseEntity.ok(accountGroupMappingService.deleteMapping(authenticationSource, id))
}
/**
* Gets a list of provided groups for a type and token.
*/
@GetMapping("{provider}/{source}/search/{token:.*}")
fun getSuggestedMappings(@PathVariable provider: String, @PathVariable source: String, @PathVariable token: String): ResponseEntity<List<String>> {
val authenticationSource = authenticationSourceRepository.getRequiredAuthenticationSource(provider, source)
return ResponseEntity.ok(
providedGroupsService.getSuggestedGroups(authenticationSource, token)
)
}
} | ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/ui/AccountGroupMappingController.kt | 1723962849 |
package be.florien.anyflow.feature.player.filter.saved
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import be.florien.anyflow.data.view.FilterGroup
import be.florien.anyflow.feature.player.filter.BaseFilterViewModel
import be.florien.anyflow.player.FiltersManager
import kotlinx.coroutines.launch
import javax.inject.Inject
class SavedFilterGroupViewModel @Inject constructor(filtersManager: FiltersManager) : BaseFilterViewModel(filtersManager) {
val filterGroups: LiveData<List<FilterGroup>> = filtersManager.filterGroups
fun changeForSavedGroup(savedGroupPosition: Int) {
viewModelScope.launch {
val filterGroup = filterGroups.value?.get(savedGroupPosition)
if (filterGroup != null) {
filtersManager.loadSavedGroup(filterGroup)
areFiltersInEdition.mutable.value = false
}
}
}
} | app/src/main/java/be/florien/anyflow/feature/player/filter/saved/SavedFilterGroupViewModel.kt | 3300776650 |
/*
* ownCloud Android client application
*
* @author David A. Velasco
* Copyright (C) 2015 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.ui.preview
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.di.Injectable
import com.nextcloud.client.media.ExoplayerListener
import com.nextcloud.client.media.NextcloudExoPlayer.createNextcloudExoplayer
import com.nextcloud.client.network.ClientFactory
import com.owncloud.android.R
import com.owncloud.android.databinding.ActivityPreviewVideoBinding
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.ui.activity.FileActivity
import com.owncloud.android.utils.MimeTypeUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Activity implementing a basic video player.
*
*/
@Suppress("TooManyFunctions")
class PreviewVideoActivity :
FileActivity(),
Player.Listener,
Injectable {
@Inject
lateinit var clientFactory: ClientFactory
@Inject
lateinit var accountManager: UserAccountManager
private var mSavedPlaybackPosition: Long = -1 // in the unit time handled by MediaPlayer.getCurrentPosition()
private var mAutoplay = false // when 'true', the playback starts immediately with the activity
private var exoPlayer: ExoPlayer? = null // view to play the file; both performs and show the playback
private var mStreamUri: Uri? = null
private lateinit var binding: ActivityPreviewVideoBinding
private lateinit var pauseButton: View
private lateinit var playButton: View
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log_OC.v(TAG, "onCreate")
binding = ActivityPreviewVideoBinding.inflate(layoutInflater)
setContentView(binding.root)
val extras = intent.extras
if (savedInstanceState == null && extras != null) {
mSavedPlaybackPosition = extras.getLong(EXTRA_START_POSITION)
mAutoplay = extras.getBoolean(EXTRA_AUTOPLAY)
mStreamUri = extras[EXTRA_STREAM_URL] as Uri?
} else if (savedInstanceState != null) {
mSavedPlaybackPosition = savedInstanceState.getLong(EXTRA_START_POSITION)
mAutoplay = savedInstanceState.getBoolean(EXTRA_AUTOPLAY)
mStreamUri = savedInstanceState[EXTRA_STREAM_URL] as Uri?
}
supportActionBar?.hide()
}
private fun setupPlayerView() {
binding.videoPlayer.player = exoPlayer
exoPlayer!!.addListener(this)
binding.root.findViewById<View>(R.id.exo_exit_fs).setOnClickListener { onBackPressed() }
pauseButton = binding.root.findViewById(R.id.exo_pause)
pauseButton.setOnClickListener { exoPlayer!!.pause() }
playButton = binding.root.findViewById(R.id.exo_play)
playButton.setOnClickListener { exoPlayer!!.play() }
if (mSavedPlaybackPosition >= 0) {
exoPlayer?.seekTo(mSavedPlaybackPosition)
}
onIsPlayingChanged(exoPlayer!!.isPlaying)
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
super.onIsPlayingChanged(isPlaying)
if (isPlaying) {
playButton.visibility = View.GONE
pauseButton.visibility = View.VISIBLE
} else {
playButton.visibility = View.VISIBLE
pauseButton.visibility = View.GONE
}
}
/**
* {@inheritDoc}
*/
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putLong(EXTRA_START_POSITION, currentPosition())
outState.putBoolean(EXTRA_AUTOPLAY, isPlaying())
outState.putParcelable(EXTRA_STREAM_URL, mStreamUri)
}
override fun onBackPressed() {
Log_OC.v(TAG, "onBackPressed")
val i = Intent()
i.putExtra(EXTRA_AUTOPLAY, isPlaying())
i.putExtra(EXTRA_START_POSITION, currentPosition())
setResult(RESULT_OK, i)
exoPlayer?.stop()
exoPlayer?.release()
super.onBackPressed()
}
private fun isPlaying() = exoPlayer?.isPlaying ?: false
private fun currentPosition() = exoPlayer?.currentPosition ?: 0
private fun play(item: MediaItem) {
exoPlayer?.addMediaItem(item)
exoPlayer?.prepare()
if (mAutoplay) {
exoPlayer?.play()
}
}
override fun onStart() {
super.onStart()
if (account != null) {
require(file != null) { throw IllegalStateException("Instanced with a NULL OCFile") }
var fileToPlay: OCFile? = file
// Validate handled file (first image to preview)
require(MimeTypeUtil.isVideo(fileToPlay)) { "Non-video file passed as argument" }
fileToPlay = storageManager.getFileById(fileToPlay!!.fileId)
if (fileToPlay != null) {
val mediaItem = when {
fileToPlay.isDown -> MediaItem.fromUri(fileToPlay.storageUri)
else -> MediaItem.fromUri(mStreamUri!!)
}
if (exoPlayer != null) {
setupPlayerView()
play(mediaItem)
} else {
val context = this
CoroutineScope(Dispatchers.IO).launch {
val client = clientFactory.createNextcloudClient(accountManager.user)
CoroutineScope(Dispatchers.Main).launch {
exoPlayer = createNextcloudExoplayer(context, client).also {
it.addListener(ExoplayerListener(context, binding.videoPlayer, it))
}
setupPlayerView()
play(mediaItem)
}
}
}
} else {
finish()
}
} else {
finish()
}
}
override fun onStop() {
super.onStop()
if (exoPlayer?.isPlaying == true) {
exoPlayer?.pause()
}
}
companion object {
/** Key to receive a flag signaling if the video should be started immediately */
const val EXTRA_AUTOPLAY = "AUTOPLAY"
/** Key to receive the position of the playback where the video should be put at start */
const val EXTRA_START_POSITION = "START_POSITION"
const val EXTRA_STREAM_URL = "STREAM_URL"
private val TAG = PreviewVideoActivity::class.java.simpleName
}
}
| app/src/main/java/com/owncloud/android/ui/preview/PreviewVideoActivity.kt | 1218747410 |
package org.rust.ide.utils
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
class PresentationInfo(
element: RsNamedElement,
val type: String?,
val name: String,
private val declaration: DeclarationInfo
) {
private val location: String?
init {
location = element.containingFile?.let { " [${it.name}]" }.orEmpty()
}
val typeNameText: String get() = if (type == null) {
name
} else "$type `$name`"
val projectStructureItemText: String get() = "$name${declaration.suffix}"
val projectStructureItemTextWithValue: String get() = "$projectStructureItemText${declaration.value}"
val signatureText: String = "${declaration.prefix}<b>$name</b>${declaration.suffix.escaped}"
val quickDocumentationText: String
get() = if (declaration.isAmbiguous && type != null) {
"<i>$type:</i> "
} else {
""
} + "$signatureText${valueText.escaped}$location"
private val valueText: String get() = if (declaration.value.isEmpty()) {
""
} else {
" ${declaration.value}"
}
}
data class DeclarationInfo(
val prefix: String = "",
val suffix: String = "",
val value: String = "",
val isAmbiguous: Boolean = false
)
val RsNamedElement.presentationInfo: PresentationInfo? get() {
val elementName = name ?: return null
val declInfo = when (this) {
is RsFunction -> Pair("function", createDeclarationInfo(this, identifier, false, listOf(whereClause, retType, valueParameterList)))
is RsStructItem -> Pair("struct", createDeclarationInfo(this, identifier, false, if (blockFields != null) listOf(whereClause) else listOf(whereClause, tupleFields)))
is RsFieldDecl -> Pair("field", createDeclarationInfo(this, identifier, false, listOf(typeReference)))
is RsEnumItem -> Pair("enum", createDeclarationInfo(this, identifier, false, listOf(whereClause)))
is RsEnumVariant -> Pair("enum variant", createDeclarationInfo(this, identifier, false, listOf(tupleFields)))
is RsTraitItem -> Pair("trait", createDeclarationInfo(this, identifier, false, listOf(whereClause)))
is RsTypeAlias -> Pair("type alias", createDeclarationInfo(this, identifier, false, listOf(typeReference, typeParamBounds, whereClause), eq))
is RsConstant -> Pair("constant", createDeclarationInfo(this, identifier, false, listOf(expr, typeReference), eq))
is RsSelfParameter -> Pair("parameter", createDeclarationInfo(this, self, false, listOf(typeReference)))
is RsTypeParameter -> Pair("type parameter", createDeclarationInfo(this, identifier, true))
is RsLifetimeDecl -> Pair("lifetime", createDeclarationInfo(this, quoteIdentifier, true))
is RsModItem -> Pair("module", createDeclarationInfo(this, identifier, false))
is RsLabelDecl -> {
val p = parent
when (p) {
is RsLoopExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.loop)))
is RsForExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.expr, p.`in`, p.`for`)))
is RsWhileExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.condition, p.`while`)))
else -> Pair("label", createDeclarationInfo(this, quoteIdentifier, true))
}
}
is RsPatBinding -> {
val patOwner = topLevelPattern.parent
when (patOwner) {
is RsLetDecl -> Pair("variable", createDeclarationInfo(patOwner, identifier, false, listOf(patOwner.typeReference)))
is RsValueParameter -> Pair("value parameter", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.typeReference)))
is RsMatchArm -> Pair("match arm binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.patList.lastOrNull())))
is RsCondition -> Pair("condition binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.lastChild)))
else -> Pair("binding", createDeclarationInfo(this, identifier, true))
}
}
is RsFile -> {
val mName = modName
if (isCrateRoot) return PresentationInfo(this, "crate", "crate", DeclarationInfo())
else if (mName != null) return PresentationInfo(this, "mod", name.substringBeforeLast(".rs"), DeclarationInfo("mod "))
else Pair("file", DeclarationInfo())
}
else -> Pair(javaClass.simpleName, createDeclarationInfo(this, navigationElement, true))
}
return declInfo.second?.let { PresentationInfo(this, declInfo.first, elementName, it) }
}
fun presentableQualifiedName(element: RsDocAndAttributeOwner): String? {
val qName = (element as? RsQualifiedNamedElement)?.qualifiedName
if (qName != null) return qName
if (element is RsMod) return element.modName
return element.name
}
private fun createDeclarationInfo(decl: RsCompositeElement, name: PsiElement?, isAmbiguous: Boolean, stopAt: List<PsiElement?> = emptyList(), valueSeparator: PsiElement? = null): DeclarationInfo? {
// Break an element declaration into elements. For example:
//
// pub const Foo: u32 = 100;
// ^^^^^^^^^ signature prefix
// ^^^ name
// ^^^^^ signature suffix
// ^^^^^ value
// ^ end
if (name == null) return null
// Remove leading spaces, comments and attributes
val signatureStart = generateSequence(decl.firstChild) { it.nextSibling }
.dropWhile { it is PsiWhiteSpace || it is PsiComment || it is RsOuterAttr }
.firstOrNull()
?.startOffsetInParent ?: return null
val nameStart = name.offsetIn(decl)
// pick (in order) elements we should stop at
// if they all fail, drop down to the end of the name element
val end = stopAt
.filterNotNull().firstOrNull()
?.let { it.startOffsetInParent + it.textLength }
?: nameStart + name.textLength
val valueStart = valueSeparator?.offsetIn(decl) ?: end
val nameEnd = nameStart + name.textLength
check(signatureStart <= nameStart && nameEnd <= valueStart
&& valueStart <= end && end <= decl.textLength)
val prefix = decl.text.substring(signatureStart, nameStart).escaped
val value = decl.text.substring(valueStart, end)
val suffix = decl.text.substring(nameEnd, end - value.length)
.replace("""\s+""".toRegex(), " ")
.replace("( ", "(")
.replace(" )", ")")
.replace(" ,", ",")
.trimEnd()
return DeclarationInfo(prefix, suffix, value, isAmbiguous)
}
private fun PsiElement.offsetIn(owner: PsiElement): Int =
ancestors.takeWhile { it != owner }.sumBy { it.startOffsetInParent }
val String.escaped: String get() = StringUtil.escapeXml(this)
fun breadcrumbName(e: RsCompositeElement): String? {
fun lastComponentWithoutGenerics(path: RsPath) = path.referenceName
return when (e) {
is RsModItem, is RsStructOrEnumItemElement, is RsTraitItem, is RsConstant, is RsMacroDefinition ->
(e as RsNamedElement).name
is RsImplItem -> {
val typeName = run {
val typeReference = e.typeReference
(typeReference as? RsBaseType)?.path?.let { lastComponentWithoutGenerics(it) }
?: typeReference?.text
?: return null
}
val traitName = e.traitRef?.path?.let { lastComponentWithoutGenerics(it) }
val start = if (traitName != null) "$traitName for" else "impl"
"$start $typeName"
}
is RsFunction -> e.name?.let { "$it()" }
else -> null
}
}
| src/main/kotlin/org/rust/ide/utils/PresentationUtils.kt | 3189412812 |
package treehou.se.habit.ui.servers.sitemaps.list
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subjects.BehaviorSubject
import kotlinx.android.synthetic.main.fragment_sitemaplist_list.*
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.connector.models.OHSitemap
import treehou.se.habit.R
import treehou.se.habit.core.db.model.ServerDB
import treehou.se.habit.core.db.model.SitemapDB
import treehou.se.habit.dagger.HasActivitySubcomponentBuilders
import treehou.se.habit.dagger.ServerLoaderFactory
import treehou.se.habit.dagger.fragment.SitemapSelectComponent
import treehou.se.habit.dagger.fragment.SitemapSelectModule
import treehou.se.habit.mvp.BaseDaggerFragment
import treehou.se.habit.ui.adapter.SitemapListAdapter
import treehou.se.habit.ui.servers.sitemaps.sitemapsettings.SitemapSettingsFragment
import treehou.se.habit.util.Settings
import javax.inject.Inject
class SitemapSelectFragment : BaseDaggerFragment<SitemapSelectContract.Presenter>(), SitemapSelectContract.View {
@Inject lateinit var settings: Settings
@Inject lateinit var serverLoader: ServerLoaderFactory
@Inject lateinit var sitemapPresenter: SitemapSelectContract.Presenter
private var sitemapAdapter: SitemapListAdapter? = null
private val serverBehaviorSubject = BehaviorSubject.create<OHServer>()
private var serverId: Long = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
serverId = arguments!!.getLong(ARG_SHOW_SERVER)
}
override fun getPresenter(): SitemapSelectContract.Presenter? {
return sitemapPresenter
}
override fun injectMembers(hasActivitySubcomponentBuilders: HasActivitySubcomponentBuilders) {
(hasActivitySubcomponentBuilders.getFragmentComponentBuilder(SitemapSelectFragment::class.java) as SitemapSelectComponent.Builder)
.fragmentModule(SitemapSelectModule(this))
.build().injectMembers(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_sitemaplist_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupActionBar()
val gridLayoutManager = GridLayoutManager(activity, 1)
listView.layoutManager = gridLayoutManager
listView.itemAnimator = DefaultItemAnimator()
sitemapAdapter = SitemapListAdapter()
sitemapAdapter!!.setSitemapSelectedListener(object : SitemapListAdapter.SitemapSelectedListener {
override fun onSelected(server: OHServer, sitemap: OHSitemap?) {
val sitemapDB = realm.where(SitemapDB::class.java)
.equalTo("server.id", serverId)
.equalTo("name", sitemap?.name)
.findFirst()
if (sitemapDB != null) {
openSitemap(sitemapDB)
}
}
override fun onErrorSelected(server: OHServer) {
serverBehaviorSubject.onNext(server)
}
override fun onCertificateErrorSelected(server: OHServer) {}
})
listView.adapter = sitemapAdapter
}
/**
* Open fragment showing sitemap.
*
* @param sitemap the name of sitemap to show.
*/
private fun openSitemap(sitemap: SitemapDB?) {
val fragmentManager = activity!!.supportFragmentManager
fragmentManager.beginTransaction()
.replace(R.id.page_container, SitemapSettingsFragment.newInstance(sitemap!!.id))
.addToBackStack(null)
.commit()
}
/**
* Setup actionbar.
*/
private fun setupActionBar() {
val actionBar = (activity as AppCompatActivity).supportActionBar
actionBar?.setTitle(R.string.sitemaps)
}
/**
* Clears list of sitemaps.
*/
private fun clearList() {
emptyView.visibility = View.VISIBLE
sitemapAdapter!!.clear()
}
override fun onResume() {
super.onResume()
clearList()
loadSitemapsFromServers()
}
/**
* Load servers from database and request their sitemaps.
*/
private fun loadSitemapsFromServers() {
val context = context ?: return
realm.where(ServerDB::class.java).equalTo("id", serverId).findAll().asFlowable().toObservable()
.flatMap<ServerDB>({ Observable.fromIterable(it) })
.map<OHServer>({ it.toGeneric() })
.distinct()
.compose<ServerLoaderFactory.ServerSitemapsResponse>(serverLoader.serverToSitemap(context))
.observeOn(AndroidSchedulers.mainThread())
.compose<ServerLoaderFactory.ServerSitemapsResponse>(bindToLifecycle<ServerLoaderFactory.ServerSitemapsResponse>())
.subscribe({ serverSitemaps ->
emptyView.visibility = View.GONE
val server = serverSitemaps.server
val sitemaps = serverSitemaps.sitemaps
if (sitemaps != null) {
for (sitemap in sitemaps) {
if (server != null) {
sitemapAdapter!!.add(server, sitemap)
}
}
}
}) { logger.e(TAG, "Request sitemap failed", it) }
}
companion object {
private val TAG = "SitemapSelectFragment"
private val ARG_SHOW_SERVER = "ARG_SHOW_SERVER"
/**
* Load sitemaps for servers.
* Open provided sitemap if loaded.
*
* @param serverId the server to load
* @return Fragment
*/
fun newInstance(serverId: Long): SitemapSelectFragment {
val fragment = SitemapSelectFragment()
val args = Bundle()
args.putLong(ARG_SHOW_SERVER, serverId)
fragment.arguments = args
return fragment
}
}
}
| mobile/src/main/java/treehou/se/habit/ui/servers/sitemaps/list/SitemapSelectFragment.kt | 2832871980 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.impl.stores.SaveSessionAndFile
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.project.ex.ProjectNameProvider
import com.intellij.openapi.project.getProjectCachePath
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.project.impl.ProjectStoreClassProvider
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.ReadonlyStatusHandler
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.computeIfAny
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.*
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.text.nullize
import java.nio.file.Path
import java.nio.file.Paths
internal const val PROJECT_FILE = "\$PROJECT_FILE$"
internal const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
val IProjectStore.nameFile: Path
get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE)
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
// cannot be `internal`, used in Upsource
abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreWithExtraComponents(), IProjectStore {
// protected setter used in upsource
// Zelix KlassMaster - ERROR: Could not find method 'getScheme()'
var scheme: StorageScheme = StorageScheme.DEFAULT
override final var loadPolicy: StateLoadPolicy = StateLoadPolicy.LOAD
override final fun isOptimiseTestLoadSpeed(): Boolean = loadPolicy != StateLoadPolicy.LOAD
override final fun getStorageScheme(): StorageScheme = scheme
override abstract val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = scheme == StorageScheme.DIRECTORY_BASED
override final fun setOptimiseTestLoadSpeed(value: Boolean) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
override fun getProjectFilePath(): String = storageManager.expandMacro(PROJECT_FILE)
/**
* `null` for default or non-directory based project.
*/
override fun getProjectConfigDir(): String? = if (isDirectoryBased) storageManager.expandMacro(PROJECT_CONFIG_DIR) else null
override final fun getWorkspaceFilePath(): String = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
override final fun clearStorages() {
storageManager.clearStorages()
}
override final fun loadProjectFromTemplate(defaultProject: Project) {
defaultProject.save()
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.runAndLogException {
if (isDirectoryBased) {
normalizeDefaultProjectElement(defaultProject, element, Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR)))
}
else {
LOG.runAndLogException {
moveComponentConfiguration(defaultProject, element) { if (it == "workspace.xml") Paths.get(workspaceFilePath) else Paths.get(projectFilePath) }
}
}
}
(storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element)
}
override final fun getProjectBasePath(): String {
if (isDirectoryBased) {
val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR))
if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) {
return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path))
}
return path
}
else {
return PathUtilRt.getParentPath(projectFilePath)
}
}
// used in upsource
protected fun setPath(filePath: String, refreshVfs: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
if (filePath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
scheme = StorageScheme.DEFAULT
storageManager.addMacro(PROJECT_FILE, filePath)
val workspacePath = composeFileBasedProjectWorkSpacePath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (refreshVfs) {
invokeAndWaitIfNeed {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
}
else {
scheme = StorageScheme.DIRECTORY_BASED
val configDir = "$filePath/${Project.DIRECTORY_STORE_FOLDER}"
storageManager.addMacro(PROJECT_CONFIG_DIR, configDir)
storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml")
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml")
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
if (refreshVfs) {
invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) }
}
}
storageManager.addMacro(StoragePathMacros.CACHE_FILE, FileUtilRt.toSystemIndependentName(project.getProjectCachePath("workspace").toString()) + ".xml")
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
var result: MutableList<Storage>? = null
for (storage in storages) {
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
if (isDirectoryBased) {
StreamProviderFactory.EP_NAME.getExtensions(project).computeIfAny {
LOG.runAndLogException { it.customizeStorageSpecs(component, storageManager, stateSpec, result!!, operation) }
}?.let {
// yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case
return it
}
}
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
if (result.first().path != StoragePathMacros.CACHE_FILE) {
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
}
return result
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE || storage.path == StoragePathMacros.CACHE_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result
}
}
}
override fun isProjectFile(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) {
return false
}
val filePath = file.path
if (!isDirectoryBased) {
return filePath == projectFilePath || filePath == workspaceFilePath
}
return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false)
}
override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean): String? = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize()
override fun getDirectoryStoreFile(): VirtualFile? = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) }
override fun getDirectoryStorePathOrBase(): String = PathUtilRt.getParentPath(projectFilePath)
}
private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) {
private var lastSavedProjectName: String? = null
init {
assert(!project.isDefault)
}
override final fun getPathMacroManagerForDefaults() = pathMacroManager
override val storageManager = ProjectStateStorageManager(TrackingPathMacroSubstitutorImpl(pathMacroManager), project)
override fun setPath(path: String) {
setPath(path, true)
}
override fun getProjectName(): String {
if (!isDirectoryBased) {
return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
val baseDir = projectBasePath
val nameFile = nameFile
if (nameFile.exists()) {
LOG.runAndLogException {
nameFile.inputStream().reader().useLines { line -> line.firstOrNull { !it.isEmpty() }?.trim() }?.let {
lastSavedProjectName = it
return it
}
}
}
return ProjectNameProvider.EP_NAME.extensionList.computeIfAny {
LOG.runAndLogException { it.getDefaultName(project) }
} ?: PathUtilRt.getFileName(baseDir).replace(":", "")
}
private fun saveProjectName() {
if (!isDirectoryBased) {
return
}
val currentProjectName = project.name
if (lastSavedProjectName == currentProjectName) {
return
}
lastSavedProjectName = currentProjectName
val basePath = projectBasePath
if (currentProjectName == PathUtilRt.getFileName(basePath)) {
// name equals to base path name - just remove name
nameFile.delete()
}
else {
if (Paths.get(basePath).isDirectory()) {
nameFile.write(currentProjectName.toByteArray())
}
}
}
override fun doSave(saveSession: SaveExecutor, readonlyFiles: MutableList<SaveSessionAndFile>, errors: MutableList<Throwable>) {
try {
saveProjectName()
}
catch (e: Throwable) {
LOG.error("Unable to store project name", e)
}
beforeSave(readonlyFiles)
super.doSave(saveSession, readonlyFiles, errors)
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (readonlyFiles.isEmpty()) {
for (notification in notifications) {
notification.expire()
}
return
}
if (!notifications.isEmpty()) {
throw IComponentStore.SaveCancelledException()
}
val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) }
if (status.hasReadonlyFiles()) {
dropUnableToSaveProjectNotification(project, status.readonlyFiles)
throw IComponentStore.SaveCancelledException()
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
for (entry in oldList) {
executeSave(entry.session, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
if (!readonlyFiles.isEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
throw IComponentStore.SaveCancelledException()
}
}
protected open fun beforeSave(readonlyFiles: MutableList<SaveSessionAndFile>) {
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) {
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].myFiles = readOnlyFiles
}
}
private fun getFilesList(readonlyFiles: List<SaveSessionAndFile>) = Array(readonlyFiles.size) { readonlyFiles[it].file }
private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) {
override fun beforeSave(readonlyFiles: MutableList<SaveSessionAndFile>) {
super.beforeSave(readonlyFiles)
for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) {
module.stateStore.save(readonlyFiles)
}
}
}
// used in upsource
class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java
}
}
@Suppress("unused")
private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java
}
}
private fun composeFileBasedProjectWorkSpacePath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}" | platform/configuration-store-impl/src/ProjectStoreImpl.kt | 273462099 |
/*
* 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
*
* 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.plaidapp.core.dagger.dribbble
import dagger.Lazy
import dagger.Module
import dagger.Provides
import io.plaidapp.core.dagger.scope.FeatureScope
import io.plaidapp.core.dribbble.data.ShotsRepository
import io.plaidapp.core.dribbble.data.search.DribbbleSearchConverter
import io.plaidapp.core.dribbble.data.search.DribbbleSearchService
import io.plaidapp.core.dribbble.data.search.SearchRemoteDataSource
import okhttp3.OkHttpClient
import retrofit2.Retrofit
/**
* Dagger module providing classes required to dribbble with data.
*/
@Module
class DribbbleDataModule {
@Provides
@FeatureScope
fun provideShotsRepository(remoteDataSource: SearchRemoteDataSource) =
ShotsRepository.getInstance(remoteDataSource)
@Provides
@FeatureScope
fun provideConverterFactory(): DribbbleSearchConverter.Factory =
DribbbleSearchConverter.Factory()
@Provides
@FeatureScope
fun provideDribbbleSearchService(
client: Lazy<OkHttpClient>,
converterFactory: DribbbleSearchConverter.Factory
): DribbbleSearchService =
Retrofit.Builder()
.baseUrl(DribbbleSearchService.ENDPOINT)
.callFactory(client.get())
.addConverterFactory(converterFactory)
.build()
.create(DribbbleSearchService::class.java)
}
| core/src/main/java/io/plaidapp/core/dagger/dribbble/DribbbleDataModule.kt | 2576522089 |
package com.engineer.plugin.transforms.tiger
import com.engineer.plugin.transforms.BaseTransform
import org.gradle.api.Project
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import java.io.InputStream
import java.io.OutputStream
import java.util.function.BiConsumer
/**
* @author rookie
* @since 01-03-2020
*/
class TigerTransform(val project: Project) : BaseTransform(project) {
override fun provideFunction(): BiConsumer<InputStream, OutputStream>? {
return BiConsumer { t, u ->
val reader = ClassReader(t)
val writer = ClassWriter(reader, ClassWriter.COMPUTE_MAXS)
val visitor = TigerClassVisitor(project, writer)
reader.accept(visitor, ClassReader.EXPAND_FRAMES)
val code = writer.toByteArray()
u.write(code)
}
}
override fun getName(): String {
return "tiger"
}
} | buildSrc/src/main/kotlin/com/engineer/plugin/transforms/tiger/TigerTransform.kt | 1030958450 |
package de.xikolo.utils
import de.xikolo.App
import java.io.File
import java.util.*
object ClientUtil {
private const val FILE_NAME = "INSTALLATION"
var id: String? = null
get() {
if (field == null) {
val installationFile = File(App.instance.filesDir, FILE_NAME)
try {
if (!installationFile.exists()) {
installationFile.writeText(
UUID.randomUUID().toString()
)
}
field = installationFile.readText()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
return field
}
}
| app/src/main/java/de/xikolo/utils/ClientUtil.kt | 143153485 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mockk.proxy.android.transformation
import io.mockk.proxy.MockKAgentException
import io.mockk.proxy.common.transformation.ClassTransformationSpecMap
import java.util.*
internal class InliningClassTransformer(
private val specMap: ClassTransformationSpecMap
) {
val identifier = newId()
@Suppress("unused") // JNI call
fun transform(classBeingRedefined: Class<*>?, classfileBuffer: ByteArray): ByteArray? {
if (classBeingRedefined == null) {
return classfileBuffer
}
val spec = specMap[classBeingRedefined]
?: return classfileBuffer
return synchronized(lock) {
try {
nativeRedefine(
identifier,
classfileBuffer,
spec.shouldDoSimpleIntercept,
spec.shouldDoStaticIntercept,
spec.shouldDoConstructorIntercept
)
} catch (ex: Exception) {
throw MockKAgentException("Transformation issue", ex)
}
}
}
fun shouldTransform(classBeingRedefined: Class<*>) = specMap.shouldTransform(classBeingRedefined)
private external fun nativeRedefine(
identifier: String,
original: ByteArray,
mockk: Boolean,
staticMockk: Boolean,
constructorMockk: Boolean
): ByteArray
companion object {
private val lock = Any()
private val rng = Random()
private fun newId() = Math.abs(rng.nextLong()).toString(16)
}
}
| modules/mockk-agent-android/src/main/kotlin/io/mockk/proxy/android/transformation/InliningClassTransformer.kt | 314112030 |
package io.mockk.it
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.spyk
import io.mockk.verify
import kotlin.test.Test
import kotlin.test.assertEquals
class PrivatePropertiesTest {
/**
* See issue #51
*/
@Test
fun testPrivateProperty() {
val mock = spyk(Team(), recordPrivateCalls = true)
every { mock getProperty "person" } returns Person("Big Ben")
every { mock setProperty "person" value Person("test") } just Runs
every { mock invoke "fn" withArguments listOf(5) } returns 3
assertEquals("Big Ben", mock.memberName)
assertEquals(3, mock.pubFn(5))
mock.memberName = "test"
assertEquals("Big Ben", mock.memberName)
verify { mock getProperty "person" }
verify { mock setProperty "person" value Person("test") }
verify { mock invoke "fn" withArguments listOf(5) }
}
data class Person(var name: String)
class Team {
protected var person: Person = Person("Init")
get() = Person("Ben")
set(value) {
field = value
}
protected fun fn(arg: Int): Int = arg + 5
fun pubFn(arg: Int) = fn(arg)
var memberName: String
get() = person.name
set(value) {
person = Person(value)
}
}
}
| modules/mockk/src/commonTest/kotlin/io/mockk/it/PrivatePropertiesTest.kt | 1327171752 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.