repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
chrisbanes/tivi | ui/episodedetails/src/main/java/app/tivi/episodedetails/EpisodeDetails.kt | 1 | 22349 | /*
* Copyright 2019 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 app.tivi.episodedetails
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ContentAlpha
import androidx.compose.material.DismissDirection
import androidx.compose.material.DismissValue
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Surface
import androidx.compose.material.SwipeToDismiss
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CalendarToday
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DeleteSweep
import androidx.compose.material.icons.filled.Publish
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material.rememberDismissState
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import app.tivi.common.compose.Layout
import app.tivi.common.compose.LocalTiviDateFormatter
import app.tivi.common.compose.theme.TiviTheme
import app.tivi.common.compose.ui.AutoSizedCircularProgressIndicator
import app.tivi.common.compose.ui.Backdrop
import app.tivi.common.compose.ui.ExpandingText
import app.tivi.common.compose.ui.ScrimmedIconButton
import app.tivi.common.compose.ui.SwipeDismissSnackbarHost
import app.tivi.common.compose.ui.TiviAlertDialog
import app.tivi.common.compose.ui.boundsInParent
import app.tivi.common.compose.ui.onPositionInParentChanged
import app.tivi.data.entities.Episode
import app.tivi.data.entities.EpisodeWatchEntry
import app.tivi.data.entities.PendingAction
import app.tivi.data.entities.Season
import app.tivi.ui.animations.lerp
import com.google.accompanist.insets.ui.Scaffold
import org.threeten.bp.OffsetDateTime
import kotlin.math.absoluteValue
import kotlin.math.hypot
import app.tivi.common.ui.resources.R as UiR
@ExperimentalMaterialApi
@Composable
fun EpisodeDetails(
expandedValue: ModalBottomSheetValue,
navigateUp: () -> Unit
) {
EpisodeDetails(
viewModel = hiltViewModel(),
expandedValue = expandedValue,
navigateUp = navigateUp
)
}
@OptIn(ExperimentalLifecycleComposeApi::class)
@ExperimentalMaterialApi
@Composable
internal fun EpisodeDetails(
viewModel: EpisodeDetailsViewModel,
expandedValue: ModalBottomSheetValue,
navigateUp: () -> Unit
) {
val viewState by viewModel.state.collectAsState()
EpisodeDetails(
viewState = viewState,
expandedValue = expandedValue,
navigateUp = navigateUp,
refresh = viewModel::refresh,
onRemoveAllWatches = viewModel::removeAllWatches,
onRemoveWatch = viewModel::removeWatchEntry,
onAddWatch = viewModel::addWatch,
onMessageShown = viewModel::clearMessage
)
}
@ExperimentalMaterialApi
@Composable
internal fun EpisodeDetails(
viewState: EpisodeDetailsViewState,
expandedValue: ModalBottomSheetValue,
navigateUp: () -> Unit,
refresh: () -> Unit,
onRemoveAllWatches: () -> Unit,
onRemoveWatch: (id: Long) -> Unit,
onAddWatch: () -> Unit,
onMessageShown: (id: Long) -> Unit
) {
val scaffoldState = rememberScaffoldState()
viewState.message?.let { message ->
LaunchedEffect(message) {
scaffoldState.snackbarHostState.showSnackbar(message.message)
// Notify the view model that the message has been dismissed
onMessageShown(message.id)
}
}
Scaffold(
scaffoldState = scaffoldState,
topBar = {
Surface {
if (viewState.episode != null && viewState.season != null) {
EpisodeDetailsBackdrop(
season = viewState.season,
episode = viewState.episode,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(16 / 9f)
)
}
Column {
AnimatedVisibility(visible = expandedValue == ModalBottomSheetValue.Expanded) {
Spacer(
Modifier
.background(MaterialTheme.colors.background.copy(alpha = 0.4f))
.windowInsetsTopHeight(WindowInsets.statusBars)
.fillMaxWidth()
)
}
EpisodeDetailsAppBar(
backgroundColor = Color.Transparent,
isRefreshing = viewState.refreshing,
navigateUp = navigateUp,
refresh = refresh,
elevation = 0.dp,
modifier = Modifier.fillMaxWidth()
)
}
}
},
snackbarHost = { snackbarHostState ->
SwipeDismissSnackbarHost(
hostState = snackbarHostState,
modifier = Modifier
.padding(horizontal = Layout.bodyMargin)
.fillMaxWidth()
)
}
) { contentPadding ->
Surface(
elevation = 2.dp,
modifier = Modifier.fillMaxSize()
) {
Column(
Modifier
.verticalScroll(rememberScrollState())
.padding(contentPadding)
) {
val episode = viewState.episode
if (episode != null) {
InfoPanes(episode)
ExpandingText(
text = episode.summary ?: "No summary",
modifier = Modifier.padding(16.dp)
)
}
if (viewState.canAddEpisodeWatch) {
Spacer(modifier = Modifier.height(8.dp))
if (viewState.watches.isEmpty()) {
MarkWatchedButton(
onClick = onAddWatch,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
} else {
AddWatchButton(
onClick = onAddWatch,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
Spacer(modifier = Modifier.height(16.dp))
if (viewState.watches.isNotEmpty()) {
var openDialog by remember { mutableStateOf(false) }
EpisodeWatchesHeader(
onSweepWatchesClick = { openDialog = true }
)
if (openDialog) {
RemoveAllWatchesDialog(
onConfirm = {
onRemoveAllWatches()
openDialog = false
},
onDismiss = { openDialog = false }
)
}
}
viewState.watches.forEach { watch ->
key(watch.id) {
val dismissState = rememberDismissState {
if (it != DismissValue.Default) {
onRemoveWatch(watch.id)
}
it != DismissValue.DismissedToEnd
}
SwipeToDismiss(
state = dismissState,
modifier = Modifier.padding(vertical = 4.dp),
directions = setOf(DismissDirection.EndToStart),
background = {
val fraction = dismissState.progress.fraction
EpisodeWatchSwipeBackground(
swipeProgress = fraction,
wouldCompleteOnRelease = fraction.absoluteValue >= 0.5f
)
},
dismissContent = { EpisodeWatch(episodeWatchEntry = watch) }
)
}
}
Spacer(Modifier.height(8.dp))
}
}
}
}
@Composable
private fun EpisodeDetailsBackdrop(
season: Season,
episode: Episode,
modifier: Modifier = Modifier
) {
TiviTheme(useDarkColors = true) {
Backdrop(
imageModel = if (episode.tmdbBackdropPath != null) episode else null,
overline = {
val epNumber = episode.number
val seasonNumber = season.number
if (seasonNumber != null && epNumber != null) {
@Suppress("DEPRECATION")
Text(
text = stringResource(
UiR.string.season_episode_number,
seasonNumber,
epNumber
).uppercase(LocalConfiguration.current.locale)
)
}
},
title = { Text(text = episode.title ?: "No title") },
modifier = modifier
)
}
}
@Composable
private fun InfoPanes(episode: Episode) {
Row {
episode.traktRating?.let { rating ->
InfoPane(
imageVector = Icons.Default.Star,
label = stringResource(UiR.string.trakt_rating_text, rating * 10f),
contentDescription = stringResource(UiR.string.cd_trakt_rating, rating * 10f),
modifier = Modifier.weight(1f)
)
}
episode.firstAired?.let { firstAired ->
val formatter = LocalTiviDateFormatter.current
val formattedDate = formatter.formatShortRelativeTime(firstAired)
InfoPane(
imageVector = Icons.Default.CalendarToday,
label = formattedDate,
contentDescription = stringResource(
UiR.string.cd_episode_first_aired,
formattedDate
),
modifier = Modifier.weight(1f)
)
}
}
}
@Composable
private fun InfoPane(
imageVector: ImageVector,
contentDescription: String?,
label: String,
modifier: Modifier = Modifier
) {
Column(modifier = modifier.padding(16.dp)) {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
Spacer(modifier = Modifier.height(4.dp))
Text(
modifier = Modifier.align(Alignment.CenterHorizontally),
text = label,
style = MaterialTheme.typography.body1
)
}
}
@Composable
private fun EpisodeWatchesHeader(onSweepWatchesClick: () -> Unit) {
Row {
Text(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.align(Alignment.CenterVertically),
text = stringResource(UiR.string.episode_watches),
style = MaterialTheme.typography.subtitle1
)
Spacer(Modifier.weight(1f))
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.disabled) {
IconButton(
modifier = Modifier.padding(end = 4.dp),
onClick = { onSweepWatchesClick() }
) {
Icon(
imageVector = Icons.Default.DeleteSweep,
contentDescription = stringResource(UiR.string.cd_delete)
)
}
}
}
}
@Composable
private fun EpisodeWatch(episodeWatchEntry: EpisodeWatchEntry) {
Surface {
Row(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.sizeIn(minWidth = 40.dp, minHeight = 40.dp)
) {
val formatter = LocalTiviDateFormatter.current
Text(
modifier = Modifier.align(Alignment.CenterVertically),
text = formatter.formatMediumDateTime(episodeWatchEntry.watchedAt),
style = MaterialTheme.typography.body2
)
Spacer(Modifier.weight(1f))
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
if (episodeWatchEntry.pendingAction != PendingAction.NOTHING) {
Icon(
imageVector = Icons.Default.Publish,
contentDescription = stringResource(UiR.string.cd_episode_syncing),
modifier = Modifier
.padding(start = 8.dp)
.align(Alignment.CenterVertically)
)
}
if (episodeWatchEntry.pendingAction == PendingAction.DELETE) {
Icon(
imageVector = Icons.Default.VisibilityOff,
contentDescription = stringResource(UiR.string.cd_episode_deleted),
modifier = Modifier
.padding(start = 8.dp)
.align(Alignment.CenterVertically)
)
}
}
}
}
}
@Composable
private fun EpisodeWatchSwipeBackground(
swipeProgress: Float,
wouldCompleteOnRelease: Boolean = false
) {
var iconCenter by remember { mutableStateOf(Offset(0f, 0f)) }
val maxRadius = hypot(iconCenter.x.toDouble(), iconCenter.y.toDouble())
val secondary = MaterialTheme.colors.error.copy(alpha = 0.5f)
val default = MaterialTheme.colors.onSurface.copy(alpha = 0.2f)
Box(
Modifier
.fillMaxSize()
.background(MaterialTheme.colors.onSurface.copy(alpha = 0.2f), RectangleShape)
) {
// A simple box to draw the growing circle, which emanates from behind the icon
Spacer(
modifier = Modifier
.fillMaxSize()
.drawGrowingCircle(
color = animateColorAsState(
targetValue = when (wouldCompleteOnRelease) {
true -> secondary
false -> default
}
).value,
center = iconCenter,
radius = lerp(
startValue = 0f,
endValue = maxRadius.toFloat(),
fraction = FastOutLinearInEasing.transform(swipeProgress)
)
)
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = stringResource(UiR.string.cd_delete),
modifier = Modifier
.onPositionInParentChanged { iconCenter = it.boundsInParent.center }
.padding(start = 0.dp, top = 0.dp, end = 16.dp, bottom = 0.dp)
.align(Alignment.CenterEnd)
)
}
}
}
private fun Modifier.drawGrowingCircle(
color: Color,
center: Offset,
radius: Float
) = drawWithContent {
drawContent()
clipRect {
drawCircle(
color = color,
radius = radius,
center = center
)
}
}
@Composable
private fun MarkWatchedButton(
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Button(
onClick = onClick,
modifier = modifier
) {
Text(
text = stringResource(UiR.string.episode_mark_watched),
style = MaterialTheme.typography.button.copy(color = LocalContentColor.current)
)
}
}
@Composable
private fun AddWatchButton(
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
OutlinedButton(
onClick = onClick,
modifier = modifier
) {
Text(text = stringResource(UiR.string.episode_add_watch))
}
}
@Composable
private fun RemoveAllWatchesDialog(
onConfirm: () -> Unit,
onDismiss: () -> Unit
) {
TiviAlertDialog(
title = stringResource(UiR.string.episode_remove_watches_dialog_title),
message = stringResource(UiR.string.episode_remove_watches_dialog_message),
confirmText = stringResource(UiR.string.episode_remove_watches_dialog_confirm),
onConfirm = { onConfirm() },
dismissText = stringResource(UiR.string.dialog_dismiss),
onDismissRequest = { onDismiss() }
)
}
@Composable
private fun EpisodeDetailsAppBar(
backgroundColor: Color,
isRefreshing: Boolean,
navigateUp: () -> Unit,
refresh: () -> Unit,
elevation: Dp,
modifier: Modifier = Modifier
) {
TopAppBar(
title = {},
navigationIcon = {
ScrimmedIconButton(showScrim = true, onClick = navigateUp) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = stringResource(UiR.string.cd_close)
)
}
},
actions = {
if (isRefreshing) {
AutoSizedCircularProgressIndicator(
modifier = Modifier
.aspectRatio(1f)
.fillMaxHeight()
.padding(14.dp)
)
} else {
ScrimmedIconButton(showScrim = true, onClick = refresh) {
Icon(
imageVector = Icons.Default.Refresh,
contentDescription = stringResource(UiR.string.cd_refresh)
)
}
}
},
elevation = elevation,
backgroundColor = backgroundColor,
modifier = modifier
)
}
@OptIn(ExperimentalMaterialApi::class)
@Preview
@Composable
fun PreviewEpisodeDetails() {
EpisodeDetails(
viewState = EpisodeDetailsViewState(
episode = Episode(
seasonId = 100,
title = "A show too far",
summary = "A long description of a episode",
traktRating = 0.5f,
traktRatingVotes = 84,
firstAired = OffsetDateTime.now()
),
season = Season(
id = 100,
showId = 0
),
watches = listOf(
EpisodeWatchEntry(
id = 10,
episodeId = 100,
watchedAt = OffsetDateTime.now()
)
)
),
expandedValue = ModalBottomSheetValue.HalfExpanded,
navigateUp = {},
refresh = {},
onRemoveAllWatches = {},
onRemoveWatch = {},
onAddWatch = {},
onMessageShown = {}
)
}
| apache-2.0 | 25dcf11b2f0f802f86cd487b1272cfd2 | 34.139937 | 99 | 0.584187 | 5.359472 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/test/java/com/garpr/android/extensions/ListExtTest.kt | 1 | 1279 | package com.garpr.android.extensions
import com.garpr.android.test.BaseTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
class ListExtTest : BaseTest() {
@Test
fun testRequireWithNullItemInList() {
val list = listOf("Hello", "World", null)
assertEquals("Hello", list.require(0))
assertEquals("World", list.require(1))
var item: Any? = null
var throwable: Throwable? = null
try {
item = list.require(2)
} catch (t: Throwable) {
throwable = t
}
assertNull(item)
assertNotNull(throwable)
}
@Test
fun testRequireWithNullList() {
val list: List<Any?>? = null
var item: Any? = null
var throwable: Throwable? = null
try {
item = list.require(0)
} catch (t: Throwable) {
throwable = t
}
assertNull(item)
assertNotNull(throwable)
}
@Test
fun testRequireWithStringList() {
val list = listOf("Hello", " ", "World")
assertEquals("Hello", list.require(0))
assertEquals(" ", list.require(1))
assertEquals("World", list.require(2))
}
}
| unlicense | 077027edbfea7e19eac44a2d76202d05 | 22.685185 | 49 | 0.583268 | 4.249169 | false | true | false | false |
square/duktape-android | zipline/src/commonMain/kotlin/app/cash/zipline/internal/bridge/CallCodec.kt | 1 | 3748 | /*
* Copyright (C) 2022 Block, 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 app.cash.zipline.internal.bridge
import app.cash.zipline.Call
import app.cash.zipline.CallResult
import app.cash.zipline.ZiplineService
import app.cash.zipline.internal.decodeFromStringFast
import app.cash.zipline.internal.encodeToStringFast
import kotlinx.serialization.KSerializer
/**
* Manages encoding an [InternalCall] to JSON and back.
*
* Zipline's support for both pass-by-value and pass-by-reference is supported by this codec. It
* keeps track of services passed by reference in both [Call] and [CallResult] instances. Service
* names are collected as a side effect of serialization by [PassByReferenceSerializer].
*/
internal class CallCodec(
private val endpoint: Endpoint,
) {
private val callSerializer = RealCallSerializer(endpoint)
/** This list collects service names as they're decoded, including members of other types. */
val decodedServiceNames = mutableListOf<String>()
/** This list collects service names as they're encoded, including members of other types. */
val encodedServiceNames = mutableListOf<String>()
/**
* The most-recently received inbound call. Due to reentrant calls it's possible that this isn't
* the currently-executing call.
*/
var lastInboundCall: Call? = null
var nextOutboundCallCallback: ((Call) -> Unit)? = null
internal fun encodeCall(
internalCall: InternalCall,
service: ZiplineService,
): Call {
encodedServiceNames.clear()
val encodedCall = endpoint.json.encodeToStringFast(callSerializer, internalCall)
val result = Call(
internalCall.serviceName,
service,
internalCall.function,
internalCall.args,
encodedCall,
encodedServiceNames
)
val callback = nextOutboundCallCallback
if (callback != null) {
callback(result)
nextOutboundCallCallback = null
}
return result
}
internal fun decodeCall(
callJson: String,
): InternalCall {
decodedServiceNames.clear()
val internalCall = endpoint.json.decodeFromStringFast(callSerializer, callJson)
val inboundService = internalCall.inboundService
?: error("no handler for ${internalCall.serviceName}")
lastInboundCall = Call(
internalCall.serviceName,
inboundService.service,
internalCall.function,
internalCall.args,
callJson,
decodedServiceNames
)
return internalCall
}
internal fun encodeResult(
function: ReturningZiplineFunction<*>,
result: Result<Any?>,
): CallResult {
encodedServiceNames.clear()
@Suppress("UNCHECKED_CAST") // We delegate to the right serializer to encode.
val resultJson = endpoint.json.encodeToStringFast(
function.kotlinResultSerializer as KSerializer<Any?>,
result,
)
return CallResult(result, resultJson, encodedServiceNames)
}
internal fun decodeResult(
function: ReturningZiplineFunction<*>,
resultJson: String,
): CallResult {
decodedServiceNames.clear()
val result = endpoint.json.decodeFromStringFast(
function.kotlinResultSerializer,
resultJson,
)
return CallResult(result, resultJson, decodedServiceNames)
}
}
| apache-2.0 | d0983d16e1a4038e96dac2c39d9de214 | 31.034188 | 98 | 0.729456 | 4.488623 | false | false | false | false |
jonninja/node.kt | src/main/kotlin/node/express/Express.kt | 1 | 12033 | package node.express
import io.netty.bootstrap.ServerBootstrap
import java.util.HashMap
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.HttpRequest
import io.netty.channel.ChannelPipeline
import io.netty.handler.codec.http.HttpRequestDecoder
import io.netty.handler.codec.http.HttpResponseEncoder
import io.netty.handler.stream.ChunkedWriteHandler
import java.util.concurrent.Executors
import java.util.ArrayList
import java.net.InetSocketAddress
import java.util.Date
import java.text.SimpleDateFormat
import java.util.TimeZone
import java.util.regex.Pattern
import java.util.regex.Matcher
import node.express.engines.FreemarkerEngine
import node.express.engines.VelocityEngine
import node.util.extension
import java.io.File
import node.util.log
import java.util.logging.Level
import com.fasterxml.jackson.databind.ObjectMapper
import node.http.HttpMethod
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Retention
import node.NotFoundException
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory
import io.netty.handler.codec.http.QueryStringDecoder
import io.netty.handler.codec.http.websocketx.WebSocketFrame
import io.netty.channel.group.DefaultChannelGroup
import io.netty.channel.Channel
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelFuture
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame
import io.netty.buffer.ByteBuf
import java.nio.ByteBuffer
import java.io.FileNotFoundException
import io.netty.channel.ChannelOutboundHandlerAdapter
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.http.HttpObjectAggregator
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.channel.SimpleChannelInboundHandler
private val json = ObjectMapper();
// The default error handler. Can be overridden by setting the errorHandler property of the
// Express instance
var defaultErrorHandler :((Throwable, Request, Response) -> Unit) = { t, req, res ->
log(Level.WARNING, "Error thrown handling request: " + req.path, t)
when (t) {
is ExpressException -> res.send(t.code, t.getMessage())
is NotFoundException -> res.notFound()
is FileNotFoundException -> res.notFound()
is IllegalArgumentException -> res.badRequest()
is IllegalAccessException -> res.forbidden()
is IllegalAccessError -> res.forbidden()
is UnsupportedOperationException -> res.notImplemented()
else -> res.internalServerError()
}
}
class RouteHandler(val req: Request, val res: Response, val nextHandler: (nextReq: Request, nextRes: Response) -> Unit) {
fun next() {
nextHandler(req, res)
}
fun next(nextReq: Request, nextRes: Response) {
nextHandler(nextReq, nextRes)
}
}
/**
* Express.kt
*/
abstract class Express() {
private val settings = HashMap<String, Any>()
public val locals:MutableMap<String, Any> = HashMap<String, Any>()
private val routes = ArrayList<Route>()
private val engines = HashMap<String, Engine>()
val params = HashMap<String, (Request, Response, Any) -> Any?>()
var errorHandler: ((Throwable, Request, Response) -> Unit) = defaultErrorHandler
init {
settings.put("views", "views/")
settings.put("jsonp callback name", "callback")
locals.put("settings", settings)
engines.put("vm", VelocityEngine())
engines.put("ftl", FreemarkerEngine())
}
/**
* Assign a setting value. Settings are available in templates as 'settings'
*/
fun set(name: String, value: Any) {
settings.put(name, value);
}
/**
* Get the value of a setting
*/
fun get(name: String): Any? {
return settings.get(name);
}
/**
* Register a rendering engine with an extension. Once registered, setting the 'view engine' setting
* to a registered extension will set the default view engine. Then, when calling 'render', if no
* file extension is part of the name, the default extension will be appended and the appropriate
* rendering engine will be used.
* @param ext the file extension to register (ie. vm, flt, etc.)
* @param engine a rendering engine that implements the Engine trait
*/
fun engine(ext: String, engine: Engine) {
engines.put(ext, engine);
}
/**
* Set a feature setting to 'true'. Identical to [[Express.set(feature, true)]].
*/
fun enable(feature: String) {
settings.put(feature, true)
}
/**
* Set a feature setting to 'false'. Identical to [[Express.set(feature, false)]].
*/
fun disable(feature: String) {
settings.put(feature, false)
}
/**
* Check if a setting is enabled. If the setting doesn't exist, returns false.
*/
fun enabled(feature: String): Boolean {
return settings.get(feature) as? Boolean ?: false
}
/**
* Map logic to route parameters. When a provided parameter is present,
* calls the builder function to assign the value. So, for example, the :user
* parameter can be mapped to a function that creates a user object.
*/
fun param(name: String, builder: (Request, Response, Any) -> Any?) {
params.put(name, builder)
}
/**
* Render a view, returning the resulting string.
* @param name the name of the view. If the extension is left off, the value of 'view engine' will
* be used as the extension.
* @param data data that will be passed to the rendering engine to be used in the rendering of the
* view. This data will be merged with 'locals', allowing you to set global data to be used in
* all rendering operations.
*/
fun render(name: String, data: Map<String, Any?>? = null): String {
var ext = name.extension();
var viewFileName = name;
if (ext == null) {
ext = settings.get("view engine") as? String ?: throw IllegalArgumentException("No default view set for view without extension")
viewFileName = name + "." + ext;
}
val renderer = engines.get(ext) ?: throw IllegalArgumentException("No renderer for ext: " + ext);
var mergedContext = HashMap<String, Any?>();
mergedContext.putAll(locals);
if (data != null) {
mergedContext.putAll(data);
}
val viewsPath = settings.get("views") as String;
val viewFile = File(viewsPath + viewFileName)
if (!viewFile.exists()) {
throw FileNotFoundException()
}
val viewPath = viewFile.getAbsolutePath();
return renderer.render(viewPath, mergedContext);
}
fun install(method: String, path: String, vararg handler: RouteHandler.() -> Unit) {
handler.forEach {
routes.add(Route(method, path, it))
}
}
private fun installAll(path: String, vararg handler: RouteHandler.() -> Unit) {
install("get", path, *handler);
install("put", path, *handler);
install("post", path, *handler);
install("delete", path, *handler);
install("head", path, *handler);
install("patch", path, *handler);
}
/**
* Install a middleware Handler object to be used for all requests.
*/
fun use(middleware: RouteHandler.() -> Unit) {
install("*", "*", middleware)
}
/**
* Install middleware for a given path expression
*/
fun use(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("*", path, *middleware)
}
/**
* Install a handler for a path for all HTTP methods.
*/
fun all(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("*", path, *middleware)
}
/**
* Install a GET handler callback for a path
*/
fun get(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("get", path, *middleware);
}
/**
* Install a POST handler callback for a path
*/
fun post(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("post", path, *middleware);
}
/**
* Install a PATCH handler callback for a path
*/
fun patch(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("patch", path, *middleware);
}
/**
* Install a PUT handler callback for a path
*/
fun put(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("put", path, *middleware);
}
/**
* Install a DELETE handler callback for a path
*/
fun delete(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("delete", path, *middleware);
}
/**
* Install a HEAD handler callback for a path
*/
fun head(path: String, vararg middleware: RouteHandler.() -> Unit) {
install("head", path, *middleware);
}
fun handleRequest(req: Request, res: Response, stackIndex: Int = 0) {
var index = stackIndex
while (true) {
if (index >= routes.size()) {
res.sendErrorResponse(404) // send a 404
break;
} else {
var route = routes[index]
if (req.checkRoute(route, res)) {
val handlerExtension: RouteHandler.() -> Unit = route.handler
val routeHandler = RouteHandler(req, res, { nextReq, nextRes ->
handleRequest(nextReq, nextRes, index + 1)
})
routeHandler.handlerExtension()
break;
} else {
index++
}
}
}
}
//
// //***************************************************************************
// // WEBSOCKET SUPPORT
// //***************************************************************************
//
// // Map of channel identifiers to WebSocketHandler instances
// private val webSocketHandlers = HashMap<Int, WebSocketHandler>()
//
// /**
// * Install web socket route
// */
// fun webSocket(path: String, handler: (WebSocketChannel) -> WebSocketHandler) {
// val route = WebSocketRoute(path)
// get(path, { req, res, next ->
// route.handshake(req.channel, req.request)
// val wsh = handler(WebSocketChannel(req.channel))
// webSocketHandlers.put(req.channel.getId()!!, wsh)
// req.channel.getCloseFuture()!!.addListener(object: ChannelFutureListener {
// public override fun operationComplete(future: ChannelFuture?) {
// wsh.closed()
// webSocketHandlers.remove(future!!.channel()!!.getId())
// }
// })
// })
// }
//
// /**
// * Defines a WebSocket route. Mainly responsible for the initial handshake.
// */
// class WebSocketRoute(val path: String) {
// val channelGroup = DefaultChannelGroup(path)
// var wsFactory: WebSocketServerHandshakerFactory? = null
//
// fun handshake(channel: Channel, req: HttpRequest) {
// val location = "ws://" + req.headers().get("host") + QueryStringDecoder(req.getUri()!!)
// if (wsFactory == null) {
// wsFactory = WebSocketServerHandshakerFactory(location, null, false)
// }
// val handshaker = wsFactory!!.newHandshaker(req);
// if (handshaker == null) {
// wsFactory!!.sendUnsupportedWebSocketVersionResponse(channel)
// } else {
// channelGroup.add(channel)
// handshaker.handshake(channel, req)
// }
// }
// }
//
//
// /**
// * Handle a web socket request. Mainly passes along data to a WebSocketHandler.
// */
// private fun handleWebSocketRequest(channel: Channel, frame: WebSocketFrame) {
// val handler = webSocketHandlers.get(channel.getId())
// if (handler == null) return
//
// handler.handle(channel, frame)
// if (frame is CloseWebSocketFrame) {
// webSocketHandlers.remove(channel.getId())
// }
// }
}
/**
* Exception thrown by Express
*/
open class ExpressException(val code: Int, msg: String? = null, cause: Throwable? = null): Exception(msg, cause)
/**
* Exception to throw whenever the request is invalid
*/
open class BadRequest(msg: String? = null, cause: Throwable? = null): ExpressException(400, msg, cause) | mit | 048e2e6166468082538cbe2a3ac01bce | 31.879781 | 134 | 0.676639 | 4.002994 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/playback/PromisedPlayedExoPlayer.kt | 1 | 3626 | package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.playback
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.upstream.HttpDataSource.InvalidResponseCodeException
import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer
import com.lasthopesoftware.bluewater.client.playback.file.PlayedFile
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.error.ExoPlayerException
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.progress.ExoPlayerFileProgressReader
import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressedPromise
import com.namehillsoftware.handoff.promises.Promise
import org.joda.time.Duration
import org.joda.time.format.PeriodFormatterBuilder
import org.slf4j.LoggerFactory
import java.io.EOFException
import java.net.ProtocolException
class PromisedPlayedExoPlayer(private val exoPlayer: PromisingExoPlayer, private val progressReader: ExoPlayerFileProgressReader, private val handler: ExoPlayerPlaybackHandler) : ProgressedPromise<Duration, PlayedFile>(), PlayedFile, Player.Listener {
companion object {
private val minutesAndSecondsFormatter by lazy {
PeriodFormatterBuilder()
.appendMinutes()
.appendSeparator(":")
.minimumPrintedDigits(2)
.maximumParsedDigits(2)
.appendSeconds()
.toFormatter()
}
private val logger by lazy { LoggerFactory.getLogger(PromisedPlayedExoPlayer::class.java) }
}
init {
exoPlayer.addListener(this)
}
override val progress: Promise<Duration>
get() = progressReader.progress
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_ENDED) {
removeListener()
resolve(this)
return
}
if (playbackState != Player.STATE_IDLE || !handler.isPlaying) return
progress
.then { p ->
handler.duration.then handler@{ d ->
val formatter = minutesAndSecondsFormatter
logger.warn(
"The player was playing, but it transitioned to idle! " +
"Playback progress: " + p.toPeriod().toString(formatter) + " / " + d.toPeriod().toString(formatter) + ". ")
}
}
.eventually { exoPlayer.getPlayWhenReady() }
.then { ready ->
if (ready) {
logger.warn("The file is set to playWhenReady, waiting for playback to resume.")
} else {
logger.warn("The file is not set to playWhenReady, triggering playback completed")
removeListener()
resolve(this)
}
}
}
override fun onPlayerError(error: PlaybackException) {
removeListener()
when (val cause = error.cause) {
is EOFException -> {
logger.warn("The file ended unexpectedly. Completing playback", error)
resolve(this)
return
}
is NoSuchElementException -> {
logger.warn("The player was unexpectedly unable to dequeue messages, completing playback", error)
resolve(this)
return
}
is ProtocolException -> {
val message = cause.message
if (message != null && message.contains("unexpected end of stream")) {
logger.warn("The stream ended unexpectedly, completing playback", error)
resolve(this)
return
}
}
is InvalidResponseCodeException -> {
if (cause.responseCode == 416) {
logger.warn("Received an error code of " + cause.responseCode + ", completing playback", cause)
resolve(this)
return
}
}
}
logger.error("A player error has occurred", error)
reject(ExoPlayerException(handler, error))
}
private fun removeListener() = exoPlayer.removeListener(this)
}
| lgpl-3.0 | 17e300c5eab289eacde0f2a1207b2d22 | 33.207547 | 251 | 0.745725 | 4.051397 | false | false | false | false |
binkley/fibs | src/main/kotlin/hm/binkley/Main.kt | 1 | 1199 | package hm.binkley
import hm.binkley.Q.Companion.fib0
import java.lang.System.err
import java.lang.System.exit
private fun usage() {
err.println("Usage: fibs <n>")
exit(2)
}
private fun n(args: Array<String>): Int? {
return if (1 == args.size) try {
args[0].toInt()
} catch (e: NumberFormatException) {
null
} else null
}
/** {@code main} Main entry point */
fun main(args: Array<String>) {
var n = n(args) ?: return usage()
val limit: Int
val next: (Q) -> Q
if (n < 0) {
next = Q::dec
limit = -n
} else {
next = Q::inc
limit = n
}
fun display(it: Q): String {
val n = it.n
return """Fib($n):
$it
(fib($n): ${it.a}; det: ${it.det()}; trace: ${it.trace()})"""
}
generateSequence(fib0) { next(it) }.
take(limit + 1).
map(::display).
forEach(::println)
println(display(fib0(7)))
println(display(fib0(-2)))
println(display(fib0.pow(0)))
println(display(fib0.pow(1)))
println(display(fib0.pow(2)))
println(display(fib0.pow(-1)))
println((fib0(0) * fib0(-1)) == fib0)
println(display(fib0(0) * fib0(-2)))
}
| unlicense | 1a02e05799e570b4db15025fa2ea2d6f | 20.8 | 61 | 0.538782 | 3.074359 | false | false | false | false |
NextFaze/dev-fun | demo/src/androidTest/java/com/nextfaze/devfun/demo/test/DaggerTests.kt | 1 | 10343 | package com.nextfaze.devfun.demo.test
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.nextfaze.devfun.core.call
import com.nextfaze.devfun.core.devFun
import com.nextfaze.devfun.demo.R
import com.nextfaze.devfun.demo.fragmentActivityTestRule
import com.nextfaze.devfun.demo.orientationLandscape
import com.nextfaze.devfun.demo.orientationPortrait
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.reflect.KClass
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotSame
@RunWith(AndroidJUnit4::class)
class DaggerInjectionTests {
@Rule
@JvmField
val activityRule = fragmentActivityTestRule<DaggerScopesActivity, DaggerScopesFragment>()
@Test
fun validateStandardDaggerBehaviour() {
onView(withId(R.id.daggerScopesFragmentRoot)).check(matches(isCompletelyDisplayed()))
// Sanity checks
fun sanityChecks(activity: DaggerScopesActivity, fragment: DaggerScopesFragment) {
assertNotSame(activity.injectableNotScopedWithZeroArgsConstructor, fragment.injectableNotScopedWithZeroArgsConstructor)
assertNotSame(activity.injectableNotScopedWithMultipleArgsConstructor, fragment.injectableNotScopedWithMultipleArgsConstructor)
assertEquals(activity.injectableRetainedScopedViaAnnotation, fragment.injectableRetainedScopedViaAnnotation)
assertEquals(activity.injectableRetainedScopedViaAnnotationWithArgs, fragment.injectableRetainedScopedViaAnnotationWithArgs)
assertEquals(activity.injectableRetainedScopedViaProvides, fragment.injectableRetainedScopedViaProvides)
assertEquals(activity.injectableRetainedScopedViaProvidesWithArgs, fragment.injectableRetainedScopedViaProvidesWithArgs)
assertEquals(activity.injectableSingletonScopedViaAnnotation, fragment.injectableSingletonScopedViaAnnotation)
assertEquals(activity.injectableSingletonScopedViaAnnotationWithArgs, fragment.injectableSingletonScopedViaAnnotationWithArgs)
assertEquals(activity.injectableSingletonScopedViaProvides, fragment.injectableSingletonScopedViaProvides)
assertEquals(activity.injectableSingletonScopedViaProvidesWithArgs, fragment.injectableSingletonScopedViaProvidesWithArgs)
// package private to test accessibility issues (not Dagger/scoping per se)
assertNotSame(activity.injectablePackagePrivateNotScoped, fragment.injectablePackagePrivateNotScoped)
assertNotSame(activity.injectablePackagePrivateNotScopedWithArgs, fragment.injectablePackagePrivateNotScopedWithArgs)
assertEquals(activity.injectablePackagePrivateRetainedViaAnnotation, fragment.injectablePackagePrivateRetainedViaAnnotation)
assertEquals(activity.injectablePackagePrivateSingletonViaAnnotation, fragment.injectablePackagePrivateSingletonViaAnnotation)
}
fun testDevFunGet(activity: DaggerScopesActivity, fragment: DaggerScopesFragment) {
// Check that DevFun can resolve them correctly
with(activity) {
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
// this should fail here, but succeed when injected in-context
assertEquals(injectableNotScopedWithZeroArgsConstructor, devFun.get())
}
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
assertEquals(injectableNotScopedWithMultipleArgsConstructor, devFun.get())
}
assertEquals(injectableActivityScopedViaAnnotation, devFun.get())
assertEquals(injectableActivityScopedViaAnnotationWithArgs, devFun.get())
assertEquals(injectableActivityScopedViaProvides, devFun.get())
assertEquals(injectableActivityScopedViaProvidesWithArgs, devFun.get())
assertEquals(injectableRetainedScopedViaAnnotation, devFun.get())
assertEquals(injectableRetainedScopedViaAnnotationWithArgs, devFun.get())
assertEquals(injectableRetainedScopedViaProvides, devFun.get())
assertEquals(injectableRetainedScopedViaProvidesWithArgs, devFun.get())
assertEquals(injectableSingletonScopedViaAnnotation, devFun.get())
assertEquals(injectableSingletonScopedViaAnnotationWithArgs, devFun.get())
assertEquals(injectableSingletonScopedViaProvides, devFun.get())
assertEquals(injectableSingletonScopedViaProvidesWithArgs, devFun.get())
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
assertEquals(injectablePackagePrivateNotScoped, devFun.get())
}
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
assertEquals(injectablePackagePrivateNotScopedWithArgs, devFun.get())
}
assertEquals(injectablePackagePrivateActivityViaAnnotation, devFun.get())
assertEquals(injectablePackagePrivateRetainedViaAnnotation, devFun.get())
assertEquals(injectablePackagePrivateSingletonViaAnnotation, devFun.get())
}
with(fragment) {
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
assertEquals(injectableNotScopedWithZeroArgsConstructor, devFun.get())
}
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
assertEquals(injectableNotScopedWithMultipleArgsConstructor, devFun.get())
}
assertEquals(injectableRetainedScopedViaAnnotation, devFun.get())
assertEquals(injectableRetainedScopedViaAnnotationWithArgs, devFun.get())
assertEquals(injectableRetainedScopedViaProvides, devFun.get())
assertEquals(injectableRetainedScopedViaProvidesWithArgs, devFun.get())
assertEquals(injectableSingletonScopedViaAnnotation, devFun.get())
assertEquals(injectableSingletonScopedViaAnnotationWithArgs, devFun.get())
assertEquals(injectableSingletonScopedViaProvides, devFun.get())
assertEquals(injectableSingletonScopedViaProvidesWithArgs, devFun.get())
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
assertEquals(injectablePackagePrivateNotScoped, devFun.get())
}
assertFailsWith<AssertionError> {
// dagger does not hold a reference to fetch for non-scoped types
assertEquals(injectablePackagePrivateNotScopedWithArgs, devFun.get())
}
assertEquals(injectablePackagePrivateRetainedViaAnnotation, devFun.get())
assertEquals(injectablePackagePrivateSingletonViaAnnotation, devFun.get())
}
// TODO? Correct injection would get type from fragment itself rather than searching components
// Now check that call-aware injection can grab it based on where it's called.
// i.e. if we're calling a function in the Fragment then we should be able to inject the non-scoped instances to the call.
// We can't get the correct non-scoped instance when we don't know the context as there could be more than one instance etc.
val testDevFunctions = listOf(
// DaggerScopesActivity::testQualifiedString1,
// DaggerScopesActivity::testQualifiedString2,
// DaggerScopesActivity::testQualifiedClasses,
// DaggerScopesActivity::testMultiset,
// DaggerScopesActivity::testInjectableNotScopedWithZeroArgsConstructor,
// DaggerScopesActivity::testInjectableNotScopedWithMultipleArgsConstructor,
// DaggerScopesActivity::testInjectablePackagePrivateNotScoped,
// DaggerScopesActivity::testInjectablePackagePrivateNotScopedWithArgs,
DaggerScopesActivity::testInjectablePackagePrivateRetainedViaAnnotation,
// DaggerScopesFragment::testInjectableNotScopedWithZeroArgsConstructor,
// DaggerScopesFragment::testInjectableNotScopedWithMultipleArgsConstructor,
// DaggerScopesFragment::testInjectablePackagePrivateNotScoped,
// DaggerScopesFragment::testInjectablePackagePrivateNotScopedWithArgs,
DaggerScopesFragment::testInjectablePackagePrivateRetainedViaAnnotation
)
val items = devFun.categories.flatMap { it.items }
testDevFunctions.forEach { devFunFunc ->
val clazz = devFunFunc.parameters.first().type.classifier as KClass<*>
val name = devFunFunc.name
val item = items.single { it.function.clazz == clazz && it.function.method.name.startsWith(name) }
item.call()!!.exception?.run { throw this }
}
}
val activity = activityRule.activity
val fragment = activityRule.fragment
sanityChecks(activity, fragment)
testDevFunGet(activity, fragment)
onView(isRoot()).perform(orientationLandscape())
try {
val activity2 = activityRule.activity
assertNotSame(activity, activity2)
assertEquals(fragment, activityRule.fragment)
sanityChecks(activity2, fragment)
testDevFunGet(activity2, fragment)
} finally {
onView(isRoot()).perform(orientationPortrait())
}
}
}
| apache-2.0 | 758e5a4a1c412a9a2863f1044e4af48e | 58.442529 | 139 | 0.710335 | 5.655003 | false | true | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/MainDebugActivityOkhttpV3.kt | 1 | 26778 | package com.didichuxing.doraemondemo
import android.Manifest
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.Uri
import android.os.*
import android.text.format.Formatter
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import coil.imageLoader
import coil.request.CachePolicy
import coil.transform.CircleCropTransformation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.navi.AMapNavi
import com.amap.api.navi.AMapNaviListener
import com.amap.api.navi.enums.PathPlanningStrategy
import com.amap.api.navi.model.*
import com.blankj.utilcode.util.*
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.didichuxing.doraemondemo.amap.AMapRouterFragment
import com.didichuxing.doraemondemo.comm.CommLauncher
import com.didichuxing.doraemondemo.databinding.ActivityMainBinding
import com.didichuxing.doraemondemo.mc.MCActivity
import com.didichuxing.doraemondemo.retrofit.GithubService
import com.didichuxing.doraemonkit.DoKit
import com.facebook.drawee.backends.pipeline.Fresco
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.Picasso
import com.squareup.picasso.RequestCreator
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.*
import okhttp3.*
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.PermissionRequest
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.*
import java.net.*
import java.util.HashMap
import kotlin.coroutines.resume
/**
* @author jintai
*/
class MainDebugActivityOkhttpV3 : BaseActivity(), View.OnClickListener, CoroutineScope by MainScope() {
private var okHttpClient: OkHttpClient? = null
private var mLocationManager: LocationManager? = null
private val UPDATE_UI = 100
private lateinit var mAdapter: MainAdapter
private val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
/**
* github 接口
*/
private var githubService: GithubService? = null
private var _binding: ActivityMainBinding? = null
@SuppressLint("HandlerLeak")
private val mHandler: Handler = object : Handler() {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
when (msg.what) {
100 -> _binding?.ivPicasso?.setImageBitmap(msg.obj as Bitmap)
else -> {
}
}
}
}
val datas = mutableListOf(
"显示/隐藏Dokit入口",
"显示工具面板",
"弹框测试",
"系统反射测试",
"获取已安装的app",
"截屏",
"跳转其他Activity",
"一机多控",
"NormalWebView",
"X5WebView",
"模拟内存泄漏",
"函数调用耗时(TAG:MethodCostUtil)",
"获取位置信息(系统)",
"获取位置信息(高德)",
"高德路径规划",
"OkHttp Mock",
"HttpURLConnection Mock",
"Retrofit Mock",
"模拟Crash",
"创建数据库",
"上传文件",
"下载文件"
)
suspend fun sleep() = suspendCancellableCoroutine<String> {
Thread.sleep(5000)
it.resume("sleep 1000ms")
}
fun sleep2(): String {
Thread.sleep(5000)
return "sleep 1000ms"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater).also {
setContentView(it.root)
mAdapter = MainAdapter(R.layout.item_main_rv, datas)
it.initView(this)
}
mAdapter.setOnItemClickListener { _, _, position ->
when (datas[position]) {
"弹框测试" -> {
// val bundle = Bundle()
// bundle.putString("text", "测试同步异常")
// DoKit.launchFloating<McDialogDoKitView>(bundle = bundle)
lifecycleScope.launch {
delay(15000)
Log.i(TAG, "===inner===")
}
Log.i(TAG, "===out===")
}
"系统反射测试" -> {
try {
val activityClass = Class.forName("dalvik.system.VMRuntime")
val field = activityClass.getDeclaredMethod("setHiddenApiExemptions", Array<String>::class.java)
field.isAccessible = true
Toast.makeText(this, "call success!!", Toast.LENGTH_SHORT).show()
} catch (e: Throwable) {
Log.e(TAG, "error:", e)
Toast.makeText(this, "error: $e", Toast.LENGTH_SHORT).show()
}
}
"显示/隐藏Dokit入口" -> {
if (DoKit.isMainIconShow) {
DoKit.hide()
} else {
DoKit.show()
}
}
"显示工具面板" -> {
DoKit.showToolPanel()
}
"获取已安装的app" -> {
packageManager.getInstalledApplications(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) PackageManager.MATCH_UNINSTALLED_PACKAGES
else PackageManager.GET_UNINSTALLED_PACKAGES
)
packageManager.getInstalledApplications(PackageManager.MATCH_UNINSTALLED_PACKAGES)
}
"截屏" -> {
// lifecycleScope.launch {
//
// DoKit.launchFloating(BorderDoKitView::class.java)
// val borderDoKitView =
// DoKit.getDoKitView(
// this@MainDebugActivityOkhttpV3,
// BorderDoKitView::class.java
// ) as BorderDoKitView
// borderDoKitView.showBorder(view)
// withContext(Dispatchers.IO) {
// delay(200)
// val bitmap = ScreenUtils.screenShot(this@MainDebugActivityOkhttpV3)
// val output = File(getCrashCacheDir(), "test.png")
// DoKitImageUtil.bitmap2File(bitmap, 100, output)
// }
//
// }
}
"跳转其他Activity" -> {
startActivity(Intent(this, SecondActivity::class.java))
}
"一机多控" -> {
startActivity(Intent(this, MCActivity::class.java))
}
"NormalWebView" -> {
startActivity(Intent(this, WebViewNormalActivity::class.java))
}
"X5WebView" -> {
startActivity(Intent(this, WebViewX5Activity::class.java))
}
"模拟内存泄漏" -> {
startActivity(Intent(this, LeakActivity::class.java))
}
"函数调用耗时(TAG:MethodCostUtil)" -> {
test1()
}
"获取位置信息(系统)" -> {
startNormaLocation()
}
"获取位置信息(高德)" ->{
startAMapLocation()
}
"高德路径规划" -> {
CommLauncher.startActivity(AMapRouterFragment::class.java, this)
}
"OkHttp Mock" -> {
val jsonObject = JSONObject()
jsonObject.put("c", "cc")
jsonObject.put("d", "dd")
OkGo.post<String>("https://wanandroid.com/user_article/list/0/json?b=bb&a=aa")
.upJson(jsonObject)
.execute(object : StringCallback() {
override fun onSuccess(response: Response<String>?) {
response?.let {
Log.i(TAG, "okhttp====onSuccess===>" + it.body())
}
}
})
// OkGo.post<String>("https://wanandroid.com/user_article/list/0/json?b=bb&a=aa")
// .params("c", "cc")
// .params("d", "dd")
// .execute()
// OkGo.get<String>("https://wanandroid.com/user_article/list/0/json?a=aa&b=bb")
// //.upJson(json.toString())
// .execute(object : StringCallback() {
// override fun onSuccess(response: Response<String>?) {
// response?.let {
// Log.i(
// MainDebugActivityOkhttpV3.TAG,
// "okhttp====onSuccess===>" + it.body()
// )
// }
// }
//
// override fun onError(response: Response<String>?) {
// response?.let {
// Log.i(
// MainDebugActivityOkhttpV3.TAG,
// "okhttp====onError===>" + it.message()
// )
// }
// }
//
// })
}
"HttpURLConnection Mock" -> {
requestByGet("https://wanandroid.com/user_article/list/0/json")
}
"Retrofit Mock" -> {
lifecycleScope.launch {
val result = githubService?.githubUserInfo("jtsky")
Log.i(TAG, "result===>${result}")
}
}
"模拟Crash" -> {
checkNotNull(testCrash())
}
"创建数据库" -> {
val dbHelper = MyDatabaseHelper(this, "BookStore.db", null, 1)
dbHelper.writableDatabase
dbHelper.close()
}
"上传文件" -> {
requestByFile(true)
}
"下载文件" -> {
requestByFile(false)
}
else -> {
}
}
}
okHttpClient = OkHttpClient().newBuilder().build()
//获取定位服务
mLocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
//高德定位服务
EasyPermissions.requestPermissions(
PermissionRequest.Builder(
this, 200,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
).build()
)
//初始化
val config = ImageLoaderConfiguration.Builder(this)
.build()
ImageLoader.getInstance().init(config)
githubService = retrofit.create(GithubService::class.java)
}
private fun ActivityMainBinding.initView(context: Context) {
tvEnv.text = "${getString(R.string.app_build_types)}:Debug"
rv.layoutManager = LinearLayoutManager(context)
rv.adapter = mAdapter
btnLoadImg.setOnClickListener(this@MainDebugActivityOkhttpV3)
}
private fun test1() {
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
test2()
}
private fun test2() {
try {
Thread.sleep(200)
} catch (e: InterruptedException) {
e.printStackTrace()
}
test3()
}
private fun test3() {
try {
Thread.sleep(200)
} catch (e: InterruptedException) {
e.printStackTrace()
}
test4()
}
private fun test4() {
try {
Thread.sleep(200)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
private val mLocationListener: LocationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
val string = "lat====>" + location.latitude + " lng====>" + location.longitude
Log.i(TAG, "系统定位====>$string")
}
override fun onProviderDisabled(arg0: String) {}
override fun onProviderEnabled(arg0: String) {}
override fun onStatusChanged(arg0: String, arg1: Int, arg2: Bundle) {}
}
/**
* 启动普通定位
*/
@SuppressLint("MissingPermission")
private fun startNormaLocation() {
mLocationManager!!.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0,
0f,
mLocationListener
)
}
/**
* 启动高德定位
*/
private fun startAMapLocation() {
// 确保调用SDK任何接口前先调用更新隐私合规updatePrivacyShow、updatePrivacyAgree两个接口并且参数值都为true,若未正确设置有崩溃风险
AMapLocationClient.updatePrivacyShow(this, true, true)
AMapLocationClient.updatePrivacyAgree(this, true)
//声明mLocationOption对象
var mLocationOption: AMapLocationClientOption? = null
val mlocationClient = AMapLocationClient(this)
//初始化定位参数
mLocationOption = AMapLocationClientOption()
//设置定位监听
mlocationClient!!.setLocationListener(mapLocationListener)
//设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
//设置定位间隔,单位毫秒,默认为2000ms
mLocationOption.interval = 2000
//设置定位参数
mlocationClient!!.setLocationOption(mLocationOption)
// 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
// 注意设置合适的定位时间的间隔(最小间隔支持为1000ms),并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后,在合适的生命周期调用onDestroy()方法
// 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
//启动定位
mlocationClient!!.startLocation()
}
/**
* 启动高德定位服务
*/
private var mapLocationListener = AMapLocationListener { aMapLocation ->
val errorCode = aMapLocation.errorCode
val errorInfo = aMapLocation.errorInfo
Log.i(
TAG,
"高德定位===lat==>" + aMapLocation.latitude + " lng==>" + aMapLocation.longitude + " errorCode===>" + errorCode + " errorInfo===>" + errorInfo
)
}
@SuppressLint("MissingPermission")
override fun onClick(v: View) {
when (v.id) {
R.id.btn_load_img -> {
//Glide 加载
val picassoImgUrl =
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2F2c.zol-img.com.cn%2Fproduct%2F124_500x2000%2F748%2FceZOdKgDAFsq2.jpg&refer=http%3A%2F%2F2c.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621652979&t=850e537c70eaa7753e892bc8b4d05f57"
val glideImageUrl =
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2F1812.img.pp.sohu.com.cn%2Fimages%2Fblog%2F2009%2F11%2F18%2F18%2F8%2F125b6560a6ag214.jpg&refer=http%3A%2F%2F1812.img.pp.sohu.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621652979&t=76d35d35d9c510f1c24a422e9e02fd46"
val frescoImageUrl =
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F035%2F063%2F726%2F3ea4031f045945e1843ae5156749d64c.jpg&refer=http%3A%2F%2Fyouimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621652979&t=7150aaa2071d512cf2f6b556e126dd66"
val imageLoaderImageUrl =
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fyouimg1.c-ctrip.com%2Ftarget%2Ftg%2F004%2F531%2F381%2F4339f96900344574a0c8ca272a7b8f27.jpg&refer=http%3A%2F%2Fyouimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621652979&t=b7e83ecc987c64cc31079469d292eb56"
val coilImageUrl =
"https://cdn.nlark.com/yuque/0/2020/png/252337/1587091196083-assets/web-upload/62122ab5-986b-4662-be88-d3007a5e31c5.png"
Picasso.get().load(picassoImgUrl)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.placeholder(R.mipmap.cat)
.error(R.mipmap.cat)
.intoOrCancel(_binding?.ivPicasso)
Glide.with(this@MainDebugActivityOkhttpV3)
.asBitmap()
.load(glideImageUrl)
.placeholder(R.mipmap.cat)
.error(R.mipmap.cat)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.transform(CircleCrop())
.intoOrCancel(_binding?.ivGlide)
//coil
_binding?.ivCoil?.apply {
val request = coil.request.ImageRequest.Builder(this.context)
.memoryCachePolicy(CachePolicy.DISABLED)
.transformations(CircleCropTransformation())
.diskCachePolicy(CachePolicy.DISABLED)
.data(coilImageUrl)
.target(this)
.build()
imageLoader.enqueue(request)
}
//imageLoader
val imageLoader = ImageLoader.getInstance()
imageLoader.displayImageOrNot(imageLoaderImageUrl, _binding?.ivImageloader)
//fresco
_binding?.ivFresco?.setImageURI(Uri.parse(frescoImageUrl))
val imagePipeline = Fresco.getImagePipeline()
// combines above two lines
imagePipeline.clearCaches()
}
else -> {
}
}
}
private fun testCrash(): String? {
return null
}
private fun requestByGet(path: String) {
ThreadUtils.executeByIo(object : ThreadUtils.SimpleTask<String?>() {
@Throws(Throwable::class)
override fun doInBackground(): String {
try {
val url = URL(path.trim())
//打开连接
val urlConnection = url.openConnection() as HttpURLConnection
//urlConnection.setRequestProperty("token", "10051:abc");
//urlConnection.setRequestProperty("Content-type", "application/json");
//int log = urlConnection.getResponseCode();
//得到输入流
val `is` = urlConnection.inputStream
return ConvertUtils.inputStream2String(`is`, "utf-8")
} catch (e: IOException) {
e.printStackTrace()
}
return "error"
}
override fun onSuccess(result: String?) {
Log.i(TAG, "httpUrlConnection====response===>===>$result")
}
})
}
/**
* 模拟上传或下载文件
*
* @param upload true上传 false下载
*/
private fun requestByFile(upload: Boolean) {
val dialog = ProgressDialog.show(this, null, null)
dialog.setCancelable(true)
var request: Request? = null
if (upload) {
try {
//模拟一个1M的文件用来上传
val length = 1L * 1024 * 1024
val temp = File(filesDir, "test.tmp")
if (!temp.exists() || temp.length() != length) {
val accessFile = RandomAccessFile(temp, "rwd")
accessFile.setLength(length)
temp.createNewFile()
}
request = Request.Builder()
.post(RequestBody.create(MediaType.parse(temp.name), temp))
.url("http://wallpaper.apc.360.cn/index.php?c=WallPaper&a=getAppsByOrder&order=create_time&start=0&count=1&from=360chrome")
.build()
} catch (e: IOException) {
e.printStackTrace()
}
} else {
//下载一个2M的文件
request = Request.Builder()
.get()
.url("http://cdn1.lbesec.com/products/history/20131220/privacyspace_rel_2.2.1617.apk")
.build()
}
val call = okHttpClient!!.newCall(request!!)
val startTime = SystemClock.uptimeMillis()
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
dialog.cancel()
onHttpFailure(e)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: okhttp3.Response) {
if (!response.isSuccessful) {
onFailure(call, IOException(response.message()))
return
}
val body = response.body()
if (!upload) {
inputStream2File(body!!.byteStream(), File(filesDir, "test.apk"))
}
dialog.cancel()
val requestLength = if (upload) call.request().body()!!.contentLength() else 0
val responseLength = if (body!!.contentLength() < 0) 0 else body.contentLength()
val endTime = SystemClock.uptimeMillis() - startTime
val speed = (if (upload) requestLength else responseLength) / endTime * 1000
val message = String.format(
"请求大小:%s,响应大小:%s,耗时:%dms,均速:%s/s",
Formatter.formatFileSize(applicationContext, requestLength),
Formatter.formatFileSize(applicationContext, responseLength),
endTime,
Formatter.formatFileSize(applicationContext, speed)
)
runOnUiThread {
Log.d("onResponse", message)
Toast.makeText(this@MainDebugActivityOkhttpV3, message, Toast.LENGTH_LONG)
.show()
}
}
})
}
private fun onHttpFailure(e: IOException) {
e.printStackTrace()
runOnUiThread {
if (e is UnknownHostException) {
Toast.makeText(this@MainDebugActivityOkhttpV3, "网络异常", Toast.LENGTH_SHORT).show()
} else if (e is SocketTimeoutException) {
Toast.makeText(this@MainDebugActivityOkhttpV3, "请求超时", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this@MainDebugActivityOkhttpV3, e.message, Toast.LENGTH_LONG)
.show()
}
}
}
private fun inputStream2File(`is`: InputStream, saveFile: File) {
var len: Int
val buf = ByteArray(2048)
val fos = FileOutputStream(saveFile)
`is`.use { input ->
fos.use { output ->
while (input.read(buf).also { len = it } != -1) {
output.write(buf, 0, len)
}
output.flush()
}
}
}
override fun onDestroy() {
super.onDestroy()
okHttpClient!!.dispatcher().cancelAll()
mLocationManager!!.removeUpdates(mLocationListener)
}
private fun requestImage(urlStr: String) {
try {
//
val url = URL(urlStr)
// http https
// ftp
val urlConnection = url.openConnection() as HttpURLConnection
//http get post
urlConnection.requestMethod = "GET"
urlConnection.connectTimeout = 5000
urlConnection.readTimeout = 5000
val responseCode = urlConnection.responseCode
if (responseCode == 200) {
val bitmap = BitmapFactory.decodeStream(urlConnection.inputStream)
//更新 ui
mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, bitmap))
}
} catch (e: MalformedURLException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun RequestCreator.intoOrCancel(target: ImageView?) {
target?.also { into(it) }
}
private fun RequestBuilder<*>.intoOrCancel(target: ImageView?) {
target?.also { into(it) }
}
private fun ImageLoader.displayImageOrNot(url: String, target: ImageView?) {
target?.also { displayImage(url, it) }
}
companion object {
const val TAG = "MainDebugActivity"
}
}
| apache-2.0 | a385cbb01b91910a781d71361334b393 | 37.304024 | 306 | 0.542526 | 4.468359 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/api/internal/registries/generators/thermopile/ThermopileRecipeManager.kt | 2 | 1244 | package com.cout970.magneticraft.api.internal.registries.generators.thermopile
import com.cout970.magneticraft.api.registries.generators.thermopile.IThermopileRecipe
import com.cout970.magneticraft.api.registries.generators.thermopile.IThermopileRecipeManager
import net.minecraft.block.state.IBlockState
/**
* Created by cout970 on 2017/08/28.
*/
object ThermopileRecipeManager : IThermopileRecipeManager {
private val recipeList = mutableListOf<IThermopileRecipe>()
override fun findRecipe(input: IBlockState?): IThermopileRecipe? {
if (input == null) return null
return recipeList.find { it.blockState == input }
}
override fun getRecipes(): MutableList<IThermopileRecipe> = recipeList.toMutableList()
override fun registerRecipe(recipe: IThermopileRecipe): Boolean {
if (findRecipe(recipe.blockState) == null) {
recipeList += recipe
return true
}
return false
}
override fun removeRecipe(recipe: IThermopileRecipe?): Boolean = recipeList.remove(recipe)
override fun createRecipe(state: IBlockState, temperature: Float, conductivity: Float): IThermopileRecipe {
return ThermopileRecipe(state, temperature, conductivity)
}
} | gpl-2.0 | f2ec5c621d8366d0f9f8d474f660c535 | 35.617647 | 111 | 0.741961 | 4.231293 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/StringParameter.kt | 1 | 2327 | /*
ParaTask 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.paratask.parameters
import javafx.util.StringConverter
import uk.co.nickthecoder.paratask.parameters.fields.StringField
import uk.co.nickthecoder.paratask.util.uncamel
class StringParameter(
name: String,
label: String = name.uncamel(),
description: String = "",
hint: String = "",
value: String = "",
required: Boolean = true,
val columns: Int = 30,
val rows: Int = 1,
val style: String? = null,
val stretchy: Boolean = true,
isBoxed: Boolean = false)
: AbstractValueParameter<String>(
name = name,
label = label,
description = description,
hint = hint,
value = value,
required = required,
isBoxed = isBoxed) {
override val converter = object : StringConverter<String>() {
override fun fromString(str: String): String? = str
override fun toString(obj: String?): String = obj ?: ""
}
override fun isStretchy(): Boolean = stretchy
override fun errorMessage(v: String?): String? {
if (isProgrammingMode()) return null
if (required && (v == null || v.isEmpty())) {
return "Required"
}
return null
}
override fun createField(): StringField = StringField(this).build() as StringField
override fun toString() = "String" + super.toString()
override fun copy() = StringParameter(name = name, label = label, description = description, hint = hint,
value = value, required = required,
columns = columns, rows = rows, style = style, stretchy = stretchy, isBoxed = isBoxed)
}
| gpl-3.0 | e80a2f028a96386cc4c4fb306e7f6f37 | 33.220588 | 109 | 0.662226 | 4.41556 | false | false | false | false |
soniccat/android-taskmanager | quizlet_repository/src/main/java/com/example/alexeyglushkov/quizletservice/QuizletService.kt | 1 | 2976 | package com.example.alexeyglushkov.quizletservice
import com.example.alexeyglushkov.authorization.Auth.Account
import com.example.alexeyglushkov.authorization.Auth.AuthCredentials
import com.example.alexeyglushkov.authorization.Auth.ServiceCommandRunner
import com.example.alexeyglushkov.authorization.OAuth.OAuthCredentials
import com.example.alexeyglushkov.quizletservice.entities.QuizletSet
import com.example.alexeyglushkov.service.SimpleService
import com.example.alexeyglushkov.streamlib.progress.ProgressListener
import io.reactivex.Single
import io.reactivex.SingleSource
import io.reactivex.functions.Function
/**
* Created by alexeyglushkov on 26.03.16.
*/
class QuizletService(account: Account,
commandProvider: QuizletCommandProvider,
commandRunner: ServiceCommandRunner) : SimpleService() {
//// Actions
suspend fun loadSets(progressListener: ProgressListener?): List<QuizletSet> {
authorizeIfNeeded()
val command = createSetsCommand(progressListener)
return runCommand(command, true)
}
// OLD restoration approach based on command internal cache
// public Single<List<QuizletSet>> restoreSets(final ProgressListener progressListener) {
// return RxTools.justOrError(getAccount().getCredentials())
// .flatMap(new Function<AuthCredentials, SingleSource<? extends QuizletSetsCommand>>() {
// @Override
// public SingleSource<? extends QuizletSetsCommand> apply(AuthCredentials authCredentials) throws Exception {
// QuizletSetsCommand command = createSetsCommand(StorageClient.CacheMode.ONLY_LOAD_FROM_CACHE, progressListener);
// return runCommand(command, false);
// }
// }).flatMap(new Function<QuizletSetsCommand, SingleSource<? extends List<QuizletSet>>>() {
// @Override
// public SingleSource<? extends List<QuizletSet>> apply(QuizletSetsCommand quizletSetsCommand) throws Exception {
// return Single.just(new ArrayList<>(Arrays.asList(quizletSetsCommand.getResponse())));
// }
// });
// }
private fun createSetsCommand(progressListener: ProgressListener?): QuizletSetsCommand {
val userId = oAuthCredentials?.userId
checkNotNull(userId)
return quizletCommandProvider.getLoadSetsCommand(SERVER, userId, progressListener)
}
// Cast Getters
private val oAuthCredentials: OAuthCredentials?
get() = account?.credentials as? OAuthCredentials
private val quizletCommandProvider: QuizletCommandProvider
get() = commandProvider as QuizletCommandProvider
companion object {
private const val SERVER = "https://api.quizlet.com/2.0"
}
//// Initialization
init {
this.account = account
setServiceCommandProvider(commandProvider)
setServiceCommandRunner(commandRunner)
}
} | mit | d0315a9ef2d58d967e6217b63e282b58 | 43.432836 | 133 | 0.713038 | 4.96 | false | false | false | false |
fallGamlet/DnestrCinema | app/src/main/java/com/fallgamlet/dnestrcinema/utils/LiveDataUtils.kt | 1 | 1014 | package com.fallgamlet.dnestrcinema.utils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
object LiveDataUtils {
fun <T> wrapMutable(liveData: LiveData<T>): MediatorLiveData<T> {
val mediator = MediatorLiveData<T>()
mediator.addSource(liveData) { mediator.setValue(it) }
return mediator
}
fun <T> getMerged(liveDataList: List<LiveData<T>>): LiveData<T> {
val liveDataMerger = MediatorLiveData<T>()
liveDataList.forEach { item ->
liveDataMerger.addSource<T>(item) { liveDataMerger.setValue(it) }
}
return liveDataMerger
}
fun <T> sendOneAndNull(liveData: MutableLiveData<T>?, value: T) {
if (liveData == null)
return
liveData.value = value
liveData.value = null
}
fun refreshSignal(vararg liveData: MutableLiveData<*>) {
liveData.forEach {
it.value = it.value
}
}
}
| gpl-3.0 | 58ad65a72bf31e402a4017521720895b | 23.142857 | 77 | 0.642012 | 4.427948 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/data/server/model/AmpacheAuthentication.kt | 1 | 1017 | package be.florien.anyflow.data.server.model
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
/**
* Server-side data structures that relate to authentication
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class AmpacheAuthentication {
var session_expire: String = ""
var auth: String = ""
var songs: Int = 0
var albums: Int = 0
var artists: Int = 0
var playlists: Int = 0
var error: AmpacheError = AmpacheError()
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class AmpachePing {
var session_expire: String = ""
var server: String = ""
var version: String = ""
var compatible: String = ""
var songs: Int = 0
var albums: Int = 0
var artists: Int = 0
var playlists: Int = 0
var error: AmpacheError = AmpacheError()
}
class AmpacheError {
var code: Int = 0
var error_text: String = "success"
} | gpl-3.0 | b998500f56a0b9a2e7a5022456cfc4af | 25.789474 | 60 | 0.699115 | 4.003937 | false | false | false | false |
Genius/groupie | example/src/main/java/com/xwray/groupie/example/item/HeartCardItem.kt | 2 | 2239 | package com.xwray.groupie.example.item
import android.graphics.drawable.Animatable
import androidx.annotation.ColorInt
import com.xwray.groupie.example.INSET
import com.xwray.groupie.example.INSET_TYPE_KEY
import com.xwray.groupie.example.R
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder
import kotlinx.android.synthetic.main.item_heart_card.*
const val FAVORITE = "FAVORITE"
class HeartCardItem(
@ColorInt private val colorInt: Int,
id: Long,
private val onFavoriteListener: (item: HeartCardItem, favorite: Boolean) -> Unit
) : Item(id) {
private var checked = false
private var inProgress = false
private var holder: com.xwray.groupie.GroupieViewHolder? = null
init {
extras[INSET_TYPE_KEY] = INSET
}
override fun getLayout() = R.layout.item_heart_card
private fun bindHeart(holder: GroupieViewHolder) {
if (inProgress) {
animateProgress(holder)
} else {
(holder.favorite.drawable as? Animatable)?.stop()
holder.favorite.setImageResource(R.drawable.favorite_state_list)
}
holder.favorite.isChecked = checked
}
private fun animateProgress(holder: GroupieViewHolder) {
holder.favorite.apply {
setImageResource(R.drawable.avd_favorite_progress)
(drawable as Animatable).start()
}
}
fun setFavorite(favorite: Boolean) {
inProgress = false
checked = favorite
}
override fun isClickable() = false
override fun bind(holder: GroupieViewHolder, position: Int) {
holder.root.setBackgroundColor(colorInt)
bindHeart(holder)
holder.text.text = (id + 1).toString()
holder.favorite.setOnClickListener {
if (!inProgress) {
inProgress = true
animateProgress(holder)
onFavoriteListener(this@HeartCardItem, !checked)
}
}
}
override fun bind(holder: GroupieViewHolder, position: Int, payloads: List<Any>) {
if (payloads.contains(FAVORITE)) {
bindHeart(holder)
} else {
bind(holder, position)
}
}
}
| mit | 65b764b9fcf7fbe4ea5207a7a078657a | 28.853333 | 86 | 0.657436 | 4.478 | false | false | false | false |
nickbutcher/plaid | dribbble/src/main/java/io/plaidapp/dribbble/ui/shot/ShotUiModel.kt | 1 | 1995 | /*
* Copyright 2019 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.dribbble.ui.shot
import io.plaidapp.core.dribbble.data.api.model.Images
import io.plaidapp.core.dribbble.data.api.model.Shot
import java.util.Date
/**
* Shot model for the UI
*/
data class ShotUiModel(
val id: Long,
val title: String,
val url: String,
val formattedDescription: CharSequence,
val imageUrl: String,
val imageSize: Images.ImageSize,
val likesCount: Int,
val formattedLikesCount: String,
val viewsCount: Int,
val formattedViewsCount: String,
val createdAt: Date?,
val userName: String,
val userAvatarUrl: String
) {
val shouldHideDescription = formattedDescription.isEmpty()
}
/**
* A sync conversion which skips long running work in order to publish a result asap. For a more
* complete conversion see [io.plaidapp.dribbble.domain.CreateShotUiModelUseCase].
*/
fun Shot.toShotUiModel(): ShotUiModel {
return ShotUiModel(
id = id,
title = title,
url = htmlUrl,
formattedDescription = "",
imageUrl = images.best(),
imageSize = images.bestSize(),
likesCount = likesCount,
formattedLikesCount = likesCount.toString(),
viewsCount = viewsCount,
formattedViewsCount = viewsCount.toString(),
createdAt = createdAt,
userName = user.name.toLowerCase(),
userAvatarUrl = user.highQualityAvatarUrl
)
}
| apache-2.0 | 1cf9d00bf3b905bfe6ba27eae5d87a3e | 30.171875 | 96 | 0.699248 | 4.226695 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/formatter/impl/alignment.kt | 1 | 3288 | package org.rust.ide.formatter.impl
import org.rust.ide.formatter.RsAlignmentStrategy
import org.rust.ide.formatter.blocks.RsFmtBlock
import org.rust.lang.core.psi.RsElementTypes.*
fun RsFmtBlock.getAlignmentStrategy(): RsAlignmentStrategy = when (node.elementType) {
TUPLE_EXPR, VALUE_ARGUMENT_LIST, FORMAT_MACRO_ARGS, TRY_MACRO_ARGS, VEC_MACRO_ARGS, USE_GLOB_LIST ->
RsAlignmentStrategy.wrap()
.alignIf { child, parent, _ ->
// Do not align if we have only one argument as this may lead to
// some quirks when that argument is tuple expr.
// Alignment do not allow "negative indentation" i.e.:
// func((
// happy tuple param
// ))
// would be formatted to:
// func((
// happy tuple param
// ))
// because due to applied alignment, closing paren has to be
// at least in the same column as the opening one.
var result = true
if (parent != null) {
val lBrace = parent.firstChildNode
val rBrace = parent.lastChildNode
if (lBrace.isBlockDelim(parent) && rBrace.isBlockDelim(parent)) {
result = child.treeNonWSPrev() != lBrace || child.treeNonWSNext() != rBrace
}
}
result
}
.alignUnlessBlockDelim()
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS)
TUPLE_TYPE, TUPLE_FIELDS ->
RsAlignmentStrategy.wrap()
.alignUnlessBlockDelim()
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS)
VALUE_PARAMETER_LIST ->
RsAlignmentStrategy.shared()
.alignUnlessBlockDelim()
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS)
in FN_DECLS ->
RsAlignmentStrategy.shared()
.alignIf { c, _, _ ->
c.elementType == RET_TYPE && ctx.rustSettings.ALIGN_RET_TYPE ||
c.elementType == WHERE_CLAUSE && ctx.rustSettings.ALIGN_WHERE_CLAUSE
}
PAT_ENUM ->
RsAlignmentStrategy.wrap()
.alignIf { c, p, x -> x.metLBrace && !c.isBlockDelim(p) }
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS)
METHOD_CALL_EXPR ->
RsAlignmentStrategy.shared()
.alignIf(DOT) // DOT is synthetic's block representative
.alignIf(ctx.commonSettings.ALIGN_MULTILINE_CHAINED_METHODS)
WHERE_CLAUSE ->
RsAlignmentStrategy.wrap()
.alignIf(WHERE_PRED)
.alignIf(ctx.rustSettings.ALIGN_WHERE_BOUNDS)
TYPE_PARAMETER_LIST ->
RsAlignmentStrategy.wrap()
.alignIf(TYPE_PARAMETER, LIFETIME_PARAMETER)
.alignIf(ctx.rustSettings.ALIGN_TYPE_PARAMS)
FOR_LIFETIMES ->
RsAlignmentStrategy.wrap()
.alignIf(LIFETIME_PARAMETER)
.alignIf(ctx.rustSettings.ALIGN_TYPE_PARAMS)
else -> RsAlignmentStrategy.NullStrategy
}
fun RsAlignmentStrategy.alignUnlessBlockDelim(): RsAlignmentStrategy = alignIf { c, p, _ -> !c.isBlockDelim(p) }
| mit | 31181e290226dae218cf0266a521fb61 | 39.592593 | 112 | 0.581509 | 4.772134 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/data/server/model/AmpacheTag.kt | 1 | 593 | package be.florien.anyflow.data.server.model
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
/**
* Server-side data structures that relates to tags
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class AmpacheTag {
var id: Long = 0
var name: String = ""
var albums: Int = 0
var artists: Int = 0
var songs: Int = 0
var video: Int = 0
var playlist: Int = 0
var stream: Int = 0
}
class AmpacheTagName {
var id: Long = 0
var name: String = ""
} | gpl-3.0 | d8ba31bcdf61c21f3f69a79506ee957e | 21.846154 | 60 | 0.694772 | 3.753165 | false | false | false | false |
ArdentDiscord/ArdentKotlin | src/main/kotlin/utils/functionality/EventWaiter.kt | 1 | 11035 | package utils.functionality
import main.factory
import main.waiter
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.MessageChannel
import net.dv8tion.jda.api.entities.MessageReaction
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.Event
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent
import net.dv8tion.jda.api.hooks.SubscribeEvent
import translation.tr
import utils.discord.embed
import utils.discord.getTextChannelById
import utils.discord.send
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class EventWaiter : EventListener {
val executor = Executors.newScheduledThreadPool(10)
private val gameEvents = CopyOnWriteArrayList<Triple<String, Long, Pair<((Message) -> Unit) /* ID of channel, Long MS of expiration */, (() -> Unit)?>>>()
private val reactionEvents = CopyOnWriteArrayList<Quadruple<String, String, /* Message ID */ Long, Pair<((User, MessageReaction) -> Unit) /* ID of channel, Long MS of expiration */, (() -> Unit)?>>>()
private val messageEvents = CopyOnWriteArrayList<Pair<Settings, (Message) -> Unit>>()
private val reactionAddEvents = CopyOnWriteArrayList<Pair<Settings, (MessageReaction) -> Unit>>()
@SubscribeEvent
fun onEvent(e: Event) {
factory.executor.execute {
when (e) {
is GuildMessageReceivedEvent -> {
if (e.author.isBot) return@execute
messageEvents.forEach { mE ->
var cont = true
val settings = mE.first
if (settings.channel != null && settings.channel != e.channel.id) cont = false
if (settings.id != null && settings.id != e.author.id) cont = false
if (settings.guild != null && settings.guild != e.guild.id) cont = false
if (cont) {
messageEvents.remove(mE)
mE.second.invoke(e.message)
}
}
gameEvents.forEach { game ->
if (e.channel.id == game.first) {
if (System.currentTimeMillis() < game.second) {
factory.executor.execute { game.third.first(e.message) }
} else gameEvents.remove(game)
}
}
}
is MessageReactionAddEvent -> {
reactionAddEvents.forEach { rAE ->
val settings = rAE.first
var cont = true
if (settings.channel != null && settings.channel != e.channel.id) cont = false
else if (settings.id != null && settings.id != e.user!!.id) cont = false
else if (settings.guild != null && settings.guild != e.guild.id) cont = false
else if (settings.message != null && settings.message != e.messageId) cont = false
if (cont) {
rAE.second.invoke(e.reaction)
reactionAddEvents.remove(rAE)
}
}
reactionEvents.forEach { game ->
if (e.channel.id == game.first && e.messageId == game.second) {
if (System.currentTimeMillis() < game.third) {
factory.executor.execute { game.fourth.first(e.user!!, e.reaction) }
} else reactionEvents.remove(game)
}
}
}
}
}
}
fun waitForReaction(settings: Settings, consumer: (MessageReaction) -> Unit, expirationConsumer: (() -> Unit)? = null, time: Int = 60, unit: TimeUnit = TimeUnit.SECONDS, silentExpiration: Boolean = false): Pair<Settings, (MessageReaction) -> Unit> {
val pair = Pair(settings, consumer)
reactionAddEvents.add(pair)
executor.schedule({
if (reactionAddEvents.contains(pair)) {
reactionAddEvents.remove(pair)
if (expirationConsumer != null) expirationConsumer.invoke()
else {
if (!silentExpiration) {
val channel: TextChannel? = getTextChannelById(settings.channel)
channel?.send("You took too long to add a reaction!".tr(channel.guild))
}
}
}
}, time.toLong(), unit)
return pair
}
fun gameReactionWait(message: Message, consumer: (User, MessageReaction) -> Unit, expirationConsumer: (() -> Unit)? = null, time: Int = 10, unit: TimeUnit = TimeUnit.SECONDS) {
val game = Quadruple(message.channel.id, message.id, System.currentTimeMillis() + unit.toMillis(time.toLong()), Pair(consumer, expirationConsumer))
reactionEvents.add(game)
executor.schedule({
if (reactionEvents.contains(game)) game.fourth.second?.invoke()
}, time.toLong(), unit)
}
fun gameChannelWait(channel: String, consumer: (Message) -> Unit, expirationConsumer: (() -> Unit)? = null, time: Int = 10, unit: TimeUnit = TimeUnit.SECONDS) {
val game = Triple(channel, System.currentTimeMillis() + unit.toMillis(time.toLong()), Pair(consumer, expirationConsumer))
gameEvents.add(game)
executor.schedule({
if (gameEvents.contains(game)) game.third.second?.invoke()
}, time.toLong(), unit)
}
fun waitForMessage(settings: Settings, consumer: (Message) -> Unit, expiration: (() -> Unit)? = null, time: Int = 20, unit: TimeUnit = TimeUnit.SECONDS, silentExpiration: Boolean = false) {
val pair = Pair(settings, consumer)
messageEvents.add(pair)
executor.schedule({
if (messageEvents.contains(pair)) {
messageEvents.remove(pair)
val channel: TextChannel? = getTextChannelById(settings.channel)
if (expiration == null && !silentExpiration) channel?.send("You took too long to respond!".tr(channel.guild))
expiration?.invoke()
}
}, time.toLong(), unit)
}
fun cancel(settings: Settings) {
reactionAddEvents.removeIf { it.first == settings }
messageEvents.removeIf { it.first == settings }
}
}
data class Settings(val id: String? = null, val channel: String? = null, val guild: String? = null, val message: String? = null)
/**
* Message in the consumer is the list selection message
*/
fun MessageChannel.selectFromList(member: Member, title: String, options: MutableList<String>, consumer: (Int, Message) -> Unit, translatedTitle: Boolean = false, footerText: String? = null, failure: (() -> Unit)? = null) {
val embed = member.embed(if (!translatedTitle) title.tr(member.guild) else title, this)
val builder = StringBuilder()
for ((index, value) in options.iterator().withIndex()) {
builder.append("${Emoji.SMALL_BLUE_DIAMOND} **${index + 1}**: $value\n")
}
if (footerText != null) builder.append("\n" + footerText.tr(member.guild) + "\n")
builder.append("\n" + "__Please select **OR** type the number corresponding with the choice that you'd like to select or select **X** to cancel__".tr(member.guild) + "\n")
try {
sendMessage(embed.setDescription(builder).build()).queue { message ->
for (x in 1..options.size) {
message.addReaction(when (x) {
1 -> Emoji.KEYCAP_DIGIT_ONE
2 -> Emoji.KEYCAP_DIGIT_TWO
3 -> Emoji.KEYCAP_DIGIT_THREE
4 -> Emoji.KEYCAP_DIGIT_FOUR
5 -> Emoji.KEYCAP_DIGIT_FIVE
6 -> Emoji.KEYCAP_DIGIT_SIX
7 -> Emoji.KEYCAP_DIGIT_SEVEN
8 -> Emoji.KEYCAP_DIGIT_EIGHT
9 -> Emoji.KEYCAP_DIGIT_NINE
10 -> Emoji.KEYCAP_TEN
else -> Emoji.HEAVY_CHECK_MARK
}.symbol).queue()
}
message.addReaction(Emoji.HEAVY_MULTIPLICATION_X.symbol).queue()
var invoked = false
waiter.waitForMessage(Settings(member.user.id, id, member.guild.id, message.id), { response ->
invoked = true
val responseInt = response.contentRaw.toIntOrNull()?.minus(1)
if (responseInt == null || responseInt !in 0..(options.size - 1) && !invoked) {
failure?.invoke() ?: send("You specified an invalid response!".tr(getTextChannelById(id)!!.guild))
} else {
if (options.contains(response.contentRaw)) {
consumer.invoke(options.getWithIndex(response.contentRaw)!!.first, message)
} else {
consumer.invoke(responseInt, message)
waiter.cancel(Settings(member.user.id, id, member.guild.id, message.id))
}
}
}, silentExpiration = true)
waiter.waitForReaction(Settings(member.user.id, id, member.guild.id, message.id), { messageReaction ->
val chosen = when (messageReaction.reactionEmote.name) {
Emoji.KEYCAP_DIGIT_ONE.symbol -> 1
Emoji.KEYCAP_DIGIT_TWO.symbol -> 2
Emoji.KEYCAP_DIGIT_THREE.symbol -> 3
Emoji.KEYCAP_DIGIT_FOUR.symbol -> 4
Emoji.KEYCAP_DIGIT_FIVE.symbol -> 5
Emoji.KEYCAP_DIGIT_SIX.symbol -> 6
Emoji.KEYCAP_DIGIT_SEVEN.symbol -> 7
Emoji.KEYCAP_DIGIT_EIGHT.symbol -> 8
Emoji.KEYCAP_DIGIT_NINE.symbol -> 9
Emoji.KEYCAP_TEN.symbol -> 10
Emoji.HEAVY_MULTIPLICATION_X.symbol -> 69
else -> 69999999
} - 1
when {
chosen in 0..(options.size - 1) -> consumer.invoke(chosen, message)
chosen != 68 -> send("You specified an invalid reaction or response, cancelling selection".tr(getTextChannelById(id)!!.guild))
else -> failure?.invoke()
}
waiter.cancel(Settings(member.user.id, id, member.guild.id, message.id))
invoked = true
}, {
if (!invoked) send("You didn't specify a reaction or response, cancelling selection".tr(getTextChannelById(id)!!.guild))
message.delete().queue()
}, time = 25, silentExpiration = true)
}
} catch (e: Exception) {
}
} | apache-2.0 | 66b04fadabf441d13a4d35e686ac7c4d | 51.303318 | 253 | 0.563208 | 4.573145 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/ImportDialog.kt | 1 | 5416 | /****************************************************************************************
* Copyright (c) 2015 Timothy Rae <[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.anki.dialogs
import android.os.Bundle
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.R
import timber.log.Timber
import java.net.URLDecoder
class ImportDialog : AsyncDialogFragment() {
interface ImportDialogListener {
fun importAdd(importPath: String?)
fun importReplace(importPath: String?)
fun dismissAllDialogFragments()
}
override fun onCreateDialog(savedInstanceState: Bundle?): MaterialDialog {
super.onCreate(savedInstanceState)
val type = requireArguments().getInt("dialogType")
val res = resources
val builder = MaterialDialog.Builder(requireActivity())
builder.cancelable(true)
val dialogMessage = requireArguments().getString("dialogMessage")!!
return when (type) {
DIALOG_IMPORT_ADD_CONFIRM -> {
val displayFileName = convertToDisplayName(dialogMessage)
builder.title(res.getString(R.string.import_title))
.content(res.getString(R.string.import_message_add_confirm, filenameFromPath(displayFileName)))
.positiveText(R.string.import_message_add)
.negativeText(R.string.dialog_cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as ImportDialogListener?)!!.importAdd(dialogMessage)
dismissAllDialogFragments()
}
.show()
}
DIALOG_IMPORT_REPLACE_CONFIRM -> {
val displayFileName = convertToDisplayName(dialogMessage)
builder.title(res.getString(R.string.import_title))
.content(res.getString(R.string.import_message_replace_confirm, displayFileName))
.positiveText(R.string.dialog_positive_replace)
.negativeText(R.string.dialog_cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as ImportDialogListener?)!!.importReplace(dialogMessage)
dismissAllDialogFragments()
}
.show()
}
else -> null!!
}
}
private fun convertToDisplayName(name: String): String {
// ImportUtils URLEncodes names, which isn't great for display.
// NICE_TO_HAVE: Pass in the DisplayFileName closer to the source of the bad data, rather than fixing it here.
return try {
URLDecoder.decode(name, "UTF-8")
} catch (e: Exception) {
Timber.w(e, "Failed to convert filename to displayable string")
name
}
}
override fun getNotificationMessage(): String {
return res().getString(R.string.import_interrupted)
}
override fun getNotificationTitle(): String {
return res().getString(R.string.import_title)
}
fun dismissAllDialogFragments() {
(activity as ImportDialogListener?)!!.dismissAllDialogFragments()
}
companion object {
const val DIALOG_IMPORT_ADD_CONFIRM = 2
const val DIALOG_IMPORT_REPLACE_CONFIRM = 3
/**
* A set of dialogs which deal with importing a file
*
* @param dialogType An integer which specifies which of the sub-dialogs to show
* @param dialogMessage An optional string which can be used to show a custom message
* or specify import path
*/
@JvmStatic
fun newInstance(dialogType: Int, dialogMessage: String): ImportDialog {
val f = ImportDialog()
val args = Bundle()
args.putInt("dialogType", dialogType)
args.putString("dialogMessage", dialogMessage)
f.arguments = args
return f
}
private fun filenameFromPath(path: String): String {
return path.split("/").toTypedArray()[path.split("/").toTypedArray().size - 1]
}
}
}
| gpl-3.0 | cbda87154674b3ca18180672fe613a65 | 45.290598 | 118 | 0.55613 | 5.54918 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/person/Persons.kt | 1 | 4945 | package ffc.app.person
import ffc.api.ApiErrorException
import ffc.api.FfcCentral
import ffc.app.mockRepository
import ffc.app.util.RepoCallback
import ffc.app.util.TaskCallback
import ffc.entity.Lang
import ffc.entity.Organization
import ffc.entity.Person
import ffc.entity.ThaiCitizenId
import ffc.entity.healthcare.Icd10
import ffc.entity.util.generateTempId
import org.joda.time.LocalDate
import retrofit2.dsl.enqueue
import retrofit2.dsl.then
interface Persons {
fun person(personId: String, dsl: RepoCallback<Person>.() -> Unit)
fun add(person: Person, callback: (Person?, Throwable?) -> Unit)
}
interface PersonManipulator {
fun update(callbackDsl: TaskCallback<Person>.() -> Unit)
}
private class InMemoryPersons : Persons {
override fun person(personId: String, dsl: RepoCallback<Person>.() -> Unit) {
val callback = RepoCallback<Person>().apply(dsl)
callback.always?.invoke()
val person = repository.firstOrNull { person -> person.id == personId }
if (person != null) {
callback.onFound!!.invoke(person)
} else {
callback.onNotFound!!.invoke()
}
}
override fun add(person: Person, callback: (Person?, Throwable?) -> Unit) {
repository.add(person)
callback(person, null)
}
companion object {
val repository: MutableList<Person> = mutableListOf(mockPerson)
}
}
private class ApiPersons(val orgId: String) : Persons {
val api = FfcCentral().service<PersonsApi>()
override fun add(person: Person, callback: (Person?, Throwable?) -> Unit) {
api.post(orgId, person).then {
callback(it, null)
}.catch { res, t ->
res?.let { callback(null, ApiErrorException(it)) }
t?.let { callback(null, it) }
}
}
override fun person(personId: String, dsl: RepoCallback<Person>.() -> Unit) {
val callback = RepoCallback<Person>().apply(dsl)
api.get(orgId, personId).enqueue {
always { callback.always?.invoke() }
onSuccess {
callback.onFound!!.invoke(body()!!)
}
onError {
if (code() == 404)
callback.onNotFound!!.invoke()
else
callback.onFail!!.invoke(ApiErrorException(this))
}
onFailure { callback.onFail!!.invoke(it) }
}
}
}
class DummyPersonManipulator(val orgId: String, val person: Person) : PersonManipulator {
override fun update(callbackDsl: TaskCallback<Person>.() -> Unit) {
val callback = TaskCallback<Person>().apply(callbackDsl)
callback.result(person)
}
}
class ApiPersonManipulator(val orgId: String, val person: Person) : PersonManipulator {
val api = FfcCentral().service<PersonsApi>()
override fun update(callbackDsl: TaskCallback<Person>.() -> Unit) {
val callback = TaskCallback<Person>().apply(callbackDsl)
api.put(orgId, person).enqueue {
onSuccess {
callback.result(body()!!)
}
onError {
callback.expception!!.invoke(ApiErrorException(this))
}
onFailure {
callback.expception!!.invoke(it)
}
}
}
}
val mockPerson = Person("5b9770e029191b0004c91a56").apply {
birthDate = LocalDate.parse("1988-02-15")
prename = "นาย"
firstname = "พิรุณ"
lastname = "พานิชผล"
sex = Person.Sex.MALE
identities.add(ThaiCitizenId("1145841548789"))
death = Person.Death(LocalDate.now(),
Icd10("ไข้หวัดใหญ่ร่วมกับปอดบวม ตรวจพบไวรัสไข้หวัดใหญ่ชนิดอื่น", "J10.0").apply {
translation[Lang.en] = "Influenza with pneumonia, other influenza virus identified"
},
Icd10("เบาหวานชนิดพึ่งอินซูลิน", "E10").apply {
translation[Lang.en] = "Insulin-dependent diabetes mellitus"
}
)
relationships.add(Person.Relationship(Person.Relate.Mother, generateTempId(), "ปานแก้ว พานิชผล"))
relationships.add(Person.Relationship(Person.Relate.Father, generateTempId(), "พิภพ พานิชผล"))
relationships.add(Person.Relationship(Person.Relate.Married, generateTempId(), "พรทิพา โชคสูงเนิน"))
}
internal fun Person.manipulator(org: Organization): PersonManipulator {
return if (mockRepository)
DummyPersonManipulator(org.id, this)
else
ApiPersonManipulator(org.id, this)
}
fun Person.pushTo(org: Organization, callbackDsl: TaskCallback<Person>.() -> Unit) {
manipulator(org).update(callbackDsl)
}
fun persons(orgId: String): Persons = if (mockRepository) InMemoryPersons() else ApiPersons(orgId)
| apache-2.0 | aa4826e1caa9997f2e69286d3e350611 | 32.184397 | 104 | 0.637957 | 3.531321 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily | app/src/main/java/chat/rocket/android/helper/ChatRoomRoleHelper.kt | 2 | 1874 | package chat.rocket.android.helper
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.server.infrastructure.ConnectionManagerFactory
import chat.rocket.common.model.RoomType
import chat.rocket.common.model.roomTypeOf
import chat.rocket.core.internal.rest.chatRoomRoles
import chat.rocket.core.model.ChatRoomRole
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Named
class ChatRoomRoleHelper @Inject constructor(
private val dbManager: DatabaseManager,
private val strategy: CancelStrategy,
@Named("currentServer") private val currentServer: String?,
factory: ConnectionManagerFactory
) {
private val manager = currentServer?.let { factory.create(it) }
private val client = manager?.client
suspend fun getChatRoles(chatRoomId: String): List<ChatRoomRole> {
val (chatRoomType, chatRoomName) = getChatRoomDetails(chatRoomId)
return try {
if (roomTypeOf(chatRoomType) !is RoomType.DirectMessage) {
withContext(Dispatchers.IO + strategy.jobs) {
client?.chatRoomRoles(
roomType = roomTypeOf(chatRoomType),
roomName = chatRoomName
) ?: emptyList()
}
} else {
emptyList()
}
} catch (ex: Exception) {
Timber.e(ex)
emptyList()
}
}
private suspend fun getChatRoomDetails(chatRoomId: String): Pair<String, String> {
return withContext(Dispatchers.IO + strategy.jobs) {
return@withContext dbManager.getRoom(chatRoomId)?.chatRoom.let {
Pair(it?.type ?: "", it?.name ?: "")
}
}
}
} | mit | 3f63961bc06a32e9b5d50bdae2cdc00c | 35.057692 | 86 | 0.66222 | 4.756345 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsImageTagDialog.kt | 1 | 8556 | package org.wikipedia.suggestededits
import android.app.Dialog
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.InsetDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextWatcher
import android.view.*
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.FragmentUtil
import org.wikipedia.databinding.DialogImageTagSelectBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.log.L
class SuggestedEditsImageTagDialog : DialogFragment() {
interface Callback {
fun onSearchSelect(item: ImageTag)
fun onSearchDismiss(searchTerm: String)
}
private lateinit var textWatcher: TextWatcher
private var _binding: DialogImageTagSelectBinding? = null
private val binding get() = _binding!!
private var currentSearchTerm: String = ""
private val adapter = ResultListAdapter(emptyList())
private val disposables = CompositeDisposable()
private val searchRunnable = Runnable {
if (isAdded) {
requestResults(currentSearchTerm)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = DialogImageTagSelectBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.imageTagsRecycler.layoutManager = LinearLayoutManager(activity)
binding.imageTagsRecycler.adapter = adapter
textWatcher = binding.imageTagsSearchText.doOnTextChanged { text, _, _, _ ->
currentSearchTerm = text?.toString() ?: ""
binding.imageTagsSearchText.removeCallbacks(searchRunnable)
binding.imageTagsSearchText.postDelayed(searchRunnable, 500)
}
applyResults(emptyList())
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
val model = ShapeAppearanceModel.builder().setAllCornerSizes(DimenUtil.dpToPx(6f)).build()
val materialShapeDrawable = MaterialShapeDrawable(model)
materialShapeDrawable.fillColor = ResourceUtil.getThemedColorStateList(requireActivity(), R.attr.searchItemBackground)
materialShapeDrawable.elevation = dialog.window!!.decorView.elevation
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
val inset = DimenUtil.roundedDpToPx(16f)
val insetDrawable = InsetDrawable(materialShapeDrawable, inset, inset, inset, inset)
dialog.window!!.setBackgroundDrawable(insetDrawable)
} else {
dialog.window!!.setBackgroundDrawable(materialShapeDrawable)
}
val params = dialog.window!!.attributes
params.gravity = Gravity.TOP
dialog.window!!.attributes = params
return dialog
}
override fun onStart() {
super.onStart()
try {
if (requireArguments().getBoolean("useClipboardText")) {
val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
if (clipboard.hasPrimaryClip() && clipboard.primaryClip != null) {
val primaryClip = clipboard.primaryClip!!
val clipText = primaryClip.getItemAt(primaryClip.itemCount - 1).coerceToText(requireContext()).toString()
if (clipText.isNotEmpty()) {
binding.imageTagsSearchText.setText(clipText)
binding.imageTagsSearchText.selectAll()
}
}
} else if (requireArguments().getString("lastText")!!.isNotEmpty()) {
binding.imageTagsSearchText.setText(requireArguments().getString("lastText")!!)
binding.imageTagsSearchText.selectAll()
}
} catch (ignore: Exception) {
}
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
override fun onDestroyView() {
super.onDestroyView()
binding.imageTagsSearchText.removeTextChangedListener(textWatcher)
binding.imageTagsSearchText.removeCallbacks(searchRunnable)
disposables.clear()
_binding = null
}
private fun requestResults(searchTerm: String) {
if (searchTerm.isEmpty()) {
applyResults(emptyList())
return
}
disposables.add(ServiceFactory.get(Constants.wikidataWikiSite).searchEntities(searchTerm, WikipediaApp.instance.appOrSystemLanguageCode, WikipediaApp.instance.appOrSystemLanguageCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ search ->
val labelList = search.results.map { ImageTag(it.id, it.label, it.description) }
applyResults(labelList)
}) { L.d(it) })
}
private fun applyResults(results: List<ImageTag>) {
adapter.setResults(results)
adapter.notifyDataSetChanged()
if (currentSearchTerm.isEmpty()) {
binding.noResultsText.visibility = View.GONE
binding.imageTagsRecycler.visibility = View.GONE
binding.imageTagsDivider.visibility = View.INVISIBLE
} else {
binding.imageTagsDivider.visibility = View.VISIBLE
if (results.isEmpty()) {
binding.noResultsText.visibility = View.VISIBLE
binding.imageTagsRecycler.visibility = View.GONE
} else {
binding.noResultsText.visibility = View.GONE
binding.imageTagsRecycler.visibility = View.VISIBLE
}
}
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
callback()?.onSearchDismiss(currentSearchTerm)
}
private inner class ResultItemHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
fun bindItem(item: ImageTag) {
itemView.findViewById<TextView>(R.id.labelName).text = item.label
itemView.findViewById<TextView>(R.id.labelDescription).text = item.description
itemView.tag = item
itemView.setOnClickListener(this)
}
override fun onClick(v: View) {
val item = v.tag as ImageTag
callback()?.onSearchSelect(item)
dismiss()
}
}
private inner class ResultListAdapter(private var results: List<ImageTag>) : RecyclerView.Adapter<ResultItemHolder>() {
fun setResults(results: List<ImageTag>) {
this.results = results
}
override fun getItemCount(): Int {
return results.size
}
override fun onCreateViewHolder(parent: ViewGroup, pos: Int): ResultItemHolder {
val view = layoutInflater.inflate(R.layout.item_wikidata_label, parent, false)
val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
view.layoutParams = params
return ResultItemHolder(view)
}
override fun onBindViewHolder(holder: ResultItemHolder, pos: Int) {
holder.bindItem(results[pos])
}
}
private fun callback(): Callback? {
return FragmentUtil.getCallback(this, Callback::class.java)
}
companion object {
fun newInstance(useClipboardText: Boolean, lastText: String): SuggestedEditsImageTagDialog {
val dialog = SuggestedEditsImageTagDialog()
dialog.arguments = bundleOf("useClipboardText" to useClipboardText, "lastText" to lastText)
return dialog
}
}
}
| apache-2.0 | 772330d21e1c12c97280dd386a67455e | 40.736585 | 191 | 0.682211 | 5.148014 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/wallet/WalletUiState.kt | 1 | 4905 | package com.stripe.android.link.ui.wallet
import com.stripe.android.link.ui.ErrorMessage
import com.stripe.android.link.ui.PrimaryButtonState
import com.stripe.android.link.ui.getErrorMessage
import com.stripe.android.model.ConsumerPaymentDetails
import com.stripe.android.model.ConsumerPaymentDetails.BankAccount
import com.stripe.android.model.ConsumerPaymentDetails.Card
import com.stripe.android.payments.paymentlauncher.PaymentResult
import com.stripe.android.ui.core.forms.FormFieldEntry
internal data class WalletUiState(
val supportedTypes: Set<String>,
val paymentDetailsList: List<ConsumerPaymentDetails.PaymentDetails> = emptyList(),
val selectedItem: ConsumerPaymentDetails.PaymentDetails? = null,
val isExpanded: Boolean = false,
val isProcessing: Boolean = false,
val hasCompleted: Boolean = false,
val errorMessage: ErrorMessage? = null,
val expiryDateInput: FormFieldEntry = FormFieldEntry(value = null),
val cvcInput: FormFieldEntry = FormFieldEntry(value = null),
val alertMessage: ErrorMessage? = null,
val paymentMethodIdBeingUpdated: String? = null
) {
val selectedCard: Card?
get() = selectedItem as? Card
val primaryButtonState: PrimaryButtonState
get() {
val card = selectedItem as? Card
val isExpired = card?.isExpired ?: false
val requiresCvcRecollection = card?.cvcCheck?.requiresRecollection ?: false
val isMissingExpiryDateInput = !(expiryDateInput.isComplete && cvcInput.isComplete)
val isMissingCvcInput = !cvcInput.isComplete
val isSelectedItemValid = selectedItem?.isValid ?: false
val disableButton = !isSelectedItemValid ||
(isExpired && isMissingExpiryDateInput) ||
(requiresCvcRecollection && isMissingCvcInput)
return if (hasCompleted) {
PrimaryButtonState.Completed
} else if (isProcessing) {
PrimaryButtonState.Processing
} else if (disableButton) {
PrimaryButtonState.Disabled
} else {
PrimaryButtonState.Enabled
}
}
fun updateWithResponse(
response: ConsumerPaymentDetails,
initialSelectedItemId: String?
): WalletUiState {
val selectedItem = (initialSelectedItemId ?: selectedItem?.id)?.let { itemId ->
response.paymentDetails.firstOrNull { it.id == itemId }
} ?: getDefaultItemSelection(response.paymentDetails)
val isSelectedItemValid = selectedItem?.isValid ?: false
return copy(
paymentDetailsList = response.paymentDetails,
selectedItem = selectedItem,
isExpanded = if (isSelectedItemValid) isExpanded else true,
isProcessing = false
)
}
fun updateWithSetDefaultResult(
updatedPaymentMethod: ConsumerPaymentDetails.PaymentDetails
): WalletUiState {
val paymentMethods = paymentDetailsList.map { paymentMethod ->
if (paymentMethod.id == updatedPaymentMethod.id) {
updatedPaymentMethod
} else {
when (paymentMethod) {
is BankAccount -> paymentMethod.copy(isDefault = false)
is Card -> paymentMethod.copy(isDefault = false)
}
}
}
val selectedItem = paymentMethods.firstOrNull { it.id == selectedItem?.id }
return copy(
paymentDetailsList = paymentMethods,
selectedItem = selectedItem,
paymentMethodIdBeingUpdated = null
)
}
fun updateWithError(errorMessage: ErrorMessage): WalletUiState {
return copy(
errorMessage = errorMessage,
isProcessing = false
)
}
fun updateWithPaymentResult(paymentResult: PaymentResult): WalletUiState {
return copy(
hasCompleted = paymentResult is PaymentResult.Completed,
errorMessage = (paymentResult as? PaymentResult.Failed)?.throwable?.getErrorMessage(),
isProcessing = false
)
}
fun setProcessing(): WalletUiState {
return copy(
isProcessing = true,
errorMessage = null
)
}
/**
* The item that should be selected by default from the [paymentDetailsList].
*
* @return the default item, if supported. Otherwise the first supported item on the list.
*/
private fun getDefaultItemSelection(
paymentDetailsList: List<ConsumerPaymentDetails.PaymentDetails>
) = paymentDetailsList.filter { supportedTypes.contains(it.type) }.let { filteredItems ->
filteredItems.firstOrNull { it.isDefault } ?: filteredItems.firstOrNull()
}
private val ConsumerPaymentDetails.PaymentDetails.isValid: Boolean
get() = supportedTypes.contains(type)
}
| mit | 89065620f17a74021f14426e918d0669 | 36.730769 | 98 | 0.66055 | 5.431894 | false | false | false | false |
AromaTech/banana-data-operations | src/test/java/tech/aroma/data/sql/serializers/EventSerializerTest.kt | 3 | 3550 | package tech.aroma.data.sql.serializers
/*
* Copyright 2017 RedRoma, 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.
*/
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.apache.thrift.TException
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.springframework.jdbc.core.JdbcOperations
import tech.aroma.data.sql.serializers.Columns.Activity
import tech.aroma.thrift.User
import tech.aroma.thrift.events.Event
import tech.aroma.thrift.generators.EventGenerators.events
import tech.aroma.thrift.generators.UserGenerators.users
import tech.sirwellington.alchemy.generator.one
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.GenerateString
import tech.sirwellington.alchemy.thrift.ThriftObjects
import java.sql.ResultSet
@RunWith(AlchemyTestRunner::class)
class EventSerializerTest
{
@Mock
private lateinit var database: JdbcOperations
@Mock
private lateinit var row: ResultSet
private lateinit var event: Event
private lateinit var user: User
private val eventId get() = event.eventId
private val userId get() = user.userId
private val serializedEvent get() = ThriftObjects.toJson(event)
@GenerateString
private lateinit var sql: String
private lateinit var instance: EventSerializer
@Before
fun setUp()
{
setupData()
setupMocks()
instance = EventSerializer()
}
@Test
fun testSave()
{
instance.save(event, sql, database)
verifyZeroInteractions(database)
}
@Test
fun testSaveWithBadArgs()
{
assertThrows {
instance.save(event, "", database)
}.isInstanceOf(IllegalArgumentException::class.java)
assertThrows {
val emptyEvent = Event()
instance.save(emptyEvent, sql, database)
}.isInstanceOf(IllegalArgumentException::class.java)
assertThrows {
val invalidEvent = Event(event).setEventId(sql)
instance.save(invalidEvent, sql, database)
}.isInstanceOf(IllegalArgumentException::class.java)
}
@Test
fun testDeserialize()
{
val result = instance.deserialize(row)
assertThat(result, equalTo(event))
}
@Test
fun testDeserializeWhenDeserializeFails()
{
whenever(row.getString(Activity.SERIALIZED_EVENT)).thenReturn(sql)
assertThrows { instance.deserialize(row) }
.isInstanceOf(TException::class.java)
}
private fun setupData()
{
event = one(events())
user = one(users())
}
private fun setupMocks()
{
whenever(row.getString(Activity.SERIALIZED_EVENT)).thenReturn(serializedEvent)
}
} | apache-2.0 | f75b9a3fa3e8c421bf8998bfebdb7a5b | 27.18254 | 86 | 0.716901 | 4.522293 | false | true | false | false |
AndroidX/androidx | camera/integration-tests/timingtestapp/src/main/java/androidx/camera/integration/antelope/AutoFitTextureView.kt | 3 | 2534 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.antelope
import android.content.Context
import android.util.AttributeSet
import android.view.TextureView
import android.view.View
/**
* A [TextureView] that can be adjusted to a specified aspect ratio.
*/
class AutoFitTextureView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : TextureView(context, attrs, defStyle) {
private var ratioWidth = 0
private var ratioHeight = 0
/**
* Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
* calculated from the parameters. Note that the actual sizes of parameters don't matter, that
* is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
*
* @param width Relative horizontal size
* @param height Relative vertical size
*/
fun setAspectRatio(width: Int, height: Int) {
if (width < 0 || height < 0) {
throw IllegalArgumentException("Size cannot be negative.")
}
ratioWidth = width
ratioHeight = height
requestLayout()
}
/**
* When the surface is given a new width/height, ensure that it maintains the correct aspect
* ratio.
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = View.MeasureSpec.getSize(widthMeasureSpec)
val height = View.MeasureSpec.getSize(heightMeasureSpec)
if (ratioWidth == 0 || ratioHeight == 0) {
setMeasuredDimension(width, height)
} else {
if (width < height * ratioWidth / ratioHeight) {
setMeasuredDimension(width, width * ratioHeight / ratioWidth)
} else {
setMeasuredDimension(height * ratioWidth / ratioHeight, height)
}
}
}
} | apache-2.0 | d4feb8759ce40dc94450154c52f79714 | 34.704225 | 100 | 0.67719 | 4.710037 | false | false | false | false |
AndroidX/androidx | room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_customTypeConverter_nullAware.kt | 3 | 4515 | import android.database.Cursor
import androidx.room.EntityInsertionAdapter
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.query
import androidx.sqlite.db.SupportSQLiteStatement
import java.lang.Class
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity>
init {
this.__db = __db
this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) {
public override fun createQuery(): String =
"INSERT OR ABORT INTO `MyEntity` (`pk`,`foo`,`bar`) VALUES (?,?,?)"
public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit {
statement.bindLong(1, entity.pk.toLong())
val _tmp: String? = FooBarConverter.toString(entity.foo)
if (_tmp == null) {
statement.bindNull(2)
} else {
statement.bindString(2, _tmp)
}
val _tmp_1: Foo = FooBarConverter.toFoo(entity.bar)
val _tmp_2: String? = FooBarConverter.toString(_tmp_1)
if (_tmp_2 == null) {
statement.bindNull(3)
} else {
statement.bindString(3, _tmp_2)
}
}
}
}
public override fun addEntity(item: MyEntity): Unit {
__db.assertNotSuspendingTransaction()
__db.beginTransaction()
try {
__insertionAdapterOfMyEntity.insert(item)
__db.setTransactionSuccessful()
} finally {
__db.endTransaction()
}
}
public override fun getEntity(): MyEntity {
val _sql: String = "SELECT * FROM MyEntity"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk")
val _cursorIndexOfFoo: Int = getColumnIndexOrThrow(_cursor, "foo")
val _cursorIndexOfBar: Int = getColumnIndexOrThrow(_cursor, "bar")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpPk: Int
_tmpPk = _cursor.getInt(_cursorIndexOfPk)
val _tmpFoo: Foo
val _tmp: String?
if (_cursor.isNull(_cursorIndexOfFoo)) {
_tmp = null
} else {
_tmp = _cursor.getString(_cursorIndexOfFoo)
}
val _tmp_1: Foo? = FooBarConverter.fromString(_tmp)
if (_tmp_1 == null) {
error("Expected non-null Foo, but it was null.")
} else {
_tmpFoo = _tmp_1
}
val _tmpBar: Bar
val _tmp_2: String?
if (_cursor.isNull(_cursorIndexOfBar)) {
_tmp_2 = null
} else {
_tmp_2 = _cursor.getString(_cursorIndexOfBar)
}
val _tmp_3: Foo? = FooBarConverter.fromString(_tmp_2)
val _tmp_4: Bar?
if (_tmp_3 == null) {
_tmp_4 = null
} else {
_tmp_4 = FooBarConverter.fromFoo(_tmp_3)
}
if (_tmp_4 == null) {
error("Expected non-null Bar, but it was null.")
} else {
_tmpBar = _tmp_4
}
_result = MyEntity(_tmpPk,_tmpFoo,_tmpBar)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | apache-2.0 | 1d079728873e45cd22d0530fc5524a6c | 36.016393 | 97 | 0.534441 | 4.708029 | false | false | false | false |
b005t3r/Kotling | core/src/main/kotlin/com/kotling/display/Container.kt | 1 | 9673 | package com.kotling.display
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.kotling.util.poolable.use
import com.kotling.rendering.Painter
import com.kotling.util.Pool
abstract class Container : Display() {
inner class DisplayList(val l : MutableList<Display>) : MutableList<Display> by l {
override fun add(element:Display):Boolean {
add(size, element)
return true
}
override fun add(index:Int, element:Display) {
if(index < 0 || index > children.size)
throw IllegalArgumentException("invalid index: $index")
requiresRedraw = true
if(element.parent == this@Container) {
var oldIndex:Int = indexOfFirst { element == it }
if (oldIndex == index)
return
if (oldIndex == -1)
throw IllegalArgumentException("child of this Container but couldn't be found?")
l.removeAt(oldIndex);
l.add(if(index < oldIndex) index else index - 1, element);
}
else {
l.add(index, element)
element.removeFromParent()
element.parent = this@Container
//element.addedToParent.dispatch()
/*
if(stage != null) {
if(element is Container) element.addedToStageEvent.broadcast()
else element.addedToStageEvent.dispatch()
}
*/
}
}
override fun addAll(index:Int, elements:Collection<Display>):Boolean {
var i = index
elements.forEach { add(i++, it) }
return true
}
override fun addAll(elements:Collection<Display>):Boolean {
elements.forEach { add(it) }
return true
}
override fun set(index:Int, element:Display):Display {
if(get(index) == element)
return element
removeAt(index)
add(index, element)
return element
}
override fun remove(element:Display):Boolean = remove(element, false)
fun remove(element:Display, dispose:Boolean):Boolean {
var index = indexOfFirst { it == element }
if(index < 0)
return false
removeAt(index, dispose)
return true
}
override fun removeAt(index:Int):Display = removeAt(index, false)
fun removeAt(index:Int, dispose:Boolean):Display {
if(index < 0 || index > size)
throw IllegalArgumentException("invalid index: $index")
requiresRedraw = true
val child = get(index)
/*
if(stage != null) {
if(child is Container) child.removedFromStageEvent.broadcast()
else child.removedFromStageEvent.dispatch()
}
*/
//child.removedFromParent.dispatch()
child.parent = null
l.remove(child)
if(dispose)
child.dispose()
return child
}
override fun clear() = clear(false)
fun clear(dispose:Boolean) {
for(i in indices.reversed())
removeAt(i, dispose)
}
override fun removeAll(elements:Collection<Display>):Boolean = removeAll(elements, false)
fun removeAll(elements:Collection<Display>, dispose:Boolean):Boolean {
var result = false
elements.forEach { result = remove(it, dispose) || result }
return result
}
override fun retainAll(elements:Collection<Display>):Boolean = retainAll(elements, false)
fun retainAll(elements:Collection<Display>, dispose:Boolean):Boolean {
var result = false
for(i in indices.reversed()) {
if(elements.contains(this[i]))
continue
result = true
removeAt(i, dispose)
}
return result
}
override fun iterator():MutableIterator<Display> = listIterator()
override fun listIterator():MutableListIterator<Display> = listIterator(0)
override fun listIterator(index:Int):MutableListIterator<Display> = DisplayListIterator(l.listIterator(index))
override fun subList(fromIndex:Int, toIndex:Int):MutableList<Display> = throw UnsupportedOperationException()
override fun equals(other:Any?):Boolean = l.equals(other)
override fun hashCode():Int = l.hashCode()
override fun toString():String = l.toString()
inner class DisplayListIterator(val iterator : MutableListIterator<Display>) : MutableListIterator<Display> by iterator {
lateinit var lastElement:Display
override fun previous():Display {
lastElement = iterator.previous()
return lastElement
}
override fun next():Display {
lastElement = iterator.next()
return lastElement
}
override fun add(element:Display) {
if(element.parent == this@Container)
throw IllegalArgumentException("adding an element already added to this Container is not possible")
requiresRedraw = true
iterator.add(element)
element.removeFromParent()
element.parent = this@Container
//element.addedToParent.dispatch()
/*
if(stage != null) {
if(child is Container) child.addedToStageEvent.broadcast()
else child.addedToStageEvent.dispatch()
}
*/
}
override fun remove() {
requiresRedraw = true
/*
if(stage != null) {
if(child is Container) child.removedFromStageEvent.broadcast()
else child.removedFromStageEvent.dispatch()
}
*/
//lastElement.removedFromParent.dispatch()
lastElement.parent = null
iterator.remove()
}
override fun set(element:Display) {
if(lastElement == element)
return
if(element.parent == this@Container)
throw IllegalArgumentException("setting an element already added to this Container is not possible")
iterator.set(element)
/*
if(stage != null) {
if(lastElement is Container) lastElement.removedFromStageEvent.broadcast()
else lastElement.removedFromStageEvent.dispatch()
}
*/
//lastElement.removedFromParent.dispatch()
lastElement.parent = null
element.removeFromParent()
element.parent = this@Container
//element.addedToParent.dispatch()
/*
if(stage != null) {
if(child is Container) child.addedToStageEvent.broadcast()
else child.addedToStageEvent.dispatch()
}
*/
}
}
}
val children:DisplayList = DisplayList(mutableListOf())
var touchGroup = false
override fun dispose() {
children.forEach { it.dispose() }
super.dispose()
}
override fun getBounds(targetSpace:Display?, result:Rectangle?):Rectangle {
val out = result ?: Rectangle()
Pool.Matrix3.use { m ->
Pool.Vector2.use { p ->
getTransformationMatrix(targetSpace, m)
p.set(0f, 0f).mul(m)
when(children.size) {
0 -> {
return out.setPosition(p).setSize(0f, 0f)
}
1 -> {
return children[0].getBounds(targetSpace, out).merge(p)
}
else -> {
Pool.Rectangle.use { r ->
var first = true
children.forEach {
if(first) {
it.getBounds(targetSpace, out)
first = false
}
else {
it.getBounds(targetSpace, r)
out.merge(r)
}
}
return out.merge(p)
}
}
}
}}
}
override fun hitTest(localPoint:Vector2):Display? {
if (! visible || ! touchable /*|| ! hitTestMask(localPoint)*/) return null
if(children.isEmpty())
return null
var target:Display? = null
Pool.Matrix3.use { m ->
Pool.Vector2.use { p ->
for(i in children.lastIndex downTo 0) {
val child = children[i]
// if(child.isMask) continue
target = child.hitTest(p.set(localPoint).mul(m.mul(child.transformationMatrix).inv()))
if(target != null)
break
}
return if(touchGroup) this else target
}}
}
override fun render(painter:Painter) {
// TODO:
}
}
| mit | 7e07a916e247db42e4d3e2e0081d287a | 31.351171 | 129 | 0.506358 | 5.406931 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/lang/parser/FortranManualPsiElementFactory.kt | 1 | 763 | package org.jetbrains.fortran.lang.parser
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.jetbrains.fortran.lang.FortranTypes
import org.jetbrains.fortran.lang.psi.impl.*
object FortranManualPsiElementFactory {
@JvmStatic
fun createElement(node: ASTNode): PsiElement? {
val type = node.elementType
return when {
type === FortranTypes.LABEL -> FortranLabelImpl(node)
type === FortranTypes.LABEL_DECL -> FortranLabelDeclImpl(node)
type === FortranTypes.LABELED_DO_CONSTRUCT -> FortranLabeledDoConstructImpl(node)
type === FortranTypes.LABEL_DO_STMT -> FortranLabelDoStmtImpl(node)
else -> null
}
}
}
| apache-2.0 | 6490f485ad2537d371e127ae8d79517b | 37.15 | 94 | 0.65924 | 4.436047 | false | false | false | false |
vjames19/kotlin-futures | kotlin-futures-jdk8/src/test/kotlin/io/github/vjames19/futures/jdk8/FutureSpec.kt | 1 | 12723 | package io.github.vjames19.futures.jdk8
import org.amshove.kluent.*
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import java.util.concurrent.CompletableFuture
/**
* Created by victor.reventos on 7/1/17.
*/
object FutureSpec : Spek({
val success = 1.toCompletableFuture()
val failed = IllegalArgumentException().toCompletableFuture<Int>()
describe("map") {
given("a successful future") {
it("should transform it") {
success.map { it + 1 }.get() shouldEqual 2
}
}
given("a failed future") {
it("should throw the exception") {
{ failed.map { it + 1 }.get() } shouldThrow AnyException
}
}
}
describe("flatMap") {
given("a successful future") {
it("should transform it") {
success.flatMap { ImmediateFuture { it + 1 } }.get() shouldEqual 2
}
}
given("a failed future") {
it("should throw the exception") {
{ failed.flatMap { ImmediateFuture { it + 1 } }.get() } shouldThrow AnyException
}
}
}
describe("flatten") {
given("a successful future") {
it("should flatten it") {
Future { Future { 1 } }.flatten().get() shouldEqual 1
}
}
given("a failed future") {
it("should throw the exception") {
{ Future { Future { throw IllegalArgumentException() } }.flatten().get() } shouldThrow AnyException
}
}
}
describe("filter") {
given("a future that meets the predicate") {
it("should return it as is") {
success.filter { it == 1 }.get() shouldEqual 1
}
}
given("a future that doesn't meet the predicate") {
it("should throw the exception") {
{ success.filter { it == 2 }.get() } shouldThrow AnyException
}
}
given("a failed future") {
it("should throw the exception") {
{ failed.filter { it == 1 }.get() } shouldThrow AnyException
}
}
}
describe("recover") {
given("a successful future") {
it("it shouldn't have to recover") {
success.recover { 2 }.get() shouldEqual 1
}
}
given("a failed future") {
it("should recover") {
failed.recover { 2 }.get() shouldEqual 2
}
}
given("an exception that we can't recover from") {
it("should throw the exception") {
{ failed.recover { throw IllegalArgumentException() }.get() } shouldThrow AnyException
}
}
}
describe("fallbackTo") {
given("a successful future") {
it("shouldn't have to use the fallback") {
success.fallbackTo { Future { 2 } }.get() shouldEqual 1
}
}
given("a failed future") {
it("should fallback to the specified future") {
failed.fallbackTo { Future { 2 } }.get() shouldEqual 2
}
}
}
describe("mapError") {
given("a successful future") {
it("it shouldn't have to map the error") {
success.mapError { _: IllegalArgumentException -> IllegalStateException() }.get() shouldEqual 1
}
}
given("a failed future") {
on("an exception type that its willing to handle") {
it("should map the error") {
{ failed.mapError { _: IllegalArgumentException -> UnsupportedOperationException() }.get() } shouldThrowTheException AnyException withCause (UnsupportedOperationException::class)
}
}
on("an exception type that it didn't register for") {
it("should throw the original error") {
{ failed.mapError { _: ClassNotFoundException -> UnsupportedOperationException() }.get() } shouldThrowTheException AnyException withCause (IllegalArgumentException::class)
}
}
on("handling the supertype Throwable") {
it("should map the error") {
{ failed.mapError { _: Throwable -> UnsupportedOperationException() }.get() } shouldThrowTheException AnyException withCause (UnsupportedOperationException::class)
}
}
}
}
describe("onFailure") {
given("a successful future") {
it("shouldn't call the callback") {
success.onFailure { throw IllegalStateException("onFailure shouldn't be called on a Successful future") }.get()
}
}
given("a failed future") {
it("should call the callback") {
var capturedThrowable: Throwable? = null
failed.onFailure { capturedThrowable = it }.recover { 1 }.get()
capturedThrowable!!.shouldBeInstanceOf(IllegalArgumentException::class.java)
}
}
}
describe("onSuccess") {
given("a successful future") {
it("should call the callback") {
var capturedResult = 0
success.onSuccess { capturedResult = it }.get()
capturedResult shouldEqual 1
}
}
given("a failed future") {
it("shouldn't call the callback") {
failed.onSuccess { throw IllegalStateException("onSuccess shouldn't be called on a Failed future") }
.recover { 1 }.get()
}
}
}
describe("zip") {
given("a successful future") {
it("should zip them") {
success.zip(success).get() shouldEqual (1 to 1)
success.zip(ImmediateFuture { "Hello" }).get() shouldEqual (1 to "Hello")
}
}
given("a failed future") {
it("should throw the exception") {
{ failed.zip(failed).get() } shouldThrow AnyException
{ success.zip(failed).get() } shouldThrow AnyException
{ failed.zip(success).get() } shouldThrow AnyException
}
}
}
describe("zip with a function being passed") {
given("a successful future") {
it("should zip them") {
success.zip(success) { a, b -> a + b }.get() shouldEqual 2
success.zip(ImmediateFuture { "Hello" }) { a, b -> a.toString() + b }.get() shouldEqual "1Hello"
}
}
given("a failed future") {
it("should throw the exception") {
{ failed.zip(failed) { a, b -> a + b }.get() } shouldThrow AnyException
{ success.zip(failed) { a, b -> a + b }.get() } shouldThrow AnyException
{ failed.zip(success) { a, b -> a + b }.get() } shouldThrow AnyException
}
}
}
describe("firstCompletedOf") {
given("a successful future") {
it("should return the first completed") {
val f3 = Future { Thread.sleep(30000); 3 }
val f2 = Future { Thread.sleep(20000); 2 }
val f1 = ImmediateFuture { 1 }
withFutures(listOf(f3, f2, f1)) {
Future.firstCompletedOf(it).get() shouldEqual 1
}
}
}
given("a failed future") {
given("that its the first to complete") {
it("should return it") {
val f3 = Future { Thread.sleep(30000); 3 }
val f2 = Future { Thread.sleep(20000); 2 }
val f1 = ImmediateFuture<Int> { throw IllegalArgumentException() }
withFutures(listOf(f3, f2, f1)) {
({ Future.firstCompletedOf(it).get() }) shouldThrow AnyException
}
}
}
given("that its not the first one to complete") {
it("should return the first one") {
val f3 = Future { Thread.sleep(30000); 3 }
val f2 = Future<Int> { Thread.sleep(20000); throw IllegalArgumentException() }
val f1 = ImmediateFuture { 1 }
withFutures(listOf(f3, f2, f1)) {
Future.firstCompletedOf(listOf(f3, f2, f1)).get() shouldEqual 1
}
}
}
}
}
describe("allAsList") {
given("a list of all successful futures") {
it("should return a successful future") {
Future.allAsList(listOf(1.toCompletableFuture(), 2.toCompletableFuture(), 3.toCompletableFuture())).get() shouldEqual listOf(1, 2, 3)
}
}
given("a list with a failed future") {
it("should return a failed future") {
{ Future.allAsList(listOf(1.toCompletableFuture(), 2.toCompletableFuture(), IllegalArgumentException().toCompletableFuture())).get() } shouldThrow AnyException
}
}
}
describe("successfulList") {
given("a list of all successful futures") {
it("should return a successful future") {
Future.successfulList(listOf(1.toCompletableFuture(), 2.toCompletableFuture(), Future { Thread.sleep(10); 3 })).get() shouldEqual listOf(1, 2, 3)
}
}
given("a list with a failed future") {
it("should return the list with the successful futures") {
Future.successfulList(listOf(1.toCompletableFuture(), 2.toCompletableFuture(), IllegalArgumentException().toCompletableFuture())).get() shouldEqual listOf(1, 2)
Future.successfulList(listOf(failed, 2.toCompletableFuture(), IllegalArgumentException().toCompletableFuture())).get() shouldEqual listOf(2)
}
}
given("a list with all failed futures") {
it("should return an empty list") {
Future.successfulList(listOf(failed, failed, failed)).get() shouldEqual emptyList()
}
}
}
describe("fold") {
given("a list of all successful futures") {
it("should fold them") {
val futures = (1..3).toList().map { it.toCompletableFuture() }
Future.fold(futures, 0) { acc, i -> acc + i }.get() shouldEqual 1 + 2 + 3
}
}
given("a list with a failed future") {
it("should return the failure") {
val futures = (1..3).toList().map { it.toCompletableFuture() } + IllegalArgumentException().toCompletableFuture<Int>()
({ Future.fold(futures, 0) { acc, i -> acc + i }.get() }) shouldThrow AnyException
}
}
}
describe("reduce") {
given("a list of all successful futures") {
it("should reduce it") {
val futures = (1..3).toList().map { it.toCompletableFuture() }
Future.reduce(futures) { acc, i -> acc + i }.get() shouldEqual (1 + 2 + 3)
}
}
given("a list with a failed future") {
it("should return the failure") {
val futures = (1..3).toList().map { it.toCompletableFuture() } + IllegalArgumentException().toCompletableFuture<Int>()
({ Future.reduce(futures) { acc, i -> acc + i }.get() }) shouldThrow AnyException
}
}
given("an empty list") {
it("should throw UnsupportedOperationException") {
({ Future.reduce(emptyList<CompletableFuture<Int>>()) { acc, i -> acc + i }.get() }) shouldThrow UnsupportedOperationException::class
}
}
}
describe("transform") {
given("a list of all successful futures") {
it("should transform them") {
Future.transform((1..3).toList().map { it.toCompletableFuture() }) { it + 1 }.get() shouldEqual (2..4).toList()
}
}
given("a list with a failed future") {
it("should return the failure") {
val futures = (1..3).toList().map { it.toCompletableFuture() } + IllegalArgumentException().toCompletableFuture<Int>()
({ Future.transform(futures) { it + 1 }.get() }) shouldThrow AnyException
}
}
}
})
private fun <T> withFutures(futures: List<CompletableFuture<T>>, f: (List<CompletableFuture<T>>) -> Unit): Unit {
f(futures)
futures.forEach { it.cancel(true) }
} | mit | 20a389acfd6eb6c35d082b76ca3a8ab6 | 35.668588 | 198 | 0.529906 | 4.839483 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/me/aurieh/ares/exposed/pg/type/JsonbMapColumnType.kt | 2 | 2559 | /*
* Copyright 2017 aurieh <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.aurieh.ares.exposed.pg.type
import org.jetbrains.exposed.sql.ColumnType
import org.json.JSONException
import org.json.JSONObject
import org.postgresql.util.PGobject
import java.sql.PreparedStatement
/**
* JsonbMap column type
*/
class JsonbMapColumnType<K, V> : ColumnType() {
/**
* SQL type string
* @return[String] jsonb
*/
override fun sqlType() = "jsonb"
/**
* Sets a statement parameter
* @param[PreparedStatement] stmt Statement
* @param[Int] index Index
* @param[Any?] value Value, should be Map<K, V>
*/
override fun setParameter(stmt: PreparedStatement, index: Int, value: Any?) {
val actualValue: String
try {
@Suppress("UNCHECKED_CAST")
actualValue = JSONObject(value!! as Map<K, V>).toString()
} catch (e: Throwable) {
when (e) {
is ClassCastException -> throw RuntimeException("value did not conform Map<K, V>")
is NullPointerException -> throw RuntimeException("value cannot be null")
else -> throw e
}
}
val obj = PGobject()
obj.type = "jsonb"
obj.value = actualValue
stmt.setObject(index, obj)
}
/**
* Value from DB
* @param[Any] value Value
* @return[Map<K, V>]
*/
override fun valueFromDB(value: Any): Any {
if (value is PGobject) {
try {
@Suppress("UNCHECKED_CAST")
return JSONObject(value.value).toMap() as Map<K, V>
} catch (e: Throwable) {
when (e) {
is ClassCastException -> throw RuntimeException("value did not conform Map<K, V>")
is JSONException -> throw RuntimeException("value is not valid jsonb")
else -> throw e
}
}
}
throw RuntimeException("value is not pgobject")
}
} | mit | aaa9854bad359d246656539640fd15a4 | 31.405063 | 102 | 0.603361 | 4.308081 | false | false | false | false |
lnds/9d9l | desafio2/kotlin/src/main/kotlin/weather/Main.kt | 1 | 4318 | package weather
import java.net.URL
import kotlin.io.*
import org.w3c.dom.*
import javax.xml.parsers.*
import java.io.*
import java.nio.charset.Charset
val noCitiesProvidedMessage = "debe ingresar una lista de ciudades"
val timeReportMessage = "tiempo ocupado para generar el reporte: "
val apiKey = System.getenv("WEATHER_API_KEY")
val maxTries = 10
val threadSleep = 100L
interface Args
object NoArgs : Args
data class SeqArgs(val args:List<String>) : Args
data class ParArgs(val args:List<String>) : Args
interface WeatherResult : Comparable<WeatherResult>
data class Error(val error:String, val city:String) : WeatherResult {
override fun compareTo(other:WeatherResult) : Int {
return -1
}
}
data class WeatherReport(val city:String, val temp:Double, val min:Double, val max:Double, val conditions:String) : WeatherResult {
override fun compareTo(other:WeatherResult) : Int {
when (other) {
is Error -> return 1
is WeatherReport -> {
return if (other.temp > this.temp) 1 else -1
}
}
return 0
}
}
fun makeUrl(city:String) : String {
return "http://api.openweathermap.org/data/2.5/weather?q=${city}&mode=xml&units=metric&appid=${apiKey}&lang=sp"
}
fun apiCall(city:String) : WeatherResult {
val url = makeUrl(city)
for (tries in 1..10) {
try {
val req = URL(url)
val rsp = req.readText()
return parseApiResponse(city, rsp)
} catch (e:Exception) {
Thread.sleep(50L)
}
}
return Error("error descargando url", city)
}
@Suppress("UNUSED_EXPRESSION")
fun parseApiResponse(city: String, response:String) : WeatherResult {
val factory = DocumentBuilderFactory.newInstance()
val builder = factory.newDocumentBuilder()
val xmlStrBuilder = StringBuilder()
xmlStrBuilder.append(response)
val str = xmlStrBuilder.toString()
val bytes = str.toByteArray(Charset.forName("UTF-8"))
val input = ByteArrayInputStream(bytes)
val doc = builder.parse(input)
val root = doc.documentElement
val cityName = root.getElementsByTagName("city").item(0).attributes.getNamedItem("name").textContent
val temp = root.getElementsByTagName("temperature").item(0).attributes.getNamedItem("value").textContent
val min = root.getElementsByTagName("temperature").item(0).attributes.getNamedItem("min").textContent
val max = root.getElementsByTagName("temperature").item(0).attributes.getNamedItem("max").textContent
val conditions = root.getElementsByTagName("weather").item(0).attributes.getNamedItem("value").textContent
return WeatherReport(cityName, temp.toDouble(), min.toDouble(), max.toDouble(), conditions)
}
fun checkArgs(args:Array<String>) : Args {
if (args.isEmpty())
return NoArgs
else if (args[0] != "-p")
return SeqArgs(args.toList())
else if (args.toList().size == 1)
return NoArgs // -p sin argumentos
else
return ParArgs(args.toList().drop(1))
}
@Suppress("UNUSED_EXPRESSION")
fun showTime(block: () -> Unit) {
val t0 = System.nanoTime()
block()
val t1 = System.nanoTime()
val elapsed = t1 - t0
val msecs = elapsed / 1000000
val hours = msecs / 3600000
val mins = (msecs % 3600000) / 60000
val secs = ((msecs % 3600000) % 60000) / 1000.0
println(timeReportMessage+ " " + "%d:%02d:%02.3f".format(hours, mins, secs))
}
fun printReports(reports:List<WeatherResult>) {
reports.sorted().forEach { r ->
when (r) {
is Error -> println("${r.city} Error: ${r.error}")
is WeatherReport -> println("%-30.30s max:%5.1f min:%5.1f actual: %5.1f %s".format(r.city, r.max, r.min, r.temp, r.conditions))
}
}
}
fun seqFetch(sa:SeqArgs) {
val cities = sa.args
val reports = cities.map(::apiCall)
printReports(reports)
}
fun parFetch(pa:ParArgs) {
val cities = pa.args
val reports = cities.par().map(::apiCall)
printReports(reports.unpar().toList())
reports.executorService.shutdown()
}
fun main(args: Array<String>) {
val l = checkArgs(args)
when (l) {
is NoArgs -> println(noCitiesProvidedMessage)
is SeqArgs -> showTime { seqFetch(l) }
is ParArgs -> showTime { parFetch(l) }
}
} | mit | a4fe88f4b20e9cb1ca6c12afd5223b3c | 30.757353 | 142 | 0.658638 | 3.678024 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/input/mouse/MouseScrollFilterTest.kt | 3 | 10214 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION") // https://github.com/JetBrains/compose-jb/issues/1514
package androidx.compose.ui.input.mouse
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.TestComposeWindow
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import com.google.common.truth.Truth.assertThat
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalComposeUiApi::class)
@RunWith(JUnit4::class)
@Ignore // TODO(b/217238066) remove after migration to ImageComposeScene (it will be upstreamed from Compose MPP 1.0.0)
class MouseScrollFilterTest {
private val window = TestComposeWindow(width = 100, height = 100, density = Density(2f))
@Test
fun `inside box`() {
var actualEvent: MouseScrollEvent? = null
var actualBounds: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent = event
actualBounds = bounds
true
}
.size(10.dp, 20.dp)
)
}
window.onMouseScroll(
x = 0,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Line(3f), MouseScrollOrientation.Vertical)
)
assertThat(actualEvent?.delta).isEqualTo(MouseScrollUnit.Line(3f))
assertThat(actualEvent?.orientation).isEqualTo(MouseScrollOrientation.Vertical)
assertThat(actualBounds).isEqualTo(IntSize(20, 40))
}
@Test
fun `outside box`() {
var actualEvent: MouseScrollEvent? = null
var actualBounds: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent = event
actualBounds = bounds
true
}
.size(10.dp, 20.dp)
)
}
window.onMouseScroll(
x = 20,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Line(3f), MouseScrollOrientation.Vertical)
)
assertThat(actualEvent).isEqualTo(null)
assertThat(actualBounds).isEqualTo(null)
}
@Test
fun `inside two overlapping boxes`() {
var actualEvent1: MouseScrollEvent? = null
var actualBounds1: IntSize? = null
var actualEvent2: MouseScrollEvent? = null
var actualBounds2: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent1 = event
actualBounds1 = bounds
true
}
.size(10.dp, 20.dp)
)
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent2 = event
actualBounds2 = bounds
true
}
.size(5.dp, 10.dp)
)
}
window.onMouseScroll(
x = 0,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Line(3f), MouseScrollOrientation.Horizontal)
)
assertThat(actualEvent1).isEqualTo(null)
assertThat(actualBounds1).isEqualTo(null)
assertThat(actualEvent2?.delta).isEqualTo(MouseScrollUnit.Line(3f))
assertThat(actualEvent2?.orientation).isEqualTo(MouseScrollOrientation.Horizontal)
assertThat(actualBounds2).isEqualTo(IntSize(10, 20))
}
@Test
fun `inside two overlapping boxes, top box doesn't handle scroll`() {
var actualEvent: MouseScrollEvent? = null
var actualBounds: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent = event
actualBounds = bounds
true
}
.size(10.dp, 20.dp)
)
Box(
Modifier
.mouseScrollFilter { _, _ ->
false
}
.size(5.dp, 10.dp)
)
}
window.onMouseScroll(
x = 0,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Line(3f), MouseScrollOrientation.Horizontal)
)
assertThat(actualEvent).isEqualTo(null)
assertThat(actualBounds).isEqualTo(null)
}
@Test
fun `inside two overlapping boxes, top box doesn't have mouseScrollFilter`() {
var actualEvent: MouseScrollEvent? = null
var actualBounds: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent = event
actualBounds = bounds
true
}
.size(10.dp, 20.dp)
)
Box(
Modifier
.size(5.dp, 10.dp)
)
}
window.onMouseScroll(
x = 0,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Line(3f), MouseScrollOrientation.Horizontal)
)
assertThat(actualEvent?.delta).isEqualTo(MouseScrollUnit.Line(3f))
assertThat(actualEvent?.orientation).isEqualTo(MouseScrollOrientation.Horizontal)
assertThat(actualBounds).isEqualTo(IntSize(20, 40))
}
@Test
fun `inside two nested boxes`() {
var actualEvent1: MouseScrollEvent? = null
var actualBounds1: IntSize? = null
var actualEvent2: MouseScrollEvent? = null
var actualBounds2: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent1 = event
actualBounds1 = bounds
true
}
.size(10.dp, 20.dp)
) {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent2 = event
actualBounds2 = bounds
true
}
.size(5.dp, 10.dp)
)
}
}
window.onMouseScroll(
x = 0,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Line(-1f), MouseScrollOrientation.Horizontal)
)
assertThat(actualEvent1).isEqualTo(null)
assertThat(actualBounds1).isEqualTo(null)
assertThat(actualEvent2?.delta).isEqualTo(MouseScrollUnit.Line(-1f))
assertThat(actualEvent2?.orientation).isEqualTo(MouseScrollOrientation.Horizontal)
assertThat(actualBounds2).isEqualTo(IntSize(10, 20))
}
@Test
fun `inside two nested boxes, nested box doesn't handle scroll`() {
var actualEvent: MouseScrollEvent? = null
var actualBounds: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent = event
actualBounds = bounds
true
}
.size(10.dp, 20.dp)
) {
Box(
Modifier
.mouseScrollFilter { _, _ ->
false
}
.size(5.dp, 10.dp)
)
}
}
window.onMouseScroll(
x = 0,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Page(1f), MouseScrollOrientation.Horizontal)
)
assertThat(actualEvent?.delta).isEqualTo(MouseScrollUnit.Page(1f))
assertThat(actualEvent?.orientation).isEqualTo(MouseScrollOrientation.Horizontal)
assertThat(actualBounds).isEqualTo(IntSize(20, 40))
}
@Test
fun `inside two nested boxes, nested box doesn't have mouseScrollFilter`() {
var actualEvent: MouseScrollEvent? = null
var actualBounds: IntSize? = null
window.setContent {
Box(
Modifier
.mouseScrollFilter { event, bounds ->
actualEvent = event
actualBounds = bounds
true
}
.size(10.dp, 20.dp)
) {
Box(
Modifier
.size(5.dp, 10.dp)
)
}
}
window.onMouseScroll(
x = 0,
y = 0,
event = MouseScrollEvent(MouseScrollUnit.Page(1f), MouseScrollOrientation.Horizontal)
)
assertThat(actualEvent?.delta).isEqualTo(MouseScrollUnit.Page(1f))
assertThat(actualEvent?.orientation).isEqualTo(MouseScrollOrientation.Horizontal)
assertThat(actualBounds).isEqualTo(IntSize(20, 40))
}
} | apache-2.0 | 22ccd58816dccb64f8fed1dc1f3fcdc3 | 31.635783 | 119 | 0.529371 | 5.021632 | false | false | false | false |
kamerok/Orny | app/src/main/kotlin/com/kamer/orny/presentation/addexpense/AddExpenseActivity.kt | 1 | 6711 | package com.kamer.orny.presentation.addexpense
import android.app.DatePickerDialog
import android.app.ProgressDialog
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.kamer.orny.R
import com.kamer.orny.data.domain.model.Author
import com.kamer.orny.interaction.model.AuthorsWithDefault
import com.kamer.orny.presentation.core.BaseActivity
import com.kamer.orny.presentation.core.VMProvider
import com.kamer.orny.utils.onTextChanged
import com.kamer.orny.utils.safeObserve
import com.kamer.orny.utils.setupToolbar
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_add_expense.*
import kotlinx.android.synthetic.main.layout_toolbar.*
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
@JvmSuppressWildcards
class AddExpenseActivity : BaseActivity(), LifecycleOwner {
companion object {
private val DATE_FORMAT = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
fun getIntent(context: Context) = Intent(context, AddExpenseActivity::class.java)
}
@Inject lateinit var viewModelProvider: VMProvider<AddExpenseViewModel>
private val viewModel: AddExpenseViewModel by lazy { viewModelProvider.get(this) }
private var authors = emptyList<Author>()
private val adapter by lazy { ArrayAdapter<String>(this, R.layout.item_edit_expense_author) }
private var dialog: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_expense)
initViews()
bindViewModel()
}
override fun onBackPressed() {
viewModel.exitScreen()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.add_expense, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_save -> {
viewModel.saveExpense()
return true
}
else -> return false
}
}
private fun initViews() {
setupToolbar(toolbarView)
amountView.onTextChanged { viewModel.amountChanged(it) }
commentView.onTextChanged { viewModel.commentChanged(it) }
commentView.setOnEditorActionListener { _, actionId, _ ->
when (actionId) {
EditorInfo.IME_ACTION_DONE -> {
viewModel.saveExpense()
true
}
else -> false
}
}
authorsSpinnerView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
viewModel.authorSelected(authors[position])
}
}
authorsSpinnerView.adapter = adapter
changeAuthorView.setOnClickListener {
authorsSpinnerView.apply {
var newSelected = selectedItemPosition + 1
if (newSelected >= count) {
newSelected = 0
}
setSelection(newSelected)
}
}
dateView.setOnClickListener { viewModel.selectDate() }
offBudgetView.setOnCheckedChangeListener { _, isChecked -> viewModel.offBudgetChanged(isChecked) }
}
private fun bindViewModel() {
viewModel.authorsStream.safeObserve(this, this::setAuthors)
viewModel.dateStream.safeObserve(this, this::setDate)
viewModel.savingProgressStream.safeObserve(this, this::setSavingProgress)
viewModel.showDatePickerStream.safeObserve(this, this::showDatePicker)
viewModel.showExitDialogStream.observe(this, Observer { showExitDialog() })
viewModel.showAmountErrorStream.safeObserve(this, this::showAmountError)
viewModel.showErrorStream.safeObserve(this, this::showError)
}
private fun setAuthors(authorsWithDefault: AuthorsWithDefault) {
this.authors = authorsWithDefault.authors
adapter.clear()
adapter.addAll(authors.map { it.name })
authorsSpinnerView.setSelection(authorsWithDefault.selectedIndex)
}
private fun setDate(date: Date) {
dateView.text = DATE_FORMAT.format(date)
}
private fun setSavingProgress(isSaving: Boolean) {
if (isSaving) {
val dialog = ProgressDialog(this)
dialog.setMessage(getString(R.string.add_expense_exit_save_progress))
dialog.setCancelable(false)
dialog.setCanceledOnTouchOutside(false)
dialog.show()
this.dialog = dialog
} else {
dialog?.dismiss()
}
}
private fun showDatePicker(date: Date) {
val calendar = Calendar.getInstance()
calendar.timeInMillis = date.time
DatePickerDialog(
this,
{ _, year, month, dayOfMonth ->
val newCalendar = Calendar.getInstance()
newCalendar.set(year, month, dayOfMonth)
val newDate = Date(newCalendar.timeInMillis)
setDate(newDate)
viewModel.dateChanged(newDate)
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)).show()
}
private fun showExitDialog() {
AlertDialog.Builder(this)
.setTitle(R.string.add_expense_exit_dialog_title)
.setMessage(R.string.add_expense_exit_dialog_message)
.setPositiveButton(R.string.add_expense_exit_dialog_save) { _, _ -> viewModel.saveExpense() }
.setNegativeButton(R.string.add_expense_exit_dialog_exit) { _, _ -> viewModel.confirmExit() }
.show()
}
private fun showAmountError(error: String) {
amountView.error = error
}
private fun showError(message: String) {
AlertDialog.Builder(this)
.setTitle(R.string.app_name)
.setMessage(message)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.show()
}
}
| apache-2.0 | fddc5043c0a99e6ca3e07553443cae24 | 35.080645 | 109 | 0.650276 | 4.776512 | false | false | false | false |
wealthfront/magellan | magellan-lint/src/main/java/com/wealthfront/magellan/InvalidChildInScreenContainer.kt | 1 | 1555 | package com.wealthfront.magellan
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.LayoutDetector
import com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPE
import com.android.tools.lint.detector.api.Severity.ERROR
import com.android.tools.lint.detector.api.XmlContext
import org.w3c.dom.Element
internal val INVALID_CHILD_IN_SCREEN_CONTAINER = Issue.create(
id = InvalidChildInScreenContainer::class.simpleName!!,
briefDescription = "ScreenContainer should not have child declared in XML.",
explanation = "ScreenContainers are used to inflate the view's associated with steps/journey's internally." +
"If you declare child views in the XML, it may result in unexpected results.",
category = Category.CORRECTNESS,
priority = PRIORITY_HIGH,
severity = ERROR,
implementation = Implementation(InvalidChildInScreenContainer::class.java, RESOURCE_FILE_SCOPE)
)
const val SCREEN_CONTAINER = "com.wealthfront.magellan.ScreenContainer"
class InvalidChildInScreenContainer : LayoutDetector() {
override fun getApplicableElements() = listOf(SCREEN_CONTAINER)
override fun visitElement(context: XmlContext, element: Element) {
if (element.hasChildNodes()) {
context.report(
INVALID_CHILD_IN_SCREEN_CONTAINER,
element,
context.getElementLocation(element),
"Remove child views inside the ScreenContainer."
)
}
}
}
| apache-2.0 | 28f741c37d1c652ac3279fb0c07a8705 | 38.871795 | 111 | 0.775563 | 4.124668 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/baseClasses/BaseAdapter.kt | 1 | 2148 | package com.commonsense.android.kotlin.views.baseClasses
import android.content.*
import android.content.res.*
import android.support.annotation.IntRange
import android.widget.*
import java.util.*
/**
* created by Kasper Tvede on 29-09-2016.
* Makes sure that the array adapter is type safe / no nulls
*
*
*/
open class BaseAdapter<T>(context: Context) : ArrayAdapter<T>(context, 0) {
override fun add(obj: T) {
if (obj != null) {
super.add(obj)
}
}
@Suppress("RedundantOverride")
override fun sort(comparator: Comparator<in T>) {
super.sort(comparator)
}
fun addAll(map: List<T>) {
map.forEach { add(it) }
}
@Suppress("RedundantOverride")
override fun addAll(collection: Collection<T>) {
super.addAll(collection)
}
override fun addAll(vararg items: T) {
items.forEach { this.add(it) }
}
override fun getItem(@IntRange(from = 0) position: Int): T? {
if (isIndexValid(position)) {
return super.getItem(position)
}
return null
}
fun getItems(): List<T> {
val list = mutableListOf<T>()
(0 until count).forEach {
getItem(it)?.let(list::add)
}
return list
}
override fun remove(obj: T) {
if (obj != null) {
super.remove(obj)
}
}
@Suppress("RedundantOverride")
override fun getPosition(item: T): Int = super.getPosition(item)
@Suppress("RedundantOverride")
@IntRange(from = 0)
override fun getCount(): Int = super.getCount()
@Suppress("RedundantOverride")
override fun setDropDownViewTheme(theme: Resources.Theme?) {
super.setDropDownViewTheme(theme)
}
/**
* insert the given item, if it is not null
*/
override fun insert(obj: T, @IntRange(from = 0) index: Int) {
if (obj != null) {
super.insert(obj, index)
}
}
/**
* Tells if the given index is valid ( in range 0 until count / [0 ;count[ )
*/
fun isIndexValid(@IntRange(from = 0) index: Int): Boolean = index in 0 until count
}
| mit | 4eed1d55bf24aa0380f927ff8da2eec2 | 22.866667 | 86 | 0.594041 | 3.912568 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-dagger/src/main/kotlin/org/ccci/gto/android/common/dagger/eager/EagerSingletonInitializer.kt | 2 | 3366 | package org.ccci.gto.android.common.dagger.eager
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.annotation.VisibleForTesting
import dagger.Lazy
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.ccci.gto.android.common.dagger.eager.EagerSingleton.LifecycleEvent.ACTIVITY_CREATED
import org.ccci.gto.android.common.dagger.eager.EagerSingleton.LifecycleEvent.IMMEDIATE
import org.ccci.gto.android.common.dagger.eager.EagerSingleton.ThreadMode.ASYNC
import org.ccci.gto.android.common.dagger.eager.EagerSingleton.ThreadMode.MAIN
import org.ccci.gto.android.common.dagger.eager.EagerSingleton.ThreadMode.MAIN_ASYNC
@Singleton
class EagerSingletonInitializer @Inject constructor(
app: Application,
@EagerSingleton(on = IMMEDIATE, threadMode = MAIN) immediateMain: Lazy<Set<Any>>,
@EagerSingleton(on = IMMEDIATE, threadMode = MAIN_ASYNC) immediateMainAsync: Lazy<Set<Any>>,
@EagerSingleton(on = IMMEDIATE, threadMode = ASYNC) immediateAsync: Lazy<Set<Any>>,
@EagerSingleton(on = ACTIVITY_CREATED, threadMode = MAIN) activityMain: Lazy<Set<Any>>,
@EagerSingleton(on = ACTIVITY_CREATED, threadMode = MAIN_ASYNC) activityMainAsync: Lazy<Set<Any>>,
@EagerSingleton(on = ACTIVITY_CREATED, threadMode = ASYNC) activityAsync: Lazy<Set<Any>>
) : Application.ActivityLifecycleCallbacks, CoroutineScope {
@VisibleForTesting
internal val job = SupervisorJob()
override val coroutineContext get() = Dispatchers.Default + job
private var app: Application? = app
private var activityMain: Lazy<Set<Any>>? = activityMain
private var activityMainAsync: Lazy<Set<Any>>? = activityMainAsync
private var activityAsync: Lazy<Set<Any>>? = activityAsync
internal var activityCreated = false
init {
initialize(immediateMain, immediateMainAsync, immediateAsync)
app.registerActivityLifecycleCallbacks(this)
}
// region Application.ActivityLifecycleCallbacks
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) =
initializeActivityCreatedSingletons()
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityResumed(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
// endregion Application.ActivityLifecycleCallbacks
private fun initialize(main: Lazy<Set<Any>>?, mainAsync: Lazy<Set<Any>>?, async: Lazy<Set<Any>>?) {
main?.get()
launch(Dispatchers.Main) {
mainAsync?.get()
withContext(Dispatchers.Default) { async?.get() }
}
}
internal fun initializeActivityCreatedSingletons() {
activityCreated = true
app?.unregisterActivityLifecycleCallbacks(this)
initialize(activityMain, activityMainAsync, activityAsync)
activityMain = null
activityMainAsync = null
activityAsync = null
app = null
}
}
| mit | 5f08dac18c48c3e00099635744d3cb4b | 44.486486 | 103 | 0.76025 | 4.610959 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/AztecHtmlSchema.kt | 1 | 934 | package org.wordpress.aztec
import org.ccil.cowan.tagsoup.HTMLSchema
class AztecHtmlSchema : HTMLSchema() {
// Remove unnecessary default values for attributes, which are not mandatory
init {
fixIframeElement()
fixLinkElement()
fixBrElement()
}
private fun fixIframeElement() {
val iframe = getElementType("iframe")
var index = iframe.atts().getIndex("frameborder")
iframe.atts().setValue(index, null)
index = iframe.atts().getIndex("scrolling")
iframe.atts().setValue(index, null)
}
private fun fixLinkElement() {
val iframe = getElementType("a")
val index = iframe.atts().getIndex("shape")
iframe.atts().setValue(index, null)
}
private fun fixBrElement() {
val iframe = getElementType("br")
val index = iframe.atts().getIndex("clear")
iframe.atts().setValue(index, null)
}
}
| mpl-2.0 | b873941bbbd3546bbed5d2e6277193f8 | 24.944444 | 80 | 0.62848 | 4.169643 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/AztecAttributes.kt | 1 | 2772 | package org.wordpress.aztec
import org.wordpress.android.util.AppLog
import org.xml.sax.Attributes
import org.xml.sax.helpers.AttributesImpl
class AztecAttributes(attributes: Attributes = AttributesImpl()) : AttributesImpl(attributes) {
fun setValue(key: String, value: String) {
val index = getIndex(key)
if (index == -1) {
try {
addAttribute("", key, key, "string", value)
} catch (e: ArrayIndexOutOfBoundsException) {
// https://github.com/wordpress-mobile/AztecEditor-Android/issues/705
AppLog.e(AppLog.T.EDITOR, "Error adding attribute with name: $key and value: $value")
logInternalState()
throw e
}
} else {
setValue(index, value)
}
}
private fun logInternalState() {
AppLog.e(AppLog.T.EDITOR, "Dumping internal state:")
AppLog.e(AppLog.T.EDITOR, "length = $length")
// Since the toString can throw OOB error we need to wrap it in a try/catch
try {
AppLog.e(AppLog.T.EDITOR, toString())
} catch (e: ArrayIndexOutOfBoundsException) {
// No need to log anything here. `toString` already writes to log details, but we need to shallow the exception
// we don't want to crash logging state of the app
}
}
fun isEmpty(): Boolean {
return length == 0
}
fun removeAttribute(key: String) {
if (hasAttribute(key)) {
val index = getIndex(key)
try {
removeAttribute(index)
} catch (e: ArrayIndexOutOfBoundsException) {
// https://github.com/wordpress-mobile/AztecEditor-Android/issues/705
AppLog.e(AppLog.T.EDITOR, "Tried to remove attribute: $key that is not in the list")
AppLog.e(AppLog.T.EDITOR, "Reported to be at index: $index")
logInternalState()
throw e
}
}
}
fun hasAttribute(key: String): Boolean {
return getValue(key) != null
}
override fun toString(): String {
val sb = StringBuilder()
try {
for (i in 0..this.length - 1) {
sb.append(this.getLocalName(i))
sb.append("=\"")
sb.append(this.getValue(i))
sb.append("\" ")
}
} catch (e: ArrayIndexOutOfBoundsException) {
// https://github.com/wordpress-mobile/AztecEditor-Android/issues/705
AppLog.e(AppLog.T.EDITOR, "IOOB occurred in toString. Dumping partial state:")
AppLog.e(AppLog.T.EDITOR, sb.trimEnd().toString())
throw e
}
return sb.trimEnd().toString()
}
}
| mpl-2.0 | 3fc08fed693bb49ff418844f63cb7b4a | 34.538462 | 123 | 0.565296 | 4.456592 | false | false | false | false |
CoderLine/alphaTab | src.kotlin/alphaTab/alphaTab/src/commonMain/kotlin/alphaTab/util/Lazy.kt | 1 | 422 | package alphaTab.util
internal object UninitializedValue
internal class Lazy<T : Any?>(factory: () -> T) {
private val _factory: () -> T = factory
private var _value:Any? = UninitializedValue
public val value:T
get() {
if(_value == UninitializedValue) {
_value = _factory()
}
@Suppress("UNCHECKED_CAST")
return _value as T
}
}
| mpl-2.0 | 5325e3fb02601f7a12c0cd12653d5f44 | 23.823529 | 49 | 0.547393 | 4.350515 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/filter/FilterMenuItemAdapter.kt | 1 | 2463 | package com.intfocus.template.dashboard.mine.adapter
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.intfocus.template.R
import com.intfocus.template.model.response.filter.MenuItem
/**
* Created by CANC on 2017/8/3.
*/
class FilterMenuItemAdapter(val context: Context,
var menuDatas: List<MenuItem>?,
var listener: FilterMenuItemListener) : RecyclerView.Adapter<FilterMenuItemAdapter.FilterMenuItemHolder>() {
var inflater = LayoutInflater.from(context)!!
fun setData(data: List<MenuItem>?) {
this.menuDatas = data
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FilterMenuItemHolder {
val contentView = inflater.inflate(R.layout.item_filter_menu_item, parent, false)
return FilterMenuItemHolder(contentView)
}
override fun onBindViewHolder(holder: FilterMenuItemHolder, position: Int) {
holder.contentView.setBackgroundResource(R.drawable.recycler_bg)
if (menuDatas != null) {
holder.tvFilterName.text = menuDatas!![position].name
if (menuDatas!![position].arrorDirection) {
holder.ivFilter.visibility = View.VISIBLE
holder.tvFilterName.setTextColor(ContextCompat.getColor(context, R.color.co1_syr))
} else {
holder.ivFilter.visibility = View.GONE
holder.tvFilterName.setTextColor(ContextCompat.getColor(context, R.color.co3_syr))
}
holder.rlFilter.setOnClickListener {
listener.menuItemClick(position)
}
}
}
override fun getItemCount(): Int = if (menuDatas == null) 0 else menuDatas!!.size
class FilterMenuItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var contentView = itemView
var rlFilter: RelativeLayout = itemView.findViewById(R.id.rl_filter)
var tvFilterName: TextView = itemView.findViewById(R.id.tv_filter_name)
var ivFilter: ImageView = itemView.findViewById(R.id.iv_filter)
}
interface FilterMenuItemListener {
fun menuItemClick(position: Int)
}
}
| gpl-3.0 | 564334565d4f0bb3a2c503982e1fe924 | 38.725806 | 136 | 0.694681 | 4.502742 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/latex/ui/widget/LatexWebView.kt | 2 | 5229 | package org.stepik.android.view.latex.ui.widget
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import org.stepic.droid.BuildConfig
import org.stepic.droid.ui.util.evaluateJavascriptCompat
import org.stepic.droid.util.contextForWebView
import org.stepik.android.view.latex.model.TextAttributes
import org.stepik.android.domain.latex.model.block.HorizontalScrollBlock
import org.stepik.android.view.latex.js_interface.ModelViewerInterface
import ru.nobird.android.view.base.ui.extension.toDp
import kotlin.math.abs
@SuppressLint("AddJavascriptInterface")
class LatexWebView
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : WebView(context.contextForWebView(), attrs, defStyleAttr),
View.OnLongClickListener,
View.OnClickListener,
View.OnTouchListener {
companion object {
private const val MAX_CLICK_DURATION = 200
private const val MIME_TYPE = "text/html"
private const val ENCODING = "UTF-8"
private const val ASSETS = "file:///android_asset/"
}
var attributes = TextAttributes.fromAttributeSet(context, attrs)
set(value) {
field = value
settings.defaultFontSize = value.textSize.toInt()
setOnLongClickListener(this.takeIf { !value.textIsSelectable })
}
var onImageClickListener: ((path: String) -> Unit)? = null
var text: String = ""
set(value) {
if (field != value) { // update check in order to prevent re-rendering
field = value
loadDataWithBaseURL(ASSETS, text, MIME_TYPE, ENCODING, "")
}
}
private var scrollState =
ScrollState()
private var startX = 0f
private var startY = 0f
init {
setBackgroundColor(Color.argb(1, 0, 0, 0))
setOnLongClickListener(this.takeIf { !attributes.textIsSelectable })
setOnTouchListener(this)
setOnClickListener(this)
isFocusable = true
isFocusableInTouchMode = true
settings.domStorageEnabled = true
@SuppressLint("SetJavaScriptEnabled")
settings.javaScriptEnabled = true
settings.defaultFontSize = attributes.textSize.toInt()
settings.mediaPlaybackRequiresUserGesture = false
addJavascriptInterface(OnScrollWebListener(), HorizontalScrollBlock.SCRIPT_NAME)
addJavascriptInterface(ModelViewerInterface(context), ModelViewerInterface.MODEL_VIEWER_INTERFACE)
isSoundEffectsEnabled = false
}
override fun onLongClick(v: View?): Boolean = true
override fun onClick(v: View?) {
val hr = hitTestResult
try {
if (hr.type == HitTestResult.IMAGE_TYPE) {
onImageClickListener?.invoke(hr.extra ?: return)
}
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
e.printStackTrace()
}
}
}
override fun onTouch(v: View?, event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_UP &&
event.downTime - event.eventTime < MAX_CLICK_DURATION
) {
performClick()
}
return false
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
startX = event.x
startY = event.y
val dpx = event.x.toDp()
val dpy = event.y.toDp()
evaluateJavascriptCompat("${HorizontalScrollBlock.METHOD_NAME}($dpx, $dpy)")
}
MotionEvent.ACTION_MOVE -> {
val dx = startX - event.x
val dy = startY - event.y
event.setLocation(event.x, event.y)
if (abs(dx) > abs(dy) && canScrollHorizontally(dx.toInt())) {
parent.requestDisallowInterceptTouchEvent(true)
}
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
parent.requestDisallowInterceptTouchEvent(false)
scrollState.reset()
}
}
return super.onTouchEvent(event)
}
override fun canScrollHorizontally(dx: Int): Boolean =
super.canScrollHorizontally(dx) ||
dx < 0 && scrollState.canScrollLeft ||
dx > 0 && scrollState.canScrollRight
private inner class OnScrollWebListener {
@JavascriptInterface
fun onScroll(offsetWidth: Float, scrollWidth: Float, scrollLeft: Float) {
scrollState.canScrollLeft = scrollLeft > 0
scrollState.canScrollRight = offsetWidth + scrollLeft < scrollWidth
}
}
private class ScrollState(
internal var canScrollLeft: Boolean = false,
internal var canScrollRight: Boolean = false
) {
internal fun reset() {
canScrollLeft = false
canScrollRight = false
}
}
} | apache-2.0 | 492892c2ea7239a45595ffab13b9a7de | 31.283951 | 106 | 0.634347 | 4.882353 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/cache/certificates/structure/DbStructureCertificate.kt | 1 | 993 | package org.stepik.android.cache.certificates.structure
import androidx.sqlite.db.SupportSQLiteDatabase
object DbStructureCertificate {
const val TABLE_NAME = "certificate"
object Columns {
const val ID = "id"
const val USER = "user"
const val COURSE = "course"
const val ISSUE_DATE = "issue_date"
const val UPDATE_DATE = "update_date"
const val GRADE = "grade"
const val TYPE = "type"
const val URL = "url"
}
fun createTable(db: SupportSQLiteDatabase) {
db.execSQL("""
CREATE TABLE IF NOT EXISTS $TABLE_NAME (
${Columns.ID} LONG PRIMARY KEY,
${Columns.USER} LONG,
${Columns.COURSE} LONG,
${Columns.ISSUE_DATE} LONG,
${Columns.UPDATE_DATE} LONG,
${Columns.GRADE} TEXT,
${Columns.TYPE} INTEGER,
${Columns.URL} TEXT
)
""".trimIndent())
}
} | apache-2.0 | 000490d2f389909e493df24a7a6f88f9 | 29.121212 | 55 | 0.545821 | 4.493213 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step_quiz_fullscreen_code/ui/adapter/CodeStepQuizFullScreenPagerAdapter.kt | 2 | 1847 | package org.stepik.android.view.step_quiz_fullscreen_code.ui.adapter
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.viewpager.widget.PagerAdapter
import org.stepic.droid.R
class CodeStepQuizFullScreenPagerAdapter(
private val context: Context,
isShowRunCode: Boolean
) : PagerAdapter() {
private val layouts: List<Pair<View, String>>
init {
val result = listOf(
inflateLayout(R.layout.layout_step_quiz_code_fullscreen_instruction, R.string.step_quiz_code_full_screen_instruction_tab),
inflateLayout(R.layout.layout_step_quiz_code_fullscreen_playground, R.string.step_quiz_code_full_screen_code_tab)
)
layouts = if (isShowRunCode) {
result + listOf(inflateLayout(R.layout.layout_step_quiz_code_fullscreen_run_code, R.string.step_quiz_code_full_screen_run_code_tab))
} else {
result
}
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = layouts[position].first
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, view: Any) {
container.removeView(layouts[position].first)
}
override fun isViewFromObject(p0: View, p1: Any): Boolean =
p0 == p1
override fun getPageTitle(position: Int): CharSequence =
layouts[position].second
override fun getCount(): Int =
layouts.size
fun getViewAt(position: Int): View =
layouts[position].first
private fun inflateLayout(@LayoutRes layoutId: Int, @StringRes stringId: Int): Pair<View, String> =
View.inflate(context, layoutId, null) to context.resources.getString(stringId)
} | apache-2.0 | 7dba1e32b2d5a30dd87e0388bfa673f0 | 33.222222 | 144 | 0.700054 | 4.131991 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/util/Converting.kt | 1 | 1219 | package org.walleth.util
import java.math.BigDecimal
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.*
// ENGLISH is used until Android O becomes the minSDK or the support-lib fixes this problem:
// https://stackoverflow.com/questions/3821539/decimal-separator-comma-with-numberdecimal-inputtype-in-edittext
val inputDecimalFormat = (NumberFormat.getInstance(Locale.ENGLISH) as DecimalFormat).apply {
isParseBigDecimal = true
}
private fun getDecimalFormatUS(): DecimalFormat = NumberFormat.getInstance(Locale.ENGLISH) as DecimalFormat
val sixDigitDecimalFormat = getDecimalFormat(6)
val twoDigitDecimalFormat = getDecimalFormat(2)
private val endingWithOneNumber = "^.*\\.[0-9]$".toRegex()
fun String.stripTrailingZeros() = trimEnd('0').trimEnd('.')
fun String.adjustToMonetary2DecimalsWhenNeeded() = if (endingWithOneNumber.matches(this)) "${this}0" else this
private fun getDecimalFormat(decimals: Int) = getDecimalFormatUS().apply {
applyPattern("#0." + "0".repeat(decimals))
isGroupingUsed = false
}
fun String.asBigDecimal() = inputDecimalFormat.parseObject(this).let {
when (it) {
is Double -> BigDecimal(it)
else -> it as BigDecimal
}
} | gpl-3.0 | c8b53a7a252f2d5f39b817b5c7acf58c | 33.857143 | 111 | 0.76128 | 3.98366 | false | false | false | false |
apollostack/apollo-android | apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/internal/ApolloConvertSchemaTask.kt | 1 | 2410 | package com.apollographql.apollo3.gradle.internal
import com.apollographql.apollo3.compiler.introspection.IntrospectionSchema
import com.apollographql.apollo3.compiler.introspection.IntrospectionSchema.Companion.wrap
import com.apollographql.apollo3.compiler.introspection.toIntrospectionSchema
import com.apollographql.apollo3.compiler.introspection.toSchema
import com.apollographql.apollo3.compiler.toJson
import com.apollographql.apollo3.graphql.ast.GraphQLParser
import com.apollographql.apollo3.graphql.ast.toUtf8WithIndents
import org.gradle.api.DefaultTask
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import java.io.File
abstract class ApolloConvertSchemaTask: DefaultTask() {
@get:Input
@get:Option(option = "from", description = "schema to convert from")
abstract val from: Property<String>
// Even if this is points to an output file, for the purpose of the task this is seen as an input
@get:Input
@get:Option(option = "to", description = "schema to convert to")
abstract val to: Property<String>
init {
/**
* This task is really meant to be called from the command line so don't do any up-to-date checks
* If someone wants to register its own conversion task, it should be easy to do using the
* compiler APIs directly (see [convert] below)
* This code actually redundant because the task has no output but adding it make it explicit.
*/
outputs.upToDateWhen { false }
outputs.cacheIf { false }
}
private fun File.isIntrospection() = extension == "json"
fun convert(from: File, to: File) {
check (from.isIntrospection() && !to.isIntrospection() || !from.isIntrospection() && to.isIntrospection()) {
"Cannot convert from ${from.name} to ${to.name}, they are already the same format"
}
if (from.isIntrospection()) {
IntrospectionSchema(from).toSchema().toDocument().toUtf8WithIndents().let {
to.writeText(it)
}
} else {
GraphQLParser.parseSchema(from).toIntrospectionSchema().wrap().toJson(to)
}
}
@TaskAction
fun taskAction() {
// Do not use Project.file() as from the command line, we expect the file to be resolved based on cwd
convert(File(from.get()), File(to.get()))
}
}
| mit | 6541a53a0d0b8abfd1e2266b34495f1d | 39.166667 | 112 | 0.743154 | 3.970346 | false | false | false | false |
redutan/nbase-arc-monitoring | src/main/kotlin/io/redutan/nbasearc/monitoring/collector/LogType.kt | 1 | 836 | package io.redutan.nbasearc.monitoring.collector
import io.redutan.nbasearc.monitoring.collector.parser.LatencyParser
import io.redutan.nbasearc.monitoring.collector.parser.StatParser
import kotlin.reflect.KClass
/**
*
* @author myeongju.jung
*/
interface LogType<T : NbaseArcLog> {
val parser: Parser<T>
val command: String
val logClass: KClass<T>
}
object LatencyType: LogType<Latency> {
override val parser: Parser<Latency>
get() = LatencyParser()
override val command: String
get() = "-l"
override val logClass: KClass<Latency>
get() = Latency::class
}
object StatType: LogType<Stat> {
override val parser: Parser<Stat>
get() = StatParser()
override val command: String
get() = "-s"
override val logClass: KClass<Stat>
get() = Stat::class
} | apache-2.0 | aef34320d08cfbc93107b34ee22e69d0 | 23.617647 | 68 | 0.680622 | 3.8 | false | false | false | false |
jainsahab/AndroidSnooper | Snooper/src/main/java/com/prateekj/snooper/infra/BackgroundManager.kt | 1 | 2828 | package com.prateekj.snooper.infra
import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import android.os.Handler
import com.prateekj.snooper.utils.Logger
import java.util.ArrayList
class BackgroundManager private constructor(application: Application) :
ActivityLifecycleCallbacks {
private var isInBackground = true
private val listeners = ArrayList<Listener>()
private val mBackgroundDelayHandler = Handler()
private var mBackgroundTransition: Runnable? = null
interface Listener {
fun onBecameForeground()
fun onBecameBackground()
}
init {
application.registerActivityLifecycleCallbacks(this)
}
fun registerListener(listener: Listener) {
listeners.add(listener)
}
fun unregisterListener(listener: Listener) {
listeners.remove(listener)
}
override fun onActivityResumed(activity: Activity?) {
if (mBackgroundTransition != null) {
mBackgroundDelayHandler.removeCallbacks(mBackgroundTransition)
mBackgroundTransition = null
}
if (isInBackground) {
isInBackground = false
notifyOnBecameForeground()
Logger.d(TAG, "Application went to foreground")
}
}
private fun notifyOnBecameForeground() {
for (listener in listeners) {
try {
listener.onBecameForeground()
} catch (e: Exception) {
Logger.e(TAG, "Listener threw exception!", e)
}
}
}
override fun onActivityPaused(activity: Activity?) {
if (!isInBackground && mBackgroundTransition == null) {
mBackgroundTransition = Runnable {
isInBackground = true
mBackgroundTransition = null
notifyOnBecameBackground()
Logger.d(TAG, "Application went to background")
}
mBackgroundDelayHandler.postDelayed(mBackgroundTransition, BACKGROUND_DELAY)
}
}
private fun notifyOnBecameBackground() {
for (listener in listeners) {
try {
listener.onBecameBackground()
} catch (e: Exception) {
Logger.e(TAG, "Listener threw exception!", e)
}
}
}
override fun onActivityStopped(activity: Activity?) {}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {}
override fun onActivityStarted(activity: Activity?) {}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {}
override fun onActivityDestroyed(activity: Activity?) {}
companion object {
private const val BACKGROUND_DELAY: Long = 500
private val TAG = BackgroundManager::class.java.simpleName
private var INSTANCE: BackgroundManager? = null
fun getInstance(application: Application): BackgroundManager {
return INSTANCE ?: BackgroundManager(application).also { INSTANCE = it }
}
}
}
| apache-2.0 | 979f5047a2e58355536b2824282a56fe | 24.944954 | 85 | 0.714286 | 4.918261 | false | false | false | false |
k9mail/k-9 | app/core/src/test/java/com/fsck/k9/notification/AuthenticationErrorNotificationControllerTest.kt | 2 | 5072 | package com.fsck.k9.notification
import android.app.Notification
import android.app.PendingIntent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.test.core.app.ApplicationProvider
import com.fsck.k9.Account
import com.fsck.k9.RobolectricTest
import com.fsck.k9.testing.MockHelper.mockBuilder
import org.junit.Test
import org.mockito.Mockito.verify
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
private const val INCOMING = true
private const val OUTGOING = false
private const val ACCOUNT_NUMBER = 1
private const val ACCOUNT_NAME = "TestAccount"
class AuthenticationErrorNotificationControllerTest : RobolectricTest() {
private val resourceProvider = TestNotificationResourceProvider()
private val notification = mock<Notification>()
private val lockScreenNotification = mock<Notification>()
private val notificationManager = mock<NotificationManagerCompat>()
private val builder = createFakeNotificationBuilder(notification)
private val lockScreenNotificationBuilder = createFakeNotificationBuilder(lockScreenNotification)
private val notificationHelper = createFakeNotificationHelper(
notificationManager,
builder,
lockScreenNotificationBuilder
)
private val account = createFakeAccount()
private val controller = TestAuthenticationErrorNotificationController()
private val contentIntent = mock<PendingIntent>()
@Test
fun showAuthenticationErrorNotification_withIncomingServer_shouldCreateNotification() {
val notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING)
controller.showAuthenticationErrorNotification(account, INCOMING)
verify(notificationManager).notify(notificationId, notification)
assertAuthenticationErrorNotificationContents()
}
@Test
fun clearAuthenticationErrorNotification_withIncomingServer_shouldCancelNotification() {
val notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING)
controller.clearAuthenticationErrorNotification(account, INCOMING)
verify(notificationManager).cancel(notificationId)
}
@Test
fun showAuthenticationErrorNotification_withOutgoingServer_shouldCreateNotification() {
val notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING)
controller.showAuthenticationErrorNotification(account, OUTGOING)
verify(notificationManager).notify(notificationId, notification)
assertAuthenticationErrorNotificationContents()
}
@Test
fun clearAuthenticationErrorNotification_withOutgoingServer_shouldCancelNotification() {
val notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING)
controller.clearAuthenticationErrorNotification(account, OUTGOING)
verify(notificationManager).cancel(notificationId)
}
private fun assertAuthenticationErrorNotificationContents() {
verify(builder).setSmallIcon(resourceProvider.iconWarning)
verify(builder).setTicker("Authentication failed")
verify(builder).setContentTitle("Authentication failed")
verify(builder).setContentText("Authentication failed for $ACCOUNT_NAME. Update your server settings.")
verify(builder).setContentIntent(contentIntent)
verify(builder).setPublicVersion(lockScreenNotification)
verify(lockScreenNotificationBuilder).setContentTitle("Authentication failed")
verify(lockScreenNotificationBuilder, never()).setContentText(any())
verify(lockScreenNotificationBuilder, never()).setTicker(any())
}
private fun createFakeNotificationBuilder(notification: Notification): NotificationCompat.Builder {
return mockBuilder {
on { build() } doReturn notification
}
}
private fun createFakeNotificationHelper(
notificationManager: NotificationManagerCompat,
notificationBuilder: NotificationCompat.Builder,
lockScreenNotificationBuilder: NotificationCompat.Builder
): NotificationHelper {
return mock {
on { getContext() } doReturn ApplicationProvider.getApplicationContext()
on { getNotificationManager() } doReturn notificationManager
on { createNotificationBuilder(any(), any()) }.doReturn(notificationBuilder, lockScreenNotificationBuilder)
}
}
private fun createFakeAccount(): Account {
return mock {
on { accountNumber } doReturn ACCOUNT_NUMBER
on { displayName } doReturn ACCOUNT_NAME
}
}
internal inner class TestAuthenticationErrorNotificationController :
AuthenticationErrorNotificationController(notificationHelper, mock(), resourceProvider) {
override fun createContentIntent(account: Account, incoming: Boolean): PendingIntent {
return contentIntent
}
}
}
| apache-2.0 | d70adf252d09c9fb8005084c502ada4a | 40.917355 | 119 | 0.767942 | 6.045292 | false | true | false | false |
danysantiago/kotlin-cursor | kotlincursor-compiler/src/main/java/kotlincursor/processor/KCursorDataProcessor.kt | 1 | 2195 | package kotlincursor.processor
import com.google.auto.service.AutoService
import kotlincursor.annotation.KCursorData
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.Filer
import javax.annotation.processing.Messager
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.Processor
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
import javax.tools.Diagnostic
import javax.tools.StandardLocation
@AutoService(Processor::class)
class KCursorDataProcessor : AbstractProcessor() {
val messager: Messager by lazy { processingEnv.messager }
val elements: Elements by lazy { processingEnv.elementUtils }
val types: Types by lazy { processingEnv.typeUtils }
val filer: Filer by lazy { processingEnv.filer }
override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
messager.printMessage(Diagnostic.Kind.OTHER, "Initialized KotlinCursorProcessor")
}
override fun getSupportedAnnotationTypes() = setOf(KCursorData::class.java.canonicalName)
override fun getSupportedSourceVersion() = SourceVersion.RELEASE_8
override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean {
val cursorDataClass = KCursorDataClass(messager, elements, types)
roundEnv.getElementsAnnotatedWith(KCursorData::class.java).forEach {
if (it is TypeElement) {
val kotlinFile = cursorDataClass.generateKotlinFile(it)
val file = filer.createResource(StandardLocation.SOURCE_OUTPUT,
kotlinFile.packageName, "${kotlinFile.fileName}.kt", it)
file.openWriter().use {
kotlinFile.writeTo(it)
}
} else {
messager.printMessage(Diagnostic.Kind.WARNING, "Found element annotated with " +
"${KCursorData::class} but its not a data class!", it)
}
}
return true
}
}
| apache-2.0 | 98aafa368d23bfc70ec049f733c9fed2 | 38.196429 | 105 | 0.722096 | 5.140515 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day02.kt | 1 | 1751 | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.*
class Day02 : Day(title = "Inventory Management System") {
override fun first(input: Sequence<String>): Any = input
.asSequence()
.map { id -> id.groupingBy { it }.eachCount().values }
.fold(Pair(0, 0)) { (twos, threes), counts ->
Pair(
if (2 in counts) twos + 1 else twos,
if (3 in counts) threes + 1 else threes
)
}.let { (twos, threes) -> twos * threes }
override fun second(input: Sequence<String>): Any = input
.toList()
.tails()
.asSequence()
.flatMap { c -> c.head.let { head -> c.tail.map { Pair(head, it) }.asSequence() } }
.mapNotNull { (current, other) ->
current.extractCommonCharacters(other).takeIf { it.length == current.length - 1 }
}
.first()
private fun String.extractCommonCharacters(other: String): String =
this.iterator().extractCommonCharacters(other.iterator())
private fun CharIterator.extractCommonCharacters(other: CharIterator): String {
tailrec fun extractCommon(
t: Char,
o: Char,
diffs: Int,
acc: StringBuilder
): StringBuilder =
if (diffs > 1) acc
else if (!this.hasNext() || !other.hasNext()) acc.applyIf({ t == o }) { append(t) }
else if (t == o) extractCommon(this.next(), other.next(), diffs, acc.append(t))
else extractCommon(this.next(), other.next(), diffs + 1, acc)
return extractCommon(this.next(), other.next(), 0, StringBuilder()).toString()
}
}
| mit | 75d7b7cd416ef195ffdf8371a4577a87 | 38.795455 | 95 | 0.584238 | 4.053241 | false | false | false | false |
kittttttan/pe | kt/pe/src/main/kotlin/ktn/pe/Pe10.kt | 1 | 1066 | package ktn.pe
import java.util.Arrays
class Pe10 : Pe {
private var limit = 2000000
override val problemNumber: Int
get() = 10
fun pe10(n: Int = limit): Long {
if (n < 2) {
return 0
}
val primes = BooleanArray(n + 1)
Arrays.fill(primes, true)
primes[0] = false
primes[1] = false
val sq = Math.sqrt(n.toDouble()).toInt()
for (i in 2 until sq + 1) {
if (primes[i]) {
var j = i * i
while (j < n + 1) {
primes[j] = false
j += i
}
}
}
return (0 until n + 1)
.filter { primes[it] }
.map { it.toLong() }
.sum()
}
override fun run() {
solve()
}
override fun setArgs(args: Array<String>) {
if (args.isNotEmpty()) {
limit = args[0].toInt()
}
}
override fun solve() {
System.out.println(PeUtils.format(this, pe10()))
}
}
| mit | f25d07dd93b52e4a801f8ecc2227d81a | 19.5 | 56 | 0.424015 | 3.904762 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/presentation/devdb/device/DevicePresenter.kt | 1 | 2329 | package forpdateam.ru.forpda.presentation.devdb.device
import moxy.InjectViewState
import forpdateam.ru.forpda.common.Utils
import forpdateam.ru.forpda.common.mvp.BasePresenter
import forpdateam.ru.forpda.entity.remote.devdb.Device
import forpdateam.ru.forpda.model.repository.devdb.DevDbRepository
import forpdateam.ru.forpda.presentation.IErrorHandler
import forpdateam.ru.forpda.presentation.ILinkHandler
import forpdateam.ru.forpda.presentation.Screen
import forpdateam.ru.forpda.presentation.TabRouter
/**
* Created by radiationx on 11.11.17.
*/
@InjectViewState
class DevicePresenter(
private val devDbRepository: DevDbRepository,
private val router: TabRouter,
private val linkHandler: ILinkHandler,
private val errorHandler: IErrorHandler
) : BasePresenter<DeviceView>() {
var deviceId: String? = null
var currentData: Device? = null
override fun onFirstViewAttach() {
super.onFirstViewAttach()
loadBrand()
}
fun loadBrand() {
devDbRepository
.getDevice(deviceId.orEmpty())
.doOnSubscribe { viewState.setRefreshing(true) }
.doAfterTerminate { viewState.setRefreshing(false) }
.subscribe({
currentData = it
viewState.showData(it)
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
fun openSearch() {
router.navigateTo(Screen.DevDbSearch())
}
fun copyLink() {
currentData?.let {
Utils.copyToClipBoard("https://4pda.to/index.php?p=${it.id}")
}
}
fun shareLink() {
currentData?.let {
Utils.shareText("https://4pda.to/devdb/${it.id}")
}
}
fun createNote() {
currentData?.let {
val title = "DevDb: ${it.brandTitle} ${it.title}"
val url = "https://4pda.to/devdb/${it.id}"
viewState.showCreateNote(title, url)
}
}
fun openDevices() {
currentData?.let {
linkHandler.handle("https://4pda.to/devdb/${it.catId}/${it.brandId}", router)
}
}
fun openBrands() {
currentData?.let {
linkHandler.handle("https://4pda.to/devdb/${it.catId}", router)
}
}
}
| gpl-3.0 | 38e7d55af7e00f24983f4f8cd3979131 | 27.060241 | 89 | 0.609274 | 4.369606 | false | false | false | false |
edwardharks/Aircraft-Recognition | app/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/filter/picker/FilterPickerRecyclerView.kt | 1 | 5254 | package com.edwardharker.aircraftrecognition.ui.filter.picker
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.edwardharker.aircraftrecognition.R
import com.edwardharker.aircraftrecognition.analytics.Events.selectFilterOptionEvent
import com.edwardharker.aircraftrecognition.analytics.eventAnalytics
import com.edwardharker.aircraftrecognition.filter.picker.FilterPickerView
import com.edwardharker.aircraftrecognition.model.Filter
import com.edwardharker.aircraftrecognition.ui.SlowScrollingLinearLayoutManager
import java.lang.Math.abs
import java.lang.Math.min
import java.util.*
class FilterPickerRecyclerView : RecyclerView, FilterPickerView {
private val pickerHeight by lazy {
resources.getDimensionPixelSize(R.dimen.filter_picker_height)
}
private val adapter = Adapter()
private val linearLayoutManager: LinearLayoutManager by lazy {
SlowScrollingLinearLayoutManager(context)
}
private val presenter = filterPickerPresenter()
private val eventAnalytics = eventAnalytics()
var scrollOnSelection = true
var showFilterListener: (() -> Unit)? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
context,
attrs,
defStyle
)
init {
clipToPadding = false
layoutManager = linearLayoutManager
setAdapter(adapter)
addOnScrollListener(ScrollListener())
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
setPadding(paddingLeft, paddingTop, paddingRight, h - pickerHeight)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
presenter.startPresenting(this)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
presenter.stopPresenting()
}
override fun showFilters(filters: List<Filter>) {
val firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition()
val currentFilter = if (firstVisibleItemPosition >= 0) {
adapter.filters[firstVisibleItemPosition]
} else null
adapter.update(filters)
val newPosition = adapter.filters.indexOf(currentFilter)
if (newPosition >= 0) {
scrollToPosition(newPosition)
}
showFilterListener?.invoke()
}
fun clearFilters() {
adapter.update(emptyList())
}
private fun snap() {
val position = linearLayoutManager.findFirstVisibleItemPosition()
if (position >= 0) {
val view = linearLayoutManager.findViewByPosition(position)!!
val scrollPos = if (abs(view.top) > view.height / 2) {
min(adapter.itemCount, position + 1)
} else {
position
}
smoothScrollToPosition(scrollPos)
}
}
private fun onFilterOptionSelected() {
handler.postDelayed({
val firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition()
if (scrollOnSelection && firstVisibleItemPosition < linearLayoutManager.itemCount - 1) {
smoothScrollToPosition(firstVisibleItemPosition + 1)
}
}, AUTO_SCROLL_DELAY)
}
private inner class ScrollListener : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (newState == SCROLL_STATE_IDLE) {
snap()
}
}
}
private inner class Adapter : RecyclerView.Adapter<ViewHolder>() {
private val _filters = ArrayList<Filter>()
val filters: List<Filter> = _filters
fun update(filters: List<Filter>) {
_filters.clear()
_filters.addAll(filters)
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val filter = filters[position]
holder.view.bindTo(filter)
holder.view.selectionListener = { selectedFilter, selectedFilterOption ->
onFilterOptionSelected()
eventAnalytics.logEvent(
selectFilterOptionEvent(
filter = selectedFilter,
filterOption = selectedFilterOption
)
)
}
}
override fun getItemCount(): Int = filters.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(FilterPicker(parent.context))
}
private inner class ViewHolder(val view: FilterPicker) : RecyclerView.ViewHolder(view) {
init {
view.layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
}
}
private companion object {
private const val AUTO_SCROLL_DELAY = 200L
}
}
| gpl-3.0 | 1c1d728f9903cb3e1a0e1dcc084612b9 | 33.116883 | 100 | 0.664065 | 5.427686 | false | false | false | false |
ingokegel/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitWorkflow.kt | 1 | 4300 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbService.isDumb
import com.intellij.openapi.project.DumbService.isDumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.checkin.CheckinMetaHandler
import com.intellij.openapi.vcs.checkin.CommitCheck
import com.intellij.openapi.vcs.checkin.CommitProblem
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
private val LOG = logger<NonModalCommitWorkflow>()
abstract class NonModalCommitWorkflow(project: Project) : AbstractCommitWorkflow(project) {
suspend fun executeBackgroundSession(sessionInfo: CommitSessionInfo, checker: suspend () -> CommitChecksResult) {
var result: CommitChecksResult = CommitChecksResult.ExecutionError
try {
result = checkCommit(sessionInfo, checker)
}
finally {
if (result.shouldCommit) {
performCommit(sessionInfo)
}
else {
endExecution()
}
}
}
private suspend fun checkCommit(sessionInfo: CommitSessionInfo, checker: suspend () -> CommitChecksResult): CommitChecksResult {
var result: CommitChecksResult = CommitChecksResult.ExecutionError
fireBeforeCommitChecksStarted(sessionInfo)
try {
result = checker()
}
catch (e: ProcessCanceledException) {
result = CommitChecksResult.Cancelled
}
finally {
fireBeforeCommitChecksEnded(sessionInfo, result)
}
return result
}
suspend fun runMetaHandlers(metaHandlers: List<CheckinMetaHandler>, commitProgressUi: CommitProgressUi, indicator: ProgressIndicator) {
// reversed to have the same order as when wrapping meta handlers into each other
for (metaHandler in metaHandlers.reversed()) {
if (metaHandler is CommitCheck<*>) {
runCommitCheck(metaHandler, commitProgressUi, indicator)
}
else {
suspendCancellableCoroutine<Unit> { continuation ->
val handlerCall = wrapWithCommitMetaHandler(metaHandler) { continuation.resume(Unit) }
handlerCall.run()
}
}
}
}
suspend fun runCommitChecks(commitChecks: List<CommitCheck<*>>,
commitProgressUi: CommitProgressUi,
indicator: ProgressIndicator): Boolean {
for (commitCheck in commitChecks) {
val success = runCommitCheck(commitCheck, commitProgressUi, indicator)
if (!success) return false
}
return true
}
/**
* @return true if there are no errors and commit shall proceed
*/
private suspend fun <P : CommitProblem> runCommitCheck(commitCheck: CommitCheck<P>,
commitProgressUi: CommitProgressUi,
indicator: ProgressIndicator): Boolean {
if (!commitCheck.isEnabled()) return true.also { LOG.debug("Commit check disabled $commitCheck") }
if (isDumb(project) && !isDumbAware(commitCheck)) return true.also { LOG.debug("Skipped commit check in dumb mode $commitCheck") }
LOG.debug("Running commit check $commitCheck")
indicator.checkCanceled()
indicator.text = ""
indicator.text2 = ""
try {
val problem = commitCheck.runCheck(indicator)
problem?.let { commitProgressUi.addCommitCheckFailure(it.text) { commitCheck.showDetails(it) } }
return problem == null
}
catch (e: Throwable) {
// Do not report error on cancellation
// DO report error if someone threw PCE for no reason, ex: IDEA-234006
if (e is ProcessCanceledException && indicator.isCanceled) throw e
LOG.warn(Throwable(e))
val err = e.message
val message = when {
err.isNullOrBlank() -> VcsBundle.message("before.checkin.error.unknown")
else -> VcsBundle.message("before.checkin.error.unknown.details", err)
}
commitProgressUi.addCommitCheckFailure(message, null)
return false
}
}
} | apache-2.0 | 40d5383e0cfe9baf9780fc50b2d57434 | 37.401786 | 140 | 0.69907 | 4.925544 | false | false | false | false |
MRylander/RylandersRealm | src/main/kotlin/rylandersrealm/Environment/Environment.kt | 1 | 1350 | /*
* Copyright 2017 Michael S Rylander
*
* 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 rylandersrealm.Environment
import rylandersrealm.target.Entrance
object LocationFactory {
fun createStartingLocation(): Location {
val firstRoom = Location("This is the first room.")
val secondRoom = Location("This is the second room.")
val thirdRoom = Location("This is the third room.")
Entrance.createAndLink(
location = firstRoom,
orientation = "east",
otherLocation = secondRoom,
otherOrientation = "west")
Entrance.createAndLink(
location = secondRoom,
orientation = "east",
otherLocation = thirdRoom,
otherOrientation = "west")
return firstRoom
}
}
| apache-2.0 | 939c792847ac3be2b7fb6019cededcc5 | 33.615385 | 75 | 0.657778 | 4.607509 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/utilities/MediaIntentHandler.kt | 1 | 2109 | package com.kelsos.mbrc.utilities
import android.content.Intent
import android.view.KeyEvent
import com.kelsos.mbrc.constants.Protocol
import com.kelsos.mbrc.constants.ProtocolEventType
import com.kelsos.mbrc.data.UserAction
import com.kelsos.mbrc.events.MessageEvent
import com.kelsos.mbrc.events.bus.RxBus
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MediaIntentHandler
@Inject
constructor(private val bus: RxBus) {
private var previousClick: Long = 0
init {
previousClick = 0
}
fun handleMediaIntent(mediaIntent: Intent?): Boolean {
var result = false
if (mediaIntent?.action == Intent.ACTION_MEDIA_BUTTON) {
val extras = mediaIntent.extras
val keyEvent = extras?.get(Intent.EXTRA_KEY_EVENT) as KeyEvent?
if (keyEvent?.action != KeyEvent.ACTION_DOWN) {
return false
}
result = when (keyEvent.keyCode) {
KeyEvent.KEYCODE_HEADSETHOOK -> {
val currentClick = System.currentTimeMillis()
if (currentClick - previousClick < DOUBLE_CLICK_INTERVAL) {
return postAction(UserAction(Protocol.PlayerNext, true))
}
previousClick = currentClick
postAction(UserAction(Protocol.PlayerPlayPause, true))
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE ->
postAction(UserAction(Protocol.PlayerPlayPause, true))
KeyEvent.KEYCODE_MEDIA_PLAY -> postAction(UserAction(Protocol.PlayerPlay, true))
KeyEvent.KEYCODE_MEDIA_PAUSE -> postAction(UserAction(Protocol.PlayerPause, true))
KeyEvent.KEYCODE_MEDIA_STOP -> postAction(UserAction(Protocol.PlayerStop, true))
KeyEvent.KEYCODE_MEDIA_NEXT -> postAction(UserAction(Protocol.PlayerNext, true))
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> postAction(UserAction(Protocol.PlayerPrevious, true))
else -> false
}
}
return result
}
private fun postAction(action: UserAction): Boolean {
bus.post(MessageEvent(ProtocolEventType.UserAction, action))
return true
}
companion object {
private const val DOUBLE_CLICK_INTERVAL = 350
}
}
| gpl-3.0 | a6085c185e76dddc3be8d9693d6c7152 | 32.47619 | 96 | 0.708867 | 4.348454 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/DynamicPluginEnabler.kt | 2 | 9943 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.intellij.application.options.RegistryManager
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.IdeBundle
import com.intellij.ide.feedback.kotlinRejecters.recordKotlinPluginDisabling
import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.components.*
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.startup.InitProjectActivity
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.project.stateStore
import com.intellij.util.xmlb.annotations.XCollection
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
@State(
name = "DynamicPluginEnabler",
storages = [Storage(value = StoragePathMacros.NON_ROAMABLE_FILE)],
reloadable = false,
)
@ApiStatus.Internal
class DynamicPluginEnabler : SimplePersistentStateComponent<DynamicPluginEnablerState>(DynamicPluginEnablerState()), PluginEnabler {
companion object {
private val isPerProjectEnabledValue: RegistryValue
get() = RegistryManager.getInstance().get("ide.plugins.per.project")
@JvmStatic
var isPerProjectEnabled: Boolean
get() = isPerProjectEnabledValue.asBoolean()
set(value) = isPerProjectEnabledValue.setValue(value)
@JvmStatic
@JvmOverloads
fun findPluginTracker(project: Project, pluginEnabler: PluginEnabler = PluginEnabler.getInstance()): ProjectPluginTracker? {
return (pluginEnabler as? DynamicPluginEnabler)?.getPluginTracker(project)
}
internal class EnableDisablePluginsActivity : InitProjectActivity {
private val dynamicPluginEnabler = PluginEnabler.getInstance() as? DynamicPluginEnabler
?: throw ExtensionNotApplicableException.create()
override suspend fun run(project: Project) {
val tracker = dynamicPluginEnabler.getPluginTracker(project)
val projects = openProjectsExcludingCurrent(project)
val pluginIdsToLoad = tracker.enabledPluginsIds
.union(dynamicPluginEnabler.locallyDisabledAndGloballyEnabledPlugins(projects))
val pluginIdsToUnload = tracker.disabledPluginsIds
if (pluginIdsToLoad.isEmpty() && pluginIdsToUnload.isEmpty()) {
return
}
val indicator = ProgressManager.getInstance().progressIndicator
withContext(Dispatchers.EDT) {
indicator?.let {
it.text = IdeBundle.message("plugins.progress.loading.plugins.for.current.project.title", project.name)
}
DynamicPlugins.loadPlugins(pluginIdsToLoad.toPluginDescriptors())
indicator?.let {
it.text = IdeBundle.message("plugins.progress.unloading.plugins.for.current.project.title", project.name)
}
dynamicPluginEnabler.unloadPlugins(
pluginIdsToUnload.toPluginDescriptors(),
project,
projects,
)
}
}
}
private fun openProjectsExcludingCurrent(project: Project?) = ProjectManager.getInstance().openProjects.filterNot { it == project }
}
val trackers: Map<String, ProjectPluginTracker>
get(): Map<String, ProjectPluginTracker> = state.trackers
private var applicationShuttingDown = false
init {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectClosing(project: Project) {
if (applicationShuttingDown) {
return
}
val tracker = getPluginTracker(project)
val projects = openProjectsExcludingCurrent(project)
val descriptorsToLoad = if (projects.isNotEmpty()) {
emptyList()
}
else {
tracker.disabledPluginsIds
.filterNot { isDisabled(it) }
.toPluginDescriptors()
}
DynamicPlugins.loadPlugins(descriptorsToLoad)
val descriptorsToUnload = tracker.enabledPluginsIds
.union(locallyDisabledPlugins(projects))
.toPluginDescriptors()
unloadPlugins(
descriptorsToUnload,
project,
projects,
)
}
})
connection.subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener {
override fun appWillBeClosed(isRestart: Boolean) {
applicationShuttingDown = true
}
})
}
fun getPluginTracker(project: Project): ProjectPluginTracker = state.findStateByProject(project)
override fun isDisabled(pluginId: PluginId) = PluginEnabler.HEADLESS.isDisabled(pluginId)
override fun enable(descriptors: Collection<IdeaPluginDescriptor>) = updatePluginsState(descriptors, PluginEnableDisableAction.ENABLE_GLOBALLY)
override fun disable(descriptors: Collection<IdeaPluginDescriptor>) = updatePluginsState(descriptors, PluginEnableDisableAction.DISABLE_GLOBALLY)
@ApiStatus.Internal
@JvmOverloads
fun updatePluginsState(
descriptors: Collection<IdeaPluginDescriptor>,
action: PluginEnableDisableAction,
project: Project? = null,
parentComponent: JComponent? = null,
): Boolean {
assert(!action.isPerProject || project != null)
val pluginIds = descriptors.toPluginIdSet()
fun unloadExcessPlugins() = unloadPlugins(
descriptors,
project,
openProjectsExcludingCurrent(project),
parentComponent,
)
PluginManagerUsageCollector.pluginsStateChanged(descriptors, action, project)
recordKotlinPluginDisabling(descriptors, action)
return when (action) {
PluginEnableDisableAction.ENABLE_GLOBALLY -> {
state.stopTracking(pluginIds)
val loaded = DynamicPlugins.loadPlugins(descriptors)
PluginEnabler.HEADLESS.enableById(pluginIds)
loaded
}
PluginEnableDisableAction.ENABLE_FOR_PROJECT -> {
state.startTracking(project!!, pluginIds, true)
DynamicPlugins.loadPlugins(descriptors)
}
PluginEnableDisableAction.ENABLE_FOR_PROJECT_DISABLE_GLOBALLY -> {
PluginEnabler.HEADLESS.disableById(pluginIds)
descriptors.forEach { it.isEnabled = true }
state.startTracking(project!!, pluginIds, true)
true
}
PluginEnableDisableAction.DISABLE_GLOBALLY -> {
PluginEnabler.HEADLESS.disableById(pluginIds)
state.stopTracking(pluginIds)
unloadExcessPlugins()
}
PluginEnableDisableAction.DISABLE_FOR_PROJECT -> {
state.startTracking(project!!, pluginIds, false)
unloadExcessPlugins()
}
PluginEnableDisableAction.DISABLE_FOR_PROJECT_ENABLE_GLOBALLY ->
false
}
}
private fun unloadPlugins(
descriptors: Collection<IdeaPluginDescriptor>,
project: Project?,
projects: List<Project>,
parentComponent: JComponent? = null,
): Boolean {
val predicate = when (project) {
null -> { _: PluginId -> true }
else -> shouldUnload(projects)
}
return DynamicPlugins.unloadPlugins(
descriptors.filter { predicate(it.pluginId) },
project,
parentComponent,
)
}
private fun locallyDisabledPlugins(projects: List<Project>): Collection<PluginId> {
return projects
.map { getPluginTracker(it) }
.flatMap { it.disabledPluginsIds }
}
private fun locallyDisabledAndGloballyEnabledPlugins(projects: List<Project>): Collection<PluginId> {
return locallyDisabledPlugins(projects)
.filterNot { isDisabled(it) }
}
private fun shouldUnload(openProjects: List<Project>) = object : (PluginId) -> Boolean {
private val trackers = openProjects
.map { getPluginTracker(it) }
private val requiredPluginIds = openProjects
.map { ExternalDependenciesManager.getInstance(it) }
.flatMap { it.getDependencies(DependencyOnPlugin::class.java) }
.mapTo(HashSet()) { it.pluginId }
override fun invoke(pluginId: PluginId): Boolean {
return !requiredPluginIds.contains(pluginId.idString) &&
!trackers.any { it.isEnabled(pluginId) } &&
(isDisabled(pluginId) || trackers.all { it.isDisabled(pluginId) })
}
}
}
@ApiStatus.Internal
class DynamicPluginEnablerState : BaseState() {
@get:XCollection(propertyElementName = "trackers", style = XCollection.Style.v2)
internal val trackers by map<String, ProjectPluginTracker>()
fun startTracking(project: Project, pluginIds: Collection<PluginId>, enable: Boolean) {
val updated = findStateByProject(project)
.startTracking(pluginIds, enable)
if (updated) {
incrementModificationCount()
}
}
fun stopTracking(pluginIds: Collection<PluginId>) {
var updated = false
trackers.values.forEach {
updated = it.stopTracking(pluginIds) || updated
}
if (updated) {
incrementModificationCount()
}
}
internal fun findStateByProject(project: Project): ProjectPluginTracker {
val workspaceId = if (project.isDefault) null else project.stateStore.projectWorkspaceId
val projectName = project.name
return trackers.computeIfAbsent(workspaceId ?: projectName) {
ProjectPluginTracker().also {
it.projectName = projectName
incrementModificationCount()
}
}
}
} | apache-2.0 | ca5f080fd4a87d62149b9b92e5923c19 | 34.769784 | 147 | 0.722418 | 4.976476 | false | false | false | false |
ingokegel/intellij-community | plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreePopupStep.kt | 1 | 8952 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui.branch
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.components.service
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.PopupStep.FINAL_CHOICE
import com.intellij.openapi.ui.popup.SpeedSearchFilter
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.psi.codeStyle.MinusculeMatcher
import com.intellij.psi.codeStyle.NameUtil
import com.intellij.ui.popup.ActionPopupStep
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.util.PlatformIcons
import com.intellij.util.containers.FList
import git4idea.GitBranch
import git4idea.GitLocalBranch
import git4idea.actions.branch.GitBranchActionsUtil
import git4idea.branch.GitBranchType
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import icons.DvcsImplIcons
import javax.swing.Icon
import javax.swing.tree.TreeModel
import javax.swing.tree.TreePath
class GitBranchesTreePopupStep(private val project: Project, internal val repository: GitRepository) : PopupStep<Any> {
private var finalRunnable: Runnable? = null
override fun getFinalRunnable() = finalRunnable
private val _treeModel: GitBranchesTreeModel
val treeModel: TreeModel
get() = _treeModel
init {
val topLevelActions = mutableListOf<PopupFactoryImpl.ActionItem>()
val actionGroup = ActionManager.getInstance().getAction(TOP_LEVEL_ACTION_GROUP) as? ActionGroup
if (actionGroup != null) {
topLevelActions.addAll(createActionItems(actionGroup, project, repository))
}
_treeModel = GitBranchesTreeModelImpl(project, repository, topLevelActions)
}
fun getPreferredSelection(): TreePath? {
return _treeModel.getPreferredSelection()
}
internal fun isSeparatorAboveRequired(path: TreePath) = path.lastPathComponent == GitBranchType.LOCAL
private val LOCAL_SEARCH_PREFIX = "/l"
private val REMOTE_SEARCH_PREFIX = "/r"
fun setSearchPattern(pattern: String?) {
if (pattern == null || pattern == "/") {
_treeModel.filterBranches()
return
}
var branchType: GitBranchType? = null
var processedPattern = pattern
if (pattern.startsWith(LOCAL_SEARCH_PREFIX)) {
branchType = GitBranchType.LOCAL
processedPattern = pattern.removePrefix(LOCAL_SEARCH_PREFIX).trimStart()
}
if (pattern.startsWith(REMOTE_SEARCH_PREFIX)) {
branchType = GitBranchType.REMOTE
processedPattern = pattern.removePrefix(REMOTE_SEARCH_PREFIX).trimStart()
}
val matcher = PreferStartMatchMatcherWrapper(NameUtil.buildMatcher("*$processedPattern").build())
_treeModel.filterBranches(branchType, matcher)
}
override fun hasSubstep(selectedValue: Any?): Boolean {
val userValue = selectedValue ?: return false
return userValue is GitBranch ||
(userValue is PopupFactoryImpl.ActionItem && userValue.isEnabled && userValue.action is ActionGroup)
}
fun isSelectable(node: Any?): Boolean {
val userValue = node ?: return false
return userValue is GitBranch ||
(userValue is PopupFactoryImpl.ActionItem && userValue.isEnabled)
}
override fun onChosen(selectedValue: Any?, finalChoice: Boolean): PopupStep<out Any>? {
if (selectedValue is GitBranch) {
val actionGroup = ActionManager.getInstance().getAction(BRANCH_ACTION_GROUP) as? ActionGroup ?: DefaultActionGroup()
return createActionStep(actionGroup, project, repository, selectedValue)
}
if (selectedValue is PopupFactoryImpl.ActionItem) {
if (!selectedValue.isEnabled) return FINAL_CHOICE
val action = selectedValue.action
if (action is ActionGroup && (!finalChoice || !selectedValue.isPerformGroup)) {
return createActionStep(action, project, repository)
}
else {
finalRunnable = Runnable {
ActionUtil.invokeAction(action, createDataContext(project, repository), ACTION_PLACE, null, null)
}
}
}
return FINAL_CHOICE
}
override fun getTitle(): String =
DvcsBundle.message("branch.popup.vcs.name.branches.in.repo", repository.vcs.displayName, DvcsUtil.getShortRepositoryName(repository))
fun getIcon(treeNode: Any?): Icon? {
val value = treeNode ?: return null
return when (value) {
is GitBranchesTreeModel.BranchesPrefixGroup -> PlatformIcons.FOLDER_ICON
is GitBranch -> getBranchIcon(value)
else -> null
}
}
private fun getBranchIcon(branch: GitBranch): Icon {
val isCurrent = repository.currentBranch == branch
val isFavorite = project.service<GitBranchManager>().isFavorite(GitBranchType.of(branch), repository, branch.name)
return when {
isCurrent && isFavorite -> DvcsImplIcons.CurrentBranchFavoriteLabel
isCurrent -> DvcsImplIcons.CurrentBranchLabel
isFavorite -> AllIcons.Nodes.Favorite
else -> AllIcons.Vcs.BranchNode
}
}
fun getText(treeNode: Any?): @NlsSafe String? {
val value = treeNode ?: return null
return when (value) {
GitBranchType.LOCAL -> GitBundle.message("group.Git.Local.Branch.title")
GitBranchType.REMOTE -> GitBundle.message("group.Git.Remote.Branch.title")
is GitBranchesTreeModel.BranchesPrefixGroup -> value.prefix.last()
is GitBranch -> value.name.split('/').last()
is PopupFactoryImpl.ActionItem -> value.text
else -> value.toString()
}
}
fun getSecondaryText(treeNode: Any?): @NlsSafe String? {
return when (treeNode) {
is PopupFactoryImpl.ActionItem -> KeymapUtil.getFirstKeyboardShortcutText(treeNode.action)
is GitLocalBranch -> treeNode.findTrackedBranch(repository)?.name
else -> null
}
}
override fun canceled() {}
override fun isMnemonicsNavigationEnabled() = false
override fun getMnemonicNavigationFilter() = null
override fun isSpeedSearchEnabled() = true
override fun getSpeedSearchFilter() = SpeedSearchFilter<Any> { node ->
when (node) {
is GitBranch -> node.name
else -> node?.let(::getText) ?: ""
}
}
override fun isAutoSelectionEnabled() = false
companion object {
private const val TOP_LEVEL_ACTION_GROUP = "Git.Branches.List"
private const val BRANCH_ACTION_GROUP = "Git.Branch"
internal val ACTION_PLACE = ActionPlaces.getPopupPlace("GitBranchesPopup")
private fun createActionItems(actionGroup: ActionGroup,
project: Project,
repository: GitRepository): List<PopupFactoryImpl.ActionItem> {
val dataContext = createDataContext(project, repository)
return ActionPopupStep
.createActionItems(actionGroup, dataContext, false, false, false, false, ACTION_PLACE, null)
}
private fun createActionStep(actionGroup: ActionGroup,
project: Project,
repository: GitRepository,
branch: GitBranch? = null): ListPopupStep<*> {
val dataContext = createDataContext(project, repository, branch)
return JBPopupFactory.getInstance()
.createActionsStep(actionGroup, dataContext, ACTION_PLACE, false, true, null, null, true, 0, false)
}
internal fun createDataContext(project: Project, repository: GitRepository, branch: GitBranch? = null): DataContext =
SimpleDataContext.builder()
.add(CommonDataKeys.PROJECT, project)
.add(GitBranchActionsUtil.REPOSITORIES_KEY, listOf(repository))
.add(GitBranchActionsUtil.BRANCHES_KEY, branch?.let(::listOf))
.build()
/**
* Adds weight to match offset. Degree of match is increased with the earlier the pattern was found in the name.
*/
private class PreferStartMatchMatcherWrapper(private val delegate: MinusculeMatcher) : MinusculeMatcher() {
override fun getPattern(): String = delegate.pattern
override fun matchingFragments(name: String): FList<TextRange>? = delegate.matchingFragments(name)
override fun matchingDegree(name: String, valueStartCaseMatch: Boolean, fragments: FList<out TextRange>?): Int {
var degree = delegate.matchingDegree(name, valueStartCaseMatch, fragments)
if (fragments.isNullOrEmpty()) return degree
degree += MATCH_OFFSET - fragments.head.startOffset
return degree
}
companion object {
private const val MATCH_OFFSET = 10000
}
}
}
}
| apache-2.0 | 8eadeb80d2268fdab3222761e8877e44 | 37.093617 | 137 | 0.723525 | 4.881134 | false | false | false | false |
mdaniel/intellij-community | platform/diagnostic/telemetry/src/trace.kt | 3 | 2224 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diagnostic.telemetry
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.SpanBuilder
import io.opentelemetry.api.trace.StatusCode
import io.opentelemetry.context.Context
import io.opentelemetry.semconv.trace.attributes.SemanticAttributes
import java.util.concurrent.Callable
import java.util.concurrent.CancellationException
import java.util.concurrent.ForkJoinTask
inline fun <T> createTask(spanBuilder: SpanBuilder, crossinline task: () -> T): ForkJoinTask<T> {
val context = Context.current()
return ForkJoinTask.adapt(Callable {
val thread = Thread.currentThread()
val span = spanBuilder
.setParent(context)
.setAttribute(SemanticAttributes.THREAD_NAME, thread.name)
.setAttribute(SemanticAttributes.THREAD_ID, thread.id)
.startSpan()
span.makeCurrent().use {
span.use {
task()
}
}
})
}
/**
* Returns a new [ForkJoinTask] that performs the given function as its action within a trace, and returns
* a null result upon [ForkJoinTask.join].
*
* See [Span](https://opentelemetry.io/docs/reference/specification).
*/
inline fun <T> forkJoinTask(spanBuilder: SpanBuilder, crossinline operation: () -> T): ForkJoinTask<T> {
val context = Context.current()
return ForkJoinTask.adapt(Callable {
val thread = Thread.currentThread()
spanBuilder
.setParent(context)
.setAttribute(SemanticAttributes.THREAD_NAME, thread.name)
.setAttribute(SemanticAttributes.THREAD_ID, thread.id)
.useWithScope {
operation()
}
})
}
inline fun <T> SpanBuilder.useWithScope(operation: (Span) -> T): T {
val span = startSpan()
return span.makeCurrent().use {
span.use(operation)
}
}
inline fun <T> SpanBuilder.use(operation: (Span) -> T): T {
return startSpan().use(operation)
}
inline fun <T> Span.use(operation: (Span) -> T): T {
try {
return operation(this)
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
recordException(e)
setStatus(StatusCode.ERROR)
throw e
}
finally {
end()
}
} | apache-2.0 | a469fad8bd6951697cde82e559871837 | 28.276316 | 120 | 0.707734 | 3.929329 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/common/feedback/WebUrlViewController.kt | 1 | 1753 | package io.ipoli.android.common.feedback
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebView
import com.bluelinelabs.conductor.RestoreViewOnCreateController
import io.ipoli.android.MyPoliApp
import io.ipoli.android.R
import io.ipoli.android.common.di.UIModule
import io.ipoli.android.common.view.inflate
import space.traversal.kapsule.Injects
import space.traversal.kapsule.inject
import space.traversal.kapsule.required
class WebUrlViewController(args: Bundle? = null) :
RestoreViewOnCreateController(
args
), Injects<UIModule> {
private val eventLogger by required { eventLogger }
private var url = ""
private var screenName = ""
constructor(
url: String,
screenName: String
) : this() {
this.url = url
this.screenName = screenName
}
override fun onContextAvailable(context: Context) {
inject(MyPoliApp.uiModule(context))
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
val view = container.inflate(R.layout.controller_feedback) as WebView
view.webChromeClient = WebChromeClient()
@SuppressLint("SetJavaScriptEnabled")
view.settings.javaScriptEnabled = true
view.settings.domStorageEnabled = true
view.loadUrl(url)
return view
}
override fun onAttach(view: View) {
super.onAttach(view)
eventLogger.logCurrentScreen(
activity!!,
screenName
)
}
} | gpl-3.0 | 5efc27ff819e105d68c883acd1106bd1 | 27.290323 | 77 | 0.706218 | 4.637566 | false | false | false | false |
fuzz-productions/Salvage | salvage-processor/src/main/java/com/fuzz/android/salvage/ClassNames.kt | 1 | 497 | package com.fuzz.android.salvage
import com.squareup.javapoet.ClassName
/**
* Description:
*
* @author Andrew Grosner (Fuzz)
*/
val PACKAGE = "com.fuzz.android.salvage"
val BUNDLE = ClassName.get("android.os", "Bundle")
val BUNDLE_PERSISTER = ClassName.get(PACKAGE, "BundlePersister")
val BASE_BUNDLE_PERSISTER = ClassName.get(PACKAGE, "BaseBundlePersister")
val SERIALIZABLE_PERSISTER = ClassName.get(PACKAGE, "SerializablePersister")
val SALVAGER = ClassName.get(PACKAGE, "Salvager") | apache-2.0 | a7d3a2159c09929cb5dc5580a29e3a2d | 22.714286 | 76 | 0.758551 | 3.248366 | false | false | false | false |
GunoH/intellij-community | platform/webSymbols/src/com/intellij/webSymbols/references/WebSymbolReferenceProvider.kt | 2 | 9210 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.webSymbols.references
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.model.Symbol
import com.intellij.model.psi.PsiExternalReferenceHost
import com.intellij.model.psi.PsiSymbolReference
import com.intellij.model.psi.PsiSymbolReferenceHints
import com.intellij.model.psi.PsiSymbolReferenceProvider
import com.intellij.model.search.SearchRequest
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.MultiMap
import com.intellij.webSymbols.WebSymbol
import com.intellij.webSymbols.WebSymbolNameSegment
import com.intellij.webSymbols.inspections.WebSymbolsInspectionsPass.Companion.getDefaultProblemMessage
import com.intellij.webSymbols.inspections.impl.WebSymbolsInspectionToolMappingEP
import com.intellij.webSymbols.utils.asSingleSymbol
import com.intellij.webSymbols.utils.getProblemKind
import com.intellij.webSymbols.utils.hasOnlyExtensions
import java.util.*
private const val IJ_IGNORE_REFS = "ij-no-psi-refs"
abstract class WebSymbolReferenceProvider<T : PsiExternalReferenceHost> : PsiSymbolReferenceProvider {
override fun getReferences(element: PsiExternalReferenceHost, hints: PsiSymbolReferenceHints): Collection<PsiSymbolReference> =
CachedValuesManager.getCachedValue(element, CachedValuesManager.getManager(element.project).getKeyForClass(this.javaClass)) {
@Suppress("UNCHECKED_CAST")
(CachedValueProvider.Result.create(getReferences(element as T),
PsiModificationTracker.MODIFICATION_COUNT))
}
override fun getSearchRequests(project: Project, target: Symbol): Collection<SearchRequest> = emptyList()
protected open fun getSymbol(psiElement: T): WebSymbol? = null
protected open fun getSymbolNameOffset(psiElement: T): Int = 0
protected open fun getOffsetsToSymbols(psiElement: T): Map<Int, WebSymbol> =
getSymbol(psiElement)
?.let { mapOf(getSymbolNameOffset(psiElement) to it) }
?: emptyMap()
protected open fun shouldShowProblems(element: T): Boolean = true
private fun getReferences(element: T): List<PsiSymbolReference> {
val showProblems = shouldShowProblems(element)
return getOffsetsToSymbols(element).flatMap { (offset, symbol) ->
getReferences(element, offset, symbol, showProblems)
}
}
private fun getReferences(element: T, symbolNameOffset: Int, symbol: WebSymbol, showProblems: Boolean): List<PsiSymbolReference> {
fun WebSymbol.removeZeroLengthSegmentsRecursively(): List<WebSymbol> {
val nameLength = matchedName.length
return nameSegments
.takeIf { it.size > 1 && it.none { segment -> segment.problem != null } }
?.find { segment -> segment.start == 0 && segment.end == nameLength }
?.let { segment -> segment.symbols.flatMap { it.removeZeroLengthSegmentsRecursively() } }
?: listOf(this)
}
val problemOnlyRanges = mutableMapOf<TextRange, Boolean>()
val result = MultiMap<TextRange, WebSymbolNameSegment>()
val queue = LinkedList(symbol.nameSegments.map { Pair(it, 0) })
while (queue.isNotEmpty()) {
val (nameSegment, offset) = queue.removeFirst()
val symbols = nameSegment.symbols
val range = TextRange(nameSegment.start + offset, nameSegment.end + offset)
if (symbols.any { it.properties[IJ_IGNORE_REFS] == true }) continue
if (symbols.all { it.nameSegments.size == 1 }) {
if (nameSegment.problem != null || symbols.let { it.isNotEmpty() && !it.hasOnlyExtensions() }) {
result.putValue(range, nameSegment)
problemOnlyRanges[range] = false
}
}
else {
if (nameSegment.problem != null) {
result.putValue(range, nameSegment)
problemOnlyRanges.putIfAbsent(range, true)
}
val unwrappedSymbols = symbols
.flatMap(WebSymbol::removeZeroLengthSegmentsRecursively)
.takeWhile { it.nameSegments.size == 1 }
if (unwrappedSymbols.isNotEmpty()) {
result.putValue(range, WebSymbolNameSegment(0, nameSegment.end, unwrappedSymbols))
problemOnlyRanges[range] = false
}
else {
symbols.getOrNull(0)
?.let { s ->
queue.addAll(s.nameSegments.map { Pair(it, offset + nameSegment.start) })
}
}
}
}
return result.entrySet()
.asSequence()
.mapNotNull { (range, segments) ->
val problemOnly = problemOnlyRanges[range] ?: false
val deprecation = segments.all { segment ->
segment.deprecated
|| segment.symbols.let { it.isNotEmpty() && it.all { symbol -> symbol.deprecated } }
}
if (showProblems && (deprecation || problemOnly || segments.any { it.problem != null })) {
NameSegmentReferenceWithProblem(element, range.shiftRight(symbolNameOffset), segments, deprecation, problemOnly)
}
else if (!range.isEmpty && !problemOnly) {
NameSegmentReference(element, range.shiftRight(symbolNameOffset), segments)
}
else null
}
.sortedWith(Comparator.comparingInt<PsiSymbolReference> { it.rangeInElement.startOffset }
.thenComparingInt { it.rangeInElement.length }
)
.toList()
}
private open class NameSegmentReference(private val element: PsiElement,
private val rangeInElement: TextRange,
protected val nameSegments: Collection<WebSymbolNameSegment>)
: WebSymbolReference {
override fun getElement(): PsiElement = element
override fun getRangeInElement(): TextRange =
rangeInElement
override fun resolveReference(): Collection<WebSymbol> =
nameSegments
.flatMap { it.symbols }
.filter { !it.extension }
.asSingleSymbol()
?.let { listOf(it) }
?: emptyList()
override fun toString(): String {
return "WebSymbolReference$rangeInElement - $nameSegments"
}
}
private class NameSegmentReferenceWithProblem(element: PsiElement,
rangeInElement: TextRange,
nameSegments: Collection<WebSymbolNameSegment>,
private val deprecation: Boolean,
private val problemOnly: Boolean)
: NameSegmentReference(element, rangeInElement, nameSegments) {
override fun resolveReference(): Collection<WebSymbol> =
if (problemOnly) emptyList() else super.resolveReference()
override fun getProblems(): Collection<WebSymbolReferenceProblem> {
val inspectionManager = InspectionManager.getInstance(element.project)
val matchProblem = nameSegments
.asSequence()
.mapNotNull { segment ->
val problemKind = segment.getProblemKind() ?: return@mapNotNull null
val toolMapping = segment.symbolKinds.map {
WebSymbolsInspectionToolMappingEP.get(it.namespace, it.kind, problemKind)
}.firstOrNull()
WebSymbolReferenceProblem(
segment.symbolKinds,
problemKind,
inspectionManager.createProblemDescriptor(
element, TextRange(segment.start, segment.end),
toolMapping?.getProblemMessage(segment.displayName)
?: problemKind.getDefaultProblemMessage(segment.displayName),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true
)
)
}.firstOrNull()
val deprecationProblem = if (deprecation) {
val symbolTypes = nameSegments.flatMapTo(LinkedHashSet()) { it.symbolKinds }
val toolMapping = symbolTypes.map {
WebSymbolsInspectionToolMappingEP.get(it.namespace, it.kind, WebSymbolReferenceProblem.ProblemKind.DeprecatedSymbol)
}.firstOrNull()
WebSymbolReferenceProblem(
symbolTypes,
WebSymbolReferenceProblem.ProblemKind.DeprecatedSymbol,
inspectionManager.createProblemDescriptor(
element, rangeInElement,
toolMapping?.getProblemMessage(null)
?: WebSymbolReferenceProblem.ProblemKind.DeprecatedSymbol.getDefaultProblemMessage(null),
ProblemHighlightType.LIKE_DEPRECATED, true
)
)
}
else null
return listOfNotNull(matchProblem, deprecationProblem)
}
}
companion object {
@JvmStatic
fun PsiElement.startOffsetIn(parent: PsiElement): Int {
var result = 0
var tmp: PsiElement? = this
while (tmp != parent && tmp != null) {
result += tmp.startOffsetInParent
tmp = tmp.parent
}
return if (tmp != null)
result
else -1
}
}
} | apache-2.0 | 35c219ad5c104d2852fcbb8e57f81f1e | 40.868182 | 132 | 0.676873 | 4.933048 | false | false | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/layoutImpl.kt | 3 | 1065 | // 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.ui.layout
import com.intellij.ui.layout.migLayout.*
import java.awt.Container
import javax.swing.ButtonGroup
import javax.swing.JLabel
@PublishedApi
@JvmOverloads
internal fun createLayoutBuilder(isUseMagic: Boolean = true): LayoutBuilder {
return LayoutBuilder(MigLayoutBuilder(createIntelliJSpacingConfiguration(), isUseMagic = isUseMagic))
}
interface LayoutBuilderImpl {
fun newRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, separated: Boolean = false): Row
// backward compatibility
@Deprecated(level = DeprecationLevel.HIDDEN, message = "deprecated")
fun newRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, separated: Boolean = false, indented: Boolean = false): Row = newRow(label, buttonGroup, separated)
fun build(container: Container, layoutConstraints: Array<out LCFlags>)
fun noteRow(text: String, linkHandler: ((url: String) -> Unit)? = null)
} | apache-2.0 | 534bd0cece836d92bd3eca0b37db6ff9 | 41.64 | 169 | 0.771831 | 4.209486 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/phone/ChannelListActivity.kt | 1 | 5790 | /*
* Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.phone
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import androidx.loader.content.Loader
import org.dvbviewer.controller.R
import org.dvbviewer.controller.activitiy.base.GroupDrawerActivity
import org.dvbviewer.controller.data.ProviderConsts
import org.dvbviewer.controller.data.entities.DVBViewerPreferences
import org.dvbviewer.controller.data.entities.IEPG
import org.dvbviewer.controller.ui.fragments.ChannelList
import org.dvbviewer.controller.ui.fragments.ChannelPager
import org.dvbviewer.controller.ui.fragments.EPGDetails
import org.dvbviewer.controller.ui.fragments.EpgPager
class ChannelListActivity : GroupDrawerActivity(), ChannelList.OnChannelSelectedListener, EpgPager.OnChannelScrolledListener, ChannelPager.OnGroupTypeChangedListener, IEpgDetailsActivity.OnIEPGClickListener {
private var mChannelPager: ChannelPager? = null
private var container: View? = null
private var groupTypeChanged: Boolean = false
/* (non-Javadoc)
* @see org.dvbviewer.controller.ui.base.BaseSinglePaneActivity#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_drawer)
super.onCreate(savedInstanceState)
container = findViewById(R.id.right_content)
initFragments(savedInstanceState)
}
private fun initFragments(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
mChannelPager = ChannelPager()
mChannelPager!!.arguments = intentToFragmentArguments(intent)
supportFragmentManager.beginTransaction()
.add(R.id.left_content, mChannelPager!!, CHANNEL_PAGER_TAG)
.commit()
if (container != null) {
mEpgPager = EpgPager()
mEpgPager!!.arguments = intentToFragmentArguments(intent)
supportFragmentManager.beginTransaction()
.add(R.id.right_content, mEpgPager!!, EPG_PAGER_TAG)
.commit()
}
} else {
mChannelPager = supportFragmentManager.findFragmentByTag(CHANNEL_PAGER_TAG) as ChannelPager?
if (container != null) {
mEpgPager = supportFragmentManager.findFragmentByTag(EPG_PAGER_TAG) as EpgPager?
}
}
}
override fun channelSelected(groupId: Long, groupIndex: Int, channelIndex: Int) {
mChannelPager!!.updateIndex(groupIndex, channelIndex)
if (container == null) {
val epgPagerIntent = Intent(this, EpgPagerActivity::class.java)
epgPagerIntent.putExtra(ChannelPager.KEY_GROUP_ID, groupId)
epgPagerIntent.putExtra(ChannelPager.KEY_GROUP_INDEX, groupIndex)
epgPagerIntent.putExtra(ChannelList.KEY_CHANNEL_INDEX, channelIndex)
startActivity(epgPagerIntent)
} else {
mEpgPager!!.setPosition(channelIndex)
}
}
override fun channelChanged(groupId: Long, channelIndex: Int) {
mChannelPager!!.setChannelSelection(groupId, channelIndex)
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
super.onItemClick(parent, view, position, id)
mChannelPager!!.setPosition(position)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
var result = super.onOptionsItemSelected(item)
if (mChannelPager != null) {
result = mChannelPager!!.onOptionsItemSelected(item)
}
if (mEpgPager != null) {
result = mEpgPager!!.onOptionsItemSelected(item)
}
return result
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) {
super.onLoadFinished(loader, data)
if (container == null) {
val f = supportFragmentManager.findFragmentByTag(CHANNEL_PAGER_TAG)
if (f == null) {
val tran = supportFragmentManager.beginTransaction()
mChannelPager = ChannelPager()
tran.add(R.id.content_frame, mChannelPager!!, CHANNEL_PAGER_TAG)
tran.commitAllowingStateLoss()
} else {
mChannelPager = f as ChannelPager?
}
}
if (container != null && groupTypeChanged) {
data.moveToFirst()
mEpgPager!!.refresh(data.getLong(data.getColumnIndex(ProviderConsts.GroupTbl._ID)), 0)
}
groupTypeChanged = false
}
override fun groupTypeChanged(type: Int) {
groupTypeChanged = true
showFavs = prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false)
supportLoaderManager.restartLoader(0, intent.extras, this)
groupIndex = 0
}
override fun onIEPGClick(iepg: IEPG) {
val details = EPGDetails()
val bundle = Bundle()
bundle.putParcelable(IEPG::class.java.simpleName, iepg)
details.arguments = bundle
details.show(supportFragmentManager, IEPG::class.java.name)
}
} | apache-2.0 | 5b3dc57ca0633b88477ed8cea01f50e7 | 40.06383 | 208 | 0.680428 | 4.661031 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/nbt/filetype/NbtFileType.kt | 1 | 692 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.filetype
import com.demonwav.mcdev.asset.PlatformAssets
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.vfs.VirtualFile
object NbtFileType : FileType {
override fun getDefaultExtension() = "nbt"
override fun getIcon() = PlatformAssets.MINECRAFT_ICON
override fun getCharset(file: VirtualFile, content: ByteArray): String? = null
override fun getName() = "NBT"
override fun getDescription() = "Named Binary Tag"
override fun isBinary() = true
override fun isReadOnly() = false
}
| mit | 845c62d67500f59539c357040ab20763 | 26.68 | 82 | 0.732659 | 4.168675 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/onthisday/OnThisDayFragment.kt | 1 | 14498 | package org.wikipedia.feed.onthisday
import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.OnThisDayFunnel
import org.wikipedia.databinding.FragmentOnThisDayBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.util.DateUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.log.L
import org.wikipedia.views.CustomDatePicker
import org.wikipedia.views.HeaderMarginItemDecoration
import java.util.*
import kotlin.math.abs
class OnThisDayFragment : Fragment(), CustomDatePicker.Callback {
private var _binding: FragmentOnThisDayBinding? = null
private val binding get() = _binding!!
private lateinit var date: Calendar
private lateinit var wiki: WikiSite
private lateinit var invokeSource: InvokeSource
private var funnel: OnThisDayFunnel? = null
private var yearOnCardView = 0
private var positionToScrollTo = 0
private val disposables = CompositeDisposable()
private val appCompatActivity get() = requireActivity() as AppCompatActivity
private var onThisDay: OnThisDay? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentOnThisDayBinding.inflate(inflater, container, false)
val topDecorationDp = 24
val age = requireArguments().getInt(OnThisDayActivity.EXTRA_AGE, 0)
wiki = requireArguments().getParcelable(OnThisDayActivity.EXTRA_WIKISITE)!!
invokeSource = requireArguments().getSerializable(Constants.INTENT_EXTRA_INVOKE_SOURCE) as InvokeSource
date = DateUtil.getDefaultDateFor(age)
yearOnCardView = requireArguments().getInt(OnThisDayActivity.EXTRA_YEAR, -1)
setUpToolbar()
binding.eventsRecycler.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
binding.eventsRecycler.addItemDecoration(HeaderMarginItemDecoration(topDecorationDp, 0))
setUpRecycler(binding.eventsRecycler)
setUpTransitionAnimation(savedInstanceState, age)
binding.progressBar.visibility = View.GONE
binding.eventsRecycler.visibility = View.GONE
binding.errorView.visibility = View.GONE
binding.errorView.backClickListener = View.OnClickListener { requireActivity().finish() }
binding.dayContainer.setOnClickListener { onCalendarClicked() }
binding.toolbarDayContainer.setOnClickListener { onCalendarClicked() }
binding.indicatorLayout.setOnClickListener { onIndicatorLayoutClicked() }
return binding.root
}
private fun setUpTransitionAnimation(savedInstanceState: Bundle?, age: Int) {
val animDelay = if (requireActivity().window.sharedElementEnterTransition != null &&
savedInstanceState == null) 500L else 0L
binding.onThisDayTitleView.postDelayed({
if (!isAdded) {
return@postDelayed
}
updateContents(age)
}, animDelay)
}
private fun updateContents(age: Int) {
val today = DateUtil.getDefaultDateFor(age)
requestEvents(today[Calendar.MONTH], today[Calendar.DATE])
funnel = OnThisDayFunnel(WikipediaApp.getInstance(), wiki, invokeSource)
}
private fun requestEvents(month: Int, date: Int) {
binding.progressBar.visibility = View.VISIBLE
binding.eventsRecycler.visibility = View.GONE
binding.errorView.visibility = View.GONE
disposables.add(ServiceFactory.getRest(wiki).getOnThisDay(month + 1, date)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
if (!isAdded) {
return@doAfterTerminate
}
binding.progressBar.visibility = View.GONE
binding.eventsRecycler.postDelayed({
if (positionToScrollTo != -1 && yearOnCardView != -1) {
binding.eventsRecycler.scrollToPosition(positionToScrollTo)
}
}, 500)
}
.subscribe({ response ->
onThisDay = response
onThisDay?.let { onThisDayResponse ->
binding.eventsRecycler.visibility = View.VISIBLE
binding.eventsRecycler.adapter = RecyclerAdapter(onThisDayResponse.events(), wiki)
val events = onThisDayResponse.events()
positionToScrollTo = events.indices.find { yearOnCardView == events[it].year() } ?: 0
val beginningYear = events[events.size - 1].year()
binding.dayInfo.text = getString(R.string.events_count_text, events.size.toString(),
DateUtil.yearToStringWithEra(beginningYear), events[0].year())
}
}) { throwable ->
L.e(throwable)
binding.errorView.setError(throwable)
binding.errorView.visibility = View.VISIBLE
binding.eventsRecycler.visibility = View.GONE
})
}
private fun setUpToolbar() {
appCompatActivity.setSupportActionBar(binding.toolbar)
appCompatActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
appCompatActivity.supportActionBar?.title = ""
binding.collapsingToolbarLayout.setCollapsedTitleTextColor(
ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_primary_color)
)
binding.day.text = DateUtil.getMonthOnlyDateString(date.time)
maybeHideDateIndicator()
binding.appBar.addOnOffsetChangedListener(OnOffsetChangedListener { appBarLayout, verticalOffset ->
binding.headerFrameLayout.alpha = 1.0f - abs(verticalOffset / appBarLayout.totalScrollRange.toFloat())
if (verticalOffset > -appBarLayout.totalScrollRange) {
binding.dropDownToolbar.visibility = View.GONE
} else if (verticalOffset <= -appBarLayout.totalScrollRange) {
binding.dropDownToolbar.visibility = View.VISIBLE
}
val newText = if (verticalOffset <= -appBarLayout.totalScrollRange) DateUtil.getMonthOnlyDateString(date.time) else ""
if (newText != binding.toolbarDay.text.toString()) {
appBarLayout.post { binding.toolbarDay.text = newText }
}
})
}
private fun maybeHideDateIndicator() {
binding.indicatorLayout.visibility =
if (date[Calendar.MONTH] == Calendar.getInstance()[Calendar.MONTH] &&
date[Calendar.DATE] == Calendar.getInstance()[Calendar.DATE]) View.GONE else View.VISIBLE
binding.indicatorDate.text = String.format(Locale.getDefault(), "%d", Calendar.getInstance()[Calendar.DATE])
}
override fun onDestroyView() {
disposables.clear()
binding.eventsRecycler.adapter = null
if (binding.eventsRecycler.adapter != null) {
funnel?.done(binding.eventsRecycler.adapter!!.itemCount)
funnel = null
}
_binding = null
super.onDestroyView()
}
private fun setUpRecycler(recycler: RecyclerView) {
recycler.isNestedScrollingEnabled = true
recycler.clipToPadding = false
}
override fun onDatePicked(month: Int, day: Int) {
binding.eventsRecycler.visibility = View.GONE
date[CustomDatePicker.LEAP_YEAR, month, day, 0] = 0
binding.day.text = DateUtil.getMonthOnlyDateString(date.time)
binding.appBar.setExpanded(true)
requestEvents(month, day)
maybeHideDateIndicator()
}
private fun onCalendarClicked() {
val newFragment = CustomDatePicker()
newFragment.setSelectedDay(date[Calendar.MONTH], date[Calendar.DATE])
newFragment.callback = this@OnThisDayFragment
newFragment.show(parentFragmentManager, "date picker")
}
private fun onIndicatorLayoutClicked() {
onDatePicked(Calendar.getInstance()[Calendar.MONTH], Calendar.getInstance()[Calendar.DATE])
}
private inner class RecyclerAdapter(private val events: List<OnThisDay.Event>,
private val wiki: WikiSite) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == Companion.VIEW_TYPE_FOOTER) {
val itemView = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.view_on_this_day_footer, viewGroup, false)
FooterViewHolder(itemView)
} else {
val itemView = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.view_events_layout, viewGroup, false)
EventsViewHolder(itemView, wiki)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is EventsViewHolder) {
holder.setFields(events[position])
funnel?.scrolledToPosition(position)
}
}
override fun getItemCount(): Int {
return events.size + 1
}
override fun getItemViewType(position: Int): Int {
return if (position < events.size) Companion.VIEW_TYPE_ITEM else Companion.VIEW_TYPE_FOOTER
}
override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
super.onViewAttachedToWindow(holder)
if (holder is EventsViewHolder) {
holder.animateRadioButton()
}
}
}
private inner class EventsViewHolder(v: View, private val wiki: WikiSite) : RecyclerView.ViewHolder(v) {
private val descTextView: TextView = v.findViewById(R.id.text)
private val yearTextView: TextView = v.findViewById(R.id.year)
private val yearsInfoTextView: TextView = v.findViewById(R.id.years_text)
private val pagesViewPager: ViewPager2 = v.findViewById(R.id.pages_pager)
private val pagesIndicator: TabLayout = v.findViewById(R.id.pages_indicator)
private val radioButtonImageView: ImageView = v.findViewById(R.id.radio_image_view)
init {
descTextView.setTextIsSelectable(true)
}
fun setFields(event: OnThisDay.Event) {
descTextView.text = event.text()
descTextView.visibility = if (event.text().isEmpty()) View.GONE else View.VISIBLE
yearTextView.text = DateUtil.yearToStringWithEra(event.year())
yearsInfoTextView.text = DateUtil.getYearDifferenceString(event.year())
setPagesViewPager(event)
}
private fun setPagesViewPager(event: OnThisDay.Event) {
event.pages()?.let {
val viewPagerAdapter = ViewPagerAdapter(childFragmentManager, it, wiki)
pagesViewPager.adapter = viewPagerAdapter
pagesViewPager.offscreenPageLimit = 2
TabLayoutMediator(pagesIndicator, pagesViewPager) { _, _ -> }.attach()
pagesViewPager.visibility = View.VISIBLE
pagesIndicator.visibility = if (it.size == 1) View.GONE else View.VISIBLE
} ?: run {
pagesViewPager.visibility = View.GONE
pagesIndicator.visibility = View.GONE
}
}
fun animateRadioButton() {
val pulse = AnimationUtils.loadAnimation(context, R.anim.pulse)
radioButtonImageView.startAnimation(pulse)
}
}
private inner class FooterViewHolder(v: View) : RecyclerView.ViewHolder(v) {
init {
val backToFutureView = v.findViewById<View>(R.id.back_to_future_text_view)
backToFutureView.setOnClickListener {
binding.appBar.setExpanded(true)
binding.eventsRecycler.scrollToPosition(0)
}
}
}
internal inner class ViewPagerAdapter(private val fragmentManager: FragmentManager,
private val pages: List<PageSummary>, private val wiki: WikiSite) : RecyclerView.Adapter<OnThisDayPagesViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): OnThisDayPagesViewHolder {
val itemView = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_on_this_day_pages, viewGroup, false)
return OnThisDayPagesViewHolder((viewGroup.context as Activity), fragmentManager, itemView, wiki)
}
override fun onBindViewHolder(onThisDayPagesViewHolder: OnThisDayPagesViewHolder, i: Int) {
onThisDayPagesViewHolder.setFields(pages[i])
}
override fun getItemCount(): Int {
return pages.size
}
}
companion object {
private const val VIEW_TYPE_ITEM = 0
private const val VIEW_TYPE_FOOTER = 1
fun newInstance(age: Int, wikiSite: WikiSite, year: Int, invokeSource: InvokeSource): OnThisDayFragment {
return OnThisDayFragment().apply {
arguments = bundleOf(OnThisDayActivity.EXTRA_AGE to age,
OnThisDayActivity.EXTRA_WIKISITE to wikiSite,
OnThisDayActivity.EXTRA_YEAR to year,
Constants.INTENT_EXTRA_INVOKE_SOURCE to invokeSource)
}
}
}
}
| apache-2.0 | 5d0b555605e6e9c8e8e3bb7921b90724 | 44.30625 | 160 | 0.6723 | 5.044537 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/packet/PacketInVehicleMove.kt | 1 | 1464 | /*
* Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.packet
data class PacketInVehicleMove(
var x: Double,
var y: Double,
var z: Double,
var yaw: Float,
var pitch: Float
) : PacketInBukkitAbstract("PacketPlayInVehicleMove"),
PacketBukkitFreshly {
@Deprecated("")
constructor() : this(.0, .0, .0, 0f, 0f)
override fun read(data: PacketBuffer) {
x = data.readDouble()
y = data.readDouble()
z = data.readDouble()
yaw = data.readFloat()
pitch = data.readFloat()
}
override fun write(data: PacketBuffer) {
data.writeDouble(x)
data.writeDouble(y)
data.writeDouble(z)
data.writeFloat(yaw)
data.writeFloat(pitch)
}
}
| gpl-3.0 | 004aa9edf5677e136d0053f887046322 | 30.148936 | 72 | 0.663251 | 4.11236 | false | false | false | false |
mdanielwork/intellij-community | plugins/git4idea/tests/git4idea/push/GitPushOperationMultiRepoTest.kt | 7 | 5909 | /*
* Copyright 2000-2014 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 git4idea.push
import com.intellij.dvcs.push.PushSpec
import com.intellij.openapi.vcs.Executor.cd
import com.intellij.util.containers.ContainerUtil
import git4idea.commands.GitCommandResult
import git4idea.repo.GitRepository
import git4idea.test.*
import git4idea.update.GitUpdateResult
import java.io.File
import java.util.*
class GitPushOperationMultiRepoTest : GitPushOperationBaseTest() {
private lateinit var community: GitRepository
private lateinit var ultimate: GitRepository
private lateinit var brultimate: File
private lateinit var brommunity: File
@Throws(Exception::class)
override fun setUp() {
super.setUp()
val mainRepo = setupRepositories(projectPath, "parent", "bro")
ultimate = mainRepo.projectRepo
brultimate = mainRepo.bro
val communityDir = File(projectPath, "community")
assertTrue(communityDir.mkdir())
val enclosingRepo = setupRepositories(communityDir.path, "community_parent", "community_bro")
community = enclosingRepo.projectRepo
brommunity = enclosingRepo.bro
cd(projectPath)
refresh()
updateRepositories()
}
fun `test try push from all roots even if one fails`() {
// fail in the first repo
git.onPush {
if (it == ultimate) GitCommandResult(false, 128, listOf("Failed to push to origin"), listOf<String>())
else null
}
cd(ultimate)
makeCommit("file.txt")
cd(community)
makeCommit("com.txt")
val spec1 = makePushSpec(ultimate, "master", "origin/master")
val spec2 = makePushSpec(community, "master", "origin/master")
val map = ContainerUtil.newHashMap<GitRepository, PushSpec<GitPushSource, GitPushTarget>>()
map.put(ultimate, spec1)
map.put(community, spec2)
val result = GitPushOperation(project, pushSupport, map, null, false, false).execute()
val result1 = result.results[ultimate]!!
val result2 = result.results[community]!!
assertResult(GitPushRepoResult.Type.ERROR, -1, "master", "origin/master", null, result1)
assertEquals("Error text is incorrect", "Failed to push to origin", result1.error)
assertResult(GitPushRepoResult.Type.SUCCESS, 1, "master", "origin/master", null, result2)
}
fun `test update all roots on reject when needed even if only one in push spec`() {
cd(brultimate)
val broHash = makeCommit("bro.txt")
git("push")
cd(brommunity)
val broCommunityHash = makeCommit("bro_com.txt")
git("push")
cd(ultimate)
makeCommit("file.txt")
val mainSpec = makePushSpec(ultimate, "master", "origin/master")
agreeToUpdate(GitRejectedPushUpdateDialog.MERGE_EXIT_CODE) // auto-update-all-roots is selected by default
val result = GitPushOperation(project, pushSupport,
Collections.singletonMap<GitRepository, PushSpec<GitPushSource, GitPushTarget>>(ultimate, mainSpec), null, false, false).execute()
val result1 = result.results[ultimate]!!
val result2 = result.results[community]
assertResult(GitPushRepoResult.Type.SUCCESS, 2, "master", "origin/master", GitUpdateResult.SUCCESS, result1)
assertNull(result2) // this was not pushed => no result should be generated
cd(community)
val lastHash = last()
assertEquals("Update in community didn't happen", broCommunityHash, lastHash)
cd(ultimate)
val lastCommitParents = git("log -1 --pretty=%P").split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
assertEquals("Merge didn't happen in main repository", 2, lastCommitParents.size)
assertRemoteCommitMerged("Commit from bro repository didn't arrive", broHash)
}
// IDEA-169877
fun `test push rejected in one repo when branch is deleted in another, should finally succeed`() {
listOf(brultimate, brommunity).forEach {
cd(it)
git("checkout -b feature")
git("push -u origin feature")
}
listOf(ultimate, community).forEach {
cd(it)
git("pull")
git("checkout -b feature origin/feature")
}
// commit in one repo to reject the push
cd(brultimate)
val broHash = tac("bro.txt")
git("push")
// remove branch in another repo
cd(brommunity)
git("push origin :feature")
cd(ultimate)
val commitToPush = tac("file.txt")
listOf(ultimate, community).forEach { it.update() }
agreeToUpdate(GitRejectedPushUpdateDialog.MERGE_EXIT_CODE) // auto-update-all-roots is selected by default
// push only to 1 repo, otherwise the push would recreate the deleted branch, and the error won't reproduce
val pushSpecs = mapOf(ultimate to makePushSpec(ultimate, "feature", "origin/feature"))
val result = GitPushOperation(project, pushSupport, pushSpecs, null, false, false).execute()
val result1 = result.results[ultimate]!!
assertResult(GitPushRepoResult.Type.SUCCESS, 2, "feature", "origin/feature", GitUpdateResult.SUCCESS, result1)
assertRemoteCommitMerged("Commit from bro repository didn't arrive", broHash)
cd(brultimate)
git("pull origin feature")
assertEquals("Commit from ultimate repository wasn't pushed", commitToPush, git("log --no-walk HEAD^1 --pretty=%H"))
}
private fun assertRemoteCommitMerged(message: String, expectedHash: String) {
assertEquals(message, expectedHash, git("log --no-walk HEAD^2 --pretty=%H"))
}
}
| apache-2.0 | cf68aecf2957b0007c434dd9bff3b9b9 | 36.398734 | 164 | 0.715519 | 4.196733 | false | false | false | false |
frc2052/FRC-Krawler | app/src/main/kotlin/com/team2052/frckrawler/metric/types/StringMetricTypeEntry.kt | 1 | 2900 | package com.team2052.frckrawler.metric.types
import com.google.common.base.Joiner
import com.google.common.collect.Lists
import com.google.gson.JsonObject
import com.team2052.frckrawler.database.metric.MetricValue
import com.team2052.frckrawler.db.Metric
import com.team2052.frckrawler.db.Robot
import com.team2052.frckrawler.metric.MetricTypeEntry
import com.team2052.frckrawler.metrics.view.MetricWidget
import com.team2052.frckrawler.tba.JSON
import com.team2052.frckrawler.util.MetricHelper
class StringMetricTypeEntry<out W : MetricWidget>(widgetType: Class<W>) : MetricTypeEntry<W>(widgetType) {
override fun compileValues(robot: Robot, metric: Metric, metricData: List<MetricValue>, compileWeight: Double): JsonObject {
val json = JsonObject()
if (metricData.size == 1) {
val value = MetricHelper.getStringMetricValue(metricData[0])
val number = MetricHelper.getMatchNumberFromMetricValue(metricData[0])
if (value.t2.isError) {
return json
}
if (!number.t2.isError) {
json.addProperty("match_number", number.t1)
}
json.addProperty("value", value.t1)
} else {
//Match Type
val map = Lists.newArrayList<JsonObject>()
for (metricValue in metricData) {
val parsedValue = MetricHelper.getStringMetricValue(metricValue)
val number = MetricHelper.getMatchNumberFromMetricValue(metricValue)
if (parsedValue.t2.isError || number.t2.isError)
continue
val valueJson = JsonObject()
valueJson.addProperty("match_number", number.t1)
valueJson.addProperty("value", parsedValue.t1)
map.add(valueJson)
}
json.add("values", JSON.getGson().toJsonTree(map).asJsonArray)
}
return json
}
override fun buildMetric(name: String, min: Int?, max: Int?, inc: Int?, commaList: List<String>?): MetricHelper.MetricFactory {
val factory = MetricHelper.MetricFactory(name)
factory.setMetricType(typeId)
return factory
}
override fun convertValueToString(value: JsonObject): String {
if (value.has("value") && !value.get("value").isJsonNull) {
var valueString = ""
if (value.has("match_number") && !value.get("match_number").isJsonNull) {
valueString += "${value.get("match_number").asInt}: "
}
valueString += value.get("value").asString
return valueString
}
val values = Lists.newArrayList<String>()
value.getAsJsonArray("values")
.map { it.asJsonObject }
.mapTo(values) { "${it.get("match_number")}: ${it.get("value").asString}" }
return Joiner.on(", ").join(values)
}
} | mit | 8b740ad98fc77ce02a6d32e18b9c58b4 | 39.291667 | 131 | 0.628276 | 4.360902 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/ide/impl/ProjectOrigin.kt | 9 | 2235 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.io.URLUtil
import org.jetbrains.annotations.VisibleForTesting
import java.net.URI
import java.nio.file.Path
@NlsSafe
fun getProjectOriginUrl(projectDir: Path?): String? {
if (projectDir == null) return null
val epName = ExtensionPointName.create<ProjectOriginInfoProvider>("com.intellij.projectOriginInfoProvider")
for (extension in epName.extensions) {
val url = extension.getOriginUrl(projectDir)
if (url != null) {
return url
}
}
return null
}
private val KNOWN_HOSTINGS = listOf(
"git.jetbrains.space",
"github.com",
"bitbucket.org",
"gitlab.com")
@VisibleForTesting
data class Origin(val protocol: String?, val host: String)
@VisibleForTesting
fun getOriginFromUrl(url: String): Origin? {
try {
val urlWithScheme = if (URLUtil.containsScheme(url)) url else "ssh://$url"
val uri = URI(urlWithScheme)
var host = uri.host
if (host == null) {
if (uri.scheme == "ssh") {
if (uri.authority != null) {
// [email protected]:JetBrains
val at = uri.authority.split("@")
val hostAndOrg = if (at.size > 1) at[1] else at[0]
val comma = hostAndOrg.split(":")
host = comma[0]
if (comma.size > 1) {
val org = comma[1]
return Origin(uri.scheme, "$host/$org")
}
}
}
}
if (host == null) return null
if (KNOWN_HOSTINGS.contains(host)) {
val path = uri.path
val secondSlash = path.indexOf("/", 1) // path always starts with '/'
val organization = if (secondSlash >= 0) path.substring(0, secondSlash) else path
return Origin(uri.scheme, uri.host + organization)
}
return Origin(uri.scheme, uri.host)
}
catch (e: Exception) {
LOG.warn("Couldn't parse URL $url", e)
}
return null
}
private val LOG = Logger.getInstance("com.intellij.ide.impl.TrustedHosts")
| apache-2.0 | 3e6883ad7f37d70093f4dfa2de15577a | 29.616438 | 158 | 0.66443 | 3.775338 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/Main.kt | 1 | 1875 | package org.javacs.kt
import com.beust.jcommander.JCommander
import com.beust.jcommander.Parameter
import java.util.concurrent.Executors
import org.eclipse.lsp4j.launch.LSPLauncher
import org.javacs.kt.util.ExitingInputStream
import org.javacs.kt.util.tcpStartServer
import org.javacs.kt.util.tcpConnectToClient
class Args {
/*
* The language server can currently be launched in three modes:
* - Stdio, in which case no argument should be specified (used by default)
* - TCP Server, in which case the client has to connect to the specified tcpServerPort (used by the Docker image)
* - TCP Client, in whcih case the server will connect to the specified tcpClientPort/tcpClientHost (optionally used by VSCode)
*/
@Parameter(names = ["--tcpServerPort", "-sp"])
var tcpServerPort: Int? = null
@Parameter(names = ["--tcpClientPort", "-p"])
var tcpClientPort: Int? = null
@Parameter(names = ["--tcpClientHost", "-h"])
var tcpClientHost: String = "localhost"
}
fun main(argv: Array<String>) {
// Redirect java.util.logging calls (e.g. from LSP4J)
LOG.connectJULFrontend()
val args = Args().also { JCommander.newBuilder().addObject(it).build().parse(*argv) }
val (inStream, outStream) = args.tcpClientPort?.let {
// Launch as TCP Client
LOG.connectStdioBackend()
tcpConnectToClient(args.tcpClientHost, it)
} ?: args.tcpServerPort?.let {
// Launch as TCP Server
LOG.connectStdioBackend()
tcpStartServer(it)
} ?: Pair(System.`in`, System.out)
val server = KotlinLanguageServer()
val threads = Executors.newSingleThreadExecutor { Thread(it, "client") }
val launcher = LSPLauncher.createServerLauncher(server, ExitingInputStream(inStream), outStream, threads) { it }
server.connect(launcher.remoteProxy)
launcher.startListening()
}
| mit | 0779b80069f66da09096e6f2749026b4 | 38.0625 | 132 | 0.705067 | 3.881988 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/training/target/TargetListFragment.kt | 1 | 8455 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.training.target
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import de.dreier.mytargets.R
import de.dreier.mytargets.base.adapters.header.ExpandableListAdapter
import de.dreier.mytargets.base.adapters.header.HeaderListAdapter
import de.dreier.mytargets.base.fragments.SelectItemFragmentBase
import de.dreier.mytargets.base.navigation.NavigationController.Companion.ITEM
import de.dreier.mytargets.databinding.FragmentTargetSelectBinding
import de.dreier.mytargets.databinding.ItemImageSimpleBinding
import de.dreier.mytargets.features.training.target.TargetListFragment.EFixedType.*
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Target
import de.dreier.mytargets.shared.targets.TargetFactory
import de.dreier.mytargets.utils.SlideInItemAnimator
import de.dreier.mytargets.utils.ToolbarUtils
import de.dreier.mytargets.utils.multiselector.SelectableViewHolder
import java.util.*
class TargetListFragment :
SelectItemFragmentBase<Target, ExpandableListAdapter<HeaderListAdapter.SimpleHeader, Target>>(),
AdapterView.OnItemSelectedListener {
private lateinit var binding: FragmentTargetSelectBinding
private var scoringStyleAdapter: ArrayAdapter<String>? = null
private var targetSizeAdapter: ArrayAdapter<String>? = null
private val themedSpinnerAdapter: ArrayAdapter<String>
get() {
val actionBar = (activity as AppCompatActivity).supportActionBar!!
val themedContext = actionBar.themedContext
val spinnerAdapter = ArrayAdapter(
themedContext,
android.R.layout.simple_spinner_item, ArrayList<String>()
)
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
return spinnerAdapter
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil
.inflate(inflater, R.layout.fragment_target_select, container, false)
adapter = TargetAdapter()
binding.recyclerView.itemAnimator = SlideInItemAnimator()
binding.recyclerView.adapter = adapter
useDoubleClickSelection = true
ToolbarUtils.setSupportActionBar(this, binding.toolbar)
ToolbarUtils.showHomeAsUp(this)
setHasOptionsMenu(true)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// Needs activity context
scoringStyleAdapter = themedSpinnerAdapter
binding.scoringStyle.adapter = scoringStyleAdapter
targetSizeAdapter = themedSpinnerAdapter
binding.targetSize.adapter = targetSizeAdapter
// Process passed arguments
val target = arguments!!.getParcelable<Target>(ITEM)!!
val fixedType = EFixedType
.valueOf(arguments!!.getString(FIXED_TYPE, NONE.name))
val list = when (fixedType) {
NONE -> TargetFactory.getList()
TARGET -> listOf(target.model)
GROUP -> TargetFactory.getList(target)
}
val targets = list
.map { value -> Target(value.id, 0) }
.toMutableList()
adapter.setList(targets)
selectItem(binding.recyclerView, target)
updateSettings()
// Set initial target size
val diameters = target.model.diameters
val diameterIndex = diameters.indices.firstOrNull { diameters[it] == target.diameter } ?: -1
setSelectionWithoutEvent(binding.scoringStyle, target.scoringStyleIndex)
setSelectionWithoutEvent(binding.targetSize, diameterIndex)
}
override fun selectItem(recyclerView: RecyclerView, item: Target) {
adapter.ensureItemIsExpanded(item)
super.selectItem(recyclerView, item)
}
override fun onClick(holder: SelectableViewHolder<Target>, item: Target?) {
super.onClick(holder, item)
if (item == null) {
return
}
updateSettings()
saveItem()
}
private fun updateSettings() {
// Init scoring styles
val target = adapter.getItemById(selector.getSelectedId()!!)
val styles = target!!.model.scoringStyles.map { it.toString() }
updateAdapter(binding.scoringStyle, scoringStyleAdapter!!, styles)
// Init target size spinner
val diameters = diameterToList(target.model.diameters)
updateAdapter(binding.targetSize, targetSizeAdapter!!, diameters)
if (diameters.size > 1) {
binding.targetSize.visibility = View.VISIBLE
} else {
binding.targetSize.visibility = View.GONE
}
}
private fun updateAdapter(
spinner: Spinner,
spinnerAdapter: ArrayAdapter<String>,
strings: List<String>
) {
val lastSelection = spinner.selectedItemPosition
spinnerAdapter.clear()
spinnerAdapter.addAll(strings)
val position = if (lastSelection < strings.size) lastSelection else strings.size - 1
setSelectionWithoutEvent(spinner, position)
}
private fun setSelectionWithoutEvent(spinner: Spinner, position: Int) {
spinner.onItemSelectedListener = null
spinner.setSelection(position, false)
spinner.onItemSelectedListener = this
}
private fun diameterToList(diameters: List<Dimension>): List<String> {
return diameters.map { it.toString() }
}
override fun onSave(): Target {
val target = super.onSave()
target.scoringStyleIndex = binding.scoringStyle.selectedItemPosition
val diameters = target.model.diameters
target.diameter = diameters[binding.targetSize.selectedItemPosition]
arguments!!.putParcelable(ITEM, target)
return target
}
override fun onItemSelected(adapterView: AdapterView<*>, view: View, pos: Int, id: Long) {
updateSettings()
saveItem()
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
enum class EFixedType {
/**
* The user has completely free choice from all target faces.
*/
NONE,
/**
* The user can change the selection within a group of target faces
* like between the WA target faces.
*/
GROUP,
/**
* The user cannot change the selected target face, but e.g. scoring style or diameter.
*/
TARGET
}
private inner class TargetAdapter internal constructor() :
ExpandableListAdapter<HeaderListAdapter.SimpleHeader, Target>({ child ->
val type = child.model.type
HeaderListAdapter.SimpleHeader(type.ordinal.toLong(), type.toString())
}, compareBy { it }, TargetFactory.comparator) {
override fun getSecondLevelViewHolder(parent: ViewGroup): ViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_image_simple, parent, false)
return ViewHolder(itemView)
}
}
private inner class ViewHolder(itemView: View) :
SelectableViewHolder<Target>(itemView, selector, this@TargetListFragment) {
private val binding = ItemImageSimpleBinding.bind(itemView)
override fun bindItem(item: Target) {
binding.name.text = item.model.toString()
binding.image.setImageDrawable(item.drawable)
}
}
companion object {
const val FIXED_TYPE = "fixed_type"
}
}
| gpl-2.0 | bb157dafd047d5c82474ed4c49f856e8 | 35.921397 | 100 | 0.692371 | 4.958944 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/targets/models/NFASField.kt | 1 | 1838 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.targets.models
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.Diameter
import de.dreier.mytargets.shared.models.ETargetType
import de.dreier.mytargets.shared.targets.scoringstyle.ArrowAwareScoringStyle
import de.dreier.mytargets.shared.targets.zone.CircularZone
import de.dreier.mytargets.shared.targets.zone.EllipseZone
import de.dreier.mytargets.shared.utils.Color.BLACK
import de.dreier.mytargets.shared.utils.Color.GRAY
import de.dreier.mytargets.shared.utils.Color.LIGHTER_GRAY
import de.dreier.mytargets.shared.utils.Color.ORANGE
import de.dreier.mytargets.shared.utils.Color.TURBO_YELLOW
class NFASField : TargetModelBase(
id = ID,
nameRes = R.string.nfas_field,
diameters = listOf(Diameter.SMALL, Diameter.MEDIUM, Diameter.LARGE, Diameter.XLARGE),
zones = listOf(
CircularZone(0.162f, TURBO_YELLOW, BLACK, 5),
EllipseZone(1f, 0f, 0f, ORANGE, BLACK, 4),
CircularZone(1.0f, LIGHTER_GRAY, GRAY, 3)
),
scoringStyles = listOf(
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(24, 20, 16), intArrayOf(14, 14, 10), intArrayOf(8, 8, 4)))
),
type = ETargetType.FIELD
) {
companion object {
const val ID = 22L
}
}
| gpl-2.0 | d731091bb8dd0c4298bc8c5bb808384a | 38.956522 | 123 | 0.72198 | 3.805383 | false | false | false | false |
opst-miyatay/LightCalendarView | library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/accent/Accent.kt | 2 | 1712 | /*
* Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD.
*
* 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 jp.co.recruit_mp.android.lightcalendarview.accent
import android.graphics.Canvas
import android.graphics.Paint
/**
* Accent that can be used to decorate a {@link DayView}
*
* See an example implementation in {@link DotAccent}.
* Created by masayuki-recruit on 9/7/16.
*/
abstract class Accent(val key: Any = Any()) {
abstract val width: Int
abstract val height: Int
abstract val marginLeftRight: Int
abstract val marginTopBottom: Int
/**
* Performs drawing the accent on {@link Canvas}
*
* @param x: horizontal center of the accent to be drawn
* @param y: vertical center of the accent to be drawn
* @param paint: {@link Paint} that can be used in the drawing process
*/
abstract fun draw(canvas: Canvas, x: Float, y: Float, paint: Paint)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Accent) return false
if (key != other.key) return false
return true
}
override fun hashCode(): Int {
return key.hashCode()
}
}
| apache-2.0 | 61a071addec6bca9e6f6bafc71a6e11b | 30.127273 | 75 | 0.684579 | 4.018779 | false | false | false | false |
flesire/ontrack | ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/ui/JobFilter.kt | 1 | 870 | package net.nemerosa.ontrack.boot.ui
import net.nemerosa.ontrack.job.JobState
import net.nemerosa.ontrack.job.JobStatus
import org.apache.commons.lang3.StringUtils
class JobFilter(
var state: JobState? = null,
var category: String? = null,
var type: String? = null,
var description: String? = null,
var errorOnly: Boolean? = null
) {
fun filter(statuses: Collection<JobStatus>) =
statuses.filter {
(state == null || state == it.state) &&
(category == null || category == it.key.type.category.key) &&
(type == null || type == it.key.type.key) &&
(description == null || StringUtils.containsIgnoreCase(it.description, description)) &&
(errorOnly == null || !errorOnly!! || it.isError)
}
}
| mit | 7873fd0f50210d176aa3e3f14397c00c | 36.826087 | 111 | 0.566667 | 4.264706 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/impl/impl.kt | 2 | 8662 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems") // KTIJ-19938
package com.intellij.lang.documentation.impl
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.lang.documentation.*
import com.intellij.lang.documentation.psi.psiDocumentationTarget
import com.intellij.model.Pointer
import com.intellij.model.psi.impl.mockEditor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.readAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.PsiFile
import com.intellij.util.AsyncSupplier
import com.intellij.util.SmartList
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.*
import org.jetbrains.annotations.TestOnly
@Internal // for Fleet
fun documentationTargets(file: PsiFile, offset: Int): List<DocumentationTarget> {
val targets = SmartList<DocumentationTarget>()
for (ext in DocumentationTargetProvider.EP_NAME.extensionList) {
targets.addAll(ext.documentationTargets(file, offset))
}
if (!targets.isEmpty()) {
return targets
}
// fallback to PSI
// TODO this fallback should be implemented inside DefaultTargetSymbolDocumentationTargetProvider, but first:
// - PsiSymbol has to hold information about origin element;
// - documentation target by argument list should be also implemented separately.
val editor = mockEditor(file) ?: return emptyList()
val documentationManager = DocumentationManager.getInstance(file.project)
val (targetElement, sourceElement) = documentationManager.findTargetElementAndContext(editor, offset, file)
?: return emptyList()
return listOf(psiDocumentationTarget(targetElement, sourceElement))
}
internal fun DocumentationTarget.documentationRequest(): DocumentationRequest {
ApplicationManager.getApplication().assertReadAccessAllowed()
return DocumentationRequest(createPointer(), presentation)
}
@Internal
fun CoroutineScope.computeDocumentationAsync(targetPointer: Pointer<out DocumentationTarget>): Deferred<DocumentationResultData?> {
return async(Dispatchers.Default) {
computeDocumentation(targetPointer)
}
}
internal suspend fun computeDocumentation(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return withContext(Dispatchers.Default) {
val documentationResult: DocumentationResult? = readAction {
targetPointer.dereference()?.computeDocumentation()
}
@Suppress("REDUNDANT_ELSE_IN_WHEN")
when (documentationResult) {
is DocumentationResultData -> documentationResult
is AsyncDocumentation -> documentationResult.supplier.invoke() as DocumentationResultData?
null -> null
else -> error("Unexpected result: $documentationResult") // this fixes Kotlin incremental compilation
}
}
}
@Internal
suspend fun handleLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult {
return withContext(Dispatchers.Default) {
tryResolveLink(targetPointer, url)
?: tryContentUpdater(targetPointer, url)
?: InternalLinkResult.CannotResolve
}
}
private suspend fun tryResolveLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return when (val resolveResult = resolveLink(targetPointer::dereference, url)) {
InternalResolveLinkResult.InvalidTarget -> InternalLinkResult.InvalidTarget
InternalResolveLinkResult.CannotResolve -> null
is InternalResolveLinkResult.Value -> InternalLinkResult.Request(resolveResult.value)
}
}
internal sealed class InternalResolveLinkResult<out X> {
object InvalidTarget : InternalResolveLinkResult<Nothing>()
object CannotResolve : InternalResolveLinkResult<Nothing>()
class Value<X>(val value: X) : InternalResolveLinkResult<X>()
}
/**
* @return `null` if [contextTarget] was invalidated, or [url] cannot be resolved
*/
@Internal // for Fleet
suspend fun resolveLinkToTarget(contextTarget: Pointer<out DocumentationTarget>, url: String): Pointer<out DocumentationTarget>? {
return when (val resolveLinkResult = resolveLink(contextTarget::dereference, url, DocumentationTarget::createPointer)) {
InternalResolveLinkResult.CannotResolve -> null
InternalResolveLinkResult.InvalidTarget -> null
is InternalResolveLinkResult.Value -> resolveLinkResult.value
}
}
internal suspend fun resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
): InternalResolveLinkResult<DocumentationRequest> {
return resolveLink(targetSupplier, url, DocumentationTarget::documentationRequest)
}
/**
* @param ram read action mapper - a function which would be applied to resolved [DocumentationTarget] while holding the read action
*/
internal suspend fun <X> resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val readActionResult = readAction {
resolveLinkInReadAction(targetSupplier, url, ram)
}
return when (readActionResult) {
is ResolveLinkInReadActionResult.Sync -> readActionResult.syncResult
is ResolveLinkInReadActionResult.Async -> asyncTarget(readActionResult.supplier, ram)
}
}
private suspend fun <X> asyncTarget(
supplier: AsyncSupplier<LinkResolveResult.Async?>,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val asyncLinkResolveResult: LinkResolveResult.Async? = supplier.invoke()
if (asyncLinkResolveResult == null) {
return InternalResolveLinkResult.CannotResolve
}
when (asyncLinkResolveResult) {
is AsyncResolvedTarget -> {
val pointer = asyncLinkResolveResult.pointer
return readAction {
val target: DocumentationTarget? = pointer.dereference()
if (target == null) {
InternalResolveLinkResult.InvalidTarget
}
else {
InternalResolveLinkResult.Value(ram(target))
}
}
}
else -> error("Unexpected result: $asyncLinkResolveResult")
}
}
private sealed class ResolveLinkInReadActionResult<out X> {
class Sync<X>(val syncResult: InternalResolveLinkResult<X>) : ResolveLinkInReadActionResult<X>()
class Async(val supplier: AsyncSupplier<LinkResolveResult.Async?>) : ResolveLinkInReadActionResult<Nothing>()
}
private fun <X> resolveLinkInReadAction(
targetSupplier: () -> DocumentationTarget?,
url: String,
m: (DocumentationTarget) -> X,
): ResolveLinkInReadActionResult<X> {
val documentationTarget = targetSupplier()
?: return ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.InvalidTarget)
@Suppress("REDUNDANT_ELSE_IN_WHEN")
return when (val linkResolveResult: LinkResolveResult? = resolveLink(documentationTarget, url)) {
null -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.CannotResolve)
is ResolvedTarget -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.Value(m(linkResolveResult.target)))
is AsyncLinkResolveResult -> ResolveLinkInReadActionResult.Async(linkResolveResult.supplier)
else -> error("Unexpected result: $linkResolveResult") // this fixes Kotlin incremental compilation
}
}
private fun resolveLink(target: DocumentationTarget, url: String): LinkResolveResult? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.resolveLink(target, url) ?: continue
}
return null
}
private suspend fun tryContentUpdater(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return readAction {
contentUpdaterInReadAction(targetPointer, url)
}
}
private fun contentUpdaterInReadAction(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
val target = targetPointer.dereference()
?: return InternalLinkResult.InvalidTarget
val updater = contentUpdater(target, url)
?: return null
return InternalLinkResult.Updater(updater)
}
private fun contentUpdater(target: DocumentationTarget, url: String): ContentUpdater? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.contentUpdater(target, url) ?: continue
}
return null
}
@TestOnly
fun computeDocumentationBlocking(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return runBlocking {
withTimeout(1000 * 60) {
computeDocumentation(targetPointer)
}
}
}
| apache-2.0 | 5f2c17ed98a0c800e5246989d7999d5c | 39.858491 | 132 | 0.772801 | 5.205529 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt | 1 | 4764 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.idea.base.psi.mustHaveOnlyPropertiesInPrimaryConstructor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class MovePropertyToClassBodyIntention : SelfTargetingIntention<KtParameter>(
KtParameter::class.java,
KotlinBundle.lazyMessage("move.to.class.body")
) {
override fun isApplicableTo(element: KtParameter, caretOffset: Int): Boolean {
if (!element.isPropertyParameter()) return false
val containingClass = element.containingClass() ?: return false
return !containingClass.mustHaveOnlyPropertiesInPrimaryConstructor()
}
override fun applyTo(element: KtParameter, editor: Editor?) {
val parentClass = PsiTreeUtil.getParentOfType(element, KtClass::class.java) ?: return
val propertyDeclaration = KtPsiFactory(element.project)
.createProperty("${element.valOrVarKeyword?.text} ${element.name} = ${element.name}")
val firstProperty = parentClass.getProperties().firstOrNull()
parentClass.addDeclarationBefore(propertyDeclaration, firstProperty).apply {
val propertyModifierList = element.modifierList?.copy() as? KtModifierList
propertyModifierList?.getModifier(KtTokens.VARARG_KEYWORD)?.delete()
propertyModifierList?.let { modifierList?.replace(it) ?: addBefore(it, firstChild) }
modifierList?.annotationEntries?.forEach {
if (!it.isAppliedToProperty()) {
it.delete()
} else if (it.useSiteTarget?.getAnnotationUseSiteTarget() == AnnotationUseSiteTarget.PROPERTY) {
it.useSiteTarget?.removeWithColon()
}
}
}
element.valOrVarKeyword?.delete()
val parameterAnnotationsText = element.modifierList?.annotationEntries
?.filter { it.isAppliedToConstructorParameter() }
?.takeIf { it.isNotEmpty() }
?.joinToString(separator = " ") { it.textWithoutUseSite() }
val hasVararg = element.hasModifier(KtTokens.VARARG_KEYWORD)
if (parameterAnnotationsText != null) {
element.modifierList?.replace(KtPsiFactory(element.project).createModifierList(parameterAnnotationsText))
} else {
element.modifierList?.delete()
}
if (hasVararg) element.addModifier(KtTokens.VARARG_KEYWORD)
}
private fun KtAnnotationEntry.isAppliedToProperty(): Boolean {
useSiteTarget?.getAnnotationUseSiteTarget()?.let {
return it == AnnotationUseSiteTarget.FIELD
|| it == AnnotationUseSiteTarget.PROPERTY
|| it == AnnotationUseSiteTarget.PROPERTY_GETTER
|| it == AnnotationUseSiteTarget.PROPERTY_SETTER
|| it == AnnotationUseSiteTarget.SETTER_PARAMETER
}
return !isApplicableToConstructorParameter()
}
private fun KtAnnotationEntry.isAppliedToConstructorParameter(): Boolean {
useSiteTarget?.getAnnotationUseSiteTarget()?.let {
return it == AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER
}
return isApplicableToConstructorParameter()
}
private fun KtAnnotationEntry.isApplicableToConstructorParameter(): Boolean {
val context = analyze(BodyResolveMode.PARTIAL)
val descriptor = context[BindingContext.ANNOTATION, this] ?: return false
val applicableTargets = AnnotationChecker.applicableTargetSet(descriptor)
return applicableTargets.contains(KotlinTarget.VALUE_PARAMETER)
}
private fun KtAnnotationEntry.textWithoutUseSite() = "@" + typeReference?.text.orEmpty() + valueArgumentList?.text.orEmpty()
private fun KtAnnotationUseSiteTarget.removeWithColon() {
nextSibling?.delete() // ':' symbol after use site
delete()
}
}
| apache-2.0 | 5d8c0566c7d80600cb4fb46c7253fc7d | 46.64 | 158 | 0.717674 | 5.539535 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/sdk/HaskellSdkType.kt | 1 | 9000 | package org.jetbrains.haskell.sdk
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.projectRoots.*
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import org.jdom.Element
import org.jetbrains.annotations.Nullable
import org.jetbrains.haskell.icons.HaskellIcons
import org.jetbrains.haskell.util.ProcessRunner
import javax.swing.*
import java.io.File
import java.io.FileFilter
import java.io.FilenameFilter
import java.util.*
import org.jetbrains.haskell.util.GHCVersion
import org.jetbrains.haskell.util.GHCUtil
import org.jetbrains.haskell.sdk.HaskellSdkType.SDKInfo
import kotlin.text.Regex
class HaskellSdkType : SdkType("GHC") {
companion object {
private val WINDOWS_EXECUTABLE_SUFFIXES = arrayOf("cmd", "exe", "bat", "com")
val INSTANCE: HaskellSdkType = HaskellSdkType()
private val GHC_ICON: Icon = HaskellIcons.HASKELL
private fun getLatestVersion(ghcPaths: List<File>): SDKInfo? {
val length = ghcPaths.size
if (length == 0)
return null
if (length == 1)
return SDKInfo(ghcPaths[0])
val ghcDirs = ArrayList<SDKInfo>()
for (name in ghcPaths) {
ghcDirs.add(SDKInfo(name))
}
Collections.sort(ghcDirs, object : Comparator<SDKInfo> {
override fun compare(d1: SDKInfo, d2: SDKInfo): Int {
return d1.version.compareTo(d2.version)
}
})
return ghcDirs.get(ghcDirs.size - 1)
}
fun checkForGhc(path: String): Boolean {
val file = File(path)
if (file.isDirectory) {
val children = file.listFiles(object : FileFilter {
override fun accept(f: File): Boolean {
if (f.isDirectory)
return false
return f.name == "ghc"
}
})
return children.isNotEmpty()
} else {
return isGhc(file.name)
}
}
fun isGhc(name : String) : Boolean =
name == "ghc" || name.matches("ghc-[.0-9*]+".toRegex())
fun getGhcVersion(ghcPath: File): String? {
if (ghcPath.isDirectory) {
return null
}
try {
return ProcessRunner(null).executeOrFail(ghcPath.toString(), "--numeric-version").trim()
} catch (ex: Exception) {
// ignore
}
return null
}
}
class SDKInfo(val ghcPath: File) {
val version: GHCVersion = getVersion(ghcPath.name)
companion object {
fun getVersion(name: String?): GHCVersion {
val versionStr : List<String> = if (name == null) {
listOf<String>()
} else {
name.split("[^0-9]+".toRegex()).filter { !it.isEmpty() }
}
val parts = ArrayList<Int>()
for (part in versionStr) {
if (part.isEmpty())
continue
try {
parts.add(part.toInt())
} catch (nfex: NumberFormatException) {
// ignore
}
}
return GHCVersion(parts)
}
}
}
override fun getHomeChooserDescriptor(): FileChooserDescriptor {
val isWindows = SystemInfo.isWindows
return object : FileChooserDescriptor(true, false, false, false, false, false) {
@Throws(Exception::class)
override fun validateSelectedFiles(files: Array<VirtualFile>?) {
if (files!!.size != 0) {
if (!isValidSdkHome(files[0].path)) {
throw Exception("Not valid ghc " + files[0].name)
}
}
}
override fun isFileVisible(file: VirtualFile, showHiddenFiles: Boolean): Boolean {
if (!file.isDirectory) {
if (!file.name.toLowerCase().startsWith("ghc")) {
return false
}
if (isWindows) {
val path = file.path
var looksExecutable = false
for (ext in WINDOWS_EXECUTABLE_SUFFIXES) {
if (path.endsWith(ext)) {
looksExecutable = true
break
}
}
return looksExecutable && super.isFileVisible(file, showHiddenFiles)
}
}
return super.isFileVisible(file, showHiddenFiles)
}
}.withTitle("Select GHC executable").withShowHiddenFiles(SystemInfo.isUnix)
}
override fun suggestHomePath(): String? {
val versions: List<File>
if (SystemInfo.isLinux) {
val versionsRoot = File("/usr/bin")
if (!versionsRoot.isDirectory) {
return null
}
versions = (versionsRoot.listFiles(object : FilenameFilter {
override fun accept(dir: File, name: String): Boolean {
return !File(dir, name).isDirectory && isGhc(name.toLowerCase())
}
})?.toList() ?: listOf())
} else if (SystemInfo.isWindows) {
throw UnsupportedOperationException()
/*
var progFiles = System.getenv("ProgramFiles(x86)")
if (progFiles == null) {
progFiles = System.getenv("ProgramFiles")
}
if (progFiles == null)
return null
val versionsRoot = File(progFiles, "Haskell Platform")
if (!versionsRoot.isDirectory)
return progFiles
versions = versionsRoot.listFiles()?.toList() ?: listOf()
*/
} else if (SystemInfo.isMac) {
throw UnsupportedOperationException()
/*
val macVersions = ArrayList<File>()
val versionsRoot = File("/Library/Frameworks/GHC.framework/Versions/")
if (versionsRoot.isDirectory()) {
macVersions.addAll(versionsRoot.listFiles()?.toList() ?: listOf())
}
val brewVersionsRoot = File("/usr/local/Cellar/ghc")
if (brewVersionsRoot.isDirectory()) {
macVersions.addAll(brewVersionsRoot.listFiles()?.toList() ?: listOf())
}
versions = macVersions
*/
} else {
return null
}
val latestVersion = getLatestVersion(versions)
return latestVersion?.ghcPath?.absolutePath
}
override fun isValidSdkHome(path: String?): Boolean {
return checkForGhc(path!!)
}
override fun suggestSdkName(currentSdkName: String?, sdkHome: String?): String {
val suggestedName: String
if (currentSdkName != null && currentSdkName.length > 0) {
suggestedName = currentSdkName
} else {
val versionString = getVersionString(sdkHome)
if (versionString != null) {
suggestedName = "GHC " + versionString
} else {
suggestedName = "Unknown"
}
}
return suggestedName
}
override fun getVersionString(sdkHome: String?): String? {
if (sdkHome == null) {
return null
}
val versionString: String? = getGhcVersion(File(sdkHome))
if (versionString != null && versionString.length == 0) {
return null
}
return versionString
}
override fun createAdditionalDataConfigurable(sdkModel: SdkModel,
sdkModificator: SdkModificator): AdditionalDataConfigurable {
return HaskellSdkConfigurable()
}
override fun saveAdditionalData(additionalData: SdkAdditionalData, additional: Element) {
if (additionalData is HaskellSdkAdditionalData) {
additionalData.save(additional)
}
}
override fun loadAdditionalData(additional: Element?): SdkAdditionalData? {
return HaskellSdkAdditionalData.load(additional!!)
}
override fun getPresentableName(): String {
return "GHC"
}
override fun getIcon(): Icon {
return GHC_ICON
}
override fun getIconForAddAction(): Icon {
return icon
}
override fun setupSdkPaths(sdk: Sdk) {
}
override fun isRootTypeApplicable(rootType: OrderRootType): Boolean {
return false
}
}
| apache-2.0 | 06c37a724d29c96570475c4362df02f3 | 33.883721 | 111 | 0.540111 | 5.090498 | false | false | false | false |
exercism/xkotlin | exercises/practice/armstrong-numbers/src/test/kotlin/ArmstrongNumberTest.kt | 1 | 1170 | import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class ArmstrongNumberTest {
@Test
fun `zero is an armstrong number`() = assertTrue(ArmstrongNumber.check(0))
@Test
fun `single digit numbers are armstrong numbers`() = assertTrue(ArmstrongNumber.check(5))
@Test
fun `there are no 2 digit armstrong numbers`() = assertFalse(ArmstrongNumber.check(10))
@Test
fun `three digit number that is an armstrong number`() = assertTrue(ArmstrongNumber.check(153))
@Test
fun `three digit number that is not an armstrong number`() = assertFalse(ArmstrongNumber.check(100))
@Test
fun `four digit number that is an armstrong number`() = assertTrue(ArmstrongNumber.check(9474))
@Test
fun `four digit number that is not an armstrong number`() = assertFalse(ArmstrongNumber.check(9475))
@Test
fun `seven digit number that is an armstrong number`() = assertTrue(ArmstrongNumber.check(9926315))
@Test
fun `seven digit number that is not an armstrong number`() = assertFalse(ArmstrongNumber.check(9926314))
}
| mit | bc18eb264923370b488bd66c54c75869 | 32.428571 | 108 | 0.733333 | 4.020619 | false | true | false | false |
allotria/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/configurers/MavenEncodingConfigurer.kt | 3 | 4184 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.importing.configurers
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.encoding.EncodingProjectManager
import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.utils.MavenLog
import java.io.File
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
/**
* @author Sergey Evdokimov
*/
class MavenEncodingConfigurer : MavenModuleConfigurer() {
override fun configure(mavenProject: MavenProject, project: Project, module: Module) {
val newMap = LinkedHashMap<VirtualFile, Charset>()
val leaveAsIsMap = LinkedHashMap<VirtualFile, Charset>()
val projectManagerImpl = (EncodingProjectManager.getInstance(project) as EncodingProjectManagerImpl)
ReadAction.compute<Unit, Throwable> {
fillSourceEncoding(mavenProject, newMap, leaveAsIsMap, projectManagerImpl)
}
ReadAction.compute<Unit, Throwable> {
fillResourceEncoding(project, mavenProject, newMap, leaveAsIsMap, projectManagerImpl)
}
if (newMap.isEmpty()) {
return
}
newMap.putAll(leaveAsIsMap)
ApplicationManager.getApplication().invokeAndWait {
projectManagerImpl.setMapping(newMap)
}
}
private fun fillResourceEncoding(project: Project,
mavenProject: MavenProject,
newMap: LinkedHashMap<VirtualFile, Charset>,
leaveAsIsMap: LinkedHashMap<VirtualFile, Charset>,
projectManagerImpl: EncodingProjectManagerImpl) {
mavenProject.getResourceEncoding(project)?.let(this::getCharset)?.let { charset ->
mavenProject.resources.forEach { resource ->
val dirVfile = LocalFileSystem.getInstance().findFileByIoFile(File(resource.directory)) ?: return
newMap[dirVfile] = charset
projectManagerImpl.allMappings.forEach {
if (FileUtil.isAncestor(resource.directory, it.key.path, false)) {
newMap[it.key] = charset
}
else {
leaveAsIsMap[it.key] = it.value
}
}
}
}
}
private fun fillSourceEncoding(mavenProject: MavenProject,
newMap: LinkedHashMap<VirtualFile, Charset>,
leaveAsIsMap: LinkedHashMap<VirtualFile, Charset>,
projectManagerImpl: EncodingProjectManagerImpl) {
mavenProject.sourceEncoding?.let(this::getCharset)?.let { charset ->
mavenProject.sources.forEach { directory ->
val dirVfile = LocalFileSystem.getInstance().findFileByIoFile(File(directory)) ?: return
newMap[dirVfile] = charset
projectManagerImpl.allMappings.forEach {
if (FileUtil.isAncestor(directory, it.key.path, false)) {
newMap[it.key] = charset
}
else {
leaveAsIsMap[it.key] = it.value
}
}
}
}
}
private fun getCharset(name: String): Charset? {
try {
return Charset.forName(name)
}
catch (e: UnsupportedCharsetException) {
MavenLog.LOG.warn("Charset ${name} is not supported")
return null
}
}
}
| apache-2.0 | 819005748e01c4a67e866c10071d2525 | 36.693694 | 105 | 0.686663 | 4.727684 | false | false | false | false |
langerhans/discord-github-webhooks | src/main/kotlin/de/langerhans/discord/gitbot/util/GithubDateTypeAdapter.kt | 1 | 1741 | package de.langerhans.discord.gitbot.util
import com.google.gson.JsonSyntaxException
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* Adapted from http://stackoverflow.com/a/37438619
*/
class GithubDateTypeAdapter : TypeAdapter<Date>() {
private val iso8601Format = buildIso8601Format()
@Throws(IOException::class)
override fun read(reader: JsonReader): Date? {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull()
return null
}
return deserializeToDate(reader.nextString())
}
@Synchronized private fun deserializeToDate(json: String): Date {
try {
return iso8601Format.parse(json)
} catch (e: ParseException) {
try {
return Date(json.toLong())
} catch (e: NumberFormatException) {
throw JsonSyntaxException(json, e)
}
}
}
@Synchronized @Throws(IOException::class)
override fun write(out: JsonWriter, value: Date?) {
if (value == null) {
out.nullValue()
return
}
val dateFormatAsString = iso8601Format.format(value)
out.value(dateFormatAsString)
}
companion object {
private fun buildIso8601Format(): DateFormat {
val iso8601Format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US)
iso8601Format.timeZone = TimeZone.getTimeZone("UTC")
return iso8601Format
}
}
}
| mit | 48a9ddae3284f87716123ea98daa90b3 | 28.508475 | 87 | 0.643308 | 4.363409 | false | false | false | false |
spring-projects/spring-framework | spring-webmvc/src/main/kotlin/org/springframework/web/servlet/function/RouterFunctionDsl.kt | 1 | 27951 | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.web.servlet.function
import org.springframework.core.io.Resource
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import java.net.URI
import java.util.Optional
import java.util.function.Supplier
/**
* Allow to create easily a WebMvc.fn [RouterFunction] with a [Reactive router Kotlin DSL][RouterFunctionDsl].
*
* Example:
*
* ```
* @Configuration
* class RouterConfiguration {
*
* @Bean
* fun mainRouter(userHandler: UserHandler) = router {
* accept(TEXT_HTML).nest {
* (GET("/user/") or GET("/users/")).invoke(userHandler::findAllView)
* GET("/users/{login}", userHandler::findViewById)
* }
* accept(APPLICATION_JSON).nest {
* (GET("/api/user/") or GET("/api/users/")).invoke(userHandler::findAll)
* POST("/api/users/", userHandler::create)
* }
* }
*
* }
* ```
* @author Sebastien Deleuze
* @author Arjen Poutsma
* @since 5.2
*/
fun router(routes: (RouterFunctionDsl.() -> Unit)) = RouterFunctionDsl(routes).build()
/**
* Provide a WebMvc.fn [RouterFunction] Reactive Kotlin DSL created by [`router { }`][router] in order to be able to write idiomatic Kotlin code.
*
* @author Sebastien Deleuze
* @since 5.2
*/
class RouterFunctionDsl internal constructor (private val init: (RouterFunctionDsl.() -> Unit)) {
@PublishedApi
internal val builder = RouterFunctions.route()
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun RequestPredicate.and(other: String): RequestPredicate = this.and(path(other))
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun RequestPredicate.or(other: String): RequestPredicate = this.or(path(other))
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) AND the [other] predicate. When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun String.and(other: RequestPredicate): RequestPredicate = path(this).and(other)
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) OR the [other] predicate. When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun String.or(other: RequestPredicate): RequestPredicate = path(this).or(other)
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `false`, then the [other] predicate is not evaluated.
* @see RequestPredicate.and
*/
infix fun RequestPredicate.and(other: RequestPredicate): RequestPredicate = this.and(other)
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `true`, then the [other] predicate is not evaluated.
* @see RequestPredicate.or
*/
infix fun RequestPredicate.or(other: RequestPredicate): RequestPredicate = this.or(other)
/**
* Return a predicate that represents the logical negation of this predicate.
*/
operator fun RequestPredicate.not(): RequestPredicate = this.negate()
/**
* Route to the given router function if the given request predicate applies. This
* method can be used to create *nested routes*, where a group of routes share a
* common path (prefix), header, or other request predicate.
* @see RouterFunctions.nest
*/
fun RequestPredicate.nest(r: (RouterFunctionDsl.() -> Unit)) {
builder.nest(this, Supplier(RouterFunctionDsl(r)::build))
}
/**
* Route to the given router function if the given request predicate (String
* processed as a path predicate) applies. This method can be used to create
* *nested routes*, where a group of routes share a common path
* (prefix), header, or other request predicate.
* @see RouterFunctions.nest
* @see RequestPredicates.path
*/
fun String.nest(r: (RouterFunctionDsl.() -> Unit)) = path(this).nest(r)
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests.
* @since 5.3
*/
fun GET(f: (ServerRequest) -> ServerResponse) {
builder.GET(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun GET(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.GET(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun GET(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.GET(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun GET(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.GET(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `GET`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.GET
*/
fun GET(pattern: String): RequestPredicate = RequestPredicates.GET(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests.
* @since 5.3
*/
fun HEAD(f: (ServerRequest) -> ServerResponse) {
builder.HEAD(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun HEAD(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.HEAD(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun HEAD(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.HEAD(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun HEAD(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.HEAD(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `HEAD`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.HEAD
*/
fun HEAD(pattern: String): RequestPredicate = RequestPredicates.HEAD(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests.
* @since 5.3
*/
fun POST(f: (ServerRequest) -> ServerResponse) {
builder.POST(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun POST(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.POST(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun POST(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.POST(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun POST(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.POST(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `POST`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.POST
*/
fun POST(pattern: String): RequestPredicate = RequestPredicates.POST(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests.
* @since 5.3
*/
fun PUT(f: (ServerRequest) -> ServerResponse) {
builder.PUT(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PUT(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.PUT(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun PUT(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PUT(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PUT(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PUT(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PUT`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.PUT
*/
fun PUT(pattern: String): RequestPredicate = RequestPredicates.PUT(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests.
* @since 5.3
*/
fun PATCH(f: (ServerRequest) -> ServerResponse) {
builder.PATCH(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PATCH(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.PATCH(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun PATCH(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PATCH(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PATCH(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PATCH(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PATCH`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `PATCH` and if the given pattern
* matches against the request path
*/
fun PATCH(pattern: String): RequestPredicate = RequestPredicates.PATCH(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests.
* @since 5.3
*/
fun DELETE(f: (ServerRequest) -> ServerResponse) {
builder.DELETE(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun DELETE(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.DELETE(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun DELETE(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.DELETE(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun DELETE(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.DELETE(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `DELETE`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `DELETE` and if the given pattern
* matches against the request path
*/
fun DELETE(pattern: String): RequestPredicate = RequestPredicates.DELETE(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests.
* @since 5.3
*/
fun OPTIONS(f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun OPTIONS(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun OPTIONS(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun OPTIONS(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `OPTIONS`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `OPTIONS` and if the given pattern
* matches against the request path
*/
fun OPTIONS(pattern: String): RequestPredicate = RequestPredicates.OPTIONS(pattern)
/**
* Route to the given handler function if the given accept predicate applies.
* @see RouterFunctions.route
*/
fun accept(mediaType: MediaType, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.accept(mediaType), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [accept][ServerRequest.Headers.accept] } header is
* [compatible][MediaType.isCompatibleWith] with any of the given media types.
* @param mediaType the media types to match the request's accept header against
* @return a predicate that tests the request's accept header against the given media types
*/
fun accept(vararg mediaType: MediaType): RequestPredicate = RequestPredicates.accept(*mediaType)
/**
* Route to the given handler function if the given contentType predicate applies.
* @see RouterFunctions.route
*/
fun contentType(mediaType: MediaType, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.contentType(mediaType), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [content type][ServerRequest.Headers.contentType] is
* [included][MediaType.includes] by any of the given media types.
* @param mediaTypes the media types to match the request's content type against
* @return a predicate that tests the request's content type against the given media types
*/
fun contentType(vararg mediaTypes: MediaType): RequestPredicate = RequestPredicates.contentType(*mediaTypes)
/**
* Route to the given handler function if the given headers predicate applies.
* @see RouterFunctions.route
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.headers(headersPredicate), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request's headers against the given headers predicate.
* @param headersPredicate a predicate that tests against the request headers
* @return a predicate that tests against the given header predicate
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean): RequestPredicate =
RequestPredicates.headers(headersPredicate)
/**
* Route to the given handler function if the given method predicate applies.
* @see RouterFunctions.route
*/
fun method(httpMethod: HttpMethod, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.method(httpMethod), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests against the given HTTP method.
* @param httpMethod the HTTP method to match to
* @return a predicate that tests against the given HTTP method
*/
fun method(httpMethod: HttpMethod): RequestPredicate = RequestPredicates.method(httpMethod)
/**
* Route to the given handler function if the given path predicate applies.
* @see RouterFunctions.route
*/
fun path(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.path(pattern), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request path against the given path pattern.
* @see RequestPredicates.path
*/
fun path(pattern: String): RequestPredicate = RequestPredicates.path(pattern)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(extension: String, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(extension), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that matches if the request's path has the given extension.
* @param extension the path extension to match against, ignoring case
* @return a predicate that matches if the request's path has the given file extension
*/
fun pathExtension(extension: String): RequestPredicate = RequestPredicates.pathExtension(extension)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(predicate: (String) -> Boolean, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(predicate), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that matches if the request's path matches the given
* predicate.
* @see RequestPredicates.pathExtension
*/
fun pathExtension(predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.pathExtension(predicate)
/**
* Route to the given handler function if the given queryParam predicate applies.
* @see RouterFunctions.route
*/
fun param(name: String, predicate: (String) -> Boolean, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.param(name, predicate), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request's query parameter of the given name
* against the given predicate.
* @param name the name of the query parameter to test against
* @param predicate the predicate to test against the query parameter value
* @return a predicate that matches the given predicate against the query parameter of the given name
* @see ServerRequest#queryParam
*/
fun param(name: String, predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.param(name, predicate)
/**
* Route to the given handler function if the given request predicate applies.
* @see RouterFunctions.route
*/
operator fun RequestPredicate.invoke(f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(this, HandlerFunction(f)))
}
/**
* Route to the given handler function if the given predicate (String
* processed as a path predicate) applies.
* @see RouterFunctions.route
*/
operator fun String.invoke(f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.path(this), HandlerFunction(f)))
}
/**
* Route requests that match the given pattern to resources relative to the given root location.
* @see RouterFunctions.resources
*/
fun resources(path: String, location: Resource) {
builder.resources(path, location)
}
/**
* Route to resources using the provided lookup function. If the lookup function provides a
* [Resource] for the given request, it will be it will be exposed using a
* [HandlerFunction] that handles GET, HEAD, and OPTIONS requests.
*/
fun resources(lookupFunction: (ServerRequest) -> Resource?) {
builder.resources {
Optional.ofNullable(lookupFunction.invoke(it))
}
}
/**
* Merge externally defined router functions into this one.
* @param routerFunction the router function to be added
* @since 5.2
*/
fun add(routerFunction: RouterFunction<ServerResponse>) {
builder.add(routerFunction)
}
/**
* Filters all routes created by this router with the given filter function. Filter
* functions are typically used to address cross-cutting concerns, such as logging,
* security, etc.
* @param filterFunction the function to filter all routes built by this router
* @since 5.2
*/
fun filter(filterFunction: (ServerRequest, (ServerRequest) -> ServerResponse) -> ServerResponse) {
builder.filter { request, next ->
filterFunction(request) { handlerRequest ->
next.handle(handlerRequest)
}
}
}
/**
* Filter the request object for all routes created by this builder with the given request
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param requestProcessor a function that transforms the request
* @since 5.2
*/
fun before(requestProcessor: (ServerRequest) -> ServerRequest) {
builder.before(requestProcessor)
}
/**
* Filter the response object for all routes created by this builder with the given response
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param responseProcessor a function that transforms the response
* @since 5.2
*/
fun after(responseProcessor: (ServerRequest, ServerResponse) -> ServerResponse) {
builder.after(responseProcessor)
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param predicate the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
fun onError(predicate: (Throwable) -> Boolean, responseProvider: (Throwable, ServerRequest) -> ServerResponse) {
builder.onError(predicate, responseProvider)
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param E the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
inline fun <reified E : Throwable> onError(noinline responseProvider: (Throwable, ServerRequest) -> ServerResponse) {
builder.onError({it is E}, responseProvider)
}
/**
* Add an attribute with the given name and value to the last route built with this builder.
* @param name the attribute name
* @param value the attribute value
* @since 6.0
*/
fun withAttribute(name: String, value: Any) {
builder.withAttribute(name, value)
}
/**
* Manipulate the attributes of the last route built with the given consumer.
*
* The map provided to the consumer is "live", so that the consumer can be used
* to [overwrite][MutableMap.put] existing attributes,
* [remove][MutableMap.remove] attributes, or use any of the other
* [MutableMap] methods.
* @param attributesConsumer a function that consumes the attributes map
* @since 6.0
*/
fun withAttributes(attributesConsumer: (MutableMap<String, Any>) -> Unit) {
builder.withAttributes(attributesConsumer)
}
/**
* Return a composed routing function created from all the registered routes.
*/
internal fun build(): RouterFunction<ServerResponse> {
init()
return builder.build()
}
/**
* @see ServerResponse.from
*/
fun from(other: ServerResponse) =
ServerResponse.from(other)
/**
* @see ServerResponse.created
*/
fun created(location: URI) =
ServerResponse.created(location)
/**
* @see ServerResponse.ok
*/
fun ok() = ServerResponse.ok()
/**
* @see ServerResponse.noContent
*/
fun noContent() = ServerResponse.noContent()
/**
* @see ServerResponse.accepted
*/
fun accepted() = ServerResponse.accepted()
/**
* @see ServerResponse.permanentRedirect
*/
fun permanentRedirect(location: URI) = ServerResponse.permanentRedirect(location)
/**
* @see ServerResponse.temporaryRedirect
*/
fun temporaryRedirect(location: URI) = ServerResponse.temporaryRedirect(location)
/**
* @see ServerResponse.seeOther
*/
fun seeOther(location: URI) = ServerResponse.seeOther(location)
/**
* @see ServerResponse.badRequest
*/
fun badRequest() = ServerResponse.badRequest()
/**
* @see ServerResponse.notFound
*/
fun notFound() = ServerResponse.notFound()
/**
* @see ServerResponse.unprocessableEntity
*/
fun unprocessableEntity() = ServerResponse.unprocessableEntity()
/**
* @see ServerResponse.status
*/
fun status(status: HttpStatusCode) = ServerResponse.status(status)
/**
* @see ServerResponse.status
*/
fun status(status: Int) = ServerResponse.status(status)
}
/**
* Equivalent to [RouterFunction.and].
*/
operator fun <T: ServerResponse> RouterFunction<T>.plus(other: RouterFunction<T>) =
this.and(other)
| apache-2.0 | 25b3f60ad65a84bbbcb18f6d9c958d17 | 33.635688 | 145 | 0.727845 | 4.151344 | false | false | false | false |
leafclick/intellij-community | platform/script-debugger/backend/src/debugger/sourcemap/SourceResolver.kt | 1 | 6225 | // 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 org.jetbrains.debugger.sourcemap
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.containers.ObjectIntHashMap
import com.intellij.util.io.URLUtil
import org.jetbrains.debugger.ScriptDebuggerUrls
import java.io.File
interface SourceFileResolver {
/**
* Return -1 if no match
*/
fun resolve(map: ObjectIntHashMap<Url>): Int = -1
fun resolve(rawSources: List<String>): Int = -1
}
class SourceResolver(private val rawSources: List<String>,
trimFileScheme: Boolean,
baseUrl: Url?,
baseUrlIsFile: Boolean = true) {
companion object {
fun isAbsolute(path: String): Boolean = path.startsWith('/') || (SystemInfo.isWindows && (path.length > 2 && path[1] == ':'))
}
val canonicalizedUrls: Array<Url> by lazy {
Array(rawSources.size) { canonicalizeUrl(rawSources[it], baseUrl, trimFileScheme, baseUrlIsFile) }
}
private val canonicalizedUrlToSourceIndex: ObjectIntHashMap<Url> by lazy {
(
if (SystemInfo.isFileSystemCaseSensitive) ObjectIntHashMap(rawSources.size)
else ObjectIntHashMap(rawSources.size, Urls.caseInsensitiveUrlHashingStrategy)
).also {
for (i in rawSources.indices) {
it.put(canonicalizedUrls[i], i)
}
}
}
fun getSource(entry: MappingEntry): Url? {
val index = entry.source
return if (index < 0) null else canonicalizedUrls[index]
}
fun getSourceIndex(url: Url): Int = canonicalizedUrlToSourceIndex[url]
internal fun findSourceIndex(resolver: SourceFileResolver): Int {
val resolveByCanonicalizedUrls = resolver.resolve(canonicalizedUrlToSourceIndex)
return if (resolveByCanonicalizedUrls != -1) resolveByCanonicalizedUrls else resolver.resolve(rawSources)
}
fun findSourceIndex(sourceUrl: Url, sourceFile: VirtualFile?, localFileUrlOnly: Boolean): Int {
val index = canonicalizedUrlToSourceIndex.get(sourceUrl)
if (index != -1) {
return index
}
if (sourceFile != null) {
return findSourceIndexByFile(sourceFile, localFileUrlOnly)
}
return -1
}
internal fun findSourceIndexByFile(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int {
if (!localFileUrlOnly) {
val index = canonicalizedUrlToSourceIndex.get(Urls.newFromVirtualFile(sourceFile).trimParameters())
if (index != -1) {
return index
}
}
if (!sourceFile.isInLocalFileSystem) {
return -1
}
val index = canonicalizedUrlToSourceIndex.get(ScriptDebuggerUrls.newLocalFileUrl(sourceFile))
if (index != -1) {
return index
}
// ok, search by canonical path
val canonicalFile = sourceFile.canonicalFile
if (canonicalFile != null && canonicalFile != sourceFile) {
for (i in canonicalizedUrls.indices) {
val url = canonicalizedUrls.get(i)
if (Urls.equalsIgnoreParameters(url, canonicalFile)) {
return i
}
}
}
return -1
}
fun getUrlIfLocalFile(entry: MappingEntry): Url? = canonicalizedUrls.getOrNull(entry.source)?.let { if (it.isInLocalFileSystem) it else null }
}
fun canonicalizePath(url: String, baseUrl: Url, baseUrlIsFile: Boolean): String {
var path = url
if (!FileUtil.isAbsolute(url) && !url.isEmpty() && url[0] != '/') {
val basePath = baseUrl.path
if (baseUrlIsFile) {
val lastSlashIndex = basePath.lastIndexOf('/')
val pathBuilder = StringBuilder()
if (lastSlashIndex == -1) {
pathBuilder.append('/')
}
else {
pathBuilder.append(basePath, 0, lastSlashIndex + 1)
}
path = pathBuilder.append(url).toString()
}
else {
path = "$basePath/$url"
}
}
return FileUtil.toCanonicalPath(path, '/')
}
// see canonicalizeUri kotlin impl and https://trac.webkit.org/browser/trunk/Source/WebCore/inspector/front-end/ParsedURL.js completeURL
fun canonicalizeUrl(url: String, baseUrl: Url?, trimFileScheme: Boolean, baseUrlIsFile: Boolean = true): Url {
if (url.startsWith(StandardFileSystems.FILE_PROTOCOL_PREFIX)) {
return ScriptDebuggerUrls.newLocalFileUrl(FileUtil.toCanonicalPath(VfsUtilCore.toIdeaUrl(url, true).substring(StandardFileSystems.FILE_PROTOCOL_PREFIX.length), '/'))
}
else if (baseUrl == null || url.contains(URLUtil.SCHEME_SEPARATOR) || url.startsWith("data:") || url.startsWith("blob:") ||
url.startsWith("javascript:") || url.startsWith("webpack:")) {
// consider checking :/ instead of :// because scheme may be followed by path, not by authority
// https://tools.ietf.org/html/rfc3986#section-1.1.2
// be careful with windows paths: C:/Users
return Urls.parseEncoded(url) ?: Urls.newUri(null, url)
}
else {
return doCanonicalize(url, baseUrl, baseUrlIsFile, true)
}
}
fun doCanonicalize(url: String, baseUrl: Url, baseUrlIsFile: Boolean, asLocalFileIfAbsoluteAndExists: Boolean): Url {
val path = canonicalizePath(url, baseUrl, baseUrlIsFile)
if (baseUrl.isInLocalFileSystem ||
asLocalFileIfAbsoluteAndExists && SourceResolver.isAbsolute(path) && File(path).exists()) {
// file:///home/user/foo.js.map, foo.ts -> file:///home/user/foo.ts (baseUrl is in local fs)
// http://localhost/home/user/foo.js.map, foo.ts -> file:///home/user/foo.ts (File(path) exists)
return ScriptDebuggerUrls.newLocalFileUrl(path)
}
else if (!path.startsWith("/")) {
// http://localhost/source.js.map, C:/foo.ts webpack-dsj3c45 -> C:/foo.ts webpack-dsj3c45
// (we can't append path suffixes unless they start with /
return ScriptDebuggerUrls.parse(path, true) ?: Urls.newUnparsable(path)
}
else {
// new url from path and baseUrl's scheme and authority
val split = path.split('?', limit = 2)
return Urls.newUrl(baseUrl.scheme, baseUrl.authority, split[0], if (split.size > 1) '?' + split[1] else null)
}
} | apache-2.0 | fd39ee9a62bc0d4f3c1d10de7c17c0c1 | 37.670807 | 169 | 0.697028 | 4.130723 | false | false | false | false |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KSearchInsertPosition.kt | 1 | 1452 | package me.consuegra.algorithms
/**
* Given a sorted array and a target value, return the index if the target is found. If not, return the index
* where it would be if it were inserted in order.
* <p>
* You may assume no duplicates in the array.
* <p>
* Here are few examples.
* [1,3,5,6], 5 → 2
* [1,3,5,6], 2 → 1
* [1,3,5,6], 7 → 4
* [1,3,5,6], 0 → 0
*/
class KSearchInsertPosition {
fun searchInsert(input: IntArray, target: Int): Int {
var low = 0
var high = input.size - 1
while (low <= high) {
val middle = (low + high) / 2
when {
input[middle] < target -> low = middle + 1
input[middle] > target -> high = middle - 1
else -> return middle
}
}
return low
}
fun searchInsertRec(input: IntArray, target: Int): Int {
if (input.isEmpty()) {
return 0
}
return searchInsertRec(input, 0, input.size - 1, target)
}
fun searchInsertRec(input: IntArray, start: Int, end: Int, target: Int): Int {
if (start > end) {
return start
}
val middle = (start + end) / 2
when {
input[middle] < target -> return searchInsertRec(input, middle + 1, end, target)
input[middle] > target -> return searchInsertRec(input, start, middle - 1, target)
else -> return middle
}
}
}
| mit | 3cac03984bd70c60653c3428c2a73460 | 27.88 | 109 | 0.534626 | 3.693095 | false | false | false | false |
rizafu/CoachMark | app/src/main/java/com/rizafu/sample/SimpleFragment.kt | 1 | 5660 | package com.rizafu.sample
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.design.widget.BaseTransientBottomBar
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.rizafu.coachmark.CoachMark
import com.rizafu.sample.databinding.RecyclerLayoutBinding
/**
* Created by RizaFu on 2/27/17.
*/
class SimpleFragment : Fragment(){
private lateinit var binding: RecyclerLayoutBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.recycler_layout, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = SimpleAdapter()
adapter.addItem("Simple Coach Mark 1", "no tooltip, click target for dismiss")
adapter.addItem("Simple Coach Mark 2", "no tooltip, dismissible")
adapter.addItem("Simple Coach Mark 3", "no tooltip, with target custom click listener")
adapter.addItem("Coach Mark 1", "simple tooltip message at alignment bottom")
adapter.addItem("Coach Mark 2", "simple tooltip message at alignment top")
adapter.addItem("Coach Mark 3", "simple tooltip pointer at alignment left")
adapter.addItem("Coach Mark 4", "simple tooltip pointer at alignment right")
adapter.addItem("Coach Mark 5", "simple tooltip no pointer")
adapter.addItem("Simple Coach Mark 1", "no tooltip, click target for dismiss")
adapter.addItem("Simple Coach Mark 2", "no tooltip, dismissible")
adapter.addItem("Simple Coach Mark 3", "no tooltip, with target custom click listener")
adapter.addItem("Coach Mark 1", "simple tooltip message at alignment bottom")
adapter.addItem("Coach Mark 2", "simple tooltip message at alignment top")
adapter.addItem("Coach Mark 3", "simple tooltip pointer at alignment left")
adapter.addItem("Coach Mark 4", "simple tooltip pointer at alignment right")
adapter.addItem("Coach Mark 5", "simple tooltip no pointer")
binding.recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
adapter.setOnItemClick({v, p -> onClick(v,p)})
}
private fun onClick(view: View, position: Int) {
activity?.let {
when (position) {
0 -> CoachMark.Builder(it)
.setTarget(view)
.show()
1 -> CoachMark.Builder(it)
.setTarget(view)
.setDismissible()
.show()
2 -> CoachMark.Builder(it)
.setTarget(view)
.setOnClickTarget { coachMark ->
coachMark.dismiss()
Snackbar.make(view.rootView, "Action click on target mark", BaseTransientBottomBar.LENGTH_LONG).show()
}
.show()
3 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_dark)
.setTooltipAlignment(CoachMark.TARGET_BOTTOM)
.setTooltipBackgroundColor(R.color.colorPrimary)
.show()
4 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
5 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP_LEFT)
.setTooltipPointer(CoachMark.POINTER_LEFT)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
6 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP_RIGHT)
.setTooltipPointer(CoachMark.POINTER_RIGHT)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
7 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP)
.setTooltipPointer(CoachMark.POINTER_GONE)
.show()
else -> { }
}
}
}
companion object {
fun newInstance(): SimpleFragment {
val args = Bundle()
val fragment = SimpleFragment()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 4cd8bffd2f007d3a1f44896bb72a5955 | 45.393443 | 130 | 0.59417 | 4.908933 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/activities/MainActivity.kt | 1 | 10778 | package tech.salroid.filmy.ui.activities
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.speech.RecognizerIntent
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.preference.PreferenceManager
import androidx.viewpager.widget.ViewPager
import com.google.android.material.appbar.AppBarLayout
import com.miguelcatalan.materialsearchview.MaterialSearchView
import com.miguelcatalan.materialsearchview.MaterialSearchView.SearchViewListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import tech.salroid.filmy.R
import tech.salroid.filmy.data.network.NetworkUtil
import tech.salroid.filmy.databinding.ActivityMainBinding
import tech.salroid.filmy.ui.FilmyIntro
import tech.salroid.filmy.ui.activities.fragment.Trending
import tech.salroid.filmy.ui.activities.fragment.UpComing
import tech.salroid.filmy.ui.adapters.CollectionsPagerAdapter
import tech.salroid.filmy.ui.fragment.InTheaters
import tech.salroid.filmy.ui.fragment.SearchFragment
import tech.salroid.filmy.utility.getQueryTextChangeStateFlow
class MainActivity : AppCompatActivity() {
var fetchingFromNetwork = false
private var trendingFragment: Trending? = null
private lateinit var searchFragment: SearchFragment
private var cantProceed = false
private var nightMode = false
private lateinit var binding: ActivityMainBinding
private val mMessageReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val statusCode = intent.getIntExtra("message", 0)
cantProceed(statusCode)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
val sp = PreferenceManager.getDefaultSharedPreferences(this)
nightMode = sp.getBoolean("dark", false)
if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base)
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar?.title = " "
introLogic()
if (nightMode) allThemeLogic() else lightThemeLogic()
/* binding.mainErrorView.apply {
title = getString(R.string.error_title_damn)
titleColor = ContextCompat.getColor(context, R.color.dark)
setSubtitle(getString(R.string.error_details))
setRetryText(getString(R.string.error_retry))
}*/
/*binding.mainErrorView.setRetryListener {
if (NetworkUtil.isNetworkConnected(this@MainActivity)) {
fetchingFromNetwork = true
// fetchMoviesFromNetwork()
}
canProceed()
}*/
//binding.mainErrorView.visibility = View.GONE
setupSearch()
}
private fun setupSearch() {
binding.searchView.setVoiceSearch(false)
binding.searchView.setOnSearchViewListener(object : SearchViewListener {
override fun onSearchViewShown() {
binding.tabLayout.visibility = View.GONE
disableToolbarScrolling()
searchFragment = SearchFragment()
supportFragmentManager.beginTransaction()
.replace(R.id.search_container, searchFragment)
.commit()
}
override fun onSearchViewClosed() {
supportFragmentManager
.beginTransaction()
.remove(searchFragment)
.commit()
enableToolbarScrolling()
}
})
// Instant search using Flow
lifecycleScope.launch(Dispatchers.IO) {
binding.searchView.getQueryTextChangeStateFlow()
.debounce(300)
.filter { query ->
return@filter query.isNotEmpty()
}
.distinctUntilChanged()
.flatMapLatest { query ->
searchFragment.showProgress()
flow {
emit(NetworkUtil.searchMovies(query))
}.catch {
emitAll(flowOf(null))
}
}
.flowOn(Dispatchers.Main)
.collect { result ->
lifecycleScope.launch(Dispatchers.Main) {
result?.results?.let { searchFragment.showSearchResults(it) }
}
}
}
}
private fun allThemeLogic() {
binding.tabLayout.setTabTextColors(Color.parseColor("#bdbdbd"), Color.parseColor("#e0e0e0"))
binding.tabLayout.setBackgroundColor(
ContextCompat.getColor(
this,
R.color.colorDarkThemePrimary
)
)
binding.tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#bdbdbd"))
binding.logo.setTextColor(Color.parseColor("#E0E0E0"))
binding.searchView.setBackgroundColor(resources.getColor(R.color.colorDarkThemePrimary))
binding.searchView.setBackIcon(
ContextCompat.getDrawable(
this,
R.drawable.ic_action_navigation_arrow_back_inverted
)
)
binding.searchView.setCloseIcon(
ContextCompat.getDrawable(
this,
R.drawable.ic_action_navigation_close_inverted
)
)
binding.searchView.setTextColor(Color.parseColor("#ffffff"))
}
private fun lightThemeLogic() {
binding.logo.setTextColor(ContextCompat.getColor(this, R.color.dark))
}
private fun introLogic() {
val thread = Thread {
val getPrefs = PreferenceManager.getDefaultSharedPreferences(baseContext)
val isFirstStart = getPrefs.getBoolean("firstStart", true)
if (isFirstStart) {
val i = Intent(this@MainActivity, FilmyIntro::class.java)
startActivity(i)
val e = getPrefs.edit()
e.putBoolean("firstStart", false)
e.apply()
}
}
thread.start()
}
fun cantProceed(status: Int) {
Handler().postDelayed({
if (trendingFragment != null && !trendingFragment!!.isShowingFromDatabase) {
cantProceed = true
binding.tabLayout.visibility = View.GONE
//binding.viewpager.visibility = View.GONE
//binding.mainErrorView.visibility = View.VISIBLE
disableToolbarScrolling()
}
}, 1000)
}
private fun canProceed() {
cantProceed = false
binding.tabLayout.visibility = View.VISIBLE
//binding.viewpager.visibility = View.VISIBLE
//binding.mainErrorView.visibility = View.GONE
//trendingFragment?.retryLoading()
enableToolbarScrolling()
}
private fun disableToolbarScrolling() {
val params = binding.toolbarScroller.layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = 0
}
private fun enableToolbarScrolling() {
val params = binding.toolbarScroller.layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = (AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)
}
private fun setupViewPager(viewPager: ViewPager) {
trendingFragment = Trending()
val inTheatersFragment = InTheaters()
val upComingFragment = UpComing()
val adapter = CollectionsPagerAdapter(supportFragmentManager)
adapter.addFragment(trendingFragment!!, getString(R.string.trending))
// adapter.addFragment(inTheatersFragment, getString(R.string.theatres))
// adapter.addFragment(upComingFragment, getString(R.string.upcoming))
viewPager.adapter = adapter
}
private fun getSearchedResult(query: String) {
searchFragment.getSearchedResult(query)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
val itemSearch = menu.findItem(R.id.action_search)
val itemAccount = menu.findItem(R.id.ic_collections)
if (nightMode) {
itemSearch.setIcon(R.drawable.ic_action_action_search)
itemAccount.setIcon(R.drawable.ic_action_collections_bookmark2)
}
binding.searchView.setMenuItem(itemSearch)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_search -> startActivity(Intent(this, SearchFragment::class.java))
R.id.ic_setting -> startActivity(Intent(this, SettingsActivity::class.java))
R.id.ic_collections -> startActivity(Intent(this, CollectionsActivity::class.java))
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) {
val matches = data!!.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
if (matches != null && matches.size > 0) {
val searchWrd = matches[0]
if (!TextUtils.isEmpty(searchWrd)) {
binding.searchView.setQuery(searchWrd, false)
}
}
return
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onBackPressed() {
if (binding.searchView.isSearchOpen) {
binding.searchView.closeSearch()
} else {
super.onBackPressed()
}
}
override fun onResume() {
super.onResume()
val sp = PreferenceManager.getDefaultSharedPreferences(this)
val nightModeNew = sp.getBoolean("dark", false)
if (nightMode != nightModeNew) recreate()
LocalBroadcastManager.getInstance(this)
.registerReceiver(mMessageReceiver, IntentFilter("fetch-failed"))
}
override fun onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver)
super.onPause()
}
} | apache-2.0 | 308b00e579b9a1d46883376fcf72ee1a | 37.088339 | 100 | 0.646409 | 5.147087 | false | false | false | false |
kivensolo/UiUsingListView | library/network/src/main/java/com/zeke/reactivehttp/datasource/BaseRemoteDataSource.kt | 1 | 6931 | package com.zeke.reactivehttp.datasource
import android.util.LruCache
import com.zeke.reactivehttp.callback.BaseRequestCallback
import com.zeke.reactivehttp.coroutine.ICoroutineEvent
import com.zeke.reactivehttp.exception.BaseHttpException
import com.zeke.reactivehttp.exception.LocalBadException
import com.zeke.reactivehttp.viewmodel.IUIActionEvent
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
/**
* @Author: leavesC
* @Date: 2020/5/4 0:56
* @Desc: 远程数据源的基类,目前用于提供网络数据。
*
* BaseRemoteDataSource处于最下层的数据提供者,只用于向上层提供数据,
* 提供了多个同步请求和异步请求方法,和 BaseReactiveViewModel 之间依靠 IUIActionEvent 接口来联系
*/
@Suppress("MemberVisibilityCanBePrivate")
abstract class BaseRemoteDataSource<Api : Any>(
protected val iUiActionEvent: IUIActionEvent?,
protected val apiServiceClass: Class<Api>
) : ICoroutineEvent {
companion object {
/**
* ApiService 缓存
*/
private val apiServiceCache = LruCache<String, Any>(30)
/**
* Retrofit 缓存
*/
private val retrofitCache = LruCache<String, Retrofit>(3)
/**
* 默认的 OKHttpClient
*/
private val defaultOkHttpClient by lazy {
OkHttpClient.Builder()
.readTimeout(10000L, TimeUnit.MILLISECONDS)
.writeTimeout(10000L, TimeUnit.MILLISECONDS)
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true).build()
}
/**
* 构建默认的 Retrofit
*/
private fun createDefaultRetrofit(baseUrl: String): Retrofit {
return Retrofit.Builder()
.client(defaultOkHttpClient)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
/**
* 和生命周期绑定的协程作用域
*/
override val lifecycleSupportedScope = iUiActionEvent?.lifecycleSupportedScope ?: GlobalScope
/**
* 由子类实现此字段以便获取 baseUrl
*/
protected abstract val baseUrl: String
/**
* 允许子类自己来实现创建 Retrofit 的逻辑
* 外部无需缓存 Retrofit 实例,ReactiveHttp 内部已做好缓存处理
* 但外部需要自己判断是否需要对 OKHttpClient 进行缓存
* @param baseUrl
*/
protected open fun createRetrofit(baseUrl: String): Retrofit {
return createDefaultRetrofit(baseUrl)
}
protected open fun generateBaseUrl(baseUrl: String): String {
if (baseUrl.isNotBlank()) {
return baseUrl
}
return this.baseUrl
}
/**
* 获取指定BaseUrl对应的API对象
* @param baseUrl 指定的baseUrl
* @return API 对应的APIServer对象
*/
fun getApiService(baseUrl: String = ""): Api {
return getApiService(generateBaseUrl(baseUrl), apiServiceClass)
}
private fun getApiService(baseUrl: String, apiServiceClazz: Class<Api>): Api {
val key = baseUrl + apiServiceClazz.canonicalName
@Suppress("UNCHECKED_CAST")
val apiCache = apiServiceCache.get(key)?.let {
it as? Api
}
if (apiCache != null) {
return apiCache
}
val retrofit = retrofitCache.get(baseUrl) ?: (createRetrofit(baseUrl).apply {
retrofitCache.put(baseUrl, this)
})
val apiService = retrofit.create(apiServiceClazz)
apiServiceCache.put(key, apiService)
return apiService
}
protected fun handleException(throwable: Throwable, callback: BaseRequestCallback?) {
if (callback == null) {
return
}
if (throwable is CancellationException) {
callback.onCancelled?.invoke()
return
}
val exception = generateBaseExceptionReal(throwable)
if (exceptionHandle(exception)) {
callback.onFailed?.invoke(exception)
if (callback.onFailToast()) {
val error = exceptionFormat(exception)
if (error.isNotBlank()) {
showToast(error)
}
}
}
}
internal fun generateBaseExceptionReal(throwable: Throwable): BaseHttpException {
return generateBaseException(throwable).apply {
exceptionRecord(this)
}
}
/**
* 如果外部想要对 Throwable 进行特殊处理,则可以重写此方法,用于改变 Exception 类型
* 例如,在 token 失效时接口一般是会返回特定一个 httpCode 用于表明移动端需要去更新 token 了
* 此时外部就可以实现一个 BaseException 的子类 TokenInvalidException 并在此处返回
* 从而做到接口异常原因强提醒的效果,而不用去纠结 httpCode 到底是多少
*/
protected open fun generateBaseException(throwable: Throwable): BaseHttpException {
return if (throwable is BaseHttpException) {
throwable
} else {
LocalBadException(throwable)
}
}
/**
* 用于由外部中转控制当抛出异常时是否走 onFail 回调,当返回 true 时则回调,否则不回调
* @param httpException
*/
protected open fun exceptionHandle(httpException: BaseHttpException): Boolean {
return true
}
/**
* 用于将网络请求过程中的异常反馈给外部,以便记录
* @param throwable
*/
protected open fun exceptionRecord(throwable: Throwable) {
}
/**
* 用于对 BaseException 进行格式化,以便在请求失败时 Toast 提示错误信息
* @param httpException
*/
protected open fun exceptionFormat(httpException: BaseHttpException): String {
return when (httpException.realException) {
null -> {
httpException.errorMessage
}
is ConnectException, is SocketTimeoutException, is UnknownHostException -> {
"连接超时,请检查您的网络设置"
}
else -> {
"请求过程抛出异常:" + httpException.errorMessage
}
}
}
protected fun showLoading(job: Job?) {
iUiActionEvent?.showLoading(job)
}
protected fun dismissLoading() {
iUiActionEvent?.dismissLoading()
}
protected open fun showToast(msg: String){
}
} | gpl-2.0 | 8d8737907844c9347f787c52a9c39901 | 28.342857 | 97 | 0.633988 | 4.480727 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/KotlinLibraryKindIndex.kt | 1 | 2349 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.vfilefinder
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.serviceOrNull
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.openapi.vfs.VirtualFileWithId
import org.jetbrains.kotlin.analysis.decompiler.stub.file.FileAttributeService
import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragment
enum class KnownLibraryKindForIndex {
COMMON, JS, UNKNOWN
}
private val KOTLIN_LIBRARY_KIND_FILE_ATTRIBUTE: String = "kotlin-library-kind".apply {
serviceOrNull<FileAttributeService>()?.register(this, 1)
}
// TODO: Detect library kind for Jar file using IdePlatformKindResolution.
fun VirtualFile.getLibraryKindForJar(): KnownLibraryKindForIndex {
if (this !is VirtualFileWithId) return detectLibraryKindFromJarContentsForIndex(this)
val service =
serviceOrNull<FileAttributeService>()
?: return detectLibraryKindFromJarContentsForIndex(this)
service
.readEnumAttribute(KOTLIN_LIBRARY_KIND_FILE_ATTRIBUTE, this, KnownLibraryKindForIndex::class.java)
?.let { return it.value }
return detectLibraryKindFromJarContentsForIndex(this).also { newValue ->
service.writeEnumAttribute(KOTLIN_LIBRARY_KIND_FILE_ATTRIBUTE, this, newValue)
}
}
private fun detectLibraryKindFromJarContentsForIndex(jarRoot: VirtualFile): KnownLibraryKindForIndex {
var result: KnownLibraryKindForIndex? = null
VfsUtil.visitChildrenRecursively(jarRoot, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean =
when (file.extension) {
"class" -> false
"kjsm" -> {
result = KnownLibraryKindForIndex.JS
false
}
MetadataPackageFragment.METADATA_FILE_EXTENSION -> {
result = KnownLibraryKindForIndex.COMMON
false
}
else -> true
}
})
return result ?: KnownLibraryKindForIndex.UNKNOWN
}
| apache-2.0 | 99552456729a38fd1c31a6f7eb5aedb5 | 38.15 | 158 | 0.719455 | 4.903967 | false | false | false | false |
sureshg/kotlin-starter | buildSrc/src/main/kotlin/tasks/MyExecTask.kt | 1 | 664 | package tasks
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.*
/**
* A custom exec task.
*/
open class MyExecTask : DefaultTask() {
init {
group = "misc"
description = "Custom Exec Task for ${project.name}"
}
@Input var command = listOf("ls")
@TaskAction fun run() {
println("Executing $command for ${this.project.name}.")
project.exec {
workingDir = project.buildDir
commandLine = command
}
}
}
fun Project.myExecTask() = task<MyExecTask>("myExecTask") | apache-2.0 | 56f236f465857e3c8be0d865b1f2fc99 | 21.166667 | 63 | 0.641566 | 3.883041 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/completion/impl-shared/src/org/jetbrains/kotlin/idea/completion/implCommon/handlers/NamedArgumentInsertHandler.kt | 1 | 3074 | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.completion.implCommon.handlers
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class NamedArgumentInsertHandler(private val parameterName: Name) : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val editor = context.editor
val (textAfterCompletionArea, doNeedTrailingSpace) = context.file.findElementAt(context.tailOffset).let { psi ->
psi?.siblings()?.firstOrNull { it !is PsiWhiteSpace }?.text to (psi !is PsiWhiteSpace)
}
var text: String
var caretOffset: Int
if (textAfterCompletionArea == "=") {
// User tries to manually rename existing named argument. We shouldn't add trailing `=` in such case
text = parameterName.render()
caretOffset = text.length
} else {
// For complicated cases let's try to normalize the document firstly in order to avoid parsing errors due to incomplete code
editor.document.replaceString(context.startOffset, context.tailOffset, "")
PsiDocumentManager.getInstance(context.project).commitDocument(editor.document)
val nextArgument = context.file.findElementAt(context.startOffset)?.siblings()
?.firstOrNull { it !is PsiWhiteSpace }?.parentsWithSelf?.takeWhile { it !is KtValueArgumentList }
?.firstIsInstanceOrNull<KtValueArgument>()
if (nextArgument?.isNamed() == true) {
if (doNeedTrailingSpace) {
text = "${parameterName.render()} = , "
caretOffset = text.length - 2
} else {
text = "${parameterName.render()} = ,"
caretOffset = text.length - 1
}
} else {
text = "${parameterName.render()} = "
caretOffset = text.length
}
}
if (context.file.findElementAt(context.startOffset - 1)?.let { it !is PsiWhiteSpace && it.text != "(" } == true) {
text = " $text"
caretOffset++
}
editor.document.replaceString(context.startOffset, context.tailOffset, text)
editor.caretModel.moveToOffset(context.startOffset + caretOffset)
}
}
| apache-2.0 | 5a18a15390af423806867f4a32b85039 | 46.292308 | 136 | 0.672414 | 5.014682 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/mapper/UserProfileModelMapper.kt | 1 | 1590 | package com.sedsoftware.yaptalker.presentation.mapper
import com.sedsoftware.yaptalker.domain.entity.base.UserProfile
import com.sedsoftware.yaptalker.presentation.mapper.util.TextTransformer
import com.sedsoftware.yaptalker.presentation.model.base.UserProfileModel
import io.reactivex.functions.Function
import javax.inject.Inject
class UserProfileModelMapper @Inject constructor(
private val textTransformer: TextTransformer
) : Function<UserProfile, UserProfileModel> {
override fun apply(profile: UserProfile): UserProfileModel =
UserProfileModel(
nickname = profile.nickname,
avatar = profile.avatar,
photo = profile.photo,
group = profile.group,
status = profile.status,
uq = textTransformer.transformRankToFormattedText(profile.uq),
signature = textTransformer.transformHtmlToSpanned(profile.signature),
rewards = textTransformer.transformHtmlToSpanned(profile.rewards),
registerDate = profile.registerDate,
timeZone = profile.timeZone,
website = textTransformer.transformWebsiteToSpanned(profile.website),
birthDate = profile.birthDate,
location = profile.location,
interests = profile.interests,
sex = profile.sex,
messagesCount = profile.messagesCount,
messsagesPerDay = profile.messsagesPerDay,
bayans = profile.bayans,
todayTopics = profile.todayTopics,
email = profile.email,
icq = profile.icq
)
}
| apache-2.0 | 3dc1dbac982c0ea5a8acea128b73a3c4 | 41.972973 | 82 | 0.689308 | 4.984326 | false | false | false | false |
GunoH/intellij-community | platform/tips-of-the-day/src/com/intellij/ide/util/TipsFeedback.kt | 2 | 2707 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.util
import com.intellij.feedback.common.FeedbackRequestType
import com.intellij.feedback.common.submitGeneralFeedback
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.components.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.xmlb.annotations.XMap
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
@Service
@State(name = "TipsFeedback", storages = [Storage(value = "tips-feedback.xml", roamingType = RoamingType.DISABLED)])
class TipsFeedback : SimplePersistentStateComponent<TipsFeedback.State>(State()) {
fun getLikenessState(tipId: String): Boolean? {
return state.tipToLikeness[tipId]
}
fun setLikenessState(tipId: String, likenessState: Boolean?) {
if (likenessState != null) {
state.tipToLikeness[tipId] = likenessState
state.intIncrementModificationCount()
}
else state.tipToLikeness.remove(tipId)?.also {
state.intIncrementModificationCount()
}
}
class State : BaseState() {
@get:XMap
val tipToLikeness by linkedMap<String, Boolean>()
}
fun scheduleFeedbackSending(tipId: String, likenessState: Boolean) {
val shortDescription = """
tipId: $tipId
like: $likenessState
""".trimIndent()
val dataJsonObject = buildJsonObject {
put("format_version", FEEDBACK_FORMAT_VERSION)
put("tip_id", tipId)
put("like", likenessState)
put("ide_name", ApplicationNamesInfo.getInstance().fullProductName)
put("ide_build", ApplicationInfo.getInstance().build.asStringWithoutProductCode())
}
submitGeneralFeedback(
project = null,
title = FEEDBACK_TITLE,
description = shortDescription,
feedbackType = FEEDBACK_TITLE,
collectedData = Json.encodeToString(dataJsonObject),
feedbackRequestType = getFeedbackRequestType(),
showNotification = false)
}
private fun getFeedbackRequestType(): FeedbackRequestType {
return when (Registry.stringValue("tips.of.the.day.feedback")) {
"production" -> FeedbackRequestType.PRODUCTION_REQUEST
"staging" -> FeedbackRequestType.TEST_REQUEST
else -> FeedbackRequestType.NO_REQUEST
}
}
companion object {
private const val FEEDBACK_TITLE = "Tips of the Day Feedback"
private const val FEEDBACK_FORMAT_VERSION = 1
@JvmStatic
fun getInstance(): TipsFeedback = service()
}
} | apache-2.0 | c9d3c65e4c25fe42a83fac6ef9ab20a1 | 35.106667 | 120 | 0.740303 | 4.296825 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/preference/SettingsMutators.kt | 3 | 4613 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test.preference
import com.intellij.debugger.settings.DebuggerSettings
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.compiler.configuration.Kotlin2JvmCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils
import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings
import org.jetbrains.kotlin.idea.debugger.core.ToggleKotlinVariablesState
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.ReflectionCallClassPatcher
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.DISABLE_KOTLIN_INTERNAL_CLASSES
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.RENDER_DELEGATED_PROPERTIES
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_CLASSLOADERS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_CONSTRUCTORS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_GETTERS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_SYNTHETIC_METHODS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.TRACING_FILTERS_ENABLED
import kotlin.reflect.KMutableProperty1
internal val SettingsMutators: List<SettingsMutator<*>> = listOf(
DebuggerSettingsMutator(SKIP_SYNTHETIC_METHODS, DebuggerSettings::SKIP_SYNTHETIC_METHODS),
DebuggerSettingsMutator(SKIP_CONSTRUCTORS, DebuggerSettings::SKIP_CONSTRUCTORS),
DebuggerSettingsMutator(SKIP_CLASSLOADERS, DebuggerSettings::SKIP_CLASSLOADERS),
DebuggerSettingsMutator(TRACING_FILTERS_ENABLED, DebuggerSettings::TRACING_FILTERS_ENABLED),
DebuggerSettingsMutator(SKIP_GETTERS, DebuggerSettings::SKIP_GETTERS),
KotlinSettingsMutator(DISABLE_KOTLIN_INTERNAL_CLASSES, KotlinDebuggerSettings::disableKotlinInternalClasses),
KotlinSettingsMutator(RENDER_DELEGATED_PROPERTIES, KotlinDebuggerSettings::renderDelegatedProperties),
KotlinVariablesModeSettingsMutator,
JvmTargetSettingsMutator,
ForceRankingSettingsMutator,
ReflectionPatchingMutator
)
private class DebuggerSettingsMutator<T : Any>(
key: DebuggerPreferenceKey<T>,
private val prop: KMutableProperty1<DebuggerSettings, T>
) : SettingsMutator<T>(key) {
override fun setValue(value: T, project: Project): T {
val debuggerSettings = DebuggerSettings.getInstance()
val oldValue = prop.get(debuggerSettings)
prop.set(debuggerSettings, value)
return oldValue
}
}
private class KotlinSettingsMutator<T : Any>(
key: DebuggerPreferenceKey<T>,
private val prop: KMutableProperty1<KotlinDebuggerSettings, T>
) : SettingsMutator<T>(key) {
override fun setValue(value: T, project: Project): T {
val debuggerSettings = KotlinDebuggerSettings.getInstance()
val oldValue = prop.get(debuggerSettings)
prop.set(debuggerSettings, value)
return oldValue
}
}
private object KotlinVariablesModeSettingsMutator : SettingsMutator<Boolean>(DebuggerPreferenceKeys.SHOW_KOTLIN_VARIABLES) {
override fun setValue(value: Boolean, project: Project): Boolean {
val service = ToggleKotlinVariablesState.getService()
val oldValue = service.kotlinVariableView
service.kotlinVariableView = value
return oldValue
}
}
private object JvmTargetSettingsMutator : SettingsMutator<String>(DebuggerPreferenceKeys.JVM_TARGET) {
override fun setValue(value: String, project: Project): String {
var oldValue: String? = null
Kotlin2JvmCompilerArgumentsHolder.getInstance(project).update {
oldValue = jvmTarget
jvmTarget = value.takeIf { it.isNotEmpty() }
}
return oldValue ?: ""
}
}
private object ForceRankingSettingsMutator : SettingsMutator<Boolean>(DebuggerPreferenceKeys.FORCE_RANKING) {
override fun setValue(value: Boolean, project: Project): Boolean {
val oldValue = DebuggerUtils.forceRanking
DebuggerUtils.forceRanking = value
return oldValue
}
}
private object ReflectionPatchingMutator : SettingsMutator<Boolean>(DebuggerPreferenceKeys.REFLECTION_PATCHING) {
override fun setValue(value: Boolean, project: Project): Boolean {
val oldValue = ReflectionCallClassPatcher.isEnabled
ReflectionCallClassPatcher.isEnabled = value
return oldValue
}
} | apache-2.0 | de1eb5041a08b23ba5d8fbbaf3ed2a9a | 48.612903 | 158 | 0.788858 | 4.669028 | false | true | false | false |
siosio/intellij-community | platform/platform-api/src/com/intellij/openapi/ui/DialogPanel.kt | 1 | 3013 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.ui
import com.intellij.openapi.Disposable
import com.intellij.ui.components.JBPanel
import java.awt.LayoutManager
import java.util.function.Supplier
import javax.swing.JComponent
import javax.swing.text.JTextComponent
class DialogPanel : JBPanel<DialogPanel> {
var preferredFocusedComponent: JComponent? = null
var validateCallbacks: List<() -> ValidationInfo?> = emptyList()
var componentValidateCallbacks: Map<JComponent, () -> ValidationInfo?> = emptyMap()
var customValidationRequestors: Map<JComponent, List<(() -> Unit) -> Unit>> = emptyMap()
var applyCallbacks: Map<JComponent?, List<() -> Unit>> = emptyMap()
var resetCallbacks: Map<JComponent?, List<() -> Unit>> = emptyMap()
var isModifiedCallbacks: Map<JComponent?, List<() -> Boolean>> = emptyMap()
private val componentValidationStatus = hashMapOf<JComponent, ValidationInfo>()
constructor() : super()
constructor(layout: LayoutManager?) : super(layout)
fun registerValidators(parentDisposable: Disposable, componentValidityChangedCallback: ((Map<JComponent, ValidationInfo>) -> Unit)? = null) {
for ((component, callback) in componentValidateCallbacks) {
val validator = ComponentValidator(parentDisposable).withValidator(Supplier {
val infoForComponent = callback()
if (componentValidationStatus[component] != infoForComponent) {
if (infoForComponent != null) {
componentValidationStatus[component] = infoForComponent
}
else {
componentValidationStatus.remove(component)
}
componentValidityChangedCallback?.invoke(componentValidationStatus)
}
infoForComponent
})
if (component is JTextComponent) {
validator.andRegisterOnDocumentListener(component)
}
registerCustomValidationRequestors(component, validator)
validator.installOn(component)
}
}
fun apply() {
for ((component, callbacks) in applyCallbacks.entries) {
if (component == null) continue
val modifiedCallbacks = isModifiedCallbacks.get(component)
if (modifiedCallbacks.isNullOrEmpty() || modifiedCallbacks.any { it() }) {
callbacks.forEach { it() }
}
}
applyCallbacks.get(null)?.forEach { it() }
}
fun reset() {
for ((component, callbacks) in resetCallbacks.entries) {
if (component == null) continue
callbacks.forEach { it() }
}
resetCallbacks.get(null)?.forEach { it() }
}
fun isModified(): Boolean {
return isModifiedCallbacks.values.any { list -> list.any { it() } }
}
private fun registerCustomValidationRequestors(component: JComponent, validator: ComponentValidator) {
for (onCustomValidationRequest in customValidationRequestors.get(component) ?: return) {
onCustomValidationRequest { validator.revalidate() }
}
}
}
| apache-2.0 | 939c0f875dd306504723aef4b0b0cfbe | 37.139241 | 143 | 0.704613 | 4.729984 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveNameFromFunctionExpressionFix.kt | 3 | 2274 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.createIntentionForFirstParentOfType
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
class RemoveNameFromFunctionExpressionFix(element: KtNamedFunction) : KotlinQuickFixAction<KtNamedFunction>(element), CleanupFix {
override fun getText(): String = KotlinBundle.message("remove.identifier.from.anonymous.function")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
removeNameFromFunction(element ?: return)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) =
diagnostic.createIntentionForFirstParentOfType(::RemoveNameFromFunctionExpressionFix)
private fun removeNameFromFunction(function: KtNamedFunction) {
var wereAutoLabelUsages = false
val name = function.nameAsName ?: return
function.forEachDescendantOfType<KtReturnExpression> {
if (!wereAutoLabelUsages && it.getLabelNameAsName() == name) {
wereAutoLabelUsages = it.analyze().get(BindingContext.LABEL_TARGET, it.getTargetLabel()) == function
}
}
function.nameIdentifier?.delete()
if (wereAutoLabelUsages) {
val psiFactory = KtPsiFactory(function)
val newFunction = psiFactory.createExpressionByPattern("$0@ $1", name, function)
function.replace(newFunction)
}
}
}
}
| apache-2.0 | 3202197b2c5f1a5648879b1de7328227 | 45.408163 | 158 | 0.734389 | 5.019868 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToStringWithStringTemplateInspection.kt | 3 | 1724 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.canDropBraces
import org.jetbrains.kotlin.idea.core.dropBraces
import org.jetbrains.kotlin.idea.intentions.isToString
import org.jetbrains.kotlin.psi.*
class ReplaceToStringWithStringTemplateInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression !is KtReferenceExpression) return false
if (element.parent is KtBlockStringTemplateEntry) return false
return element.isToString()
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val variable = element.receiverExpression.text
val replaced = element.replace(KtPsiFactory(element).createExpression("\"\${$variable}\""))
val blockStringTemplateEntry = (replaced as? KtStringTemplateExpression)?.entries?.firstOrNull() as? KtBlockStringTemplateEntry
if (blockStringTemplateEntry?.canDropBraces() == true) blockStringTemplateEntry.dropBraces()
}
override fun inspectionText(element: KtDotQualifiedExpression) =
KotlinBundle.message("inspection.replace.to.string.with.string.template.display.name")
override val defaultFixText get() = KotlinBundle.message("replace.tostring.with.string.template")
} | apache-2.0 | 9a80dab9c334f1baf5f0f377fbdc03b1 | 51.272727 | 158 | 0.787123 | 5.085546 | false | false | false | false |
smmribeiro/intellij-community | plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseEml2ModulesTest.kt | 4 | 1405 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.eclipse
import com.intellij.testFramework.ApplicationExtension
import com.intellij.testFramework.rules.TempDirectoryExtension
import com.intellij.testFramework.rules.TestNameExtension
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
class EclipseEml2ModulesTest {
@JvmField
@RegisterExtension
val tempDirectory = TempDirectoryExtension()
@JvmField
@RegisterExtension
val testName = TestNameExtension()
@Test
fun testSourceRootPaths() {
doTest("ws-internals")
}
@Test
fun testAnotherSourceRootPaths() {
doTest("anotherPath")
}
private fun doTest(secondRootName: String) {
val testName = testName.methodName.removePrefix("test").decapitalize()
val testRoot = eclipseTestDataRoot.resolve("eml").resolve(testName)
val commonRoot = eclipseTestDataRoot.resolve("common").resolve("twoModulesWithClasspathStorage")
checkEmlFileGeneration(listOf(testRoot, commonRoot), tempDirectory, listOf(
"test" to "srcPath/sourceRootPaths/sourceRootPaths",
"ws-internals" to "srcPath/$secondRootName/ws-internals"
))
}
companion object {
@JvmField
@RegisterExtension
val appRule = ApplicationExtension()
}
} | apache-2.0 | 42a3037dacccec3d3153754b2d7d5331 | 30.954545 | 158 | 0.767972 | 4.517685 | false | true | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Module/Main/PetalActivity.kt | 1 | 10365 | package stan.androiddemo.project.petal.Module.Main
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.facebook.drawee.view.SimpleDraweeView
import com.jakewharton.rxbinding.view.RxView
import kotlinx.android.synthetic.main.activity_petal.*
import stan.androiddemo.R
import stan.androiddemo.project.petal.Base.BasePetalActivity
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnPinsFragmentInteractionListener
import stan.androiddemo.project.petal.Model.PinsMainInfo
import stan.androiddemo.project.petal.Module.Follow.PetalFollowActivity
import stan.androiddemo.project.petal.Module.ImageDetail.PetalImageDetailActivity
import stan.androiddemo.project.petal.Module.Login.PetalLoginActivity
import stan.androiddemo.project.petal.Module.PetalList.PetalListFragment
import stan.androiddemo.project.petal.Module.Search.SearchPetalActivity
import stan.androiddemo.project.petal.Module.Setting.PetalSettingActivity
import stan.androiddemo.project.petal.Module.UserInfo.PetalUserInfoActivity
import stan.androiddemo.tool.CompatUtils
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
import stan.androiddemo.tool.Logger
import stan.androiddemo.tool.SPUtils
import java.util.concurrent.TimeUnit
class PetalActivity : BasePetalActivity(),OnPinsFragmentInteractionListener, SharedPreferences.OnSharedPreferenceChangeListener {
lateinit var fragmentManage: FragmentManager
lateinit var types:Array<String>
lateinit var titles:Array<String>
private var mUserName = ""
private var mUserId = ""
lateinit var fragment:PetalListFragment
lateinit var imgNavHead:SimpleDraweeView
lateinit var txtNavUsername:TextView
lateinit var txtNavUserEmail:TextView
override fun getTag(): String {return this.toString()}
override fun getLayoutId(): Int {
return R.layout.activity_petal
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(toolbar)
fragmentManage = supportFragmentManager
getData()
getSharedPreferences("share_data", Context.MODE_PRIVATE).registerOnSharedPreferenceChangeListener(this)
initDrawer(toolbar)
initNavHeadView()
initNavMenuView()
selectFragment(0)
}
override fun onResume() {
super.onResume()
setNavUserInfo()
}
//取出各种需要用的全局变量
fun getData(){
types = resources.getStringArray(R.array.type_array)
titles = resources.getStringArray(R.array.title_array)
isLogin = SPUtils.get(mContext,Config.ISLOGIN,false) as Boolean
if (isLogin){
mUserName = SPUtils.get(mContext,Config.USERNAME,mUserName) as String
mUserId = SPUtils.get(mContext,Config.USERID,mUserId) as String
}
}
//初始化DrawLayout
fun initDrawer(tb: android.support.v7.widget.Toolbar){
val toggle = ActionBarDrawerToggle(this,drawer_layout_petal,tb,
R.string.navigation_drawer_open,R.string.navigation_drawer_close)
drawer_layout_petal.addDrawerListener(toggle)
toggle.syncState()
navigation_view_petal.setNavigationItemSelectedListener {
if (it.groupId == R.id.menu_group_type){
fragment.mKey = types[it.itemId]
fragment.setRefresh()
title = titles[it.itemId]
}
else{
when(it.itemId){
R.id.nav_petal_setting->{
PetalSettingActivity.launch(this@PetalActivity)
}
R.id.nav_petal_quit->{
SPUtils.clear(mContext)
finish()
}
}
}
drawer_layout_petal.closeDrawer(GravityCompat.START)
return@setNavigationItemSelectedListener true
}
}
//初始化HeadNav
fun initNavHeadView(){
val headView = navigation_view_petal.inflateHeaderView(R.layout.petal_nav_header)
imgNavHead = headView.findViewById(R.id.img_petal_my_header)
imgNavHead.setOnClickListener {
if (isLogin){
PetalUserInfoActivity.launch(this@PetalActivity,mUserId,mUserName)
}
else{
PetalLoginActivity.launch(this@PetalActivity)
}
}
txtNavUsername = headView.findViewById(R.id.txt_nav_username)
txtNavUsername.setOnClickListener {
Logger.e("click txtNavUsername")
}
txtNavUserEmail = headView.findViewById(R.id.txt_nav_email)
val btnAttention = headView.findViewById<Button>(R.id.btn_nav_attention)
btnAttention.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_loyalty_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
btnAttention.setOnClickListener {
if (!isLogin){
PetalLoginActivity.launch(this@PetalActivity)
}
else{
PetalFollowActivity.launch(this@PetalActivity)
}
}
val btnGather = headView.findViewById<Button>(R.id.btn_nav_gather)
btnGather.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_camera_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
val btnMessage = headView.findViewById<Button>(R.id.btn_nav_message)
btnMessage.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_message_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
val btnFriend = headView.findViewById<Button>(R.id.btn_nav_friends)
btnFriend.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_people_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
}
fun setNavUserInfo(){
val drawable = CompatUtils.getTintDrawable(mContext,R.drawable.ic_account_circle_gray_48dp,Color.GRAY)
if (isLogin){
var key = SPUtils.get(mContext,Config.USERHEADKEY,"") as String
if (!key.isNullOrEmpty()){
key = resources.getString(R.string.urlImageRoot) + key
ImageLoadBuilder.Start(mContext,imgNavHead,key).setPlaceHolderImage(drawable).setIsCircle(true,true).build()
}
else{
Logger.d("User Head Key is empty")
}
if (!mUserName.isNullOrEmpty()){
txtNavUsername.text = mUserName
}
val email = SPUtils.get(mContext,Config.USEREMAIL,"") as String
if (!email.isNullOrEmpty()){
txtNavUserEmail.text = email
}
}
else{
ImageLoadBuilder.Start(mContext,imgNavHead,"").setPlaceHolderImage(drawable).setIsCircle(true,true).build()
}
}
//初始化NavMenu
fun initNavMenuView(){
val menu = navigation_view_petal.menu
val titleList = resources.getStringArray(R.array.title_array)
val icons = arrayListOf(R.drawable.ic_toys_black_24dp,R.drawable.ic_camera_black_24dp,R.drawable.ic_camera_alt_black_24dp,R.drawable.ic_local_dining_black_24dp,R.drawable.ic_loyalty_black_24dp)
for(i in 0 until titleList.size){
menu.add(R.id.menu_group_type,i, Menu.NONE,titleList[i]).setIcon(icons[i]).setCheckable(true)
}
menu.getItem(0).isChecked = true
}
fun selectFragment(position:Int){
val transaction = fragmentManage.beginTransaction()
val type = types[position]
val tt = titles[position]
fragment = PetalListFragment.createListFragment(type,tt)
transaction.replace(R.id.frame_layout_petal_with_refresh,fragment)
transaction.commit()
title = tt
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.petal_search_result,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
//do something
return super.onOptionsItemSelected(item)
}
override fun initResAndListener() {
float_button_search.setImageResource(R.drawable.ic_search_black_24dp)
RxView.clicks(float_button_search).throttleFirst(Config.throttDuration.toLong(),TimeUnit.MILLISECONDS)
.subscribe({
SearchPetalActivity.launch(this@PetalActivity)
})
}
override fun onBackPressed() {
if (drawer_layout_petal.isDrawerOpen(GravityCompat.START)){
drawer_layout_petal.closeDrawers()
}
else{
super.onBackPressed()
}
}
override fun onSharedPreferenceChanged(p0: SharedPreferences, p1: String) {
if (Config.ISLOGIN == p1){
isLogin = p0.getBoolean(Config.ISLOGIN, false)
}
}
override fun onClickPinsItemImage(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalActivity,PetalImageDetailActivity.ACTION_MAIN)
}
override fun onClickPinsItemText(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalActivity,PetalImageDetailActivity.ACTION_MAIN)
}
companion object {
fun launch(activity:Activity){
val intent = Intent(activity,PetalActivity::class.java)
activity.startActivity(intent)
}
fun launch(activity:Activity,flag:Int){
val intent = Intent(activity,PetalActivity::class.java)
intent.flags = flag
activity.startActivity(intent)
}
}
}
| mit | 9595c85c1765e2ceaad310b805e38e6f | 37.233333 | 201 | 0.674223 | 4.547577 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/Game2048/InputListener.kt | 1 | 7557 | package stan.androiddemo.project.Game2048
import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import java.util.*
/**
* Created by hugfo on 2017/8/19.
*/
class InputListener(view: MainView) : View.OnTouchListener{
private val SWIPE_MIN_DISTANCE = 0
private val SWIPE_THRESHOLD_VELOCITY = 25
private val MOVE_THRESHOLD = 250
private val RESET_STARTING = 10
private var timer: Timer? = null
private var x: Float = 0F
private var y: Float = 0F
private var lastdx: Float = 0F
private var lastdy: Float = 0F
private var previousX: Float = 0F
private var previousY: Float = 0F
private var startingX: Float = 0F
private var startingY: Float = 0F
private var previousDirection = 1
private var veryLastDirection = 1
private var hasMoved = false
private var isAutoRun = false
internal var mView: MainView = view
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
x = event.x
y = event.y
startingX = x
startingY = y
previousX = x
previousY = y
lastdx = 0f
lastdy = 0f
hasMoved = false
return true
}
MotionEvent.ACTION_MOVE -> {
x = event.x
y = event.y
if (isAutoRun){
//TODO("auto run")
return true
}
if (mView.game.isActive()) {
val dx = x - previousX
if (Math.abs(lastdx + dx) < Math.abs(lastdx) + Math.abs(dx)
&& Math.abs(dx) > RESET_STARTING
&& Math.abs(x - startingX) > SWIPE_MIN_DISTANCE) {
startingX = x
startingY = y
lastdx = dx
previousDirection = veryLastDirection
}
if (lastdx == 0f) {
lastdx = dx
}
val dy = y - previousY
if (Math.abs(lastdy + dy) < Math.abs(lastdy) + Math.abs(dy)
&& Math.abs(dy) > RESET_STARTING
&& Math.abs(y - startingY) > SWIPE_MIN_DISTANCE) {
startingX = x
startingY = y
lastdy = dy
previousDirection = veryLastDirection
}
if (lastdy == 0f) {
lastdy = dy
}
if (pathMoved() > SWIPE_MIN_DISTANCE * SWIPE_MIN_DISTANCE) {
var moved = false
if ((dy >= SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || y - startingY >= MOVE_THRESHOLD) && previousDirection % 2 != 0) {
moved = true
previousDirection *= 2
veryLastDirection = 2
mView.game.move(2)
} else if ((dy <= -SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || y - startingY <= -MOVE_THRESHOLD) && previousDirection % 3 != 0) {
moved = true
previousDirection *= 3
veryLastDirection = 3
mView.game.move(0)
} else if ((dx >= SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || x - startingX >= MOVE_THRESHOLD) && previousDirection % 5 != 0) {
moved = true
previousDirection *= 5
veryLastDirection = 5
mView.game.move(1)
} else if ((dx <= -SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || x - startingX <= -MOVE_THRESHOLD) && previousDirection % 7 != 0) {
moved = true
previousDirection *= 7
veryLastDirection = 7
mView.game.move(3)
}
if (moved) {
hasMoved = true
startingX = x
startingY = y
}
}
}
previousX = x
previousY = y
return true
}
MotionEvent.ACTION_UP -> {
x = event.x
y = event.y
previousDirection = 1
veryLastDirection = 1
// "Menu" inputs
if (!hasMoved) {
if (iconPressed(mView.sXNewGame, mView.sYIcons)) {
mView.game.newGame()
} else if (iconPressed(mView.sXUndo, mView.sYIcons)) {
mView.game.revertUndoState()
} else if (iconPressed(mView.sXCheat, mView.sYIcons)) {
mView.game.cheat()
} else if (iconPressed(mView.sXAuto, mView.sYIcons)) {
if (!mView.game.isActive()){
return true
}
isAutoRun = !isAutoRun
if (isAutoRun&&mView.game.isActive()){
if (timer == null){
timer = Timer()
setTimeTask()
}
}
else{
timer?.cancel()
timer = null
}
}
else if (isTap(2)
&& inRange(mView.startingX.toFloat(), x, mView.endingX.toFloat())
&& inRange(mView.startingY.toFloat(), x, mView.endingY.toFloat())
&& mView.continueButtonEnabled) {
mView.game.setEndlessMode()
}
}
}
}
return true
}
private fun setTimeTask(){
timer?.schedule(object:TimerTask(){
override fun run() {
if (!mView.game.isActive()){
timer?.cancel()
timer = null
isAutoRun = false
}
//TODO("start ai action")
val best = mView.game.ai?.getBest()
if (best != null){
mView.post {
mView.game.move(best!!.move!!)
}
}
}
},300,MOVE_THRESHOLD.toLong())
}
private fun pathMoved(): Float {
return (x - startingX) * (x - startingX) + (y - startingY) * (y - startingY)
}
private fun iconPressed(sx: Int, sy: Int): Boolean {
return isTap(1) && inRange(sx.toFloat(), x, sx + mView.iconSize.toFloat())
&& inRange(sy.toFloat(), y, sy + mView.iconSize.toFloat())
}
private fun inRange(starting: Float, check: Float, ending: Float): Boolean {
return check in starting..ending
}
private fun isTap(factor: Int): Boolean {
return pathMoved() <= mView.iconSize * factor
}
} | mit | a5de56a1795f28dae83a1b1c82eaa3a0 | 37.958763 | 163 | 0.426492 | 5.218923 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/tool/Extension.kt | 1 | 2071 | package stan.androiddemo.tool
import android.graphics.Bitmap
import android.media.Image
import android.os.Environment
import android.widget.ImageView
import okhttp3.internal.Util
//import org.opencv.android.Utils
//import org.opencv.core.Mat
//import org.opencv.imgproc.Imgproc
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
/**
* Created by hugfo on 2017/8/5.
*/
fun Int.ToFixedInt(num:Int):String{
if (this.toString().length > num){
return this.toString()
}
else {
var str = this.toString()
while (str.length < num){
str = "0$str"
}
return str
}
}
fun String.ConvertUrl():String{
return this.replace(".","_").replace(":","=").replace("/","-")
}
fun Image.Save(name:String){
val buffer = this.planes[0].buffer
val data = ByteArray(buffer.remaining())
buffer.get(data)
val filePath = Environment.getExternalStorageDirectory().path + "/DCIM/Camera"
val photoPath = "$name.jpeg"
val file = File(filePath,photoPath)
try {
//存到本地相册
val fileOutputStream = FileOutputStream(file)
fileOutputStream.write(data)
fileOutputStream.close()
}
catch (e: FileNotFoundException){
e.printStackTrace()
}
catch (e: IOException){
e.printStackTrace()
}
finally {
this.close()
}
}
//fun ImageView.setMat(mat:Mat){
// val bitmat = Bitmap.createBitmap(mat.width(),mat.height(),Bitmap.Config.ARGB_8888)
// val matResult = Mat()
//// Imgproc.cvtColor(mat,matResult,Imgproc.COLOR_BGR2RGBA)
// Utils.matToBitmap(mat,bitmat)
// setImageBitmap(bitmat)
// matResult.release()
//}
fun ImageView.getBitmap():Bitmap{
this.isDrawingCacheEnabled = true
val bitmap = Bitmap.createBitmap(this.drawingCache)
this.isDrawingCacheEnabled = false
return bitmap
}
//fun ImageView.getMat():Mat{
// val bitmap = getBitmap()
// val mat = Mat()
// Utils.bitmapToMat(bitmap,mat)
// return mat
//}
| mit | 627e3ec6b78d9cb62d6b3e17f4e9ddac | 24.419753 | 88 | 0.659543 | 3.644248 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.