repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/gui/components/CompBackground.kt
|
2
|
4731
|
package com.cout970.magneticraft.systems.gui.components
import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.misc.guiTexture
import com.cout970.magneticraft.misc.vector.Vec2d
import com.cout970.magneticraft.misc.vector.vec2Of
import com.cout970.magneticraft.systems.gui.render.DrawableBox
import com.cout970.magneticraft.systems.gui.render.IComponent
import com.cout970.magneticraft.systems.gui.render.IGui
import com.cout970.magneticraft.systems.gui.render.isCtrlKeyDown
import net.minecraft.client.renderer.GlStateManager.color
import net.minecraft.util.ResourceLocation
/**
* Created by cout970 on 08/07/2016.
*/
class CompBackground(
val texture: ResourceLocation,
val textureSize: Vec2d = Vec2d(256, 256),
override val size: Vec2d = Vec2d(176, 166)
) : IComponent {
override val pos: IVector2 = Vec2d.ZERO
override lateinit var gui: IGui
lateinit var back: DrawableBox
override fun init() {
back = DrawableBox(gui.pos, size, Vec2d.ZERO, size, textureSize)
}
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
gui.bindTexture(texture)
gui.drawTexture(back)
}
}
class CompDebugOutline(
override val pos: IVector2,
override val size: IVector2
) : IComponent {
override lateinit var gui: IGui
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {}
override fun drawSecondLayer(mouse: Vec2d) {
if (!isCtrlKeyDown()) return
color(1f, 1f, 1f, 1f)
val start = pos
val end = start + size
gui.drawColor(start, end, 0xFF000000.toInt())
gui.drawColor(start + 1, end - 1, -1)
}
}
class CompDynamicBackground(
override val pos: IVector2,
override val size: IVector2
) : IComponent {
override lateinit var gui: IGui
lateinit var dynamicBack: List<DrawableBox>
override fun init() {
dynamicBack = createTextureBox(gui.pos + pos, size)
}
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
color(1f, 1f, 1f, 1f)
gui.bindTexture(guiTexture("misc2"))
dynamicBack.forEach { gui.drawTexture(it) }
}
fun createTextureBox(pPos: IVector2, pSize: IVector2): List<DrawableBox> {
val texSize = vec2Of(256, 256)
val leftUp = DrawableBox(
screenPos = pPos,
screenSize = vec2Of(4),
texturePos = vec2Of(0),
textureSize = vec2Of(4),
textureScale = texSize
)
val leftDown = DrawableBox(
screenPos = pPos + vec2Of(0, pSize.yi - 4),
screenSize = vec2Of(4),
texturePos = vec2Of(0, 5),
textureSize = vec2Of(4),
textureScale = texSize
)
val rightUp = DrawableBox(
screenPos = pPos + vec2Of(pSize.xi - 4, 0),
screenSize = vec2Of(4),
texturePos = vec2Of(5, 0),
textureSize = vec2Of(4),
textureScale = texSize
)
val rightDown = DrawableBox(
screenPos = pPos + vec2Of(pSize.xi - 4, pSize.yi - 4),
screenSize = vec2Of(4),
texturePos = vec2Of(5, 5),
textureSize = vec2Of(4),
textureScale = texSize
)
val left = DrawableBox(
screenPos = pPos + vec2Of(0, 4),
screenSize = vec2Of(4, pSize.y - 8),
texturePos = vec2Of(0, 10),
textureSize = vec2Of(4, pSize.y - 8),
textureScale = texSize
)
val right = DrawableBox(
screenPos = pPos + vec2Of(pSize.xi - 4, 4),
screenSize = vec2Of(4, pSize.yi - 8),
texturePos = vec2Of(5, 10),
textureSize = vec2Of(4, pSize.yi - 8),
textureScale = texSize
)
val up = DrawableBox(
screenPos = pPos + vec2Of(4, 0),
screenSize = vec2Of(pSize.xi - 8, 4),
texturePos = vec2Of(10, 0),
textureSize = vec2Of(pSize.xi - 8, 4),
textureScale = texSize
)
val down = DrawableBox(
screenPos = pPos + vec2Of(4, pSize.yi - 4),
screenSize = vec2Of(pSize.xi - 8, 4),
texturePos = vec2Of(10, 5),
textureSize = vec2Of(pSize.xi - 8, 4),
textureScale = texSize
)
val center = DrawableBox(
screenPos = pPos + vec2Of(4, 4),
screenSize = vec2Of(pSize.xi - 8, pSize.yi - 8),
texturePos = vec2Of(5, 3),
textureSize = vec2Of(1, 1),
textureScale = texSize
)
return listOf(
leftUp, leftDown, rightUp, rightDown,
left, right, up, down, center
)
}
}
|
gpl-2.0
|
a34e485ad55eef4896f6f2640463a616
| 29.140127 | 78 | 0.592898 | 3.725197 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer
|
settings/src/main/kotlin/voice/settings/views/autoRewind.kt
|
1
|
1340
|
package voice.settings.views
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import voice.settings.R
@Composable
internal fun AutoRewindRow(autoRewindInSeconds: Int, openAutoRewindDialog: () -> Unit) {
ListItem(
modifier = Modifier
.clickable {
openAutoRewindDialog()
}
.fillMaxWidth(),
text = {
Text(text = stringResource(R.string.pref_auto_rewind_title))
},
secondaryText = {
Text(
text = LocalContext.current.resources.getQuantityString(
R.plurals.seconds,
autoRewindInSeconds,
autoRewindInSeconds
)
)
}
)
}
@Composable
internal fun AutoRewindAmountDialog(
currentSeconds: Int,
onSecondsConfirmed: (Int) -> Unit,
onDismiss: () -> Unit
) {
TimeSettingDialog(
title = stringResource(R.string.pref_seek_time),
currentSeconds = currentSeconds,
minSeconds = 0,
maxSeconds = 20,
textPluralRes = R.plurals.seconds,
onSecondsConfirmed = onSecondsConfirmed,
onDismiss = onDismiss
)
}
|
lgpl-3.0
|
cef20dd63c7bd55e3e841860f231b13c
| 25.27451 | 88 | 0.715672 | 4.227129 | false | false | false | false |
spark/photon-tinker-android
|
cloudsdk/src/main/java/io/particle/android/sdk/cloud/SDKGlobals.kt
|
1
|
907
|
package io.particle.android.sdk.cloud
import android.content.Context
import io.particle.android.sdk.persistance.AppDataStorage
import io.particle.android.sdk.persistance.AppDataStorageImpl
import io.particle.android.sdk.persistance.SensitiveDataStorage
import io.particle.android.sdk.persistance.SensitiveDataStorageImpl
object SDKGlobals {
@JvmStatic
@Volatile
var sensitiveDataStorage: SensitiveDataStorage? = null
internal set
@JvmStatic
@Volatile
var appDataStorage: AppDataStorage? = null
internal set
private var isInitialized = false
@JvmStatic
@Synchronized
fun init(context: Context) {
val ctx = context.applicationContext
if (isInitialized) {
return
}
sensitiveDataStorage = SensitiveDataStorageImpl(ctx)
appDataStorage = AppDataStorageImpl(ctx)
isInitialized = true
}
}
|
apache-2.0
|
00a88b5c3feb2bbcd2c42bcc58fe961c
| 24.942857 | 67 | 0.725469 | 4.699482 | false | false | false | false |
shaeberling/euler
|
kotlin/src/com/s13g/aoc/aoc2021/Day3.kt
|
1
|
1507
|
package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
/**
* --- Day 3: Binary Diagnostic ---
* https://adventofcode.com/2021/day/3
*/
class Day3 : Solver {
override fun solve(lines: List<String>): Result {
val ge = lines[0].indices.map { i -> lines.fold(Counter(0, 0)) { cnt, s -> cnt.add(s[i]) } }
.fold(GammaEpsi("", "")) { res, cnt -> res.add(cnt) }
val partA = ge.g.toInt(2) * ge.e.toInt(2)
val partB = processB(lines, 0 /* Most common */) * processB(lines, 1 /* Least common */)
return resultFrom(partA, partB)
}
private fun processB(lines: List<String>, mostLeastIdx: Int): Int {
val ratingValues = lines.toCollection(mutableListOf())
for (i in lines[0].indices) {
val cnt = ratingValues.fold(Counter(0, 0)) { cnt, s -> cnt.add(s[i]) }
for (l in ratingValues.toCollection(mutableListOf())) {
if (l[i] != cnt.hiLow()[mostLeastIdx] && ratingValues.size > 1) ratingValues.remove(l)
}
}
return ratingValues[0].toInt(2)
}
private data class GammaEpsi(val g: String, val e: String) {
fun add(cnt: Counter) = cnt.hiLow().let { GammaEpsi(this.g + it[0], this.e + it[1]) }
}
private data class Counter(val zeros: Int, val ones: Int) {
fun add(c: Char) = if (c == '0') Counter(this.zeros + 1, this.ones) else Counter(this.zeros, this.ones + 1)
fun hiLow() = if (this.zeros > this.ones) listOf('0', '1') else listOf('1', '0')
}
}
|
apache-2.0
|
fce8b2c1e5ebb412f68e7220aba6479f
| 37.666667 | 111 | 0.614466 | 3.007984 | false | false | false | false |
shaeberling/euler
|
kotlin/src/com/s13g/aoc/aoc2020/Day25.kt
|
1
|
923
|
package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 25: Combo Breaker ---
* https://adventofcode.com/2020/day/25
*/
class Day25 : Solver {
override fun solve(lines: List<String>): Result {
val input = lines.map { it.toLong() }.map { Pair(it, transform(7, it)) }
val encKey1 = loopIt(input[0].first, input[1].second)
val encKey2 = loopIt(input[1].first, input[0].second)
assert(encKey1 == encKey2)
return Result("$encKey1", "")
}
private fun loopIt(subjectNo: Long, times: Long): Long {
var value = 1L
var loop = 0L
for (i in 1..times) {
value = (value * subjectNo) % 20201227L
loop++
}
return value
}
private fun transform(subjectNo: Long, key: Long): Long {
var value = 1L
var loop = 0L
while (value != key) {
value = (value * subjectNo) % 20201227L
loop++
}
return loop
}
}
|
apache-2.0
|
19eb17fbe4ea8542d3fa1f09ab500fb0
| 23.315789 | 76 | 0.608884 | 3.097315 | false | false | false | false |
googleapis/gax-kotlin
|
examples-android/app/src/main/java/com/google/api/kgax/examples/grpc/LanguageActivity.kt
|
1
|
2509
|
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kgax.examples.grpc
import android.os.Bundle
import android.support.test.espresso.idling.CountingIdlingResource
import com.google.api.kgax.grpc.StubFactory
import com.google.cloud.language.v1.AnalyzeEntitiesRequest
import com.google.cloud.language.v1.Document
import com.google.cloud.language.v1.LanguageServiceGrpc
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
/**
* Kotlin example using KGax with gRPC and the Google Natural Language API.
*/
class LanguageActivity : AbstractExampleActivity<LanguageServiceGrpc.LanguageServiceFutureStub>(
CountingIdlingResource("Language")
) {
lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override val factory = StubFactory(
LanguageServiceGrpc.LanguageServiceFutureStub::class,
"language.googleapis.com", 443
)
override val stub by lazy {
applicationContext.resources.openRawResource(R.raw.sa).use {
factory.fromServiceAccount(
it,
listOf("https://www.googleapis.com/auth/cloud-platform")
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
job = Job()
// call the api
launch(Dispatchers.Main) {
val response = stub.execute {
it.analyzeEntities(
AnalyzeEntitiesRequest.newBuilder().apply {
document = Document.newBuilder().apply {
content = "Hi there Joe"
type = Document.Type.PLAIN_TEXT
}.build()
}.build()
)
}
updateUIWithExampleResult(response.toString())
}
}
}
|
apache-2.0
|
af3d543f6c85527225949a746cc5252b
| 32.453333 | 96 | 0.6668 | 4.742911 | false | false | false | false |
toastkidjp/Yobidashi_kt
|
app/src/main/java/jp/toastkid/yobidashi/browser/webview/factory/LongTapItemHolder.kt
|
2
|
847
|
/*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.webview.factory
import android.os.Bundle
/**
* @author toastkidjp
*/
data class LongTapItemHolder(var title: String = "", var anchor: String = "") {
fun reset() {
title = ""
anchor = ""
}
fun extract(bundle: Bundle) {
title = bundle.get(KEY_TITLE)?.toString()?.trim() ?: ""
anchor = bundle.get(KEY_URL)?.toString() ?: ""
}
companion object {
private const val KEY_TITLE = "title"
private const val KEY_URL = "url"
}
}
|
epl-1.0
|
dec62090611832b8dad7d5f2e4e3f167
| 23.228571 | 88 | 0.642267 | 3.957944 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/parser/SyntheticFlexmarkNodes.kt
|
1
|
3051
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.parser
import com.intellij.psi.tree.IElementType
import com.vladsch.flexmark.util.ast.Node
import com.vladsch.flexmark.util.sequence.BasedSequence
import java.util.*
class SyntheticFlexmarkNodes(val node: Node, val nodeType: IElementType, val nodeTokenType: IElementType) {
val chars: BasedSequence = node.chars
val nodes = ArrayList<SyntheticNode>()
val nodeStart: Int get() = chars.startOffset
val nodeEnd: Int get() = chars.endOffset
// constructor(node: Node, nodeType: IElementType) : this(node, nodeType, MultiMarkdownTypes.NONE)
override fun toString(): String {
return nodeType.toString() + "[" + chars.startOffset + "," + chars.endOffset + ") " + chars.toString()
}
data class SyntheticNode(val chars: BasedSequence, val type: IElementType, val compositeType: IElementType? = null) {
fun isComposite(): Boolean {
return compositeType != null
}
val startOffset: Int get() = chars.startOffset
val endOffset: Int get() = chars.endOffset
override fun toString(): String {
return (if (isComposite()) "*" else "") + type.toString() + "[" + startOffset + ", " + endOffset + "]"
}
}
fun addLeaf(chars: BasedSequence, type: IElementType): SyntheticFlexmarkNodes {
if (chars.isNotNull && chars.isNotEmpty()) nodes.add(SyntheticNode(chars, type, null))
return this
}
fun addComposite(chars: BasedSequence, compositeType: IElementType, type: IElementType): SyntheticFlexmarkNodes {
if (chars.isNotNull) nodes.add(SyntheticNode(chars, type, compositeType))
return this
}
// fun addComposite(chars: BasedSequence, compositeType: IElementType): SyntheticFlexmarkNodes {
// if (chars.isNotNull) nodes.add(SyntheticNode(chars, MultiMarkdownTypes.NONE, compositeType))
// return this;
// }
// fun addNodes(chars: Array<BasedSequence>, types: Array<IElementType>): SyntheticFlexmarkNodes {
// if (chars.size != types.size) {
// throw IllegalArgumentException("chars.size ${chars.size} not equal to types.size ${types.size}")
// }
//
// for (i in 0..chars.size - 1) {
// addLeaf(chars[i], types[i])
// }
//
// return this;
// }
//
// fun addComposites(chars: Array<BasedSequence>, compositeTypes: Array<IElementType>): SyntheticFlexmarkNodes {
// if (chars.size != compositeTypes.size) {
// throw IllegalArgumentException("chars.size ${chars.size} not equal to compositeTypes.size ${compositeTypes.size}")
// }
//
// for (i in 0..chars.size - 1) {
// addComposite(chars[i], compositeTypes[i])
// }
//
// return this;
// }
}
|
apache-2.0
|
88df268ac5270b986519f9afc41b6ef5
| 40.794521 | 177 | 0.633563 | 4.196699 | false | false | false | false |
chrisbanes/tivi
|
app/src/main/java/app/tivi/home/Home.kt
|
1
|
13971
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.home
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.animation.Crossfade
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.NavigationRail
import androidx.compose.material.NavigationRailDefaults
import androidx.compose.material.NavigationRailItem
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.contentColorFor
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.Weekend
import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.material.icons.outlined.Weekend
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import app.tivi.AppNavigation
import app.tivi.Screen
import app.tivi.common.compose.theme.AppBarAlphas
import app.tivi.debugLabel
import app.tivi.util.Analytics
import com.google.accompanist.insets.ui.BottomNavigation
import com.google.accompanist.insets.ui.Scaffold
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi
import com.google.accompanist.navigation.material.ModalBottomSheetLayout
import com.google.accompanist.navigation.material.rememberBottomSheetNavigator
import app.tivi.common.ui.resources.R as UiR
@OptIn(
ExperimentalAnimationApi::class,
ExperimentalMaterialApi::class,
ExperimentalMaterialNavigationApi::class
)
@Composable
internal fun Home(
analytics: Analytics,
onOpenSettings: () -> Unit
) {
val bottomSheetNavigator = rememberBottomSheetNavigator()
val navController = rememberAnimatedNavController(bottomSheetNavigator)
// Launch an effect to track changes to the current back stack entry, and push them
// as a screen views to analytics
LaunchedEffect(navController, analytics) {
navController.currentBackStackEntryFlow.collect { entry ->
analytics.trackScreenView(
label = entry.debugLabel,
route = entry.destination.route,
arguments = entry.arguments
)
}
}
val configuration = LocalConfiguration.current
val useBottomNavigation by remember {
derivedStateOf { configuration.smallestScreenWidthDp < 600 }
}
Scaffold(
bottomBar = {
if (useBottomNavigation) {
val currentSelectedItem by navController.currentScreenAsState()
HomeBottomNavigation(
selectedNavigation = currentSelectedItem,
onNavigationSelected = { selected ->
navController.navigate(selected.route) {
launchSingleTop = true
restoreState = true
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
}
},
modifier = Modifier.fillMaxWidth()
)
} else {
Spacer(
Modifier
.windowInsetsBottomHeight(WindowInsets.navigationBars)
.fillMaxWidth()
)
}
}
) {
Row(Modifier.fillMaxSize()) {
if (!useBottomNavigation) {
val currentSelectedItem by navController.currentScreenAsState()
HomeNavigationRail(
selectedNavigation = currentSelectedItem,
onNavigationSelected = { selected ->
navController.navigate(selected.route) {
launchSingleTop = true
restoreState = true
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
}
},
modifier = Modifier.fillMaxHeight()
)
Divider(
Modifier
.fillMaxHeight()
.width(1.dp)
)
}
ModalBottomSheetLayout(bottomSheetNavigator) {
AppNavigation(
navController = navController,
onOpenSettings = onOpenSettings,
modifier = Modifier
.weight(1f)
.fillMaxHeight()
)
}
}
}
}
/**
* Adds an [NavController.OnDestinationChangedListener] to this [NavController] and updates the
* returned [State] which is updated as the destination changes.
*/
@Stable
@Composable
private fun NavController.currentScreenAsState(): State<Screen> {
val selectedItem = remember { mutableStateOf<Screen>(Screen.Discover) }
DisposableEffect(this) {
val listener = NavController.OnDestinationChangedListener { _, destination, _ ->
when {
destination.hierarchy.any { it.route == Screen.Discover.route } -> {
selectedItem.value = Screen.Discover
}
destination.hierarchy.any { it.route == Screen.Watched.route } -> {
selectedItem.value = Screen.Watched
}
destination.hierarchy.any { it.route == Screen.Following.route } -> {
selectedItem.value = Screen.Following
}
destination.hierarchy.any { it.route == Screen.Search.route } -> {
selectedItem.value = Screen.Search
}
}
}
addOnDestinationChangedListener(listener)
onDispose {
removeOnDestinationChangedListener(listener)
}
}
return selectedItem
}
@Composable
internal fun HomeBottomNavigation(
selectedNavigation: Screen,
onNavigationSelected: (Screen) -> Unit,
modifier: Modifier = Modifier
) {
BottomNavigation(
backgroundColor = MaterialTheme.colors.surface.copy(alpha = AppBarAlphas.translucentBarAlpha()),
contentColor = contentColorFor(MaterialTheme.colors.surface),
contentPadding = WindowInsets.navigationBars.asPaddingValues(),
modifier = modifier
) {
HomeNavigationItems.forEach { item ->
BottomNavigationItem(
icon = {
HomeNavigationItemIcon(
item = item,
selected = selectedNavigation == item.screen
)
},
label = { Text(text = stringResource(item.labelResId)) },
selected = selectedNavigation == item.screen,
onClick = { onNavigationSelected(item.screen) }
)
}
}
}
@ExperimentalMaterialApi
@Composable
internal fun HomeNavigationRail(
selectedNavigation: Screen,
onNavigationSelected: (Screen) -> Unit,
modifier: Modifier = Modifier
) {
Surface(
color = MaterialTheme.colors.surface,
elevation = NavigationRailDefaults.Elevation,
modifier = modifier
) {
NavigationRail(
backgroundColor = Color.Transparent,
contentColor = MaterialTheme.colors.onSurface,
elevation = 0.dp,
modifier = Modifier.padding(
WindowInsets.systemBars
.only(WindowInsetsSides.Start + WindowInsetsSides.Vertical)
.asPaddingValues()
)
) {
HomeNavigationItems.forEach { item ->
NavigationRailItem(
icon = {
HomeNavigationItemIcon(
item = item,
selected = selectedNavigation == item.screen
)
},
alwaysShowLabel = false,
label = { Text(text = stringResource(item.labelResId)) },
selected = selectedNavigation == item.screen,
onClick = { onNavigationSelected(item.screen) }
)
}
}
}
}
@Composable
private fun HomeNavigationItemIcon(item: HomeNavigationItem, selected: Boolean) {
val painter = when (item) {
is HomeNavigationItem.ResourceIcon -> painterResource(item.iconResId)
is HomeNavigationItem.ImageVectorIcon -> rememberVectorPainter(item.iconImageVector)
}
val selectedPainter = when (item) {
is HomeNavigationItem.ResourceIcon -> item.selectedIconResId?.let { painterResource(it) }
is HomeNavigationItem.ImageVectorIcon -> item.selectedImageVector?.let { rememberVectorPainter(it) }
}
if (selectedPainter != null) {
Crossfade(targetState = selected) {
Icon(
painter = if (it) selectedPainter else painter,
contentDescription = stringResource(item.contentDescriptionResId)
)
}
} else {
Icon(
painter = painter,
contentDescription = stringResource(item.contentDescriptionResId)
)
}
}
private sealed class HomeNavigationItem(
val screen: Screen,
@StringRes val labelResId: Int,
@StringRes val contentDescriptionResId: Int
) {
class ResourceIcon(
screen: Screen,
@StringRes labelResId: Int,
@StringRes contentDescriptionResId: Int,
@DrawableRes val iconResId: Int,
@DrawableRes val selectedIconResId: Int? = null
) : HomeNavigationItem(screen, labelResId, contentDescriptionResId)
class ImageVectorIcon(
screen: Screen,
@StringRes labelResId: Int,
@StringRes contentDescriptionResId: Int,
val iconImageVector: ImageVector,
val selectedImageVector: ImageVector? = null
) : HomeNavigationItem(screen, labelResId, contentDescriptionResId)
}
private val HomeNavigationItems = listOf(
HomeNavigationItem.ImageVectorIcon(
screen = Screen.Discover,
labelResId = UiR.string.discover_title,
contentDescriptionResId = UiR.string.cd_discover_title,
iconImageVector = Icons.Outlined.Weekend,
selectedImageVector = Icons.Default.Weekend
),
HomeNavigationItem.ImageVectorIcon(
screen = Screen.Following,
labelResId = UiR.string.following_shows_title,
contentDescriptionResId = UiR.string.cd_following_shows_title,
iconImageVector = Icons.Default.FavoriteBorder,
selectedImageVector = Icons.Default.Favorite
),
HomeNavigationItem.ImageVectorIcon(
screen = Screen.Watched,
labelResId = UiR.string.watched_shows_title,
contentDescriptionResId = UiR.string.cd_watched_shows_title,
iconImageVector = Icons.Outlined.Visibility,
selectedImageVector = Icons.Default.Visibility
),
HomeNavigationItem.ImageVectorIcon(
screen = Screen.Search,
labelResId = UiR.string.search_navigation_title,
contentDescriptionResId = UiR.string.cd_search_navigation_title,
iconImageVector = Icons.Default.Search
)
)
|
apache-2.0
|
494020e92c49f8503a91df810dc31e23
| 37.381868 | 108 | 0.659294 | 5.400464 | false | false | false | false |
noties/Markwon
|
app-sample/src/main/java/io/noties/markwon/app/sample/ui/adapt/SampleItem.kt
|
1
|
3947
|
package io.noties.markwon.app.sample.ui.adapt
import android.text.Spanned
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import io.noties.adapt.Item
import io.noties.markwon.Markwon
import io.noties.markwon.app.R
import io.noties.markwon.app.sample.Sample
import io.noties.markwon.app.utils.displayName
import io.noties.markwon.app.utils.hidden
import io.noties.markwon.app.utils.tagDisplayName
import io.noties.markwon.app.widget.FlowLayout
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.utils.NoCopySpannableFactory
class SampleItem(
private val markwon: Markwon,
private val sample: Sample,
private val onArtifactClick: (MarkwonArtifact) -> Unit,
private val onTagClick: (String) -> Unit,
private val onSampleClick: (Sample) -> Unit
) : Item<SampleItem.Holder>(sample.id.hashCode().toLong()) {
// var search: String? = null
private val text: Spanned by lazy(LazyThreadSafetyMode.NONE) {
markwon.toMarkdown(sample.description)
}
override fun createHolder(inflater: LayoutInflater, parent: ViewGroup): Holder {
return Holder(inflater.inflate(R.layout.adapt_sample, parent, false)).apply {
description.setSpannableFactory(NoCopySpannableFactory.getInstance())
}
}
override fun render(holder: Holder) {
holder.apply {
title.text = sample.title
val text = [email protected]
if (text.isEmpty()) {
description.text = ""
description.hidden = true
} else {
markwon.setParsedMarkdown(description, text)
description.hidden = false
}
// there is no need to display the core artifact (it is implicit),
// hide if empty (removed core)
artifacts.ensure(sample.artifacts.size, R.layout.view_artifact)
.zip(sample.artifacts)
.forEach { (view, artifact) ->
(view as TextView).text = artifact.displayName
view.setOnClickListener {
onArtifactClick(artifact)
}
}
tags.ensure(sample.tags.size, R.layout.view_tag)
.zip(sample.tags)
.forEach { (view, tag) ->
(view as TextView).text = tag.tagDisplayName
view.setOnClickListener {
onTagClick(tag)
}
}
itemView.setOnClickListener {
onSampleClick(sample)
}
}
}
class Holder(itemView: View) : Item.Holder(itemView) {
val title: TextView = requireView(R.id.title)
val description: TextView = requireView(R.id.description)
val artifacts: FlowLayout = requireView(R.id.artifacts)
val tags: FlowLayout = requireView(R.id.tags)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SampleItem
if (sample != other.sample) return false
return true
}
override fun hashCode(): Int {
return sample.hashCode()
}
}
private fun FlowLayout.ensure(viewsCount: Int, layoutResId: Int): List<View> {
if (viewsCount > childCount) {
// inflate new views
val inflater = LayoutInflater.from(context)
for (i in 0 until (viewsCount - childCount)) {
addView(inflater.inflate(layoutResId, this, false))
}
} else {
// return requested vies and GONE the rest
for (i in viewsCount until childCount) {
getChildAt(i).hidden = true
}
}
return (0 until viewsCount).map { getChildAt(it) }
}
|
apache-2.0
|
08084649bc5cc596a854a592753b9439
| 33.321739 | 85 | 0.60527 | 4.578886 | false | false | false | false |
iluu/algs-progfun
|
src/main/kotlin/com/hackerrank/ConnectedCellsInAGrid.kt
|
1
|
2181
|
package com.hackerrank
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextInt()
val m = scan.nextInt()
val arr = Array(n, { Array(m, { scan.nextInt() }) })
println(sizeOfMaxRegion(Board(arr, n, m)))
}
fun sizeOfMaxRegion(board: Board): Int {
var maxSize = 0
for (i in 0..board.n - 1) {
for (j in 0..board.m - 1) {
val node = Pair(i, j)
if (!board.wasVisited(node)) {
val size = regionSize(node, board)
if (size > maxSize) {
maxSize = size
}
}
}
}
return maxSize
}
fun regionSize(node: Pair<Int, Int>, board: Board): Int {
var region = if (board.isNode(node)) 1 else 0
board.markVisited(node)
board.neighbours(node)
.map { regionSize(it, board) }
.forEach { region += it }
return region
}
class Board(val arr: Array<Array<Int>>, val n: Int, val m: Int) {
private var visited = mutableSetOf<Pair<Int, Int>>()
fun markVisited(node: Pair<Int, Int>) {
visited.add(node)
}
fun neighbours(node: Pair<Int, Int>): List<Pair<Int, Int>> {
val neighbours = setOf(
Pair(node.first - 1, node.second - 1),
Pair(node.first - 1, node.second),
Pair(node.first - 1, node.second + 1),
Pair(node.first, node.second - 1),
Pair(node.first, node.second + 1),
Pair(node.first + 1, node.second - 1),
Pair(node.first + 1, node.second),
Pair(node.first + 1, node.second + 1))
return neighbours.filter { (first, second) -> valid(first, second) }
}
fun isNode(pair: Pair<Int, Int>): Boolean {
return arr[pair.first][pair.second] == 1 && !wasVisited(pair)
}
fun wasVisited(pair: Pair<Int, Int>): Boolean {
return visited.contains(pair)
}
private fun valid(row: Int, col: Int): Boolean {
return row in 0..n - 1
&& col in 0..m - 1
&& arr[row][col] == 1
&& !wasVisited(Pair(row, col))
}
}
|
mit
|
48bfd6635c685a507560297f58c9fe89
| 27.710526 | 76 | 0.522696 | 3.587171 | false | false | false | false |
dataloom/conductor-client
|
src/test/kotlin/com/openlattice/graph/processing/GraphProcessorQueryTest.kt
|
1
|
2454
|
package com.openlattice.graph.processing
import com.openlattice.edm.type.PropertyType
import com.openlattice.graph.PagedNeighborRequest
import com.openlattice.graph.getFilteredNeighborhoodSql
import com.openlattice.search.requests.EntityNeighborsFilter
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind
import org.apache.olingo.commons.api.edm.FullQualifiedName
import org.junit.Test
import org.slf4j.LoggerFactory
import java.util.*
class GraphProcessorQueryTest {
private val logger = LoggerFactory.getLogger(GraphProcessingService::class.java)
@Test
fun testPropagationQuery() {
val neighborEntitySetIds: Collection<UUID> = listOf(UUID.fromString("0241bc09-bed9-4954-a8e8-6b258ca2f2b8"),
UUID.fromString("0241bc09-bed9-4954-a8e8-6b258ca2f2b8"))
val neighborPropertyTypeIds: Set<UUID> = setOf(UUID.fromString("7674c064-c8fb-42b0-a1ca-c7cab0e0829d"),
UUID.fromString("6675a7e8-2159-41b1-9431-4053690fa3c9"))
val entitySetIds: Collection<UUID> = listOf(UUID.fromString("0241bc09-bed9-4954-a8e8-6b258ca2f2b8"))
val propertyTypeUUID = UUID.fromString("736818e8-0ad9-4c83-8b53-3e00005fed2b")
val propertyType = PropertyType(UUID.fromString("736818e8-0ad9-4c83-8b53-3e00005fed2b"),
FullQualifiedName("datetime.alerted"), "Alerted date-time",
Optional.of("A CFS Alerted DateTime"), setOf(FullQualifiedName("v2.v2")),
EdmPrimitiveTypeKind.DateTimeOffset)
val propertyTypes: Map<UUID, PropertyType> = mapOf(propertyTypeUUID to propertyType)
val associationType = false
val isSelf = true
buildPropagationQueries(neighborEntitySetIds, neighborPropertyTypeIds, entitySetIds, propertyTypes,
associationType, isSelf).forEach { logger.info(it) }
}
@Test
fun testGetFilteredNeighborhoodSql() {
val entityKeyIds = (0 until 10).map { UUID.randomUUID() }.toSet()
val filter = EntityNeighborsFilter(
entityKeyIds,
Optional.of(setOf(UUID.randomUUID())),
Optional.of(setOf(UUID.randomUUID())),
Optional.of(setOf(UUID.randomUUID())))
val query = getFilteredNeighborhoodSql(PagedNeighborRequest(filter), setOf(1, 2, 3))
val uuidArray = "'{\"${UUID.randomUUID()}\"}'"
val preparedQuery = query.replace("?", uuidArray)
logger.info(preparedQuery)
}
}
|
gpl-3.0
|
fc4b4cf50c03d65c88a15340838eb2df
| 45.320755 | 116 | 0.707416 | 3.798762 | false | true | false | false |
http4k/http4k
|
http4k-metrics-micrometer/src/test/kotlin/org/http4k/filter/MicrometerMetricsServerTest.kt
|
1
|
6763
|
package org.http4k.filter
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import io.micrometer.core.instrument.Tag
import io.micrometer.core.instrument.simple.SimpleMeterRegistry
import org.http4k.core.Method
import org.http4k.core.Method.DELETE
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.Status.Companion.INTERNAL_SERVER_ERROR
import org.http4k.core.Status.Companion.OK
import org.http4k.hamkrest.hasBody
import org.http4k.hamkrest.hasStatus
import org.http4k.lens.Path
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.http4k.routing.static
import org.http4k.util.TickingClock
import org.junit.jupiter.api.Test
class MicrometerMetricsServerTest {
private val registry = SimpleMeterRegistry()
private val clock = TickingClock()
private var requestTimer = ServerFilters.MicrometerMetrics.RequestTimer(registry, clock = clock)
private var requestCounter = ServerFilters.MicrometerMetrics.RequestCounter(registry, clock = clock)
private val server by lazy {
routes(
"/timed" bind routes(
"/one" bind GET to { Response(OK) },
"/two/{name:.*}" bind POST to { Response(OK).body(Path.of("name")(it)) }
).withFilter(requestTimer),
"/counted" bind routes(
"/one" bind GET to { Response(OK) },
"/two/{name:.*}" bind POST to { Response(OK).body(Path.of("name")(it)) }
).withFilter(requestCounter),
"/unmetered" bind routes(
"one" bind GET to { Response(OK) },
"two" bind DELETE to { Response(INTERNAL_SERVER_ERROR) }
),
"/otherTimed" bind static().withFilter(requestTimer),
"/otherCounted" bind static().withFilter(requestCounter)
)
}
@Test
fun `routes with timer generate request timing metrics tagged with path and method and status`() {
assertThat(server(Request(GET, "/timed/one")), hasStatus(OK))
repeat(2) {
assertThat(server(Request(POST, "/timed/two/bob")), (hasStatus(OK) and hasBody("bob")))
}
assert(registry,
hasRequestTimer(1, 1, tags = arrayOf(
"path" to "timed_one", "method" to "GET", "status" to "200")),
hasRequestTimer(2, 2, tags = arrayOf(
"path" to "timed_two_name", "method" to "POST", "status" to "200"))
)
}
@Test
fun `routes with counter generate request count metrics tagged with path and method and status`() {
assertThat(server(Request(GET, "/counted/one")), hasStatus(OK))
repeat(2) {
assertThat(server(Request(POST, "/counted/two/bob")), (hasStatus(OK) and hasBody("bob")))
}
assert(registry,
hasRequestCounter(1, tags = arrayOf("path" to "counted_one", "method" to "GET", "status" to "200")),
hasRequestCounter(2, tags = arrayOf("path" to "counted_two_name", "method" to "POST", "status" to "200"))
)
}
@Test
fun `routes without metrics generate nothing`() {
assertThat(server(Request(GET, "/unmetered/one")), hasStatus(OK))
assertThat(server(Request(DELETE, "/unmetered/two")), hasStatus(INTERNAL_SERVER_ERROR))
assert(registry,
hasNoRequestTimer(GET, "unmetered_one", OK),
hasNoRequestTimer(DELETE, "unmetered_two", INTERNAL_SERVER_ERROR),
hasNoRequestCounter(GET, "unmetered_one", OK),
hasNoRequestCounter(DELETE, "unmetered_two", INTERNAL_SERVER_ERROR)
)
}
@Test
fun `request timer meter names and request id formatter can be configured`() {
requestTimer = ServerFilters.MicrometerMetrics.RequestTimer(registry, "custom.requests", "custom.description",
{ it.label("foo", "bar") }, clock)
assertThat(server(Request(GET, "/timed/one")), hasStatus(OK))
assert(registry,
hasRequestTimer(1, 1, "custom.requests", "custom.description", "foo" to "bar")
)
}
@Test
fun `request counter meter names and request id formatter can be configured`() {
requestCounter = ServerFilters.MicrometerMetrics.RequestCounter(registry, "custom.requests", "custom.description",
{ it.label("foo", "bar") })
assertThat(server(Request(GET, "/counted/one")), hasStatus(OK))
assert(registry,
hasRequestCounter(1, "custom.requests", "custom.description", "foo" to "bar")
)
}
@Test
fun `timed routes without uri template generate request timing metrics tagged with unmapped path value`() {
assertThat(server(Request(GET, "/otherTimed/test.json")), hasStatus(OK))
assert(registry, hasRequestTimer(1, 1, tags = arrayOf("path" to "UNMAPPED", "method" to "GET", "status" to "200")))
}
@Test
fun `counted routes without uri template generate request count metrics tagged with unmapped path value`() {
assertThat(server(Request(GET, "/otherCounted/test.json")), hasStatus(OK))
assert(registry, hasRequestCounter(1, tags = arrayOf("path" to "UNMAPPED", "method" to "GET", "status" to "200")))
}
private fun hasRequestCounter(count: Long,
name: String = "http.server.request.count",
description: String = "Total number of server requests",
vararg tags: Pair<String, String>) = hasCounter(name,
tags.asList()
.map { Tag.of(it.first, it.second) },
description(description) and counterCount(count)
)
private fun hasRequestTimer(count: Long, totalTimeSec: Long,
name: String = "http.server.request.latency",
description: String = "Timing of server requests",
vararg tags: Pair<String, String>) = hasTimer(name,
tags.asList()
.map { Tag.of(it.first, it.second) },
description(description) and timerCount(count) and timerTotalTime(totalTimeSec * 1000)
)
private fun hasNoRequestTimer(method: Method, path: String, status: Status) =
!hasTimer("http.server.request.latency",
listOf(Tag.of("path", path), Tag.of("method", method.name), Tag.of("status", status.code.toString()))
)
private fun hasNoRequestCounter(method: Method, path: String, status: Status) =
!hasCounter("http.server.request.count",
listOf(Tag.of("path", path), Tag.of("method", method.name), Tag.of("status", status.code.toString()))
)
}
|
apache-2.0
|
81a2448cf9bf50751df008e185326e8d
| 42.915584 | 123 | 0.631672 | 4.047277 | false | true | false | false |
fan123199/V2ex-simple
|
app/src/main/java/im/fdx/v2ex/ui/SettingsActivity.kt
|
1
|
6124
|
package im.fdx.v2ex.ui
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
import androidx.core.net.toUri
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.work.WorkManager
import com.elvishew.xlog.XLog
import im.fdx.v2ex.*
import im.fdx.v2ex.network.HttpHelper
import im.fdx.v2ex.utils.Keys
import im.fdx.v2ex.utils.Keys.PREF_NIGHT_MODE
import im.fdx.v2ex.utils.Keys.PREF_TAB
import im.fdx.v2ex.utils.Keys.PREF_TEXT_SIZE
import im.fdx.v2ex.utils.Keys.PREF_VERSION
import im.fdx.v2ex.utils.Keys.TAG_WORKER
import im.fdx.v2ex.utils.Keys.notifyID
import im.fdx.v2ex.utils.extensions.setUpToolbar
import org.jetbrains.anko.longToast
import org.jetbrains.anko.toast
class SettingsActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
setUpToolbar("设置")
supportFragmentManager.beginTransaction()
.replace(R.id.container, SettingsFragment())
.commit()
}
class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener {
private var count: Int = 0
override fun onCreatePreferences(savedInstanceState: Bundle?, what: String?) {
addPreferencesFromResource(R.xml.preference)
prefTab()
prefNightMode()
prefRate()
prefVersion()
if (myApp.isLogin) {
addPreferencesFromResource(R.xml.preference_login)
findPreference<Preference>("group_user")?.title = pref.getString(Keys.PREF_USERNAME, "user")
prefUser()
prefMessage()
}
}
private fun prefNightMode() {
}
private fun prefMessage() {
val listPreference = findPreference<ListPreference>("pref_msg_period")
if (!pref.getBoolean("pref_msg", false)) {
findPreference<Preference>("pref_background_msg")?.isEnabled = false
findPreference<Preference>("pref_msg_period")?.isEnabled = false
}
}
private fun prefTab() {
findPreference<Preference>("pref_tab_bar")?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
startActivity(Intent(requireActivity(), TabSettingActivity::class.java))
true
}
}
private fun prefUser() {
findPreference<Preference>(Keys.PREF_LOGOUT)?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
AlertDialog.Builder(requireActivity())
.setTitle("提示")
.setMessage("确定要退出吗")
.setPositiveButton(R.string.ok) { _, _ ->
HttpHelper.myCookieJar.clear()
setLogin(false)
findPreference<Preference>(Keys.PREF_LOGOUT)?.isEnabled = false
pref.edit {
remove(PREF_TEXT_SIZE)
remove(PREF_TAB)
}
activity?.finish()
activity?.toast("已退出登录")
}
.setNegativeButton(R.string.cancel) { _, _ ->
}
.show()
true
}
}
private fun prefVersion() {
findPreference<Preference>(PREF_VERSION)?.summary = BuildConfig.VERSION_NAME
val ha = resources.getStringArray(R.array.j)
count = 7
findPreference<Preference>(PREF_VERSION)?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
if (count < 0) {
count = 3
activity?.longToast(ha[(System.currentTimeMillis() / 100 % ha.size).toInt()])
}
count--
true
}
}
private fun prefRate() {
findPreference<Preference>(Keys.PREF_RATES)?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
try {
val uri = "market://details?id=im.fdx.v2ex".toUri()
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
} catch (e: Exception) {
activity?.toast("没有可用的应用商店,请检查后重试")
}
true
}
}
override fun onResume() {
super.onResume()
pref.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
pref.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
Log.w("PREF", key)
when (key) {
"pref_msg" ->
if (sharedPreferences.getBoolean(key, false)) {
findPreference<Preference>("pref_msg_period")?.isEnabled = true
findPreference<Preference>("pref_background_msg")?.isEnabled = true
} else {
val notificationManager = activity?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(notifyID)
WorkManager.getInstance().cancelAllWorkByTag(TAG_WORKER)
findPreference<Preference>("pref_msg_period")?.isEnabled = false
findPreference<Preference>("pref_background_msg")?.isEnabled = false
}
"pref_background_msg" -> {}
"pref_msg_period" -> {}
"pref_add_row" -> {}
PREF_NIGHT_MODE -> {
val mode = pref.getString(PREF_NIGHT_MODE, "1")!!
AppCompatDelegate.setDefaultNightMode(mode.toInt())
}
PREF_TEXT_SIZE -> {
LocalBroadcastManager.getInstance(myApp).sendBroadcast(Intent(Keys.ACTION_TEXT_SIZE_CHANGE))
activity?.finish()
}
}
}
}
}
|
apache-2.0
|
a27409f468fbd7c49e6f91a153b7b460
| 32.677778 | 118 | 0.67189 | 4.638103 | false | false | false | false |
annekellyc/kotlin-koans
|
src/i_introduction/_7_Nullable_Types/NullableTypes.kt
|
1
|
647
|
package i_introduction._7_Nullable_Types
/*
Task 7.
Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression.
Declarations of Client, PersonalInfo and Mailer are given below.
*/
fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) {
if (client == null || message == null) return
val personalInfo = client.personalInfo ?: return
val email = personalInfo.email ?: return
mailer.sendMessage(email, message)
}
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
}
|
mit
|
6b907d728de7a91865a5bea6b5717e5b
| 25.958333 | 84 | 0.724884 | 4.284768 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/AddOpeningHours.kt
|
1
|
8850
|
package de.westnordost.streetcomplete.quests.opening_hours
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.osmfeatures.FeatureDictionary
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
import de.westnordost.streetcomplete.ktx.containsAny
import de.westnordost.streetcomplete.quests.opening_hours.parser.isSupported
import de.westnordost.streetcomplete.quests.opening_hours.parser.toOpeningHoursRules
import java.util.concurrent.FutureTask
class AddOpeningHours (
private val featureDictionaryFuture: FutureTask<FeatureDictionary>
) : OsmElementQuestType<OpeningHoursAnswer> {
/* See also AddWheelchairAccessBusiness and AddPlaceName, which has a similar list and is/should
be ordered in the same way for better overview */
private val filter by lazy { ("""
nodes, ways, relations with
(
(
(
shop and shop !~ no|vacant
or amenity = bicycle_parking and bicycle_parking = building
or amenity = parking and parking = multi-storey
or amenity = recycling and recycling_type = centre
or tourism = information and information = office
or tourism = attraction
or heritage:operator = whc
or """.trimIndent() +
// The common list is shared by the name quest, the opening hours quest and the wheelchair quest.
// So when adding other tags to the common list keep in mind that they need to be appropriate for all those quests.
// Independent tags can by added in the "opening_hours only" tab.
mapOf(
"amenity" to arrayOf(
// common
"restaurant", "cafe", "ice_cream", "fast_food", "bar", "pub", "biergarten", "food_court", "nightclub", // eat & drink
"cinema", "planetarium", "casino", // amenities
"townhall", "courthouse", "embassy", "community_centre", "youth_centre", "library", // civic
"bank", "bureau_de_change", "money_transfer", "post_office", "marketplace", "internet_cafe", // commercial
"car_wash", "car_rental", "fuel", // car stuff
"dentist", "doctors", "clinic", "pharmacy", "veterinary", // health
"animal_boarding", "animal_shelter", "animal_breeding", // animals
// name & opening hours
"boat_rental"
// not ATM because too often it's simply 24/7 and too often it is confused with
// a bank that might be just next door because the app does not tell the user what
// kind of object this is about
),
"tourism" to arrayOf(
// common
"zoo", "aquarium", "theme_park", "gallery", "museum"
// and tourism = information, see above
),
"leisure" to arrayOf(
// common
"fitness_centre", "golf_course", "water_park", "miniature_golf", "bowling_alley",
"amusement_arcade", "adult_gaming_centre", "tanning_salon",
// name & opening hours
"horse_riding"
// not sports_centre, dance etc because these are often sports clubs which have no
// walk-in opening hours but training times
),
"office" to arrayOf(
// common
"insurance", "government", "travel_agent", "tax_advisor", "religion",
"employment_agency", "diplomatic"
),
"craft" to arrayOf(
// common
"carpenter", "shoemaker", "tailor", "photographer", "dressmaker",
"electronics_repair", "key_cutter", "stonemason"
)
).map { it.key + " ~ " + it.value.joinToString("|") }.joinToString("\n or ") + "\n" + """
)
and !opening_hours
)
or opening_hours older today -0.75 years
)
and (access !~ private|no)
and (name or brand or noname = yes or name:signed = no)
and opening_hours:signed != no
""".trimIndent()).toElementFilterExpression() }
private val nameTags = listOf("name", "brand")
override val commitMessage = "Add opening hours"
override val wikiLink = "Key:opening_hours"
override val icon = R.drawable.ic_quest_opening_hours
override val isReplaceShopEnabled = true
override val questTypeAchievements = listOf(CITIZEN)
override fun getTitle(tags: Map<String, String>): Int {
val hasProperName = hasProperName(tags)
val hasFeatureName = hasFeatureName(tags)
// treat invalid opening hours like it is not set at all
val hasValidOpeningHours = tags["opening_hours"]?.toOpeningHoursRules() != null
return if (hasValidOpeningHours) {
when {
!hasProperName -> R.string.quest_openingHours_resurvey_no_name_title
!hasFeatureName -> R.string.quest_openingHours_resurvey_name_title
else -> R.string.quest_openingHours_resurvey_name_type_title
}
} else {
when {
!hasProperName -> R.string.quest_openingHours_no_name_title
!hasFeatureName -> R.string.quest_openingHours_name_title
else -> R.string.quest_openingHours_name_type_title
}
}
}
override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> {
val name = tags["name"] ?: tags["brand"]
val hasProperName = name != null
val hasFeatureName = hasFeatureName(tags)
return when {
!hasProperName -> arrayOf(featureName.value.toString())
!hasFeatureName -> arrayOf(name!!)
else -> arrayOf(name!!, featureName.value.toString())
}
}
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> =
mapData.filter { isApplicableTo(it) }
override fun isApplicableTo(element: Element) : Boolean {
if (!filter.matches(element)) return false
val tags = element.tags
// only show places that can be named somehow
if (!hasName(tags)) return false
// no opening_hours yet -> new survey
val oh = tags["opening_hours"] ?: return true
// invalid opening_hours rules -> applicable because we want to ask for opening hours again
val rules = oh.toOpeningHoursRules() ?: return true
// only display supported rules
return rules.isSupported()
}
override fun createForm() = AddOpeningHoursForm()
override fun applyAnswerTo(answer: OpeningHoursAnswer, changes: StringMapChangesBuilder) {
when(answer) {
is RegularOpeningHours -> {
changes.updateWithCheckDate("opening_hours", answer.hours.toString())
changes.deleteIfPreviously("opening_hours:signed", "no")
}
is AlwaysOpen -> {
changes.updateWithCheckDate("opening_hours", "24/7")
changes.deleteIfPreviously("opening_hours:signed", "no")
}
is DescribeOpeningHours -> {
val text = answer.text.replace("\"","")
changes.updateWithCheckDate("opening_hours", "\"$text\"")
changes.deleteIfPreviously("opening_hours:signed", "no")
}
is NoOpeningHoursSign -> {
changes.addOrModify("opening_hours:signed", "no")
// don't delete current opening hours: these may be the correct hours, they are just not visible anywhere on the door
}
}
}
private fun hasName(tags: Map<String, String>) = hasProperName(tags) || hasFeatureName(tags)
private fun hasProperName(tags: Map<String, String>): Boolean =
tags.keys.containsAny(nameTags)
private fun hasFeatureName(tags: Map<String, String>): Boolean =
featureDictionaryFuture.get().byTags(tags).isSuggestion(false).find().isNotEmpty()
}
|
gpl-3.0
|
2f9b243800f9729f024e9db668157685
| 47.360656 | 133 | 0.597401 | 4.727564 | false | false | false | false |
songzhw/Hello-kotlin
|
KotlinPlayground/src/main/kotlin/ca/six/klplay/tutorial/abbasic/Array02.kt
|
1
|
1135
|
package cn.song.abbasic
/**
* Created by hzsongzhengwang on 2015/8/18.
*/
fun array2(args: Array<String>) {
val ary1 = arrayOf(1,2,3,"4")
ary1.forEach{ println(it)} //=> 1,2,3,4
// ary1.forEach { println(it+1) } // error!
// error 1: Kotlin语法不支持这样的赋值
// var ary0 = []
//error 2:
// val ary0 = arrayOfNulls(3) // error. Need to know which type is null
// 之所以声明类型,是因为arrayOfNulls要求指定数组存储的数据类型
val ary2 : Array<Int?> = arrayOfNulls(5)
ary2[2] = 23 //后期才给赋值
var ary3 = Array(5, {(it * it ).toString()}) //=> 0 1 4 9 16
var ary4 = intArrayOf(1,2,3) // int array
var ary5 = arrayListOf("1","2", "3") // string array
}
// IntArray不用每取次值都自动封箱, 直接存为int[]
// Array<Int>其实存的是Integer[], 都得去封箱
fun twoTypeIntArray() {
val intArray = intArrayOf(1, 2, 3)
val arrayOfInt = arrayOf(1, 2, 3)
println("intArray = ${intArray}") //=> [I@27c170f0
println("arrayOfInt = ${arrayOfInt}") //=> [Ljava.lang.Integer;@5451c3a8
}
|
apache-2.0
|
864366d1ab1d8a7b10226fe6635413b1
| 24.125 | 81 | 0.593035 | 2.68 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/service/SyncCollectionUnupdated.kt
|
1
|
6430
|
package com.boardgamegeek.service
import android.accounts.Account
import android.content.SyncResult
import com.boardgamegeek.BggApplication
import com.boardgamegeek.R
import com.boardgamegeek.db.CollectionDao
import com.boardgamegeek.extensions.formatList
import com.boardgamegeek.extensions.whereZeroOrNull
import com.boardgamegeek.io.BggService
import com.boardgamegeek.mappers.mapToEntities
import com.boardgamegeek.provider.BggContract.Collection
import com.boardgamegeek.provider.BggContract.Games
import com.boardgamegeek.util.RemoteConfig
import kotlinx.coroutines.runBlocking
import timber.log.Timber
import java.io.IOException
/**
* Syncs collection items that have not yet been updated completely with stats and private info (in batches).
*/
class SyncCollectionUnupdated(
application: BggApplication,
service: BggService,
syncResult: SyncResult,
private val account: Account
) : SyncTask(application, service, syncResult) {
private var detail: String = ""
override val syncType = SyncService.FLAG_SYNC_COLLECTION_DOWNLOAD
override val notificationSummaryMessageId = R.string.sync_notification_collection_unupdated
private val fetchPauseMillis = RemoteConfig.getLong(RemoteConfig.KEY_SYNC_COLLECTION_FETCH_PAUSE_MILLIS)
private val gamesPerFetch = RemoteConfig.getInt(RemoteConfig.KEY_SYNC_COLLECTION_GAMES_PER_FETCH)
private val maxFetchCount = RemoteConfig.getInt(RemoteConfig.KEY_SYNC_COLLECTION_FETCH_MAX)
override fun execute() {
Timber.i("Syncing unupdated collection list...")
try {
var numberOfFetches = 0
val dao = CollectionDao(application)
val options = mutableMapOf(
BggService.COLLECTION_QUERY_KEY_SHOW_PRIVATE to "1",
BggService.COLLECTION_QUERY_KEY_STATS to "1",
)
var previousGameList = mapOf<Int, String>()
do {
if (isCancelled) break
if (numberOfFetches > 0) if (wasSleepInterrupted(fetchPauseMillis)) return
numberOfFetches++
val gameList = queryGames()
if (gameList == previousGameList) {
Timber.i("...didn't update any games; breaking out of fetch loop")
break
}
previousGameList = gameList.toMap()
if (gameList.isNotEmpty()) {
val gameDescription = gameList.values.toList().formatList()
detail = context.getString(
R.string.sync_notification_collection_update_games,
gameList.size,
gameDescription
)
if (numberOfFetches > 1) {
detail = context.getString(R.string.sync_notification_page_suffix, detail, numberOfFetches)
}
updateProgressNotification(detail)
Timber.i("...found %,d games to update [%s]", gameList.size, gameDescription)
options[BggService.COLLECTION_QUERY_KEY_ID] = gameList.keys.joinToString(",")
options.remove(BggService.COLLECTION_QUERY_KEY_SUBTYPE)
val itemCount = requestAndPersist(account.name, dao, options)
if (itemCount < 0) {
Timber.i("...unsuccessful sync; breaking out of fetch loop")
cancel()
break
}
options[BggService.COLLECTION_QUERY_KEY_SUBTYPE] = BggService.THING_SUBTYPE_BOARDGAME_ACCESSORY
val accessoryCount = requestAndPersist(account.name, dao, options)
if (accessoryCount < 0) {
Timber.i("...unsuccessful sync; breaking out of fetch loop")
cancel()
break
}
if (itemCount + accessoryCount == 0) {
Timber.i("...unsuccessful sync; breaking out of fetch loop")
break
}
} else {
Timber.i("...no more unupdated collection items")
break
}
} while (numberOfFetches < maxFetchCount)
} finally {
Timber.i("...complete!")
}
}
private fun queryGames(): Map<Int, String> {
val games = mutableMapOf<Int, String>()
val cursor = context.contentResolver.query(
Collection.CONTENT_URI,
arrayOf(Games.Columns.GAME_ID, Games.Columns.GAME_NAME),
"collection.${Collection.Columns.UPDATED}".whereZeroOrNull(),
null,
"collection.${Collection.Columns.UPDATED_LIST} DESC LIMIT $gamesPerFetch"
)
cursor?.use {
while (it.moveToNext()) {
games[it.getInt(0)] = it.getString(1)
}
}
return games
}
private fun requestAndPersist(username: String, dao: CollectionDao, options: Map<String, String>): Int {
Timber.i("..requesting collection items with options %s", options)
val call = service.collection(username, options)
try {
val timestamp = System.currentTimeMillis()
val response = call.execute()
if (response.isSuccessful) {
val items = response.body()?.items
return if (items != null && items.size > 0) {
for (item in items) {
val (collectionItem, game) = item.mapToEntities()
runBlocking {
dao.saveItem(collectionItem, game, timestamp)
}
}
syncResult.stats.numUpdates += items.size.toLong()
Timber.i("...saved %,d collection items", items.size)
items.size
} else {
Timber.i("...no collection items found for these games")
0
}
} else {
showError(detail, response.code())
syncResult.stats.numIoExceptions++
return -1
}
} catch (e: IOException) {
showError(detail, e)
syncResult.stats.numIoExceptions++
return -1
}
}
}
|
gpl-3.0
|
a51a5eee981535bdd07dcba85733cdf5
| 38.691358 | 115 | 0.566874 | 5.160514 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/repository/ImageRepository.kt
|
1
|
2473
|
package com.boardgamegeek.repository
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.annotation.WorkerThread
import com.boardgamegeek.BggApplication
import com.boardgamegeek.R
import com.boardgamegeek.db.ImageDao
import com.boardgamegeek.provider.BggContract.Companion.PATH_THUMBNAILS
import com.boardgamegeek.util.FileUtils
import com.squareup.picasso.Picasso
import timber.log.Timber
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class ImageRepository(val application: BggApplication) {
private val imageDao = ImageDao(application)
/** Get a bitmap for the given URL, either from disk or from the network. */
@WorkerThread
fun fetchThumbnail(thumbnailUrl: String?): Bitmap? {
if (thumbnailUrl == null) return null
if (application.applicationContext == null) return null
if (thumbnailUrl.isBlank()) return null
val file = getThumbnailFile(application.applicationContext, thumbnailUrl)
val bitmap: Bitmap? = if (file?.exists() == true) {
BitmapFactory.decodeFile(file.absolutePath)
} else {
try {
Picasso.with(application.applicationContext)
.load(thumbnailUrl)
.resizeDimen(R.dimen.shortcut_icon_size, R.dimen.shortcut_icon_size)
.centerCrop()
.get()
} catch (e: IOException) {
Timber.e(e, "Error downloading the thumbnail.")
null
}
}
if (bitmap != null && file != null) {
try {
BufferedOutputStream(FileOutputStream(file)).use { out ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
}
} catch (e: IOException) {
Timber.e(e, "Error saving the thumbnail file.")
}
}
return bitmap
}
suspend fun delete() {
imageDao.deleteThumbnails()
imageDao.deleteAvatars()
}
private fun getThumbnailFile(context: Context, url: String): File? {
if (url.isNotBlank()) {
val filename = FileUtils.getFileNameFromUrl(url)
return if (filename.isNotBlank())
File(FileUtils.generateContentPath(context, PATH_THUMBNAILS), filename)
else null
}
return null
}
}
|
gpl-3.0
|
05dbfdb884e726ba6cf5cc20d5e869b2
| 34.84058 | 88 | 0.634048 | 4.811284 | false | false | false | false |
adityaDave2017/my-vocab
|
app/src/main/java/com/android/vocab/adapter/ShowListAdapter.kt
|
1
|
2717
|
package com.android.vocab.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.android.vocab.R
import com.android.vocab.holder.AddButtonHolder
import com.android.vocab.holder.TextShowHolder
import com.android.vocab.provider.bean.*
@Suppress("unused")
class ShowListAdapter(val context:Context, val type: SupportedTypes, val list: List<*>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val LOG_TAG: String = ShowListAdapter::class.java.simpleName
private val TEXT_VIEW_TYPE: Int = 0
private val BUTTON_VIEW_TYPE: Int = 1
init {
if (context !is ShowListAdapter.OnButtonClicked) {
throw ClassCastException("Must implement AddButtonHolder.OnButtonClicked")
}
}
interface OnButtonClicked {
fun onButtonClicked(type: SupportedTypes)
}
enum class SupportedTypes {
SENTENCE_TYPE, SYNONYM_TYPE, ANTONYM_TYPE
}
override fun getItemCount(): Int = list.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is TextShowHolder) {
holder.textView.text = when(type) {
SupportedTypes.SENTENCE_TYPE -> (list[position] as Sentence).sentence
SupportedTypes.SYNONYM_TYPE -> (list[position] as SynonymWord).word
SupportedTypes.ANTONYM_TYPE -> (list[position] as AntonymWord).word
}
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder =
if(viewType == BUTTON_VIEW_TYPE) {
val view: View = LayoutInflater.from(context).inflate(R.layout.add_button, parent, false)
AddButtonHolder(
view,
when(type){ SupportedTypes.SENTENCE_TYPE -> context.resources.getString(R.string.add_sentence)
SupportedTypes.SYNONYM_TYPE -> context.resources.getString(R.string.add_synonym)
SupportedTypes.ANTONYM_TYPE -> context.resources.getString(R.string.add_antonym)
},
object: AddButtonHolder.OnButtonClicked {
override fun buttonClicked() = (context as OnButtonClicked).onButtonClicked(type)
}
)
} else {
val view: View = LayoutInflater.from(context).inflate(R.layout.text_view_for_display, parent, false)
TextShowHolder(view)
}
override fun getItemViewType(position: Int): Int = if(list[position] == null) BUTTON_VIEW_TYPE else TEXT_VIEW_TYPE
}
|
mit
|
f66f95f146ec42065911039bd5d29b8b
| 35.24 | 138 | 0.655502 | 4.513289 | false | false | false | false |
kantega/niagara
|
niagara-http-undertow/src/main/kotlin/org/kantega/niagara/http/undertow/NiagaraHttpHandler.kt
|
1
|
2503
|
package org.kantega.niagara.http.undertow
import io.undertow.server.HttpHandler
import io.undertow.server.HttpServerExchange
import org.kantega.niagara.eff.Task
import org.kantega.niagara.http.Response
import org.kantega.niagara.http.Route
class NiagaraHttpHandler(val route: Route<Response>) : HttpHandler {
@Throws(Exception::class)
override fun handleRequest(exchange: HttpServerExchange) {
val output = route.handle(fromExchange(exchange))
output.run(
{ outputMatched ->
intoExcehange(outputMatched.value._2, exchange)
exchange.endExchange()
},
{ _ ->
exchange.statusCode = 404
exchange.endExchange()
},
{ outputFailed ->
exchange.statusCode = 500
exchange.endExchange()
throw RuntimeException(outputFailed.toString())
}
)
}
}
class NiagaraTaskHttpHandler(val route: Route<Task<Response>>, val executor: (Task<*>) -> Unit) : HttpHandler {
@Throws(Exception::class)
override fun handleRequest(exchange: HttpServerExchange) {
val runnable:()->Unit =
{
executor(
Task {
exchange.startBlocking()
val req = fromExchange(exchange)
val output = route.handle(req)
output.run(
{ outputMatched ->
executor(outputMatched.value._2
.handle { t ->
Task {
t.printStackTrace()
Response(statusCode = 500)
}
}
.bind { resp ->
Task {
intoExcehange(resp, exchange)
exchange.endExchange()
}
})
},
{ _ ->
exchange.statusCode = 404
exchange.endExchange()
},
{ outputFailed ->
exchange.endExchange()
println(outputFailed.failure)
throw RuntimeException(outputFailed.toString())
}
)
}
)}
exchange.dispatch(runnable)
}
}
|
apache-2.0
|
28aeb3cc377e672369adbf6ed5b60b1b
| 32.386667 | 111 | 0.459049 | 5.875587 | false | false | false | false |
ginz/VkMusicDownloader2
|
src/main/java/ws/ginzburg/vk/music2/AudioDownloader.kt
|
1
|
2645
|
package ws.ginzburg.vk.music2
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.URL
import java.nio.channels.Channels
/**
* Created by Ginzburg on 04/06/2017.
*/
class AudioDownloader(val audios: List<Audio>, val directory: File, val overwriteExisting: Boolean, val progressReporter: (Int) -> Unit, val finishReporter: () -> Unit, val failReporter: (Audio, Throwable) -> ErrorResponse) {
private @Volatile var isCanceled = false
fun start() {
Thread({
for ((i, audio) in audios.withIndex()) {
var stepFinished = false
while (!stepFinished) {
if (isCanceled) break
try {
val fileName = normalizeFileName(audio.artist + " - " + audio.title) + ".mp3"
val file = File(directory, fileName)
if (overwriteExisting || !file.exists()) {
val audioURL = URL(audio.url)
val channel = Channels.newChannel(audioURL.openStream())
val outputStream = FileOutputStream(file)
val debugThrowException = false
if (debugThrowException) throw IOException("Debug exception")
outputStream.channel.transferFrom(channel, 0, Long.MAX_VALUE)
outputStream.close()
}
stepFinished = true
} catch (e: Throwable) {
val action = failReporter(audio, e)
when (action) {
ErrorResponse.CANCEL -> {
cancel()
stepFinished = true
}
ErrorResponse.RETRY -> {
stepFinished = false
}
ErrorResponse.SKIP -> {
stepFinished = true
}
}
}
}
progressReporter(i + 1)
}
finishReporter()
}).start()
}
fun cancel() {
isCanceled = true
}
private fun normalizeFileName(fileName: String):String {
val shortened =
if (fileName.length > 100)
fileName.substring(0, 97) + "..."
else
fileName
return shortened.replace(Regex("[^\\pL0-9.-]"), "_")
}
}
|
gpl-3.0
|
794121e2a05cc17d997a0c4137c0ef78
| 35.75 | 225 | 0.453686 | 5.675966 | false | false | false | false |
benjamingarcia/mifuchi
|
src/main/kotlin/org/benji/mifuchi/command/InitGameCommandHandler.kt
|
1
|
3578
|
package org.benji.mifuchi.command
import org.benji.mifuchi.common.CommandHandler
import org.benji.mifuchi.common.CommandResponse
import org.benji.mifuchi.domain.*
import org.benji.mifuchi.domain.repositories.CardRepository
import org.benji.mifuchi.domain.repositories.GameRepository
import org.benji.mifuchi.domain.repositories.PlayerRepository
import org.benji.mifuchi.domain.repositories.TreasureRepository
import org.benji.mifuchi.event.GameInitialized
import java.util.*
import javax.inject.Singleton
@Singleton
class InitGameCommandHandler(private val gameRepository: GameRepository,
private val playerRepository : PlayerRepository,
private val cardRepository: CardRepository,
private val treasureRepository: TreasureRepository) : CommandHandler<InitGameCommand> {
private val defaultDeck = LinkedList<CardName>()
private val defaultTreasure = LinkedList<TreasureName>()
init {
//3 cawotte
defaultDeck.add(CardName.CAWOTTE)
defaultDeck.add(CardName.CAWOTTE)
defaultDeck.add(CardName.CAWOTTE)
//3 lenald
defaultDeck.add(CardName.LENALD)
defaultDeck.add(CardName.LENALD)
defaultDeck.add(CardName.LENALD)
//6 rocks
defaultDeck.add(CardName.ROCK)
defaultDeck.add(CardName.ROCK)
defaultDeck.add(CardName.ROCK)
defaultDeck.add(CardName.ROCK)
defaultDeck.add(CardName.ROCK)
defaultDeck.add(CardName.ROCK)
//6 scissors
defaultDeck.add(CardName.SCISSORS)
defaultDeck.add(CardName.SCISSORS)
defaultDeck.add(CardName.SCISSORS)
defaultDeck.add(CardName.SCISSORS)
defaultDeck.add(CardName.SCISSORS)
defaultDeck.add(CardName.SCISSORS)
//6 leafs
defaultDeck.add(CardName.LEAF)
defaultDeck.add(CardName.LEAF)
defaultDeck.add(CardName.LEAF)
defaultDeck.add(CardName.LEAF)
defaultDeck.add(CardName.LEAF)
defaultDeck.add(CardName.LEAF)
// 1 dofus
defaultDeck.add(CardName.DOFUS)
defaultTreasure.add(TreasureName.CAPE)
defaultTreasure.add(TreasureName.CROWN)
defaultTreasure.add(TreasureName.STICK)
}
override fun handle(command: InitGameCommand): CommandResponse {
val uuid = UUID.randomUUID()
val bluePlayer = Player(UUID.randomUUID(), command.blueUserName, PlayerColor.BLUE)
val orangePlayer = Player(UUID.randomUUID(), command.orangeUserName, PlayerColor.ORANGE)
playerRepository.add(bluePlayer)
playerRepository.add(orangePlayer)
val blueCardList: List<Card> = defaultDeck.map { cardName -> Card(UUID.randomUUID(), cardName, CardState.DECK, bluePlayer.uuid) }
val orangeCardList: List<Card> = defaultDeck.map { cardName -> Card(UUID.randomUUID(), cardName, CardState.DECK, orangePlayer.uuid) }
cardRepository.add(blueCardList)
cardRepository.add(orangeCardList)
val newGame = Game(uuid, bluePlayer.uuid, orangePlayer.uuid, 4, WaWabbitOrientation.NONE)
gameRepository.add(newGame)
val treasureList: List<Treasure> = defaultTreasure.map { treasureName -> Treasure(UUID.randomUUID(), treasureName, TreasureState.BOARD, newGame.uuid) }
treasureRepository.add(treasureList)
return InitGameCommandResponse(uuid, GameInitialized(newGame.uuid, newGame.gamer1Id, newGame.gamer2Id))
}
override fun listenTo(): String {
return InitGameCommand::class.qualifiedName!!
}
}
|
mit
|
2b70cdce5e7b087e93b9b40686bfa80d
| 37.483871 | 159 | 0.707099 | 4.011211 | false | false | false | false |
crunchersaspire/worshipsongs-android
|
app/src/main/java/org/worshipsongs/domain/Topics.kt
|
3
|
1224
|
package org.worshipsongs.domain
import org.apache.commons.lang3.builder.EqualsBuilder
import org.apache.commons.lang3.builder.HashCodeBuilder
/**
* Author : Madasamy
* Version : 3.x
*/
class Topics
{
var id: Int = 0
var name: String? = null
var tamilName: String? = null
var defaultName: String? = null
var noOfSongs: Int = 0
constructor()
{
//Do nothing
}
constructor(name: String)
{
this.name = name
}
override fun toString(): String
{
return "Topics{" + "id=" + id + ", name='" + name + '\''.toString() + ", tamilName='" + tamilName + '\''.toString() + ", defaultName='" + defaultName + '\''.toString() + '}'.toString()
}
override fun equals(`object`: Any?): Boolean
{
if (`object` is Topics)
{
val otherObject = `object` as Topics?
val equalsBuilder = EqualsBuilder()
equalsBuilder.append(name, otherObject!!.name)
return equalsBuilder.isEquals
}
return false
}
override fun hashCode(): Int
{
val hashCodeBuilder = HashCodeBuilder()
hashCodeBuilder.append(name)
return hashCodeBuilder.hashCode()
}
}
|
gpl-3.0
|
61eeb9b52957f1915d0f58b798d6db1f
| 22.09434 | 192 | 0.580882 | 4.177474 | false | false | false | false |
qaware/kubepad
|
src/main/kotlin/de/qaware/cloud/nativ/kpad/ClusterNode.kt
|
1
|
1977
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 QAware GmbH, Munich, Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.qaware.cloud.nativ.kpad
import java.util.concurrent.atomic.AtomicBoolean
/**
* The data class to represent one node instance on the grid.
*/
data class ClusterNode(val row: Int, val column: Int,
var phase: Phase = ClusterNode.Phase.Unknown,
val active: AtomicBoolean = AtomicBoolean(false)) {
fun activate(): ClusterNode {
active.compareAndSet(false, true)
phase = Phase.Running
return this
}
fun update(p: Phase) {
if (active.get()) {
phase = p
}
}
fun deactivate(): ClusterNode {
active.compareAndSet(true, false)
phase = Phase.Terminated
return this
}
enum class Phase {
Pending, Running, Terminated, Succeeded, Failed, Unknown
}
}
|
mit
|
299036447d97bb2994d1b9ef078a7615
| 33.701754 | 80 | 0.690946 | 4.462754 | false | false | false | false |
danrien/projectBlueWater
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAPlayingPlaybackEngine/WhenNotObservingPlayback.kt
|
1
|
2724
|
package com.lasthopesoftware.bluewater.client.playback.engine.GivenAPlayingPlaybackEngine
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.joda.time.Duration
import org.junit.Test
class WhenNotObservingPlayback {
companion object {
private val library = Library(_id = 1, _nowPlayingId = 5)
private val playbackEngine by lazy {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
val libraryProvider = mockk<ISpecificLibraryProvider>()
every { libraryProvider.library } returns Promise(library)
val libraryStorage = mockk<ILibraryStorage>()
every { libraryStorage.saveLibrary(any()) } returns Promise(library)
val playbackEngine = PlaybackEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 }, listOf(CompletingFileQueueProvider()),
NowPlayingRepository(libraryProvider, libraryStorage),
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f))
)
playbackEngine
.startPlaylist(
listOf(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
), 0, Duration.ZERO
)
val resolveablePlaybackHandler =
fakePlaybackPreparerProvider.deferredResolution.resolve()
fakePlaybackPreparerProvider.deferredResolution.resolve()
resolveablePlaybackHandler.resolve()
playbackEngine
}
}
@Test
fun thenTheSavedTrackPositionIsOne() {
assertThat(library.nowPlayingId).isEqualTo(1)
}
@Test
fun thenTheManagerIsPlaying() {
assertThat(playbackEngine.isPlaying).isTrue
}
}
|
lgpl-3.0
|
3ae08c0708e364b4cfa59aad8df6533e
| 39.058824 | 120 | 0.821953 | 4.632653 | false | false | false | false |
danrien/projectBlueWater
|
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/properties/playstats/factory/PlaystatsUpdateSelector.kt
|
2
|
2033
|
package com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.factory
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ProvideScopedFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.IPlaystatsUpdate
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.fileproperties.FilePropertiesPlayStatsUpdater
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.playedfile.PlayedFilePlayStatsUpdater
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.storage.ScopedFilePropertiesStorage
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.servers.version.IProgramVersionProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
class PlaystatsUpdateSelector(
private val connectionProvider: IConnectionProvider,
private val filePropertiesProvider: ProvideScopedFileProperties,
private val scopedFilePropertiesStorage: ScopedFilePropertiesStorage,
private val programVersionProvider: IProgramVersionProvider
) {
private val sync = Any()
@Volatile
private var promisedPlaystatsUpdater = Promise.empty<IPlaystatsUpdate>()
fun promisePlaystatsUpdater(): Promise<IPlaystatsUpdate> =
synchronized(sync) {
promisedPlaystatsUpdater.eventually(
{ u -> u?.toPromise() ?: promiseNewPlaystatsUpdater() },
{ promiseNewPlaystatsUpdater() })
}
private fun promiseNewPlaystatsUpdater(): Promise<IPlaystatsUpdate> =
synchronized(sync) {
programVersionProvider.promiseServerVersion()
.then { v ->
if (v != null && v.major >= 22) PlayedFilePlayStatsUpdater(connectionProvider)
else FilePropertiesPlayStatsUpdater(filePropertiesProvider, scopedFilePropertiesStorage)
}
.also {
promisedPlaystatsUpdater = it
}
}
}
|
lgpl-3.0
|
e620c1007bced887015d3f734463f575
| 47.404762 | 138 | 0.833743 | 4.409978 | false | false | false | false |
natanieljr/droidmate
|
project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/explorationWatchers/WidgetCountingMF.kt
|
1
|
3372
|
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.explorationWatchers
import org.droidmate.deviceInterface.exploration.isQueueStart
import org.droidmate.exploration.modelFeatures.*
import org.droidmate.explorationModel.interaction.Interaction
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
abstract class WidgetCountingMF : ModelFeature() {
// records how often a specific widget was selected and from which state-eContext (widget.uid -> Map<state.uid -> numActions>)
private val wCnt: ConcurrentHashMap<UUID, MutableMap<UUID, Int>> = ConcurrentHashMap()
protected fun List<Interaction<*>>.firstEntry() = first { !it.actionType.isQueueStart() }
/**
* this function is used to increase the counter of a specific widget with [wId] in the eContext of [stateId]
* if there is no entry yet for the given widget id, the counter value is initialized to 1
* @param wId the unique id of the target widget for the (new) action
* @param stateId the unique id of the state (the prevState) from which the widget was triggered
*/
fun incCnt(wId: UUID, stateId: UUID){
wCnt.compute(wId) { _, m -> m?.incCnt(stateId) ?: mutableMapOf(stateId to 1) }
}
/** decrease the counter for a given widget id [wId] and state eContext [stateId].
* The minimal possible value is 0 for any counter value.
*/
fun decCnt(wId: UUID, stateId: UUID){
wCnt.compute(wId) { _, m -> m?.decCnt(stateId) ?: mutableMapOf(stateId to 0)}
}
suspend fun isBlacklisted(wId: UUID, threshold: Int = 1): Boolean {
join()
return wCnt.sumCounter(wId) >= threshold
}
suspend fun isBlacklistedInState(wId: UUID, sId: UUID, threshold: Int = 1): Boolean {
join()
return wCnt.getCounter(wId, sId) >= threshold
}
/** dumping the current state of the widget counter
* job.joinChildren() before dumping to ensure that all updating co-routines completed
*/
suspend fun dump(file: Path){
join()
val out = StringBuffer()
out.appendln(header)
wCnt.toSortedMap(compareBy { it.toString() }).forEach { wMap ->
wMap.value.entries.forEach { (sId, cnt) ->
out.appendln("${wMap.key} ;\t$sId ;\t$cnt")
}
}
Files.write(file, out.lines())
}
companion object {
@JvmStatic
val header = "WidgetId".padEnd(38)+"; State-Context".padEnd(38)+"; # listed"
}
}
|
gpl-3.0
|
01f5c3a2e5c3e48231b68262a9d876a3
| 37.329545 | 127 | 0.728351 | 3.713656 | false | false | false | false |
tasks/tasks
|
app/src/googleplay/java/org/tasks/billing/Purchase.kt
|
1
|
2138
|
package org.tasks.billing
import com.android.billingclient.api.Purchase
import com.google.gson.GsonBuilder
import org.tasks.billing.BillingClientImpl.Companion.STATE_PURCHASED
import java.util.regex.Pattern
class Purchase(private val purchase: Purchase) {
constructor(json: String?) : this(GsonBuilder().create().fromJson<Purchase>(json, Purchase::class.java))
fun toJson(): String {
return GsonBuilder().create().toJson(purchase)
}
override fun toString(): String {
return "Purchase(purchase=$purchase)"
}
val originalJson: String
get() = purchase.originalJson
val signature: String
get() = purchase.signature
val sku: String
get() = purchase.skus.first()
val purchaseToken: String
get() = purchase.purchaseToken
val isProSubscription: Boolean
get() = PATTERN.matcher(sku).matches()
val isMonthly: Boolean
get() = sku.startsWith("monthly")
val isCanceled: Boolean
get() = !purchase.isAutoRenewing
val needsAcknowledgement: Boolean
get() = purchase.needsAcknowledgement
val isPurchased: Boolean
get() = purchase.isPurchased
val subscriptionPrice: Int?
get() {
val matcher = PATTERN.matcher(sku)
if (matcher.matches()) {
val price = matcher.group(2).toInt()
return if (price == 499) 5 else price
}
return null
}
val isTasksSubscription: Boolean
get() {
return subscriptionPrice
?.let {
if (isMonthly) {
it >= 3
} else {
it >= 30
}
}
?: false
}
companion object {
private val PATTERN = Pattern.compile("^(annual|monthly)_([0-3][0-9]|499)$")
val Purchase.isPurchased: Boolean
get() = purchaseState == STATE_PURCHASED
val Purchase.needsAcknowledgement: Boolean
get() = isPurchased && !isAcknowledged
}
}
|
gpl-3.0
|
3f80507edae36583979deb047a0fe4c6
| 26.075949 | 108 | 0.568756 | 4.914943 | false | false | false | false |
arturbosch/detekt
|
detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/optional/OptionalUnit.kt
|
1
|
5162
|
package io.gitlab.arturbosch.detekt.rules.style.optional
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isOverride
import org.jetbrains.kotlin.cfg.WhenChecker
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
/**
* It is not necessary to define a return type of `Unit` on functions or to specify a lone Unit statement.
* This rule detects and reports instances where the `Unit` return type is specified on functions and the occurrences
* of a lone Unit statement.
*
* <noncompliant>
* fun foo(): Unit {
* return Unit
* }
* fun foo() = Unit
*
* fun doesNothing() {
* Unit
* }
* </noncompliant>
*
* <compliant>
* fun foo() { }
*
* // overridden no-op functions are allowed
* override fun foo() = Unit
* </compliant>
*/
class OptionalUnit(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"Return type of 'Unit' is unnecessary and can be safely removed.",
Debt.FIVE_MINS
)
override fun visitNamedFunction(function: KtNamedFunction) {
if (function.hasDeclaredReturnType()) {
checkFunctionWithExplicitReturnType(function)
} else if (!function.isOverride()) {
checkFunctionWithInferredReturnType(function)
}
super.visitNamedFunction(function)
}
override fun visitBlockExpression(expression: KtBlockExpression) {
val statements = expression.statements
val lastStatement = statements.lastOrNull() ?: return
statements
.filter {
when {
it !is KtNameReferenceExpression || it.text != UNIT -> false
it != lastStatement || bindingContext == BindingContext.EMPTY -> true
!it.isUsedAsExpression(bindingContext) -> true
else -> {
val prev =
it.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtExpression>()
prev?.getType(bindingContext)?.isUnit() == true && prev.canBeUsedAsValue()
}
}
}
.onEach {
report(
CodeSmell(
issue,
Entity.from(expression),
"A single Unit expression is unnecessary and can safely be removed"
)
)
}
super.visitBlockExpression(expression)
}
private fun KtExpression.canBeUsedAsValue(): Boolean {
return when (this) {
is KtIfExpression -> {
val elseExpression = `else`
if (elseExpression is KtIfExpression) elseExpression.canBeUsedAsValue() else elseExpression != null
}
is KtWhenExpression ->
entries.lastOrNull()?.elseKeyword != null || WhenChecker.getMissingCases(this, bindingContext).isEmpty()
else ->
true
}
}
private fun checkFunctionWithExplicitReturnType(function: KtNamedFunction) {
val typeReference = function.typeReference
val typeElementText = typeReference?.typeElement?.text
if (typeElementText == UNIT) {
if (function.initializer.isNothingType()) return
report(CodeSmell(issue, Entity.from(typeReference), createMessage(function)))
}
}
private fun checkFunctionWithInferredReturnType(function: KtNamedFunction) {
val referenceExpression = function.bodyExpression as? KtNameReferenceExpression
if (referenceExpression != null && referenceExpression.text == UNIT) {
report(CodeSmell(issue, Entity.from(referenceExpression), createMessage(function)))
}
}
private fun createMessage(function: KtNamedFunction) = "The function ${function.name} " +
"defines a return type of Unit. This is unnecessary and can safely be removed."
private fun KtExpression?.isNothingType() =
bindingContext != BindingContext.EMPTY && this?.getType(bindingContext)?.isNothing() == true
companion object {
private const val UNIT = "Unit"
}
}
|
apache-2.0
|
a7724869be7e1143e91452331411c320
| 37.796992 | 120 | 0.661434 | 5.07874 | false | false | false | false |
cwoolner/flex-poker
|
src/test/kotlin/com/flexpoker/table/command/aggregate/generic/RemovePlayerFromTableTest.kt
|
1
|
1549
|
package com.flexpoker.table.command.aggregate.generic
import com.flexpoker.table.command.aggregate.applyEvents
import com.flexpoker.table.command.aggregate.eventproducers.removePlayer
import com.flexpoker.table.command.aggregate.testhelpers.createBasicTable
import com.flexpoker.table.command.aggregate.testhelpers.createBasicTableAndStartHand
import com.flexpoker.table.command.events.PlayerRemovedEvent
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import java.util.UUID
class RemovePlayerFromTableTest {
@Test
fun testRemovePlayerSuccess() {
val existingPlayer = UUID.randomUUID()
val initState = createBasicTable(UUID.randomUUID(), UUID.randomUUID(), existingPlayer)
val events = removePlayer(initState, existingPlayer)
assertEquals(PlayerRemovedEvent::class.java, events[0].javaClass)
}
@Test
fun testRemovingNonExistingPlayer() {
val initState = createBasicTable(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())
assertThrows(IllegalArgumentException::class.java) { removePlayer(initState, UUID.randomUUID()) }
}
@Test
fun testRemovingDuringAHand() {
val existingPlayer = UUID.randomUUID()
val events = createBasicTableAndStartHand(UUID.randomUUID(), UUID.randomUUID(), existingPlayer)
val initState = applyEvents(events)
assertThrows(IllegalArgumentException::class.java) { removePlayer(initState, existingPlayer) }
}
}
|
gpl-2.0
|
4c6e72245e23b2c5b1a39ad5273320d2
| 40.891892 | 105 | 0.770174 | 4.542522 | false | true | false | false |
d9n/intellij-rust
|
src/main/kotlin/org/rust/lang/doc/RsDocPipeline.kt
|
1
|
4049
|
package org.rust.lang.doc
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.flavours.MarkdownFlavourDescriptor
import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor
import org.intellij.markdown.html.HtmlGenerator
import org.intellij.markdown.parser.LinkMap
import org.intellij.markdown.parser.MarkdownParser
import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_BLOCK_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_EOL_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_BLOCK_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsDocAndAttributeOwner
import org.rust.lang.core.psi.ext.stringLiteralValue
import org.rust.lang.doc.psi.RsDocKind
import java.net.URI
fun RsDocAndAttributeOwner.documentation(): String? =
(outerDocs() + innerDocs())
.map { it.first to it.second.splitToSequence("\r\n", "\r", "\n") }
.flatMap { it.first.removeDecoration(it.second) }
.joinToString("\n")
fun RsDocAndAttributeOwner.documentationAsHtml(): String? {
val text = documentation() ?: return null
val flavour = RustDocMarkdownFlavourDescriptor()
val root = MarkdownParser(flavour).buildMarkdownTreeFromString(text)
return HtmlGenerator(text, root, flavour).generateHtml()
}
private fun RsDocAndAttributeOwner.outerDocs(): Sequence<Pair<RsDocKind, String>> {
// rustdoc appends the contents of each doc comment and doc attribute in order
// so we have to resolve these attributes that are edge-bound at the top of the
// children list.
val childOuterIterator = PsiTreeUtil.childIterator(this, PsiElement::class.java)
return childOuterIterator.asSequence()
// All these outer elements have been edge bound; if we reach something that isn't one
// of these, we have reached the actual parse children of this item.
.takeWhile { it is RsOuterAttr || it is PsiComment || it is PsiWhiteSpace }
.mapNotNull {
when {
it is RsOuterAttr -> it.metaItem.docAttr?.let { RsDocKind.Attr to it }
it is PsiComment && (it.tokenType == OUTER_EOL_DOC_COMMENT
|| it.tokenType == OUTER_BLOCK_DOC_COMMENT) -> RsDocKind.of(it.tokenType) to it.text
else -> null
}
}
}
private fun RsDocAndAttributeOwner.innerDocs(): Sequence<Pair<RsDocKind, String>> {
// Next, we have to consider inner comments and meta. These, like the outer case, are appended in
// lexical order, after the outer elements. This only applies to functions and modules.
val childBlock = PsiTreeUtil.getChildOfType(this, RsBlock::class.java) ?: this
val childInnerIterator = PsiTreeUtil.childIterator(childBlock, PsiElement::class.java)
return childInnerIterator.asSequence()
.mapNotNull {
when {
it is RsInnerAttr -> it.metaItem.docAttr?.let { RsDocKind.Attr to it }
it is PsiComment && (it.tokenType == INNER_EOL_DOC_COMMENT
|| it.tokenType == INNER_BLOCK_DOC_COMMENT) -> RsDocKind.of(it.tokenType) to it.text
else -> null
}
}
}
private val RsMetaItem.docAttr: String?
get() = if (identifier.text == "doc") litExpr?.stringLiteralValue else null
private class RustDocMarkdownFlavourDescriptor(
private val gfm: MarkdownFlavourDescriptor = GFMFlavourDescriptor()
) : MarkdownFlavourDescriptor by gfm {
override fun createHtmlGeneratingProviders(linkMap: LinkMap, baseURI: URI?) =
gfm.createHtmlGeneratingProviders(linkMap, baseURI)
// Filter out MARKDOWN_FILE to avoid producing unnecessary <body> tags
.filterKeys { it != MarkdownElementTypes.MARKDOWN_FILE }
}
|
mit
|
cd2718063e76b9f47ad57378ea1b936b
| 47.202381 | 104 | 0.722401 | 4.222106 | false | false | false | false |
paulograbin/LightsControl
|
src/main/java/com/sap/lightsControl/LightCommandRoute.kt
|
1
|
1439
|
package com.sap.lightsControl
import org.eclipse.jetty.http.HttpStatus
import spark.Request
import spark.Response
import spark.Route
class LightCommandRoute(val lightDriver: LightDriver) : Route {
override fun handle(req: Request?, res: Response?): String {
println()
println("Header: " + req?.headers())
println("Request from " + req?.host())
println("URL " + req?.url())
val commandParam = req!!.params(":command")
if(commandParam!!.length != 3) {
return sendErrorResponse(res)
}
val state = extractLightsState(commandParam.split(""))
if(!state.isValid())
return sendErrorResponse(res)
activateLights(state)
return sendSucessfulResponse(res)
}
private fun activateLights(state: State) {
lightDriver.applyState(state)
}
private fun extractLightsState(lights: List<String>?): State {
val red = Integer.valueOf(lights?.get(1))
val yellow = Integer.valueOf(lights?.get(2))
val green = Integer.valueOf(lights?.get(3))
return State(red = red, yellow = yellow, green = green)
}
private fun sendSucessfulResponse(res: Response?): String {
res!!.status(HttpStatus.OK_200)
return "OK \n"
}
private fun sendErrorResponse(res: Response?): String {
res!!.status(HttpStatus.NOT_FOUND_404)
return "NOK \n"
}
}
|
mit
|
60560538a8d6c6759916fb7c333a7d07
| 24.245614 | 66 | 0.624739 | 4.171014 | false | false | false | false |
ProxyApp/Proxy
|
Application/src/main/kotlin/com/shareyourproxy/api/rx/RxGroupContactSync.kt
|
1
|
2740
|
package com.shareyourproxy.api.rx
import android.content.Context
import android.util.Pair
import com.shareyourproxy.api.RestClient.getUserService
import com.shareyourproxy.api.domain.model.Group
import com.shareyourproxy.api.domain.model.GroupToggle
import com.shareyourproxy.api.domain.model.User
import com.shareyourproxy.api.rx.RxHelper.updateRealmUser
import com.shareyourproxy.api.rx.command.eventcallback.EventCallback
import com.shareyourproxy.api.rx.command.eventcallback.GroupContactsUpdatedEventCallback
import rx.Observable
import rx.functions.Func1
import java.util.*
/**
* Update Group contacts and User contacts when they've been added or removed to any groups.
*/
object RxGroupContactSync {
fun updateGroupContacts(
context: Context, user: User,
editGroups: ArrayList<GroupToggle>, contact: User): EventCallback {
return Observable.just(editGroups).map(userUpdateContacts(user, contact.id())).map(saveUserToDB(context, contact)).map(createGroupContactEvent(contact.id())).toBlocking().single()
}
fun saveUserToDB(context: Context, contact: User):
Func1<Pair<User, List<Group>>, Pair<User, List<Group>>> {
return Func1 { userListPair ->
val newUser = userListPair.first
val userId = newUser.id()
updateRealmUser(context, newUser)
updateRealmUser(context, contact)
getUserService(context).updateUser(userId, newUser).subscribe()
userListPair
}
}
private fun userUpdateContacts(
user: User, contactId: String): Func1<ArrayList<GroupToggle>, Pair<User, List<Group>>> {
return Func1 { groupToggles ->
var groupHasContact = false
val contactInGroup = ArrayList<Group>()
for (groupToggle in groupToggles) {
val groupId = groupToggle.group.id()
if (groupToggle.isChecked) {
groupHasContact = true
user.groups()!![groupId]?.contacts()!!.add(contactId)
contactInGroup.add(user.groups()!![groupId]!!)
} else {
user.groups()!![groupId]?.contacts()!!.remove(contactId)
}
}
if (groupHasContact) {
user.contacts()!!.add(contactId)
} else {
user.contacts()!!.remove(contactId)
}
Pair(user, contactInGroup)
}
}
private fun createGroupContactEvent(contactId: String): Func1<Pair<User, List<Group>>, EventCallback> {
return Func1 { groups ->
GroupContactsUpdatedEventCallback(
groups.first, contactId, groups.second)
}
}
}
|
apache-2.0
|
474824307361576b92af639132fc1184
| 38.710145 | 187 | 0.640511 | 4.620573 | false | false | false | false |
soywiz/korge
|
korge/src/commonMain/kotlin/com/soywiz/korge/component/length/BindLengthComponent.kt
|
1
|
6478
|
package com.soywiz.korge.component.length
import com.soywiz.kds.*
import com.soywiz.klock.*
import com.soywiz.kmem.toInt
import com.soywiz.korge.annotations.*
import com.soywiz.korge.baseview.*
import com.soywiz.korge.component.*
import com.soywiz.korge.view.*
import com.soywiz.korio.lang.*
import com.soywiz.korma.geom.*
import com.soywiz.korui.layout.*
import kotlin.reflect.*
/**
* Binds a property [prop] in this [View] to the [Length] value returned by [value].
* The binding will register a component that will compute the [Length] for that view in its container/context
* and will set the specific property.
*
* The binding requires to know if the property is vertical or horizontal.
* The direction will be tried to be determined by its name by default, but you can explicitly specify it with [horizontal]
*
* Returns a [Cancellable] to stop the binding.
*/
@KorgeExperimental
fun View.bindLength(prop: KMutableProperty1<View, Double>, horizontal: Boolean = prop.isHorizontal, value: LengthExtensions.() -> Length): Cancellable {
return bindLength(prop.name, { prop.set(this, it) }, horizontal, value)
}
@KorgeExperimental
fun View.bindLength(name: String, setProp: (Double) -> Unit, horizontal: Boolean, value: LengthExtensions.() -> Length): Cancellable {
val component = getOrCreateComponentUpdateWithViews { BindLengthComponent(it) }
component.setBind(horizontal, name, setProp, value(LengthExtensions))
return Cancellable {
component.removeBind(horizontal, name)
}
}
// @TODO: Extension properties for inline classes seem to not be supported for now. This should be more efficient than the Extra.PropertyThis once supported
//val View.lengths get() = ViewWithLength(this)
//inline class ViewWithLength(val view: View) : LengthExtensions
/**
* Supports setting/binding properties by using [Length] units, until they are set to null.
*
* Usage:
*
* ```
* view.lengths { width = 50.vw }
* ```
*
* The current implementation has some side effects to have into consideration:
* - The component is using the view to hold a component that will update these properties on each frame
* - If the original property is changed, it will be overriden by the computed [Length] on each frame
* - To remove the binding, set the property to null
*/
@KorgeExperimental
val View.lengths by Extra.PropertyThis { ViewWithLength(this) }
class ViewWithLength(val view: View) : LengthExtensions {
inline operator fun <T> invoke(block: ViewWithLength.() -> T): T = block()
}
var ViewWithLength.width: Length? by ViewWithLengthProp(View::scaledWidth)
var ViewWithLength.height: Length? by ViewWithLengthProp(View::scaledHeight)
var ViewWithLength.x: Length? by ViewWithLengthProp(View::x)
var ViewWithLength.y: Length? by ViewWithLengthProp(View::y)
var ViewWithLength.scale: Length? by ViewWithLengthProp(View::scale)
var ViewWithLength.scaleX: Length? by ViewWithLengthProp(View::scaleX)
var ViewWithLength.scaleY: Length? by ViewWithLengthProp(View::scaleY)
fun ViewWithLengthProp(prop: KMutableProperty1<View, Double>, horizontal: Boolean? = null) = LengthDelegatedProperty<ViewWithLength>(prop, horizontal) { it.view }
fun LengthDelegatedProperty(prop: KMutableProperty1<View, Double>, horizontal: Boolean? = null) = LengthDelegatedProperty<View>(prop, horizontal) { it }
class LengthDelegatedProperty<T>(val prop: KMutableProperty1<View, Double>, horizontal: Boolean? = null, val getView: (T) -> View) {
val horizontal = horizontal ?: prop.isHorizontal
private fun getBind(view: View): BindLengthComponent =
view.getOrCreateComponentUpdateWithViews { BindLengthComponent(it) }
operator fun getValue(viewHolder: T, property: KProperty<*>): Length? {
return getBind(getView(viewHolder)).getLength(prop.name, horizontal)
}
operator fun setValue(viewHolder: T, property: KProperty<*>, length: Length?) {
val view = getView(viewHolder)
val bind = getBind(view)
if (length == null) {
bind.removeBind(horizontal, prop.name)
} else {
bind.setBind(horizontal, prop.name, { prop.set(view, it) }, length)
}
}
}
internal val KCallable<*>.isHorizontal get() = when (name) {
"x", "width" -> true
else -> name.contains("x") || name.contains("X") || name.contains("width") || name.contains("Width")
}
internal class BindLengthComponent(override val view: BaseView) : UpdateComponentWithViews {
private val binds = Array(2) { LinkedHashMap<String, Pair<(Double) -> Unit, Length>>() }
private lateinit var views: Views
fun getLength(key: String, horizontal: Boolean): Length? {
return binds[horizontal.toInt()][key]?.second
}
private open class BaseLengthContext : Length.Context() {
override var pixelRatio: Double = 1.0
}
private val context = BaseLengthContext()
fun setBind(x: Boolean, name: String, prop: (Double) -> Unit, value: Length) {
binds[x.toInt()][name] = prop to value
}
fun removeBind(x: Boolean, name: String) {
binds[x.toInt()].remove(name)
if (binds[0].isEmpty() && binds[1].isEmpty()) {
removeFromView()
}
}
private val tempTransform = Matrix.Transform()
override fun update(views: Views, dt: TimeSpan) {
this.views = views
val container = (view as? View?)?.parent ?: views.stage
tempTransform.setMatrixNoReturn(container.globalMatrix)
val scaleAvgInv = 1.0 / tempTransform.scaleAvg
context.fontSize = 16.0 // @TODO: Can we store something in the views?
context.viewportWidth = if (views.clipBorders || views.scaleAnchor != Anchor.TOP_LEFT) views.virtualWidthDouble else views.actualVirtualWidth.toDouble()
context.viewportHeight = if (views.clipBorders || views.scaleAnchor != Anchor.TOP_LEFT) views.virtualHeightDouble else views.actualVirtualHeight.toDouble()
context.pixelRatio = views.ag.devicePixelRatio * scaleAvgInv
context.pixelsPerInch = views.ag.pixelsPerInch * scaleAvgInv
for (horizontal in arrayOf(false, true)) {
val size = if (horizontal) container.width else container.height
context.size = size.toInt()
for ((_, value) in binds[horizontal.toInt()]) {
val pointValue = value.second.calc(context).toDouble()
//println("$prop -> $pointValue [$value]")
value.first(pointValue)
}
}
}
}
|
apache-2.0
|
c768d31a6e505705e8757b8ad91540f7
| 43.675862 | 163 | 0.706236 | 4.031114 | false | false | false | false |
fablue/imko
|
example/src/ImkoExample.kt
|
1
|
3981
|
import io.sellmair.imko.Immutable
import java.awt.Color
/*
* Copyright 2017 Sebastian Sellmair
*
* 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.
*/
class TuningKit(boost: Int) : Immutable<TuningKit>() {
constructor() : this(0)
/**
* Defines how many ps per cylinder are boosted
*/
val boostPerCylinder = ivar(boost)
}
class Engine(cylinders: Int) : Immutable<Engine>() {
constructor() : this(0)
/**
* Defines how many ps each cylinder has. This
* cannot be changed
*/
val baselinePower = ival(25)
/**
* The number of cylinders cannot be changed
*/
val cylinders = ival(cylinders)
/**
* But the tuning
*/
val tuningKit = ivar<TuningKit?>(null)
}
class Car(modelNumber: Long) : Immutable<Car>() {
constructor() : this(-1)
/**
* The cars model number (cannot be changed)
*/
val modelNumber = ival(modelNumber)
/**
* The color can be changed by bringing the car to the paint shop
*/
val color = ivar(Color.BLUE)
/**
* We can tune the car!
*/
val engine = ivar(Engine(cylinders = 6))
/**
* A function telling us how much power the car has
*/
fun power(): Int {
val cylinders = engine().cylinders()
val baselinePower = engine().baselinePower()
val tuningBoost = engine().tuningKit()?.boostPerCylinder?.get() ?: 0
return cylinders * (baselinePower + tuningBoost)
}
}
fun aliG() {
// Lets buy the first car, which should have
val firstCar = Car(modelNumber = 1)
print(firstCar.power()) //Our first car has 150 ps! //150
print(firstCar.color()) // And it is blue! //java.awt.Color[r=0,g=0,b=255]
//lets get a yellow version of the car
val yellowCar = firstCar.color { Color.YELLOW }
// Now we have two nearly identical cars: One blue, One yellow.
// Color of the first car: java.awt.Color[r=0,g=0,b=255] ; second car: java.awt.Color[r=255,g=255,b=0]
print("Color of the first car: ${firstCar.color()} ; second car: ${yellowCar.color()}")
//Lets tune the yellow car!
val tunedYellowCar = yellowCar {
engine {
tuningKit {
TuningKit(15)
}
}
}
// We now have a tuned version of our yellow car!
// Power: yellow car: 150 ; tuned version: 240
print("Power: yellow car: ${yellowCar.power()} ; tuned version: ${tunedYellowCar.power()}")
//But now we want to get professional with our yellow car. We want to further tune it, but instead
//Of simply defining another boost we want to multiply the current boost with the count of cylinders
val monsterCar = tunedYellowCar {
engine {
tuningKit {
this?.boostPerCylinder?.mutate {
// You have access to the number of cylinders here.
// This is extremely cool, because it is part of the engine
// but technically not part of the tuning kit
cylinders() * this
}
}
}
}
// It worked! We have a monster version of our car!..: AliG would be proud of his yellow monster
//Power: tuned car: 240 ; monser version: 690
print("Power: tuned car: ${tunedYellowCar.power()} ; monser version: ${monsterCar.power()}")
}
fun print(a: Any) {
System.out.println(a)
}
fun main(args: Array<String>) {
aliG()
}
|
apache-2.0
|
20f44f3471963eff09d66f0ab3b44576
| 27.847826 | 106 | 0.615172 | 3.872568 | false | false | false | false |
Ribesg/anko
|
dsl/testData/functional/sdk19/ServicesTest.kt
|
2
|
5090
|
val Context.accessibilityManager: android.view.accessibility.AccessibilityManager
get() = getSystemService(Context.ACCESSIBILITY_SERVICE) as android.view.accessibility.AccessibilityManager
val Context.accountManager: android.accounts.AccountManager
get() = getSystemService(Context.ACCOUNT_SERVICE) as android.accounts.AccountManager
val Context.activityManager: android.app.ActivityManager
get() = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
val Context.alarmManager: android.app.AlarmManager
get() = getSystemService(Context.ALARM_SERVICE) as android.app.AlarmManager
val Context.appOpsManager: android.app.AppOpsManager
get() = getSystemService(Context.APP_OPS_SERVICE) as android.app.AppOpsManager
val Context.audioManager: android.media.AudioManager
get() = getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager
val Context.bluetoothManager: android.bluetooth.BluetoothManager
get() = getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
val Context.captioningManager: android.view.accessibility.CaptioningManager
get() = getSystemService(Context.CAPTIONING_SERVICE) as android.view.accessibility.CaptioningManager
val Context.clipboardManager: android.text.ClipboardManager
get() = getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager
val Context.connectivityManager: android.net.ConnectivityManager
get() = getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager
val Context.consumerIrManager: android.hardware.ConsumerIrManager
get() = getSystemService(Context.CONSUMER_IR_SERVICE) as android.hardware.ConsumerIrManager
val Context.devicePolicyManager: android.app.admin.DevicePolicyManager
get() = getSystemService(Context.DEVICE_POLICY_SERVICE) as android.app.admin.DevicePolicyManager
val Context.displayManager: android.hardware.display.DisplayManager
get() = getSystemService(Context.DISPLAY_SERVICE) as android.hardware.display.DisplayManager
val Context.downloadManager: android.app.DownloadManager
get() = getSystemService(Context.DOWNLOAD_SERVICE) as android.app.DownloadManager
val Context.inputMethodManager: android.view.inputmethod.InputMethodManager
get() = getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
val Context.inputManager: android.hardware.input.InputManager
get() = getSystemService(Context.INPUT_SERVICE) as android.hardware.input.InputManager
val Context.keyguardManager: android.app.KeyguardManager
get() = getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
val Context.locationManager: android.location.LocationManager
get() = getSystemService(Context.LOCATION_SERVICE) as android.location.LocationManager
val Context.nfcManager: android.nfc.NfcManager
get() = getSystemService(Context.NFC_SERVICE) as android.nfc.NfcManager
val Context.notificationManager: android.app.NotificationManager
get() = getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
val Context.nsdManager: android.net.nsd.NsdManager
get() = getSystemService(Context.NSD_SERVICE) as android.net.nsd.NsdManager
val Context.powerManager: android.os.PowerManager
get() = getSystemService(Context.POWER_SERVICE) as android.os.PowerManager
val Context.printManager: android.print.PrintManager
get() = getSystemService(Context.PRINT_SERVICE) as android.print.PrintManager
val Context.searchManager: android.app.SearchManager
get() = getSystemService(Context.SEARCH_SERVICE) as android.app.SearchManager
val Context.sensorManager: android.hardware.SensorManager
get() = getSystemService(Context.SENSOR_SERVICE) as android.hardware.SensorManager
val Context.storageManager: android.os.storage.StorageManager
get() = getSystemService(Context.STORAGE_SERVICE) as android.os.storage.StorageManager
val Context.telephonyManager: android.telephony.TelephonyManager
get() = getSystemService(Context.TELEPHONY_SERVICE) as android.telephony.TelephonyManager
val Context.uiModeManager: android.app.UiModeManager
get() = getSystemService(Context.UI_MODE_SERVICE) as android.app.UiModeManager
val Context.usbManager: android.hardware.usb.UsbManager
get() = getSystemService(Context.USB_SERVICE) as android.hardware.usb.UsbManager
val Context.userManager: android.os.UserManager
get() = getSystemService(Context.USER_SERVICE) as android.os.UserManager
val Context.wallpaperManager: android.app.WallpaperManager
get() = getSystemService(Context.WALLPAPER_SERVICE) as android.app.WallpaperManager
val Context.wifiP2pManager: android.net.wifi.p2p.WifiP2pManager
get() = getSystemService(Context.WIFI_P2P_SERVICE) as android.net.wifi.p2p.WifiP2pManager
val Context.wifiManager: android.net.wifi.WifiManager
get() = getSystemService(Context.WIFI_SERVICE) as android.net.wifi.WifiManager
val Context.windowManager: android.view.WindowManager
get() = getSystemService(Context.WINDOW_SERVICE) as android.view.WindowManager
|
apache-2.0
|
f57ba6305ae9b3dc43555c1e66461f69
| 49.405941 | 110 | 0.820825 | 4.618875 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/ParcelableGroupsAdapter.kt
|
1
|
5252
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.RequestManager
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.contains
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.adapter.iface.IGroupsAdapter
import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter
import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter.Companion.ITEM_VIEW_TYPE_LOAD_INDICATOR
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.model.ParcelableGroup
import de.vanita5.twittnuker.view.holder.GroupViewHolder
import de.vanita5.twittnuker.view.holder.LoadIndicatorViewHolder
class ParcelableGroupsAdapter(
context: Context,
requestManager: RequestManager
) : LoadMoreSupportAdapter<RecyclerView.ViewHolder>(context, requestManager), IGroupsAdapter<List<ParcelableGroup>> {
override val showAccountsColor: Boolean
get() = false
override val nameFirst = preferences[nameFirstKey]
override var groupAdapterListener: IGroupsAdapter.GroupAdapterListener? = null
private val inflater = LayoutInflater.from(context)
private val eventListener: EventListener
private var data: List<ParcelableGroup>? = null
init {
eventListener = EventListener(this)
}
fun getData(): List<ParcelableGroup>? {
return data
}
override fun setData(data: List<ParcelableGroup>?) {
this.data = data
notifyDataSetChanged()
}
private fun bindGroup(holder: GroupViewHolder, position: Int) {
holder.displayGroup(getGroup(position)!!)
}
override fun getItemCount(): Int {
val position = loadMoreIndicatorPosition
var count = groupsCount
if (position and ILoadMoreSupportAdapter.START != 0L) {
count++
}
if (position and ILoadMoreSupportAdapter.END != 0L) {
count++
}
return count
}
override fun getGroup(position: Int): ParcelableGroup? {
if (position == groupsCount) return null
return data!![position]
}
override fun getGroupId(position: Int): String? {
if (position == groupsCount) return null
return data!![position].id
}
override val groupsCount: Int
get() = data?.size ?: 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
ITEM_VIEW_TYPE_USER_LIST -> {
val view: View = inflater.inflate(R.layout.card_item_group_compact, parent, false)
val holder = GroupViewHolder(this, view)
holder.setOnClickListeners()
holder.setupViewOptions()
return holder
}
ITEM_VIEW_TYPE_LOAD_INDICATOR -> {
val view = inflater.inflate(R.layout.list_item_load_indicator, parent, false)
return LoadIndicatorViewHolder(view)
}
}
throw IllegalStateException("Unknown view type " + viewType)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder.itemViewType) {
ITEM_VIEW_TYPE_USER_LIST -> {
bindGroup(holder as GroupViewHolder, position)
}
}
}
override fun getItemViewType(position: Int): Int {
if (position == 0 && ILoadMoreSupportAdapter.START in loadMoreIndicatorPosition) {
return ITEM_VIEW_TYPE_LOAD_INDICATOR
}
if (position == groupsCount) {
return ITEM_VIEW_TYPE_LOAD_INDICATOR
}
return ITEM_VIEW_TYPE_USER_LIST
}
internal class EventListener(private val adapter: ParcelableGroupsAdapter) : IGroupsAdapter.GroupAdapterListener {
override fun onGroupClick(holder: GroupViewHolder, position: Int) {
adapter.groupAdapterListener?.onGroupClick(holder, position)
}
override fun onGroupLongClick(holder: GroupViewHolder, position: Int): Boolean {
return adapter.groupAdapterListener?.onGroupLongClick(holder, position) ?: false
}
}
companion object {
val ITEM_VIEW_TYPE_USER_LIST = 2
}
}
|
gpl-3.0
|
12138ae93419a19e34dbafa14740b30a
| 34.02 | 118 | 0.68888 | 4.680927 | false | false | false | false |
calebprior/Android-Boilerplate
|
app/src/main/kotlin/com/calebprior/boilerplate/ui/transisitions/SharedSlideChangeHandlerCompat.kt
|
1
|
4317
|
package com.calebprior.boilerplate.ui.transisitions
import android.annotation.TargetApi
import android.os.Build
import android.support.v4.view.GravityCompat
import android.transition.*
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler
import com.bluelinelabs.conductor.changehandler.TransitionChangeHandler
import com.bluelinelabs.conductor.changehandler.TransitionChangeHandlerCompat
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.childrenSequence
class SharedSlideChangeHandlerCompat(
reverse: Boolean = false,
leftToRight:Boolean = true
) : TransitionChangeHandlerCompat(
ArcFadeMoveChangeHandler(reverse, leftToRight),
FadeChangeHandler()
) {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private class ArcFadeMoveChangeHandler(val reverse: Boolean = false, var leftToRight:Boolean = true) : TransitionChangeHandler(), AnkoLogger {
override fun getTransition(container: ViewGroup, from: View?, to: View?, isPush: Boolean): Transition {
val outgoingSlide = Slide()
outgoingSlide.duration = 500
val incomingSlide = Slide()
incomingSlide.duration = 500
if(leftToRight) {
outgoingSlide.slideEdge = GravityCompat.getAbsoluteGravity(GravityCompat.START, container.layoutDirection)
incomingSlide.slideEdge = GravityCompat.getAbsoluteGravity(GravityCompat.END, container.layoutDirection)
} else {
outgoingSlide.slideEdge = Gravity.TOP
incomingSlide.slideEdge = Gravity.BOTTOM
}
var overlapSharedViews = emptyList<View>()
from?.childrenSequence()?.forEach {
if (it.transitionName == null) {
if (isPush && ! reverse) {
outgoingSlide.addTarget(it)
} else {
incomingSlide.addTarget(it)
}
} else {
overlapSharedViews = overlapSharedViews.plus(it)
}
}
to?.childrenSequence()?.forEach {
if (it.transitionName == null) {
if (isPush && ! reverse) {
incomingSlide.addTarget(it)
} else {
outgoingSlide.addTarget(it)
}
} else {
val view = it
if (overlapSharedViews.count { it.transitionName == view.transitionName } == 0) {
if (isPush && ! reverse) {
incomingSlide.addTarget(it)
} else {
outgoingSlide.addTarget(it)
}
overlapSharedViews.filterNot { it.transitionName == view.transitionName }.forEach {
if (isPush && ! reverse) {
outgoingSlide.addTarget(it)
} else {
incomingSlide.addTarget(it)
}
}
}
}
}
if (isPush && ! reverse) {
val transition = TransitionSet()
.setOrdering(TransitionSet.ORDERING_SEQUENTIAL)
.addTransition(outgoingSlide)
.addTransition(TransitionSet().addTransition(ChangeBounds()).addTransition(ChangeClipBounds()).addTransition(ChangeTransform()))
.addTransition(incomingSlide)
transition.pathMotion = ArcMotion()
return transition
} else {
val transition = TransitionSet()
.setOrdering(TransitionSet.ORDERING_SEQUENTIAL)
.addTransition(incomingSlide)
.addTransition(TransitionSet().addTransition(ChangeBounds()).addTransition(ChangeClipBounds()).addTransition(ChangeTransform()))
.addTransition(outgoingSlide)
transition.pathMotion = ArcMotion()
return transition
}
}
}
}
|
mit
|
4c102af4708e978b00b51a633e6426d5
| 37.900901 | 152 | 0.556868 | 5.946281 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/test/java/com/stripe/android/model/parsers/ConsumerPaymentDetailsJsonParserTest.kt
|
1
|
7478
|
package com.stripe.android.model.parsers
import com.stripe.android.core.model.CountryCode
import com.stripe.android.model.CardBrand
import com.stripe.android.model.ConsumerFixtures
import com.stripe.android.model.ConsumerPaymentDetails
import com.stripe.android.model.CvcCheck
import org.json.JSONObject
import org.junit.Test
import kotlin.test.assertEquals
class ConsumerPaymentDetailsJsonParserTest {
@Test
fun `parse single card payment details`() {
assertEquals(
ConsumerPaymentDetailsJsonParser()
.parse(ConsumerFixtures.CONSUMER_SINGLE_CARD_PAYMENT_DETAILS_JSON),
ConsumerPaymentDetails(
listOf(
ConsumerPaymentDetails.Card(
id = "QAAAKJ6",
isDefault = true,
expiryYear = 2023,
expiryMonth = 12,
brand = CardBrand.MasterCard,
last4 = "4444",
cvcCheck = CvcCheck.Pass,
billingAddress = ConsumerPaymentDetails.BillingAddress(
CountryCode.US,
"12312"
)
)
)
)
)
}
@Test
fun `parse single bank account payment details`() {
assertEquals(
ConsumerPaymentDetailsJsonParser()
.parse(ConsumerFixtures.CONSUMER_SINGLE_BANK_ACCOUNT_PAYMENT_DETAILS_JSON),
ConsumerPaymentDetails(
listOf(
ConsumerPaymentDetails.BankAccount(
id = "wAAACGA",
isDefault = true,
bankIconCode = null,
bankName = "STRIPE TEST BANK",
last4 = "6789"
)
)
)
)
}
@Test
fun `parse multiple payment details`() {
assertEquals(
ConsumerPaymentDetailsJsonParser().parse(ConsumerFixtures.CONSUMER_PAYMENT_DETAILS_JSON),
ConsumerPaymentDetails(
listOf(
ConsumerPaymentDetails.Card(
id = "QAAAKJ6",
isDefault = true,
expiryYear = 2023,
expiryMonth = 12,
brand = CardBrand.MasterCard,
last4 = "4444",
cvcCheck = CvcCheck.Pass,
billingAddress = ConsumerPaymentDetails.BillingAddress(
CountryCode.US,
"12312"
)
),
ConsumerPaymentDetails.Card(
id = "QAAAKIL",
isDefault = false,
expiryYear = 2024,
expiryMonth = 4,
brand = CardBrand.Visa,
last4 = "4242",
cvcCheck = CvcCheck.Fail,
billingAddress = ConsumerPaymentDetails.BillingAddress(
CountryCode.US,
"42424"
)
),
ConsumerPaymentDetails.BankAccount(
id = "wAAACGA",
isDefault = false,
bankIconCode = null,
bankName = "STRIPE TEST BANK",
last4 = "6789"
)
)
)
)
}
@Suppress("LongMethod")
@Test
fun `AMERICAN_EXPRESS and DINERS_CLUB card brands are fixed`() {
val json = JSONObject(
"""
{
"redacted_payment_details": [
{
"id": "QAAAKJ6",
"bank_account_details": null,
"billing_address": {
"administrative_area": null,
"country_code": "US",
"dependent_locality": null,
"line_1": null,
"line_2": null,
"locality": null,
"name": null,
"postal_code": "12312",
"sorting_code": null
},
"billing_email_address": "",
"card_details": {
"brand": "AMERICAN_EXPRESS",
"checks": {
"address_line1_check": "STATE_INVALID",
"address_postal_code_check": "PASS",
"cvc_check": "PASS"
},
"exp_month": 12,
"exp_year": 2023,
"last4": "4444"
},
"is_default": true,
"type": "CARD"
},
{
"id": "QAAAKIL",
"bank_account_details": null,
"billing_address": {
"administrative_area": null,
"country_code": "US",
"dependent_locality": null,
"line_1": null,
"line_2": null,
"locality": null,
"name": null,
"postal_code": "42424",
"sorting_code": null
},
"billing_email_address": "",
"card_details": {
"brand": "DINERS_CLUB",
"checks": {
"address_line1_check": "STATE_INVALID",
"address_postal_code_check": "PASS",
"cvc_check": "FAIL"
},
"exp_month": 4,
"exp_year": 2024,
"last4": "4242"
},
"is_default": false,
"type": "CARD"
}
]
}
""".trimIndent()
)
assertEquals(
ConsumerPaymentDetailsJsonParser()
.parse(json),
ConsumerPaymentDetails(
listOf(
ConsumerPaymentDetails.Card(
id = "QAAAKJ6",
isDefault = true,
expiryYear = 2023,
expiryMonth = 12,
brand = CardBrand.AmericanExpress,
last4 = "4444",
cvcCheck = CvcCheck.Pass,
billingAddress = ConsumerPaymentDetails.BillingAddress(
CountryCode.US,
"12312"
)
),
ConsumerPaymentDetails.Card(
id = "QAAAKIL",
isDefault = false,
expiryYear = 2024,
expiryMonth = 4,
brand = CardBrand.DinersClub,
last4 = "4242",
cvcCheck = CvcCheck.Fail,
billingAddress = ConsumerPaymentDetails.BillingAddress(
CountryCode.US,
"42424"
)
)
)
)
)
}
}
|
mit
|
a137795571d66a9c28a52fa8aafe264c
| 35.125604 | 101 | 0.389543 | 5.85133 | false | false | false | false |
stripe/stripe-android
|
stripecardscan/src/main/java/com/stripe/android/stripecardscan/payment/ml/ssd/CombinePriors.kt
|
1
|
2323
|
package com.stripe.android.stripecardscan.payment.ml.ssd
import android.util.Size
import com.stripe.android.stripecardscan.framework.ml.ssd.SizeAndCenter
import com.stripe.android.stripecardscan.framework.ml.ssd.clampAll
import com.stripe.android.stripecardscan.framework.ml.ssd.sizeAndCenter
import kotlin.math.sqrt
private const val NUMBER_OF_PRIORS = 3
internal fun combinePriors(trainedImageSize: Size): Array<SizeAndCenter> {
val priorsOne: Array<SizeAndCenter> =
generatePriors(
trainedImageSize = trainedImageSize,
featureMapSize = Size(38, 24),
shrinkage = Size(16, 16),
boxSizeMin = 14F,
boxSizeMax = 30F,
aspectRatio = 3F
)
val priorsTwo: Array<SizeAndCenter> =
generatePriors(
trainedImageSize = trainedImageSize,
featureMapSize = Size(19, 12),
shrinkage = Size(31, 31),
boxSizeMin = 30F,
boxSizeMax = 45F,
aspectRatio = 3F
)
return (priorsOne + priorsTwo).apply { forEach { it.clampAll(0F, 1F) } }
}
private fun generatePriors(
trainedImageSize: Size,
featureMapSize: Size,
shrinkage: Size,
boxSizeMin: Float,
boxSizeMax: Float,
aspectRatio: Float
): Array<SizeAndCenter> {
val scaleWidth = trainedImageSize.width.toFloat() / shrinkage.width
val scaleHeight = trainedImageSize.height.toFloat() / shrinkage.height
val ratio = sqrt(aspectRatio)
fun generatePrior(column: Int, row: Int, sizeFactor: Float, ratio: Float) =
sizeAndCenter(
centerX = (column + 0.5F) / scaleWidth,
centerY = (row + 0.5F) / scaleHeight,
width = sizeFactor / trainedImageSize.width,
height = sizeFactor / trainedImageSize.height * ratio
)
return Array(featureMapSize.width * featureMapSize.height * NUMBER_OF_PRIORS) { index ->
val row = index / NUMBER_OF_PRIORS / featureMapSize.width
val column = (index / NUMBER_OF_PRIORS) % featureMapSize.width
when (index % NUMBER_OF_PRIORS) {
0 -> generatePrior(column, row, boxSizeMin, 1F)
1 -> generatePrior(column, row, sqrt(boxSizeMax * boxSizeMin), ratio)
else -> generatePrior(column, row, boxSizeMin, ratio)
}
}
}
|
mit
|
303bb1d154b938d10855ce13db4fc6e1
| 35.296875 | 92 | 0.649161 | 3.964164 | false | false | false | false |
exponent/exponent
|
android/app/src/androidTest/java/host/exp/exponent/utils/TestServerUtils.kt
|
2
|
4633
|
package host.exp.exponent.utils
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.test.InstrumentationRegistry
import androidx.test.espresso.Espresso
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.Until
import host.exp.exponent.generated.ExponentBuildConstants
import host.exp.exponent.kernel.ExponentUrls
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.util.*
object TestServerUtils {
private const val LAUNCH_TIMEOUT = 5000
private val JSON = MediaType.parse("application/json; charset=utf-8")
private val isTestServerAvailable: Boolean
get() = ExponentBuildConstants.TEST_SERVER_URL != "TODO"
@Throws(Exception::class)
fun runFixtureTest(device: UiDevice, fixtureName: String) {
if (!isTestServerAvailable) {
return
}
// Get a fixture server
val fixtureServer = getFixtureServerInstance(fixtureName)
// Launch the app
val context = InstrumentationRegistry.getContext()
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(fixtureServer!!.manifestServerUrl)).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
// Wait for the app to appear
device.wait(Until.hasObject(By.pkg("host.exp.exponent").depth(0)), LAUNCH_TIMEOUT.toLong())
// Need this to wait on idling resources
Espresso.onView(ExponentMatchers.withTestId("test_container"))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
for (event in fixtureServer.testEvents) {
event.waitForCompleted(device, fixtureServer.manifestServerUrl)
}
}
@Throws(IOException::class)
private fun httpRequest(request: Request): String {
val client = OkHttpClient()
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
throw IOException("Unexpected code $response")
}
return response.body()!!.string()
}
private fun getFixtureServerInstance(fixtureName: String): FixtureServerInstance? {
try {
val request = Request.Builder()
.url(ExponentBuildConstants.TEST_SERVER_URL + "/start-fixture-server?fixtureName=" + fixtureName)
.build()
val responseJson = JSONObject(httpRequest(request))
val manifestServerUrl = responseJson.getString("manifestServerUrl")
val jsonTestEvents = responseJson.getJSONArray("testEvents")
val testEvents: MutableList<TestEvent> = ArrayList()
for (i in 0 until jsonTestEvents.length()) {
val jsonTestEvent = jsonTestEvents.getJSONObject(i)
testEvents.add(
TestEvent(
jsonTestEvent.getString("type"),
jsonTestEvent.getString("data"),
jsonTestEvent.getInt("testEventId")
)
)
}
return FixtureServerInstance(manifestServerUrl, testEvents)
} catch (e: IOException) {
e.printStackTrace()
} catch (e: JSONException) {
e.printStackTrace()
}
return null
}
@Throws(Exception::class)
fun reportTestResult(success: Boolean, testName: String?, logs: String?) {
if (!isTestServerAvailable) {
return
}
val jsonBody = JSONObject().apply {
put("testRunId", ExponentBuildConstants.TEST_RUN_ID)
put("testName", testName)
put("success", success)
put("logs", logs)
put("deviceName", Build.MODEL)
put("systemVersion", Build.VERSION.RELEASE)
}
val request = Request.Builder()
.url(ExponentBuildConstants.TEST_SERVER_URL + "/report-test-result")
.post(RequestBody.create(JSON, jsonBody.toString()))
.build()
httpRequest(request)
}
class TestEvent(private val type: String, private val data: String, private val testEventId: Int) {
@Throws(Exception::class)
fun waitForCompleted(device: UiDevice, manifestUrl: String) {
if (type == "findTextOnScreen") {
ExpoConditionWatcher.waitForText(device, data)
}
try {
val request = Request.Builder()
.url(ExponentUrls.toHttp(manifestUrl) + "/finished-test-event")
.addHeader("test-event-id", testEventId.toString())
.build()
httpRequest(request)
} catch (e: RuntimeException) {
} catch (e: IOException) {
}
}
}
class FixtureServerInstance(val manifestServerUrl: String, val testEvents: List<TestEvent>)
}
|
bsd-3-clause
|
28ef8a694d460c076073b71b8c963905
| 33.318519 | 105 | 0.704943 | 4.342081 | false | true | false | false |
exponent/exponent
|
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/universal/notifications/ScopedNotificationScheduler.kt
|
2
|
5524
|
package abi43_0_0.host.exp.exponent.modules.universal.notifications
import android.content.Context
import android.os.Bundle
import android.os.ResultReceiver
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.notifications.notifications.NotificationSerializer
import expo.modules.notifications.notifications.interfaces.NotificationTrigger
import expo.modules.notifications.notifications.model.NotificationContent
import expo.modules.notifications.notifications.model.NotificationRequest
import abi43_0_0.expo.modules.notifications.notifications.scheduling.NotificationScheduler
import abi43_0_0.expo.modules.notifications.service.NotificationsService
import host.exp.exponent.kernel.ExperienceKey
import host.exp.exponent.notifications.ScopedNotificationsUtils
import host.exp.exponent.notifications.model.ScopedNotificationRequest
import host.exp.exponent.utils.ScopedContext
import java.util.*
class ScopedNotificationScheduler(context: Context, private val experienceKey: ExperienceKey) :
NotificationScheduler(context) {
private val scopedNotificationsUtils: ScopedNotificationsUtils = ScopedNotificationsUtils(context)
override fun getSchedulingContext(): Context {
return if (context is ScopedContext) {
(context as ScopedContext).baseContext
} else context
}
override fun createNotificationRequest(
identifier: String,
content: NotificationContent,
notificationTrigger: NotificationTrigger?
): NotificationRequest {
return ScopedNotificationRequest(identifier, content, notificationTrigger, experienceKey.scopeKey)
}
override fun serializeScheduledNotificationRequests(requests: Collection<NotificationRequest>): Collection<Bundle> {
val serializedRequests: MutableCollection<Bundle> = ArrayList(requests.size)
for (request in requests) {
if (scopedNotificationsUtils.shouldHandleNotification(request, experienceKey)) {
serializedRequests.add(NotificationSerializer.toBundle(request))
}
}
return serializedRequests
}
override fun cancelScheduledNotificationAsync(identifier: String, promise: Promise) {
NotificationsService.getScheduledNotification(
schedulingContext,
identifier,
object : ResultReceiver(HANDLER) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
super.onReceiveResult(resultCode, resultData)
if (resultCode == NotificationsService.SUCCESS_CODE) {
val request = resultData?.getParcelable<NotificationRequest>(NotificationsService.NOTIFICATION_REQUESTS_KEY)
if (request == null || !scopedNotificationsUtils.shouldHandleNotification(request, experienceKey)) {
promise.resolve(null)
}
doCancelScheduledNotificationAsync(identifier, promise)
} else {
val e = resultData!!.getSerializable(NotificationsService.EXCEPTION_KEY) as Exception
promise.reject(
"ERR_NOTIFICATIONS_FAILED_TO_FETCH",
"Failed to fetch scheduled notifications.",
e
)
}
}
}
)
}
override fun cancelAllScheduledNotificationsAsync(promise: Promise) {
NotificationsService.getAllScheduledNotifications(
schedulingContext,
object : ResultReceiver(HANDLER) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
super.onReceiveResult(resultCode, resultData)
if (resultCode == NotificationsService.SUCCESS_CODE) {
val requests = resultData?.getParcelableArrayList<NotificationRequest>(
NotificationsService.NOTIFICATION_REQUESTS_KEY
)
if (requests == null) {
promise.resolve(null)
return
}
val toRemove = mutableListOf<String>()
for (request in requests) {
if (scopedNotificationsUtils.shouldHandleNotification(request, experienceKey)) {
toRemove.add(request.identifier)
}
}
if (toRemove.size == 0) {
promise.resolve(null)
return
}
cancelSelectedNotificationsAsync(toRemove.toTypedArray(), promise)
} else {
val e = resultData!!.getSerializable(NotificationsService.EXCEPTION_KEY) as Exception
promise.reject(
"ERR_NOTIFICATIONS_FAILED_TO_CANCEL",
"Failed to cancel all notifications.",
e
)
}
}
}
)
}
private fun doCancelScheduledNotificationAsync(identifier: String, promise: Promise) {
super.cancelScheduledNotificationAsync(identifier, promise)
}
private fun cancelSelectedNotificationsAsync(identifiers: Array<String>, promise: Promise) {
NotificationsService.removeScheduledNotifications(
schedulingContext,
identifiers.toList(),
object : ResultReceiver(HANDLER) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
super.onReceiveResult(resultCode, resultData)
if (resultCode == NotificationsService.SUCCESS_CODE) {
promise.resolve(null)
} else {
val e = resultData!!.getSerializable(NotificationsService.EXCEPTION_KEY) as Exception
promise.reject(
"ERR_NOTIFICATIONS_FAILED_TO_CANCEL",
"Failed to cancel all notifications.",
e
)
}
}
}
)
}
}
|
bsd-3-clause
|
ecd79cd99f4b5f8476e2263740bead39
| 38.457143 | 120 | 0.695148 | 5.480159 | false | false | false | false |
AndroidX/androidx
|
room/room-compiler/src/main/kotlin/androidx/room/solver/query/result/PojoRowAdapter.kt
|
3
|
5796
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.solver.query.result
import androidx.room.compiler.processing.XType
import androidx.room.parser.ParsedQuery
import androidx.room.processor.Context
import androidx.room.processor.ProcessorErrors
import androidx.room.solver.CodeGenScope
import androidx.room.verifier.QueryResultInfo
import androidx.room.vo.ColumnIndexVar
import androidx.room.vo.Field
import androidx.room.vo.FieldWithIndex
import androidx.room.vo.Pojo
import androidx.room.vo.RelationCollector
import androidx.room.writer.FieldReadWriteWriter
/**
* Creates the entity from the given info.
*
* The info comes from the query processor so we know about the order of columns in the result etc.
*/
class PojoRowAdapter(
private val context: Context,
private val info: QueryResultInfo?,
private val query: ParsedQuery?,
val pojo: Pojo,
out: XType
) : QueryMappedRowAdapter(out) {
override val mapping: PojoMapping
val relationCollectors: List<RelationCollector>
private val indexAdapter: PojoIndexAdapter
// Set when cursor is ready.
private lateinit var fieldsWithIndices: List<FieldWithIndex>
init {
val remainingFields = pojo.fields.toMutableList()
val unusedColumns = arrayListOf<String>()
val matchedFields: List<Field>
if (info != null) {
matchedFields = info.columns.mapNotNull { column ->
val field = remainingFields.firstOrNull { it.columnName == column.name }
if (field == null) {
unusedColumns.add(column.name)
null
} else {
remainingFields.remove(field)
field
}
}
val nonNulls = remainingFields.filter { it.nonNull }
if (nonNulls.isNotEmpty()) {
context.logger.e(
ProcessorErrors.pojoMissingNonNull(
pojoTypeName = pojo.typeName.toString(context.codeLanguage),
missingPojoFields = nonNulls.map { it.name },
allQueryColumns = info.columns.map { it.name }
)
)
}
if (matchedFields.isEmpty()) {
context.logger.e(
ProcessorErrors.cannotFindQueryResultAdapter(
out.asTypeName().toString(context.codeLanguage)
)
)
}
} else {
matchedFields = remainingFields.map { it }
remainingFields.clear()
}
relationCollectors = RelationCollector.createCollectors(context, pojo.relations)
mapping = PojoMapping(
pojo = pojo,
matchedFields = matchedFields,
unusedColumns = unusedColumns,
unusedFields = remainingFields
)
indexAdapter = PojoIndexAdapter(mapping, info, query)
}
fun relationTableNames(): List<String> {
return relationCollectors.flatMap {
val queryTableNames = it.loadAllQuery.tables.map { it.name }
if (it.rowAdapter is PojoRowAdapter) {
it.rowAdapter.relationTableNames() + queryTableNames
} else {
queryTableNames
}
}.distinct()
}
override fun onCursorReady(
cursorVarName: String,
scope: CodeGenScope,
indices: List<ColumnIndexVar>
) {
fieldsWithIndices = indices.map { (column, indexVar) ->
val field = mapping.matchedFields.first { it.columnName == column }
FieldWithIndex(field = field, indexVar = indexVar, alwaysExists = info != null)
}
emitRelationCollectorsReady(cursorVarName, scope)
}
private fun emitRelationCollectorsReady(cursorVarName: String, scope: CodeGenScope) {
if (relationCollectors.isNotEmpty()) {
relationCollectors.forEach { it.writeInitCode(scope) }
scope.builder.apply {
beginControlFlow("while (%L.moveToNext())", cursorVarName).apply {
relationCollectors.forEach {
it.writeReadParentKeyCode(cursorVarName, fieldsWithIndices, scope)
}
}
endControlFlow()
addStatement("%L.moveToPosition(-1)", cursorVarName)
}
relationCollectors.forEach { it.writeFetchRelationCall(scope) }
}
}
override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) {
FieldReadWriteWriter.readFromCursor(
outVar = outVarName,
outPojo = pojo,
cursorVar = cursorVarName,
fieldsWithIndices = fieldsWithIndices,
relationCollectors = relationCollectors,
scope = scope
)
}
override fun getDefaultIndexAdapter() = indexAdapter
data class PojoMapping(
val pojo: Pojo,
val matchedFields: List<Field>,
val unusedColumns: List<String>,
val unusedFields: List<Field>
) : Mapping() {
override val usedColumns = matchedFields.map { it.columnName }
}
}
|
apache-2.0
|
c8905baa2f38d5107c4c0cca9d340844
| 35.225 | 99 | 0.621636 | 4.945392 | false | false | false | false |
peterLaurence/TrekAdvisor
|
app/src/main/java/com/peterlaurence/trekme/ui/mapview/MapViewFragmentPresenter.kt
|
1
|
2912
|
package com.peterlaurence.trekme.ui.mapview
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import com.peterlaurence.mapview.MapView
import com.peterlaurence.trekme.R
import com.peterlaurence.trekme.databinding.FragmentMapViewBinding
import com.peterlaurence.trekme.ui.mapview.components.CompassView
import com.peterlaurence.trekme.ui.mapview.components.PositionOrientationMarker
/**
* Presenter for [MapViewFragment]. It is loosely coupled with it, so a different view could be used.
* It uses data binding from Android Jetpack.
*
* @author peterLaurence on 19/03/16 -- Converted to Kotlin on 10/05/2019
*/
class MapViewFragmentPresenter
constructor(layoutInflater: LayoutInflater, container: ViewGroup?, context: Context) : MapViewFragmentContract.Presenter {
private val binding = FragmentMapViewBinding.inflate(layoutInflater, container, false)
private val layout = binding.root as ConstraintLayout
private val customView: MapViewFragmentContract.View = object : MapViewFragmentContract.View {
private val marker = PositionOrientationMarker(context)
override val speedIndicator: MapViewFragment.SpeedListener
get() = binding.indicatorOverlay
override val distanceIndicator: DistanceLayer.DistanceListener
get() = binding.indicatorOverlay
override val positionMarker: PositionOrientationMarker
get() = marker
override val compassView: CompassView
get() = binding.compass
}
override val androidView: View
get() = binding.root
override val view: MapViewFragmentContract.View
get() = customView
private var positionTouchListener: PositionTouchListener? = null
init {
binding.fabPosition.setOnClickListener {
/* How to change the icon color */
binding.fabPosition.drawable.mutate().setTint(context.resources.getColor(R.color.colorAccent, null))
positionTouchListener?.onPositionTouch()
}
}
override fun setPositionTouchListener(listener: PositionTouchListener) {
positionTouchListener = listener
}
override fun setMapView(mapView: MapView) {
layout.addView(mapView, 0)
binding.fabPosition.visibility = View.VISIBLE
binding.frgmtMapViewMsg.visibility = View.GONE
}
override fun removeMapView(mapView: MapView?) {
if (mapView != null) {
layout.removeView(mapView)
}
binding.indicatorOverlay.visibility = View.GONE
binding.fabPosition.visibility = View.GONE
}
override fun showMessage(msg: String) {
binding.message = msg
binding.frgmtMapViewMsg.visibility = View.VISIBLE
}
interface PositionTouchListener {
fun onPositionTouch()
}
}
|
gpl-3.0
|
c73a22e683b31de353af4ce419793b8e
| 34.512195 | 122 | 0.728022 | 4.894118 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/macros/tt/FlatTree.kt
|
2
|
6457
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros.tt
import gnu.trove.TIntArrayList
import org.rust.lang.core.psi.MacroBraces
import org.rust.stdext.dequeOf
import java.util.*
/**
* See https://github.com/rust-analyzer/rust-analyzer/blob/3e4ac8a2c9136052/crates/proc_macro_api/src/msg/flat.rs
*/
class FlatTree(
val subtree: TIntArrayList,
val literal: TIntArrayList,
val punct: TIntArrayList,
val ident: TIntArrayList,
val tokenTree: TIntArrayList,
val text: List<String>,
) {
fun toTokenTree(): TokenTree.Subtree {
val res: MutableList<TokenTree.Subtree?> = ArrayList(subtree.size())
repeat(subtree.size()) { res.add(null) }
for (i in (0 until subtree.size()).step(4).reversed()) {
val delimiterId = subtree[i]
val kind = subtree[i + 1]
val lo = subtree[i + 2]
val len = subtree[i + 3]
val rawTokenTrees = tokenTree
val tokenTrees = ArrayList<TokenTree>(len - lo)
for (j in lo until len) {
val idxTag = rawTokenTrees[j]
val tag = idxTag and 0b11
val idx = idxTag shr 2
tokenTrees += when (tag) {
0b00 -> res[idx]!! // we iterate subtrees in reverse to guarantee that this subtree exists
0b01 -> {
val index = idx * 2
val tokenId = literal[index]
val text = literal[index + 1]
TokenTree.Leaf.Literal(this.text[text], tokenId)
}
0b10 -> {
val index = idx * 3
val tokenId = punct[index]
val chr = punct[index + 1].toChar()
val spacing = when (val spacing = punct[index + 2]) {
0 -> Spacing.Alone
1 -> Spacing.Joint
else -> error("Unknown spacing $spacing")
}
TokenTree.Leaf.Punct(chr.toString(), spacing, tokenId)
}
0b11 -> {
val index = idx * 2
val tokenId = ident[index]
val text = ident[index + 1]
TokenTree.Leaf.Ident(this.text[text], tokenId)
}
else -> error("bad tag $tag")
}
}
val delimiterKind = when (kind) {
0 -> null
1 -> MacroBraces.PARENS
2 -> MacroBraces.BRACES
3 -> MacroBraces.BRACKS
else -> error("Unknown kind $kind")
}
res[i / 4] = TokenTree.Subtree(
delimiterKind?.let { Delimiter(delimiterId, delimiterKind) },
tokenTrees,
)
}
return res[0]!!
}
companion object {
fun fromSubtree(root: TokenTree.Subtree): FlatTree =
FlatTreeBuilder().apply { write(root) }.toFlatTree()
}
}
private class FlatTreeBuilder {
private val work: Deque<Pair<Int, TokenTree.Subtree>> = dequeOf()
private val stringTable: HashMap<String, Int> = hashMapOf()
private val subtree: TIntArrayList = TIntArrayList()
private val literal: TIntArrayList = TIntArrayList()
private val punct: TIntArrayList = TIntArrayList()
private val ident: TIntArrayList = TIntArrayList()
private val tokenTree: TIntArrayList = TIntArrayList()
private val text: MutableList<String> = mutableListOf()
fun toFlatTree(): FlatTree = FlatTree(subtree, literal, punct, ident, tokenTree, text)
fun write(root: TokenTree.Subtree) {
enqueue(root)
while (true) {
val (idx, subtree) = work.pollFirst() ?: break
subtree(idx, subtree)
}
}
private fun subtree(subtreeId: Int, subtree: TokenTree.Subtree) {
var firstTt = tokenTree.size()
val nTt = subtree.tokenTrees.size
tokenTree.fill(firstTt, firstTt + nTt, -1)
this.subtree[subtreeId * 4 + 2] = firstTt
this.subtree[subtreeId * 4 + 3] = firstTt + nTt
for (child in subtree.tokenTrees) {
val idxTag = when (child) {
is TokenTree.Subtree -> {
val idx = this.enqueue(child)
idx.shl(2).or(0b00)
}
is TokenTree.Leaf.Literal -> {
val idx = this.literal.size() / 2
val text = this.intern(child.text)
this.literal.add(child.id)
this.literal.add(text)
idx.shl(2).or(0b01)
}
is TokenTree.Leaf.Punct -> {
val idx = this.punct.size() / 3
this.punct.add(child.id)
this.punct.add(child.char[0].code)
this.punct.add(when (child.spacing) {
Spacing.Alone -> 0
Spacing.Joint -> 1
})
idx.shl(2).or(0b10)
}
is TokenTree.Leaf.Ident -> {
val idx = this.ident.size() / 2
val text = this.intern(child.text)
this.ident.add(child.id)
this.ident.add(text)
idx.shl(2).or(0b11)
}
}
this.tokenTree[firstTt] = idxTag
firstTt += 1
}
}
private fun enqueue(subtree: TokenTree.Subtree): Int {
val idx = this.subtree.size() / 4
val delimiterId = subtree.delimiter?.id ?: -1
val delimiterKind = subtree.delimiter?.kind
this.subtree.apply {
add(delimiterId)
add(when (delimiterKind) {
null -> 0
MacroBraces.PARENS -> 1
MacroBraces.BRACES -> 2
MacroBraces.BRACKS -> 3
})
add(-1)
add(-1)
}
this.work.addLast(Pair(idx, subtree))
return idx
}
private fun intern(text: String): Int {
return stringTable.getOrPut(text) {
val idx = this.text.size
this.text.add(text)
idx
}
}
}
|
mit
|
b5ba3018079a5c5b68a6d75b02886d59
| 34.284153 | 113 | 0.496051 | 4.386549 | false | false | false | false |
colesadam/hill-lists
|
app/src/main/java/uk/colessoft/android/hilllist/domain/Business.kt
|
1
|
359
|
package uk.colessoft.android.hilllist.domain
data class Business (
var latitude: Float = 0.toFloat(),
var longitude: Float = 0.toFloat(),
var companyname: String? = null,
var resultNumber: Int = 0,
var telephone: String? = null,
var address: List<String>? = null,
var postCode: String? = null,
var scootLink: String? = null)
|
mit
|
746994246237db5595cd4c6e5c2c42d3
| 28.916667 | 44 | 0.660167 | 3.701031 | false | false | false | false |
charleskorn/batect
|
app/src/main/kotlin/batect/docker/DockerImageNameValidator.kt
|
1
|
1151
|
/*
Copyright 2017-2020 Charles Korn.
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 batect.docker
object DockerImageNameValidator {
private const val separators = """(\.|_|__|-+)"""
private const val nonSeparators = "([a-z0-9]+)"
private val nameRegex = Regex("^$nonSeparators($separators$nonSeparators)*$")
const val validNameDescription = "must contain only lowercase letters, digits, dashes (-), single consecutive periods (.) or one or two consecutive underscores (_), and must not start or end with dashes, periods or underscores"
fun isValidImageName(name: String): Boolean = nameRegex.matches(name)
}
|
apache-2.0
|
4f6ddcda6c63820bf43d331ded477cf6
| 41.62963 | 231 | 0.732407 | 4.62249 | false | false | false | false |
google/dokka
|
core/src/main/kotlin/Languages/NewJavaLanguageService.kt
|
1
|
8345
|
package org.jetbrains.dokka
import org.jetbrains.dokka.Formats.classNodeNameWithOuterClass
import org.jetbrains.dokka.LanguageService.RenderMode
/**
* Implements [LanguageService] and provides rendering of symbols in Java language
*/
class NewJavaLanguageService : CommonLanguageService() {
override fun showModifierInSummary(node: DocumentationNode): Boolean {
return true
}
override fun render(node: DocumentationNode, renderMode: RenderMode): ContentNode {
return content {
(when (node.kind) {
NodeKind.Package -> renderPackage(node)
in NodeKind.classLike -> renderClass(node, renderMode)
NodeKind.Modifier -> renderModifier(this, node, renderMode)
NodeKind.TypeParameter -> renderTypeParameter(node)
NodeKind.Type,
NodeKind.UpperBound -> renderType(node)
NodeKind.Parameter -> renderParameter(node)
NodeKind.Constructor,
NodeKind.Function -> renderFunction(node)
NodeKind.Property -> renderProperty(node)
NodeKind.Field -> renderField(node, renderMode)
NodeKind.EnumItem -> renderClass(node, renderMode)
else -> "${node.kind}: ${node.name}"
})
}
}
override fun summarizeSignatures(nodes: List<DocumentationNode>): ContentNode? = null
override fun renderModifier(block: ContentBlock, node: DocumentationNode, renderMode: RenderMode, nowrap: Boolean) {
when (node.name) {
"open", "internal" -> {
}
else -> super.renderModifier(block, node, renderMode, nowrap)
}
}
fun getArrayElementType(node: DocumentationNode): DocumentationNode? = when (node.qualifiedName()) {
"kotlin.Array" ->
node.details(NodeKind.Type).singleOrNull()?.let { et -> getArrayElementType(et) ?: et }
?: DocumentationNode("Object", node.content, NodeKind.ExternalClass)
"kotlin.IntArray", "kotlin.LongArray", "kotlin.ShortArray", "kotlin.ByteArray",
"kotlin.CharArray", "kotlin.DoubleArray", "kotlin.FloatArray", "kotlin.BooleanArray" ->
DocumentationNode(node.name.removeSuffix("Array").toLowerCase(), node.content, NodeKind.Type)
else -> null
}
fun getArrayDimension(node: DocumentationNode): Int = when (node.qualifiedName()) {
"kotlin.Array" ->
1 + (node.details(NodeKind.Type).singleOrNull()?.let { getArrayDimension(it) } ?: 0)
"kotlin.IntArray", "kotlin.LongArray", "kotlin.ShortArray", "kotlin.ByteArray",
"kotlin.CharArray", "kotlin.DoubleArray", "kotlin.FloatArray", "kotlin.BooleanArray" ->
1
else -> 0
}
fun ContentBlock.renderType(node: DocumentationNode) {
when (node.name) {
"Unit" -> identifier("void")
"Int" -> identifier("int")
"Long" -> identifier("long")
"Double" -> identifier("double")
"Float" -> identifier("float")
"Char" -> identifier("char")
"Boolean" -> identifier("bool")
// TODO: render arrays
else -> {
renderLinked(this, node) {
identifier(
it.typeDeclarationClass?.classNodeNameWithOuterClass() ?: it.name,
IdentifierKind.TypeName
)
}
renderTypeArgumentsForType(node)
}
}
}
private fun ContentBlock.renderTypeParameter(node: DocumentationNode) {
val constraints = node.details(NodeKind.UpperBound)
if (constraints.none())
identifier(node.name)
else {
identifier(node.name)
text(" ")
keyword("extends")
text(" ")
constraints.forEach { renderType(node) }
}
}
private fun ContentBlock.renderParameter(node: DocumentationNode) {
renderType(node.detail(NodeKind.Type))
text(" ")
identifier(node.name)
}
private fun ContentBlock.renderTypeParametersForNode(node: DocumentationNode) {
val typeParameters = node.details(NodeKind.TypeParameter)
if (typeParameters.any()) {
symbol("<")
renderList(typeParameters, noWrap = true) {
renderTypeParameter(it)
}
symbol(">")
text(" ")
}
}
private fun ContentBlock.renderTypeArgumentsForType(node: DocumentationNode) {
val typeArguments = node.details(NodeKind.Type)
if (typeArguments.any()) {
symbol("<")
renderList(typeArguments, noWrap = true) {
renderType(it)
}
symbol(">")
}
}
// private fun renderModifiersForNode(node: DocumentationNode): String {
// val modifiers = node.details(NodeKind.Modifier).map { renderModifier(it) }.filter { it != "" }
// if (modifiers.none())
// return ""
// return modifiers.joinToString(" ", postfix = " ")
// }
private fun ContentBlock.renderClassKind(node: DocumentationNode) {
when (node.kind) {
NodeKind.Interface -> {
keyword("interface")
}
NodeKind.EnumItem -> {
keyword("enum value")
}
NodeKind.Enum -> {
keyword("enum")
}
NodeKind.Class, NodeKind.Exception, NodeKind.Object -> {
keyword("class")
}
else -> throw IllegalArgumentException("Node $node is not a class-like object")
}
text(" ")
}
private fun ContentBlock.renderClass(node: DocumentationNode, renderMode: RenderMode) {
renderModifiersForNode(node, renderMode)
renderClassKind(node)
identifier(node.name)
renderTypeParametersForNode(node)
val superClassType = node.superclassType
val interfaces = node.supertypes - superClassType
if (superClassType != null) {
text(" ")
keyword("extends")
text(" ")
renderType(superClassType)
}
if (interfaces.isNotEmpty()) {
text(" ")
keyword("implements")
text(" ")
renderList(interfaces.filterNotNull()) {
renderType(it)
}
}
}
private fun ContentBlock.renderParameters(nodes: List<DocumentationNode>) {
renderList(nodes) {
renderParameter(it)
}
}
private fun ContentBlock.renderFunction(node: DocumentationNode) {
when (node.kind) {
NodeKind.Constructor -> identifier(node.owner?.name ?: "")
NodeKind.Function -> {
renderTypeParametersForNode(node)
renderType(node.detail(NodeKind.Type))
text(" ")
identifier(node.name)
}
else -> throw IllegalArgumentException("Node $node is not a function-like object")
}
val receiver = node.details(NodeKind.Receiver).singleOrNull()
symbol("(")
if (receiver != null)
renderParameters(listOf(receiver) + node.details(NodeKind.Parameter))
else
renderParameters(node.details(NodeKind.Parameter))
symbol(")")
}
private fun ContentBlock.renderProperty(node: DocumentationNode) {
when (node.kind) {
NodeKind.Property -> {
keyword("val")
text(" ")
}
else -> throw IllegalArgumentException("Node $node is not a property")
}
renderTypeParametersForNode(node)
val receiver = node.details(NodeKind.Receiver).singleOrNull()
if (receiver != null) {
renderType(receiver.detail(NodeKind.Type))
symbol(".")
}
identifier(node.name)
symbol(":")
text(" ")
renderType(node.detail(NodeKind.Type))
}
private fun ContentBlock.renderField(node: DocumentationNode, renderMode: RenderMode) {
renderModifiersForNode(node, renderMode)
renderType(node.detail(NodeKind.Type))
text(" ")
identifier(node.name)
}
}
|
apache-2.0
|
261c50eec066cb0978542167dcc3b989
| 33.775 | 120 | 0.572678 | 5.051453 | false | false | false | false |
nimakro/tornadofx
|
src/main/java/tornadofx/SmartResize.kt
|
1
|
23268
|
package tornadofx
import javafx.application.Platform
import javafx.beans.property.ObjectProperty
import javafx.beans.property.ReadOnlyProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.value.ChangeListener
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.scene.control.TableColumn
import javafx.scene.control.TableView
import javafx.scene.control.TreeTableColumn
import javafx.scene.control.TreeTableView
import javafx.util.Callback
import tornadofx.adapters.*
import kotlin.collections.set
import kotlin.math.abs
//private const val SMART_RESIZE_INSTALLED = "tornadofx.smartResizeInstalled"
private const val SMART_RESIZE = "tornadofx.smartResize"
private const val IS_SMART_RESIZING = "tornadofx.isSmartResizing"
const val RESIZE_TYPE_KEY = "tornadofx.smartColumnResizeType"
sealed class ResizeType(val isResizable: Boolean) {
class Pref(val width: Number) : ResizeType(true)
class Fixed(val width: Number) : ResizeType(false)
class Weight(val weight: Number, val padding: Number = 0.0, val minContentWidth: Boolean = false, var minRecorded: Boolean = false) : ResizeType(true)
class Pct(val value: Number) : ResizeType(true)
class Content(val padding: Number = 0.0, val useAsMin: Boolean = false, val useAsMax: Boolean = false, var minRecorded: Boolean = false, var maxRecorded: Boolean = false) : ResizeType(true)
class Remaining : ResizeType(true)
var delta: Double = 0.0
}
typealias TableViewResizeCallback = Callback<TableView.ResizeFeatures<out Any>, Boolean>
typealias TreeTableViewResizeCallback = Callback<TreeTableView.ResizeFeatures<out Any>, Boolean>
class SmartResize private constructor() : TableViewResizeCallback {
override fun call(param: TableView.ResizeFeatures<out Any>) = resizeCall(param.toTornadoFXFeatures()) { table ->
if (!isPolicyInstalled(table)) install(table)
}
fun requestResize(table: TableView<*>) {
Platform.runLater {
call(TableView.ResizeFeatures(table, null, 0.0))
}
}
companion object {
val POLICY = SmartResize()
val ResizeTypeKey = "tornadofx.smartColumnResizeType"
private var TableView<*>.isSmartResizing: Boolean
get() = properties[IS_SMART_RESIZING] == true
set(value) {
properties[IS_SMART_RESIZING] = value
}
private val policyChangeListener = ChangeListener<Callback<TableView.ResizeFeatures<*>, Boolean>> { observable, _, newValue ->
val table = (observable as ObjectProperty<*>).bean as TableView<*>
if (newValue == POLICY) install(table) else uninstall(table)
}
private val itemsChangeListener = ChangeListener<ObservableList<*>> { observable, _, _ ->
val table = (observable as ObjectProperty<*>).bean as TableView<*>
POLICY.requestResize(table)
}
private val columnsChangeListener = ListChangeListener<TableColumn<*, *>> { s ->
while (s.next()) {
if (s.wasAdded()) s.addedSubList.forEach {
it.widthProperty().addListener(columnWidthChangeListener)
}
if (s.wasRemoved()) s.removed.forEach {
it.widthProperty().removeListener(columnWidthChangeListener)
}
}
}
@Suppress("UNCHECKED_CAST")
private val columnWidthChangeListener = ChangeListener<Number> { observable, oldValue, newValue ->
val column = (observable as ReadOnlyProperty<*>).bean as TableColumn<*, *>
val table: TableView<out Any>? = column.tableView
if (table?.isSmartResizing == false) {
val rt = column.resizeType
val diff = oldValue.toDouble() - newValue.toDouble()
rt.delta -= diff
POLICY.call(TableView.ResizeFeatures<Any>(table as TableView<Any>?, null, 0.0))
}
}
private fun isPolicyInstalled(table: TableView<*>) = table.properties[SMART_RESIZE] == true
private fun install(table: TableView<*>) {
table.columnResizePolicyProperty().addListener(policyChangeListener)
table.columns.addListener(columnsChangeListener)
table.itemsProperty().addListener(itemsChangeListener)
table.columns.forEach { it.widthProperty().addListener(columnWidthChangeListener) }
table.properties[SMART_RESIZE] = true
}
private fun uninstall(table: TableView<*>) {
table.columnResizePolicyProperty().removeListener(policyChangeListener)
table.columns.removeListener(columnsChangeListener)
table.itemsProperty().removeListener(itemsChangeListener)
table.columns.forEach { it.widthProperty().removeListener(columnWidthChangeListener) }
table.properties.remove(SMART_RESIZE)
}
}
}
class TreeTableSmartResize private constructor() : TreeTableViewResizeCallback {
override fun call(param: TreeTableView.ResizeFeatures<out Any>) = resizeCall(param.toTornadoFXResizeFeatures()) { table ->
if (!isPolicyInstalled(table)) install(table)
}
fun requestResize(table: TreeTableView<*>) {
Platform.runLater {
call(TreeTableView.ResizeFeatures(table, null, 0.0))
}
}
companion object {
val POLICY = TreeTableSmartResize()
const val ResizeTypeKey = "tornadofx.smartColumnResizeType"
internal var TreeTableView<*>.isSmartResizing: Boolean
get() = properties[IS_SMART_RESIZING] == true
set(value) {
properties[IS_SMART_RESIZING] = value
}
private val policyChangeListener = ChangeListener<Callback<TreeTableView.ResizeFeatures<*>, Boolean>> { observable, oldValue, newValue ->
val table = (observable as ObjectProperty<*>).bean as TreeTableView<*>
if (newValue == POLICY) install(table) else uninstall(table)
}
private val columnsChangeListener = ListChangeListener<TreeTableColumn<*, *>> { s ->
while (s.next()) {
if (s.wasAdded()) s.addedSubList.forEach {
it.widthProperty().addListener(columnWidthChangeListener)
}
if (s.wasRemoved()) s.removed.forEach {
it.widthProperty().removeListener(columnWidthChangeListener)
}
}
}
@Suppress("UNCHECKED_CAST")
private val columnWidthChangeListener = ChangeListener<Number> { observable, oldValue, newValue ->
val column = (observable as ReadOnlyProperty<*>).bean as TreeTableColumn<*, *>
val table: TreeTableView<out Any>? = column.treeTableView
if (table != null && !table.isSmartResizing) {
val rt = column.resizeType
val diff = oldValue.toDouble() - newValue.toDouble()
rt.delta -= diff
POLICY.call(TreeTableView.ResizeFeatures<Any>(table as TreeTableView<Any>?, null, 0.0))
}
}
private fun isPolicyInstalled(table: TreeTableView<*>) = table.properties[SMART_RESIZE] == true
private fun install(table: TreeTableView<*>) {
table.columnResizePolicyProperty().addListener(policyChangeListener)
table.columns.addListener(columnsChangeListener)
table.columns.forEach { it.widthProperty().addListener(columnWidthChangeListener) }
table.properties[SMART_RESIZE] = true
}
private fun uninstall(table: TreeTableView<*>) {
table.columnResizePolicyProperty().removeListener(policyChangeListener)
table.columns.removeListener(columnsChangeListener)
table.columns.forEach { it.widthProperty().removeListener(columnWidthChangeListener) }
table.properties.remove(SMART_RESIZE)
}
}
}
fun TableView<*>.smartResize() {
columnResizePolicy = SmartResize.POLICY
}
fun TableView<*>.requestResize() {
SmartResize.POLICY.requestResize(this)
}
fun TreeTableView<*>.smartResize() {
columnResizePolicy = TreeTableSmartResize.POLICY
}
fun TreeTableView<*>.requestResize() {
TreeTableSmartResize.POLICY.requestResize(this)
}
/**
* Get the width of the area available for columns inside the TableView
*/
fun TableView<*>.getContentWidth() = TableView::class.java.getDeclaredField("contentWidth").let {
it.isAccessible = true
it.get(this@getContentWidth) as Double
}
/**
* Get the width of the area available for columns inside the TableView
*/
fun TreeTableView<*>.getContentWidth() = TreeTableView::class.java.getDeclaredField("contentWidth").let {
it.isAccessible = true
it.get(this@getContentWidth) as Double
}
val TableView<*>.contentColumns: List<TableColumn<*, *>>
get() = columns.flatMap {
if (it.columns.isEmpty()) listOf(it) else it.columns
}
val TreeTableView<*>.contentColumns: List<TreeTableColumn<*, *>>
get() = columns.flatMap {
if (it.columns.isEmpty()) listOf(it) else it.columns
}
internal var TableColumn<*, *>.resizeType: ResizeType
get() = resizeTypeProperty().value
set(value) {
resizeTypeProperty().value = value
}
internal var TreeTableColumn<*, *>.resizeType: ResizeType
get() = resizeTypeProperty().value
set(value) {
resizeTypeProperty().value = value
}
@Suppress("UNCHECKED_CAST")
internal fun TableColumn<*, *>.resizeTypeProperty() =
properties.getOrPut(SmartResize.ResizeTypeKey) { SimpleObjectProperty(ResizeType.Content()) } as ObjectProperty<ResizeType>
@Suppress("UNCHECKED_CAST")
internal fun TreeTableColumn<*, *>.resizeTypeProperty() =
properties.getOrPut(TreeTableSmartResize.ResizeTypeKey) { SimpleObjectProperty(ResizeType.Content()) } as ObjectProperty<ResizeType>
fun <S, T> TableColumn<S, T>.fixedWidth(width: Number) = apply {
minWidth = width.toDouble()
maxWidth = width.toDouble()
resizeType = ResizeType.Fixed(width.toDouble())
}
fun <S, T> TreeTableColumn<S, T>.fixedWidth(width: Number) = apply {
minWidth = width.toDouble()
maxWidth = width.toDouble()
resizeType = ResizeType.Fixed(width.toDouble())
}
fun <S, T> TableColumn<S, T>.minWidth(width: Number) = apply { minWidth = width.toDouble() }
fun <S, T> TreeTableColumn<S, T>.minWidth(width: Number) = apply { minWidth = width.toDouble() }
fun <S, T> TableColumn<S, T>.maxWidth(width: Number) = apply { maxWidth = width.toDouble() }
fun <S, T> TreeTableColumn<S, T>.maxWidth(width: Number) = apply { maxWidth = width.toDouble() }
fun <S, T> TableColumn<S, T>.prefWidth(width: Number) = apply { prefWidth = width.toDouble() }
fun <S, T> TreeTableColumn<S, T>.prefWidth(width: Number) = apply { prefWidth = width.toDouble() }
fun <S, T> TableColumn<S, T>.remainingWidth() = apply { resizeType = ResizeType.Remaining() }
fun <S, T> TreeTableColumn<S, T>.remainingWidth() = apply { resizeType = ResizeType.Remaining() }
fun <S, T> TableColumn<S, T>.weightedWidth(weight: Number, padding: Double = 0.0, minContentWidth: Boolean = false) = apply {
resizeType = ResizeType.Weight(weight.toDouble(), padding, minContentWidth)
}
fun <S, T> TreeTableColumn<S, T>.weightedWidth(weight: Number, padding: Double = 0.0, minContentWidth: Boolean = false) = apply {
resizeType = ResizeType.Weight(weight.toDouble(), padding, minContentWidth)
}
fun <S, T> TableColumn<S, T>.pctWidth(pct: Number) = apply {
resizeType = ResizeType.Pct(pct.toDouble())
}
fun <S, T> TreeTableColumn<S, T>.pctWidth(pct: Number) = apply {
resizeType = ResizeType.Pct(pct.toDouble())
}
/**
* Make the column fit the content plus an optional padding width. Optionally constrain the min or max width to be this width.
*/
fun <S, T> TableColumn<S, T>.contentWidth(padding: Double = 0.0, useAsMin: Boolean = false, useAsMax: Boolean = false) = apply {
resizeType = ResizeType.Content(padding, useAsMin, useAsMax)
}
/**
* Make the column fit the content plus an optional padding width. Optionally constrain the min or max width to be this width.
*/
fun <S, T> TreeTableColumn<S, T>.contentWidth(padding: Number = 0.0, useAsMin: Boolean = false, useAsMax: Boolean = false) = apply {
resizeType = ResizeType.Content(padding, useAsMin, useAsMax)
}
internal var TornadoFXColumn<*>.resizeType: ResizeType
get() = resizeTypeProperty().value
set(value) {
resizeTypeProperty().value = value
}
@Suppress("UNCHECKED_CAST")
internal fun TornadoFXColumn<*>.resizeTypeProperty() =
properties.getOrPut(RESIZE_TYPE_KEY) { SimpleObjectProperty(ResizeType.Content()) } as ObjectProperty<ResizeType>
var TornadoFXTable<*, *>.isSmartResizing: Boolean
get() = properties[IS_SMART_RESIZING] == true
set(value) {
properties[IS_SMART_RESIZING] = value
}
fun <S> TornadoFXColumn<S>.fixedWidth(width: Number) = apply {
minWidth = width.toDouble()
maxWidth = width.toDouble()
resizeType = ResizeType.Fixed(width.toDouble())
}
fun <S> TornadoFXColumn<S>.minWidth(width: Number) = apply {
minWidth = width.toDouble()
}
fun <S> TornadoFXColumn<S>.maxWidth(width: Number) = apply {
maxWidth = width.toDouble()
}
fun <S> TornadoFXColumn<S>.prefWidth(width: Number) = apply {
prefWidth = width.toDouble()
}
fun <S> TornadoFXColumn<S>.remainingWidth() = apply {
resizeType = ResizeType.Remaining()
}
fun <S> TornadoFXColumn<S>.weightedWidth(weight: Number, padding: Double = 0.0, minContentWidth: Boolean = false) = apply {
resizeType = ResizeType.Weight(weight.toDouble(), padding, minContentWidth)
}
fun <S> TornadoFXColumn<S>.pctWidth(pct: Number) = apply {
resizeType = ResizeType.Pct(pct.toDouble())
}
/**
* Make the column fit the content plus an optional padding width. Optionally constrain the min or max width to be this width.
*/
fun <S> TornadoFXColumn<S>.contentWidth(padding: Double = 0.0, useAsMin: Boolean = false, useAsMax: Boolean = false) = apply {
resizeType = ResizeType.Content(padding, useAsMin, useAsMax)
}
fun <S, T : Any> TornadoFXTable<S, T>.resizeColumnsToFitContent(resizeColumns: List<TornadoFXColumn<*>> = contentColumns, maxRows: Int = 50, afterResize: () -> Unit = {}) {
when (table) {
is TableView<*> -> (table as TableView<*>).resizeColumnsToFitContent(resizeColumns.map { it.column as TableColumn<*, *> }, maxRows, afterResize)
is TreeTableView<*> -> (table as TreeTableView<*>).resizeColumnsToFitContent(resizeColumns.map { it.column as TreeTableColumn<*, *> }, maxRows, afterResize)
else -> throw IllegalArgumentException("Unable to resize columns for unknown table type $table")
}
}
fun <TABLE : Any> resizeCall(
param: TornadoFXResizeFeatures<*, TABLE>,
installIfNeeded: (TABLE) -> Unit
): Boolean {
param.table.isSmartResizing = true
val paramColumn = param.column
try {
if (paramColumn == null) {
// Resize all columns
val contentWidth = param.table.contentWidth
if (contentWidth == 0.0) return false
installIfNeeded(param.table.table)
var remainingWidth = contentWidth
val groupedColumns = param.table.contentColumns.groupBy { it.resizeType::class }
// Fixed columns always keep their size
groupedColumns[ResizeType.Fixed::class]?.forEach {
val rt = it.resizeType as ResizeType.Fixed
it.prefWidth = rt.width.toDouble()
remainingWidth -= it.width
}
// Preferred sized columns get their size and are adjusted for resize-delta that affected them
groupedColumns[ResizeType.Pref::class]?.forEach {
val rt = it.resizeType as ResizeType.Pref
it.prefWidth = rt.width.toDouble() + rt.delta.toDouble()
remainingWidth -= it.width
}
// Content columns are resized to their content and adjusted for resize-delta that affected them
groupedColumns[ResizeType.Content::class]?.also { contentColumns ->
param.table.resizeColumnsToFitContent(contentColumns)
contentColumns.forEach {
val rt = it.resizeType as ResizeType.Content
it.prefWidth = it.width + rt.delta + rt.padding.toDouble()
// Save minWidth if different from default
if (rt.useAsMin && !rt.minRecorded && it.width != 80.0) {
it.minWidth = it.width
rt.minRecorded = true
}
// Save maxWidth if different from default
if (rt.useAsMax && !rt.maxRecorded && it.width != 80.0) {
it.maxWidth = it.width
rt.maxRecorded = true
}
remainingWidth -= it.width
}
}
// Pct columns share what's left of space from here
groupedColumns[ResizeType.Pct::class]?.also { pctColumn ->
val widthPerPct = contentWidth / 100.0
pctColumn.forEach {
val rt = it.resizeType as ResizeType.Pct
it.prefWidth = (widthPerPct * rt.value.toDouble()) + rt.delta.toDouble()
remainingWidth -= it.width
}
}
// Weighted columns shouldn't be combined with Pct. Weight is converted to pct of remaining width
// and distributed to weigthed columns + remaining type columns
groupedColumns[ResizeType.Weight::class]?.also { weightColumns ->
val consideredColumns = weightColumns + param.table.contentColumns.filter { it.resizeType is ResizeType.Remaining }
// Combining with "Remaining" typed columns. Remaining columns will get a default weight of 1
fun TornadoFXColumn<*>.weight() = (resizeType as? ResizeType.Weight)?.weight?.toDouble() ?: 1.0
val totalWeight = consideredColumns.sumByDouble { it.weight() }
val perWeight = remainingWidth / totalWeight
consideredColumns.forEach {
val rt = it.resizeType
if (rt is ResizeType.Weight) {
if (rt.minContentWidth && !rt.minRecorded) {
rt.minRecorded = true
it.minWidth = it.width + rt.padding.toDouble()
}
it.prefWidth = Math.max(it.minWidth, (perWeight * rt.weight.toDouble()) + rt.delta + rt.padding.toDouble())
} else {
it.prefWidth = Math.max(it.minWidth, perWeight + rt.delta)
}
remainingWidth -= it.width
}
} ?: run {
// If no weighted columns, give the rest of the width to the "Remaining" columns
groupedColumns[ResizeType.Remaining::class]?.also { remainingColumns ->
if (remainingWidth > 0) {
val perColumn = remainingWidth / remainingColumns.size.toDouble()
remainingColumns.forEach {
it.prefWidth = perColumn + it.resizeType.delta
remainingWidth -= it.width
}
}
}
}
// Adjustment if we didn't assign all width
if (remainingWidth > 0.0) {
// Give remaining width to the right-most resizable column
val rightMostResizable = param.table.contentColumns.lastOrNull { it.resizeType.isResizable }
rightMostResizable?.apply {
prefWidth = width + remainingWidth
remainingWidth -= width
}
// Adjustment for where we assigned more width that we have
} else if (remainingWidth < 0.0) {
// Reduce from resizable columns, for now we reduce the column with largest reduction potential
// We should consider reducing based on the resize type of the column as well
param.table.contentColumns.filter { it.resizeType.isResizable }.reduceSorted(
// sort the column by the largest reduction potential: the gap between size and minSize
sorter = { minWidth - width },
filter = { minWidth < width }
) {
val reduceBy = minOf(1.0, abs(remainingWidth))
val toWidth = it.width - reduceBy
it.prefWidth = toWidth
remainingWidth += reduceBy
return remainingWidth < 0.0
}
}
} else {
// Handle specific column size operation
val rt = paramColumn.resizeType
if (!rt.isResizable) return false
val targetWidth = paramColumn.width + param.delta
// Would resize result in illegal width?
if (targetWidth !in paramColumn.minWidthProperty.value..paramColumn.maxWidthProperty.value) return false
// Prepare to adjust the right column by the same amount we subtract or add to this column
val rightColDelta = param.delta * -1.0
val colIndex = param.table.contentColumns.indexOf(paramColumn)
val rightCol = param.table.contentColumns
.filterIndexed { i, c -> i > colIndex && c.resizeType.isResizable }.firstOrNull {
val newWidth = it.width + rightColDelta
newWidth in it.minWidthProperty.value..it.maxWidthProperty.value
} ?: return false
// Apply negative delta and set new with for the right column
with(rightCol) {
resizeType.delta += rightColDelta
prefWidth = width + rightColDelta
}
// Apply delta and set new width for the resized column
with(paramColumn) {
rt.delta += param.delta
prefWidth = width + param.delta
}
return true
}
return true
} finally {
param.table.isSmartResizing = false
}
}
/**
* Removes elements from the list in a sorted way with a cycle:
*
* 1. removes elements that fail the [filter]
* 2. find the first sorted element with the [sorter]
* 3. change the state of the element with the [iteration]
* 4. if [iteration] returns true, start again.
*
* @return the reduced list
*/
private inline fun <T, R : Comparable<R>> List<T>.reduceSorted(
crossinline sorter: T.() -> R,
noinline filter: T.() -> Boolean,
iteration: (T) -> Boolean
): List<T> {
val removingList = asSequence().filter(filter).sortedBy(sorter).toMutableList()
while (removingList.any()) {
val element = removingList.first()
if (!iteration(element)) break
if (!element.filter()) removingList.remove(element)
removingList.sortBy(sorter)
}
return removingList
}
|
apache-2.0
|
6621891d4f3bf3ccf3c403ce6cf5e261
| 40.700717 | 193 | 0.63525 | 4.59388 | false | false | false | false |
jrgonzalezg/OpenLibraryApp
|
app/src/main/kotlin/com/github/jrgonzalezg/openlibrary/app/NetworkModule.kt
|
1
|
2120
|
/*
* Copyright (C) 2017 Juan Ramón González González (https://github.com/jrgonzalezg)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jrgonzalezg.openlibrary.app
import com.github.jrgonzalezg.openlibrary.BuildConfig
import com.github.jrgonzalezg.openlibrary.features.books.data.api.OpenLibraryService
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton
@Module
class NetworkModule {
val HTTP_LOGGING_ENABLED: Boolean = BuildConfig.HTTP_LOGGING_ENABLED
val OPEN_LIBRARY_BASE_URL: String = "https://openlibrary.org"
@Provides
@Singleton
protected fun provideOkHttpClient(): OkHttpClient {
val okHttpClientBuilder = OkHttpClient.Builder()
if (HTTP_LOGGING_ENABLED) {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
okHttpClientBuilder.addInterceptor(httpLoggingInterceptor)
}
return okHttpClientBuilder.build()
}
@Provides
@Singleton
protected fun provideOpenLibraryService(retrofit: Retrofit): OpenLibraryService {
return retrofit.create(OpenLibraryService::class.java)
}
@Provides
@Singleton
protected fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
val retrofit = Retrofit.Builder().baseUrl(OPEN_LIBRARY_BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.client(okHttpClient)
.build()
return retrofit
}
}
|
apache-2.0
|
15b02f950d7509cb668f86432ce46e4b
| 32.078125 | 84 | 0.771847 | 4.6122 | false | false | false | false |
andstatus/andstatus
|
app/src/main/kotlin/org/andstatus/app/widget/WebViewFragment.kt
|
1
|
4081
|
/*
* Copyright (C) 2018 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.widget
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RawRes
import androidx.fragment.app.Fragment
import org.andstatus.app.R
import org.andstatus.app.context.MyLocale
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.SharedPreferencesUtil
import org.andstatus.app.util.Xslt
class WebViewFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val context = inflater.context
val output = getTransformedContent(context)
return try {
val view = inflater.inflate(R.layout.webview_fragment, container, false) as WebView
// See http://stackoverflow.com/questions/14474223/utf-8-not-encoding-html-in-webview-android
view.settings.defaultTextEncodingName = "utf-8"
view.settings.textZoom = configuredTextZoom()
view.settings.javaScriptEnabled = true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
view.settings.safeBrowsingEnabled = false
}
// Used this answer for adding a stylesheet: http://stackoverflow.com/a/7736654/297710
// See also http://stackoverflow.com/questions/13638892/where-is-the-path-file-android-asset-documented
view.loadDataWithBaseURL("file:///android_asset/", output, "text/html", "utf-8", null)
view
} catch (e: Throwable) {
val view = inflater.inflate(R.layout.empty_layout, container, false) as LinearLayout
val contentView = view.findViewById<TextView?>(R.id.content)
val text = "Error initializing WebView: ${e.message}\n\n$output"
contentView.text = text
MyLog.w(this, text, e)
view
}
}
private fun getTransformedContent(context: Context): String {
return try {
var output: String = Xslt.toHtmlString(context, arguments?.getInt(SOURCE_XML) ?: 0,
arguments?.getInt(SOURCE_XSL) ?: 0)
if (!MyLocale.isEnLocale()) {
output = output.replace("Translator credits",
context.getText(R.string.translator_credits) as String)
}
output
} catch (e: Exception) {
"Error during transformation: " + e.message
}
}
companion object {
private val SOURCE_XML: String = "sourceXml"
private val SOURCE_XSL: String = "sourceXsl"
fun from(@RawRes resXml: Int, @RawRes resXsl: Int): WebViewFragment {
val fragment = WebViewFragment()
val bundle = Bundle()
bundle.putInt(SOURCE_XML, resXml)
bundle.putInt(SOURCE_XSL, resXsl)
fragment.arguments = bundle
return fragment
}
private fun configuredTextZoom(): Int {
return when (SharedPreferencesUtil.getString(MyPreferences.KEY_THEME_SIZE, "")) {
"Large" -> 170
"Larger" -> 145
"Smaller" -> 108
"Small" -> 90
else -> 125
}
}
}
}
|
apache-2.0
|
1b1091e01919db78a07c4b22a3a130af
| 40.222222 | 116 | 0.64788 | 4.35539 | false | false | false | false |
kenrube/Fantlab-client
|
app/src/main/kotlin/ru/fantlab/android/ui/modules/work/responses/overview/ResponseOverviewActivity.kt
|
2
|
7137
|
package ru.fantlab.android.ui.modules.work.responses.overview
import android.app.Application
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.evernote.android.state.State
import kotlinx.android.synthetic.main.appbar_response_layout.*
import kotlinx.android.synthetic.main.response_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.ContextMenuBuilder
import ru.fantlab.android.data.dao.model.ContextMenus
import ru.fantlab.android.data.dao.model.Response
import ru.fantlab.android.helper.*
import ru.fantlab.android.provider.scheme.LinkParserHelper
import ru.fantlab.android.provider.storage.WorkTypesProvider
import ru.fantlab.android.ui.base.BaseActivity
import ru.fantlab.android.ui.modules.editor.EditorActivity
import ru.fantlab.android.ui.modules.user.UserPagerActivity
import ru.fantlab.android.ui.modules.work.CyclePagerActivity
import ru.fantlab.android.ui.modules.work.WorkPagerActivity
import ru.fantlab.android.ui.widgets.dialog.ContextMenuDialogView
class ResponseOverviewActivity : BaseActivity<ResponseOverviewMvp.View, ResponseOverviewPresenter>(),
ResponseOverviewMvp.View {
@State lateinit var response: Response
override fun layout(): Int = R.layout.response_layout
override fun isTransparent(): Boolean = false
override fun canBack(): Boolean = true
override fun providePresenter(): ResponseOverviewPresenter = ResponseOverviewPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
response = intent!!.extras.getParcelable(BundleConstant.EXTRA)
onInitViews(response)
} else onInitViews(response)
if (response.id == -1) {
finish()
return
}
fab.setOnClickListener { onFabClicked() }
title = "«" + (if (response.workName.isNotEmpty()) response.workName else response.workNameOrig) + "»"
toolbar?.subtitle = getString(R.string.view_response)
hideShowShadow(true)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.share_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.share -> {
ActivityHelper.shareUrl(this, Uri.Builder().scheme(LinkParserHelper.PROTOCOL_HTTPS)
.authority(LinkParserHelper.HOST_DEFAULT)
.appendEncodedPath("work${response.workId}/toresponse${response.id}")
.toString())
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onInitViews(response: Response) {
avatarLayout.setUrl("https://${LinkParserHelper.HOST_DATA}/images/users/${response.userId}")
responseUser.text = response.userName.capitalize()
date.text = response.dateIso.parseFullDate(true).getTimeAgo()
authors.text = if (!InputHelper.isEmpty(response.workAuthor)) response.workAuthor else response.workAuthorOrig
workName.text = if (response.workName.isNotEmpty()) response.workName else response.workNameOrig
workBlock.setOnClickListener { openWorkPager() }
coverLayout.setUrl("https:${response.workImage}", WorkTypesProvider.getCoverByTypeId(response.workTypeId))
userInfo.setOnClickListener { showUserMenu() }
responseText.html = response.text
if (response.mark == null) {
rating.visibility = View.GONE
} else {
rating.text = response.mark.toString()
rating.visibility = View.VISIBLE
}
response.voteCount.let {
when {
it < 0 -> {
votes.setDrawables(R.drawable.ic_thumb_down)
votes.text = response.voteCount.toString()
votes.visibility = View.VISIBLE
}
it > 0 -> {
votes.setDrawables(R.drawable.ic_thumb_up)
votes.text = response.voteCount.toString()
votes.visibility = View.VISIBLE
}
else -> votes.visibility = View.GONE
}
}
if (isLoggedIn() && PrefGetter.getLoggedUser()?.id != response.userId) {
fab.setImageResource(R.drawable.ic_thumb_up_down)
fab.visibility = View.VISIBLE
} else if (isLoggedIn()) {
fab.setImageResource(R.drawable.ic_response)
fab.visibility = View.VISIBLE
} else {
fab.visibility = View.GONE
}
}
private fun openWorkPager() {
if (response.workTypeId == FantlabHelper.WorkType.WORK_TYPE_CYCLE.id)
CyclePagerActivity.startActivity(this, response.workId, response.workName, 0)
else
WorkPagerActivity.startActivity(this, response.workId, response.workName, 0)
}
private fun showUserMenu() {
val dialogView = ContextMenuDialogView()
dialogView.initArguments("main", ContextMenuBuilder.buildForProfile(responseUser.context), response, 0)
dialogView.show(supportFragmentManager, "ContextMenuDialogView")
}
private fun onFabClicked() {
if (PrefGetter.getLoggedUser()?.id == response.userId) {
startActivityForResult(Intent(this, EditorActivity::class.java)
.putExtra(BundleConstant.EXTRA_TYPE, BundleConstant.EDITOR_EDIT_RESPONSE)
.putExtra(BundleConstant.EXTRA, response.text)
.putExtra(BundleConstant.EXTRA_TWO, response.id)
.putExtra(BundleConstant.ID, response.workId),
BundleConstant.REFRESH_RESPONSE_CODE
)
} else presenter.onGetUserLevel()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
BundleConstant.REFRESH_RESPONSE_CODE -> {
if (data != null) {
val responseNewText = data.extras?.getCharSequence(BundleConstant.EXTRA)
responseText.html = responseNewText
response.text = responseNewText.toString()
}
}
}
}
override fun onShowVotesDialog(userLevel: Float) {
hideProgress()
val dialogView = ContextMenuDialogView()
val variants = ContextMenuBuilder.buildForResponse()
if (userLevel < FantlabHelper.minLevelToVote) variants[0].items.removeAt(1)
dialogView.initArguments("votes", variants, response, 0)
dialogView.show(supportFragmentManager, "ContextMenuDialogView")
}
override fun onSetVote(votesCount: String) {
hideProgress()
votes.text = votesCount
}
override fun onItemSelected(parent: String, item: ContextMenus.MenuItem, position: Int, listItem: Any) {
listItem as Response
when (item.id) {
"vote" -> {
presenter.onSendVote(listItem, if (item.title.contains("+")) "plus" else "minus")
}
"profile" -> {
UserPagerActivity.startActivity(this, listItem.userName, listItem.userId, 0)
}
"message" -> {
startActivity(Intent(this, EditorActivity::class.java)
.putExtra(BundleConstant.EXTRA_TYPE, BundleConstant.EDITOR_NEW_MESSAGE)
.putExtra(BundleConstant.ID, listItem.userId)
)
}
}
}
companion object {
fun startActivity(context: Context, response: Response) {
val intent = Intent(context, ResponseOverviewActivity::class.java)
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA, response)
.end())
if (context is Service || context is Application) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
}
}
}
|
gpl-3.0
|
1202fb4bfa9175ad6f9bb31fdbf8cf7b
| 32.97619 | 112 | 0.751507 | 3.775132 | false | false | false | false |
SiimKinks/sqlitemagic
|
sqlitemagic-tests/app-kotlin/src/test/kotlin/com/siimkinks/sqlitemagic/InternalAssertions.kt
|
1
|
2860
|
package com.siimkinks.sqlitemagic
import com.google.common.truth.Truth.assertThat
import com.siimkinks.sqlitemagic.AuthorTable.AUTHOR
import com.siimkinks.sqlitemagic.Utils.*
import org.junit.Before
import org.mockito.Mockito
interface DSLTests {
@Before
fun setUp() {
val instance = SqliteMagic.SingletonHolder.instance
instance.defaultConnection = Mockito.mock<DbConnectionImpl>(DbConnectionImpl::class.java)
}
}
fun DeleteSqlNode.isEqualTo(expectedSql: String, vararg withArgs: String) {
val sql = SqlCreator.getSql(this, 3)
assertThat(sql).isEqualTo(expectedSql)
assertThat(this.deleteBuilder.args).containsExactly(*withArgs)
}
fun UpdateSqlNode.isEqualTo(sql: String, nodeCount: Int, vararg args: String?) {
val updateBuilder = updateBuilder
val actualSql = SqlCreator.getSql(updateBuilder.sqlTreeRoot, updateBuilder.sqlNodeCount)
assertThat(actualSql).isEqualTo(sql)
assertThat(updateBuilder.sqlNodeCount).isEqualTo(nodeCount)
assertThat(updateBuilder.args).isNotNull()
assertThat(updateBuilder.args).containsExactly(*args)
}
fun CompiledRawSelect.isEqualTo(expectedSql: String,
expectedObservedTables: Array<String> = emptyArray(),
expectedArgs: Array<String>? = null) {
val select = this as RawSelect.CompiledRawSelectImpl
assertThat(select.sql).isEqualTo(expectedSql)
assertThat(select.observedTables).isEqualTo(expectedObservedTables)
assertThat(select.args).isEqualTo(expectedArgs)
}
fun SelectSqlNode<*>.isEqualTo(expectedOutput: String) {
val generatedSql = generateSql(this)
assertThat(generatedSql).isEqualTo(expectedOutput)
}
fun SelectSqlNode<*>.isEqualTo(expectedOutput: String, vararg expectedArgs: String) {
val generatedSql = generateSql(this)
assertThat(generatedSql).isEqualTo(expectedOutput)
assertThat(this.selectBuilder.args).containsExactly(*expectedArgs)
}
fun Expr.isEqualTo(expectedExpr: String,
vararg args: String) {
(SELECT FROM AUTHOR WHERE this)
.isEqualTo("SELECT * FROM author WHERE $expectedExpr ", *args)
}
fun generateSql(sqlNode: SelectSqlNode<*>): String {
val selectBuilder = sqlNode.selectBuilder
if (selectBuilder.columnsNode != null) {
selectBuilder.columnsNode.compileColumns(null)
}
return SqlCreator.getSql(sqlNode, selectBuilder.sqlNodeCount)
}
fun <T, R, ET, P, N> Column<T, R, ET, P, N>.parsesWith(valueParser: ValueParser) {
assertThat(this.valueParser).isEqualTo(when (valueParser) {
ValueParser.STRING -> STRING_PARSER
ValueParser.INTEGER -> INTEGER_PARSER
ValueParser.LONG -> LONG_PARSER
ValueParser.SHORT -> SHORT_PARSER
ValueParser.BYTE -> BYTE_PARSER
ValueParser.FLOAT -> FLOAT_PARSER
ValueParser.DOUBLE -> DOUBLE_PARSER
})
}
enum class ValueParser {
STRING, INTEGER, LONG, SHORT, BYTE, FLOAT, DOUBLE
}
|
apache-2.0
|
8c33c1243ebf090b18b7a503ff69e4b1
| 34.75 | 93 | 0.753846 | 4.074074 | false | false | false | false |
y2k/JoyReactor
|
core/src/main/kotlin/y2k/joyreactor/common/ServiceLocator.kt
|
1
|
5484
|
package y2k.joyreactor.common
import y2k.joyreactor.common.http.CookieStorage
import y2k.joyreactor.common.http.DefaultHttpClient
import y2k.joyreactor.common.http.HttpClient
import y2k.joyreactor.common.platform.NavigationService
import y2k.joyreactor.common.platform.Platform
import y2k.joyreactor.services.*
import y2k.joyreactor.services.images.DiskCache
import y2k.joyreactor.services.repository.Entities
import y2k.joyreactor.services.repository.IDataContext
import y2k.joyreactor.services.repository.ormlite.OrmLiteDataContext
import y2k.joyreactor.services.requests.*
import y2k.joyreactor.services.requests.parser.LikeParser
import y2k.joyreactor.services.requests.parser.PostParser
import y2k.joyreactor.services.synchronizers.MyTagFetcher
import y2k.joyreactor.services.synchronizers.PostMerger
import y2k.joyreactor.services.synchronizers.PrivateMessageFetcher
import y2k.joyreactor.viewmodel.*
import java.util.*
import kotlin.reflect.KClass
/**
* Created by y2k on 07/12/15.
*/
object ServiceLocator {
private val map = HashMap <KClass<*>, () -> Any>()
init {
registerSingleton<HttpClient> { DefaultHttpClient(CookieStorage(resolve())) }
register { PostViewModel(resolve(), resolve(), resolve(), resolve()) }
register { NavigationService.instance }
register { ThreadsViewModel(resolve(), resolve(), resolve()) }
register { MessagesViewModel(resolve(), resolve()) }
register { resolve<Platform>().makeReportService() }
register { BroadcastService }
register { PostParser(resolve<LikeParser>()) }
register { TokenRequest(resolve()) }
register { ChangePostFavoriteRequest(resolve(), resolve()) }
register { LikePostRequest(resolve(), resolve<TokenRequest>(), resolve<LikeParser>()) }
register { MessageListRequest(resolve(), resolve()) }
register { PostMerger(resolve(), resolve()) }
register { MemoryBuffer }
register { MyTagFetcher(resolve(), resolve(), resolve()) }
register { PrivateMessageFetcher(resolve(), resolve()) }
register { PostsForTagRequest(resolve(), resolve(), resolve()) }
register { AddTagRequest(resolve()) }
register { UserNameRequest(resolve()) }
register { TagsForUserRequest(resolve(), resolve()) }
register { OriginalImageRequestFactory(resolve(), resolve()) }
register { PostRequest(resolve(), resolve<PostParser>()) }
register { ProfileRequest(resolve()) }
register { LoginRequestFactory(resolve()) }
register { SendMessageRequest(resolve()) }
register { CreateCommentRequest(resolve()) }
register { PostService(resolve(), resolve<PostRequest>(), resolve(), resolve(), resolve(), resolve(), resolve()) }
register { TagService(resolve(), resolve(), resolve(), resolve()) }
register { UserService(resolve(), resolve(), resolve(), resolve()) }
register { ProfileService(resolve(), resolve<ProfileRequest>(), resolve<UserNameRequest>(), resolve()) }
register { UserMessagesService(resolve(), resolve(), resolve()) }
register { CommentService(resolve<CreateCommentRequest>(), resolve()) }
register { LoginViewModel(resolve(), resolve()) }
register { MenuViewModel(resolve(), resolve(), resolve()) }
register { GalleryViewModel(resolve(), resolve()) }
register { ImageViewModel(resolve(), resolve()) }
register { VideoViewModel(resolve(), resolve()) }
register { ProfileViewModel(resolve(), resolve()) }
register { AddTagViewModel(resolve(), resolve()) }
register { MainViewModel(resolve(), resolve(), resolve(), resolve(), resolve(), resolve()) }
register { PostLikeViewModel(resolve(), resolve()) }
register { CreateCommentViewModel(resolve(), resolve(), resolve()) }
register { CommentsViewModel(resolve(), resolve(), resolve(), resolve()) }
register { DiskCache(resolve()) }
register { ImageService(resolve(), resolve(), resolve(), resolve()) }
registerSingleton<IDataContext> { OrmLiteDataContext(resolve()) }
register { Entities(resolve()) }
}
// ==========================================
// Private methods
// ==========================================
inline fun <reified T : Any> resolve(lifeCycleService: LifeCycleService): T {
register { lifeCycleService }
try {
return resolve()
} finally {
unregister(LifeCycleService::class)
}
}
inline fun <reified T : Any> resolve(): T {
return resolve(T::class)
}
@Suppress("UNCHECKED_CAST")
fun <T : Any> resolve(type: KClass<T>): T {
try {
return map[type]?.let { it() as T } ?: type.java.newInstance()
} catch (e: InstantiationException) {
throw IllegalArgumentException("Can't resolve type $type", e)
}
}
inline fun <reified T : Any> registerSingleton(noinline factory: () -> T) {
var singleton: T? = null
register(T::class, {
if (singleton == null) singleton = factory()
singleton!!
})
}
inline fun <reified T : Any> register(noinline factory: () -> T) {
register(T::class, factory)
}
fun <T : Any> register(type: KClass<T>, factory: () -> T) {
map[type] = factory
}
fun <T : Any> unregister(type: KClass<T>) {
map.remove(type)
}
}
|
gpl-2.0
|
f824744b40066bebcfa86e7235b258c6
| 40.55303 | 122 | 0.645332 | 4.663265 | false | false | false | false |
java-opengl-labs/learn-OpenGL
|
src/main/kotlin/learnOpenGL/common/Shader.kt
|
1
|
3241
|
package learnOpenGL.common
import org.lwjgl.opengl.GL11.GL_FALSE
import org.lwjgl.opengl.GL20.*
import java.io.File
import kotlin.reflect.KClass
/**
* Created by elect on 24/04/17.
*/
class Shader(root: String, vertexName: String, fragmentName: String) {
constructor(root: String, shader: String) : this(root, shader, shader)
val id: Int
init {
// 1. retrieve the vertex/fragment source code from filePath
val vShaderCode = readFile("$root/$vertexName.vert")
val fShaderCode = readFile("$root/$fragmentName.frag")
// 2. compile shaders
val vertex = glCreateShader(GL_VERTEX_SHADER)
glShaderSource(vertex, vShaderCode)
glCompileShader(vertex)
checkCompileErrors(vertex, "vertex")
// fragment Shader
val fragment = glCreateShader(GL_FRAGMENT_SHADER)
glShaderSource(fragment, fShaderCode)
glCompileShader(fragment)
checkCompileErrors(fragment, "fragment")
// shader Program
id = glCreateProgram()
glAttachShader(id, vertex)
glAttachShader(id, fragment)
glLinkProgram(id)
checkCompileErrors(id, "program")
// delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex)
glDeleteShader(fragment)
}
fun readFile(filePath: String) = File(javaClass.classLoader.getResource(filePath).toURI()).readText()
/** activate the shader */
fun use() = glUseProgram(id)
}
fun shaderOf(context: KClass<*>, root: String, shader: String) = shaderOf(context, root, shader, shader)
fun shaderOf(context: KClass<*>, root: String, vertexName: String, fragmentName: String): Int {
// 1. retrieve the vertex/fragment source code from filePath
val vShaderCode = readFile("$root/$vertexName.vert")
val fShaderCode = readFile("$root/$fragmentName.frag")
// 2. compile shaders
val vertex = glCreateShader(GL_VERTEX_SHADER)
glShaderSource(vertex, vShaderCode)
glCompileShader(vertex)
checkCompileErrors(vertex, "vertex")
// fragment Shader
val fragment = glCreateShader(GL_FRAGMENT_SHADER)
glShaderSource(fragment, fShaderCode)
glCompileShader(fragment)
checkCompileErrors(fragment, "fragment")
// shader Program
val id = glCreateProgram()
glAttachShader(id, vertex)
glAttachShader(id, fragment)
glLinkProgram(id)
checkCompileErrors(id, "program")
// delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex)
glDeleteShader(fragment)
return id
}
/** utility function for checking shader compilation/linking errors. */
fun checkCompileErrors(shader: Int, type: String) {
if (type != "program") {
if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) {
val infoLog = glGetShaderInfoLog(shader)
System.err.println("ERROR::SHADER_COMPILATION_ERROR of type: $type\n$infoLog")
}
} else {
if (glGetProgrami(shader, GL_LINK_STATUS) == GL_FALSE) {
val infoLog = glGetProgramInfoLog(shader)
System.err.println("ERROR::PROGRAM_LINKING_ERROR of type: $type\n$infoLog")
}
}
}
|
mit
|
5f815af03ca8e10eed34c9d9fbd1bfcc
| 31.42 | 105 | 0.676952 | 4.270092 | false | false | false | false |
wax911/AniTrendApp
|
app/src/main/java/com/mxt/anitrend/binding/RichMarkdownExtensions.kt
|
1
|
1503
|
package com.mxt.anitrend.binding
import android.text.Html
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.databinding.BindingAdapter
import com.mxt.anitrend.base.custom.view.text.RichMarkdownTextView
import com.mxt.anitrend.util.markdown.MarkDownUtil
import com.mxt.anitrend.util.markdown.RegexUtil
@BindingAdapter("markDown")
fun RichMarkdownTextView.markDown(markdown: String?) {
val strippedText = RegexUtil.removeTags(markdown)
val markdownSpan = MarkDownUtil.convert(strippedText)
setText(markdownSpan, TextView.BufferType.SPANNABLE)
}
@BindingAdapter("textHtml")
fun RichMarkdownTextView.htmlText(html: String?) {
val markdownSpan = MarkDownUtil.convert(html)
setText(markdownSpan, TextView.BufferType.SPANNABLE)
}
@BindingAdapter("basicHtml")
fun RichMarkdownTextView.basicText(html: String?) {
val htmlSpan = Html.fromHtml(html)
text = htmlSpan
}
@BindingAdapter("textHtml")
fun RichMarkdownTextView.htmlText(@StringRes resId: Int) {
val text = context.getString(resId)
val markdownSpan = MarkDownUtil.convert(text)
setText(markdownSpan, TextView.BufferType.SPANNABLE)
}
@BindingAdapter("richMarkDown")
fun RichMarkdownTextView.richMarkDown(markdown: String?) {
val tagsStripped = RegexUtil.removeTags(markdown)
val userTagsConverted = RegexUtil.findUserTags(tagsStripped)
val standardMarkdown = RegexUtil.convertToStandardMarkdown(userTagsConverted)
markwon.setMarkdown(this, standardMarkdown)
}
|
lgpl-3.0
|
c9bd18f00d94d18470ef8a0a058e6295
| 33.181818 | 81 | 0.800399 | 3.99734 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days
|
ProjectImagePuzzle/app/src/main/java/me/liuqingwen/android/projectimagepuzzle/Utils.kt
|
1
|
1203
|
package me.liuqingwen.android.projectimagepuzzle
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Rect
import java.io.InputStream
import kotlin.math.min
/**
* Created by Qingwen on 2018-2018-8-6, project: ProjectImagePuzzle.
*
* @Author: Qingwen
* @DateTime: 2018-8-6
* @Package: me.liuqingwen.android.projectimagepuzzle in project: ProjectImagePuzzle
*
* Notice: If you are using this class or file, check it and do some modification.
*/
fun sampleBitmapData(destWidth: Int, destHeight: Int, stream: InputStream): Bitmap?
{
if (destWidth <= 0 || destHeight <= 0)
{
return null
}
return stream.use {
val option = BitmapFactory.Options().apply { this.inJustDecodeBounds = true }
BitmapFactory.decodeStream(it, Rect(-1, -1, -1, -1), option)
val srcWidth = option.outWidth
val srcHeight = option.outHeight
val ratio = min(srcWidth / destWidth, srcHeight / destHeight)
it.reset()
with(option){
this.inJustDecodeBounds = false
this.inSampleSize = ratio
}
BitmapFactory.decodeStream(it, Rect(-1, -1, -1, -1), option)
}
}
|
mit
|
a7a45aae879babb4c6d8dff8b2f7fed7
| 29.1 | 85 | 0.669992 | 3.996678 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/ExtensionsPresenter.kt
|
1
|
8495
|
package eu.kanade.tachiyomi.ui.browse.extension
import android.app.Application
import androidx.annotation.StringRes
import eu.kanade.domain.extension.interactor.GetExtensionsByType
import eu.kanade.domain.source.service.SourcePreferences
import eu.kanade.presentation.browse.ExtensionState
import eu.kanade.presentation.browse.ExtensionsState
import eu.kanade.presentation.browse.ExtensionsStateImpl
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.extension.ExtensionManager
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.extension.model.InstallStep
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.system.LocaleHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import rx.Observable
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class ExtensionsPresenter(
private val presenterScope: CoroutineScope,
private val state: ExtensionsStateImpl = ExtensionState() as ExtensionsStateImpl,
private val preferences: SourcePreferences = Injekt.get(),
private val extensionManager: ExtensionManager = Injekt.get(),
private val getExtensions: GetExtensionsByType = Injekt.get(),
) : ExtensionsState by state {
private val _query: MutableStateFlow<String?> = MutableStateFlow(null)
val query: StateFlow<String?> = _query.asStateFlow()
private var _currentDownloads = MutableStateFlow<Map<String, InstallStep>>(hashMapOf())
fun onCreate() {
val context = Injekt.get<Application>()
val extensionMapper: (Map<String, InstallStep>) -> ((Extension) -> ExtensionUiModel) = { map ->
{
ExtensionUiModel.Item(it, map[it.pkgName] ?: InstallStep.Idle)
}
}
val queryFilter: (String) -> ((Extension) -> Boolean) = { query ->
filter@{ extension ->
if (query.isEmpty()) return@filter true
query.split(",").any { _input ->
val input = _input.trim()
if (input.isEmpty()) return@any false
when (extension) {
is Extension.Available -> {
extension.sources.any {
it.name.contains(input, ignoreCase = true) ||
it.baseUrl.contains(input, ignoreCase = true) ||
it.id == input.toLongOrNull()
} || extension.name.contains(input, ignoreCase = true)
}
is Extension.Installed -> {
extension.sources.any {
it.name.contains(input, ignoreCase = true) ||
it.id == input.toLongOrNull() ||
if (it is HttpSource) { it.baseUrl.contains(input, ignoreCase = true) } else false
} || extension.name.contains(input, ignoreCase = true)
}
is Extension.Untrusted -> extension.name.contains(input, ignoreCase = true)
}
}
}
}
presenterScope.launchIO {
combine(
_query,
_currentDownloads,
getExtensions.subscribe(),
) { query, downloads, (_updates, _installed, _available, _untrusted) ->
val searchQuery = query ?: ""
val languagesWithExtensions = _available
.filter(queryFilter(searchQuery))
.groupBy { LocaleHelper.getSourceDisplayName(it.lang, context) }
.toSortedMap()
.flatMap { (lang, exts) ->
listOf(
ExtensionUiModel.Header.Text(lang),
*exts.map(extensionMapper(downloads)).toTypedArray(),
)
}
val items = mutableListOf<ExtensionUiModel>()
val updates = _updates.filter(queryFilter(searchQuery)).map(extensionMapper(downloads))
if (updates.isNotEmpty()) {
items.add(ExtensionUiModel.Header.Resource(R.string.ext_updates_pending))
items.addAll(updates)
}
val installed = _installed.filter(queryFilter(searchQuery)).map(extensionMapper(downloads))
val untrusted = _untrusted.filter(queryFilter(searchQuery)).map(extensionMapper(downloads))
if (installed.isNotEmpty() || untrusted.isNotEmpty()) {
items.add(ExtensionUiModel.Header.Resource(R.string.ext_installed))
items.addAll(installed)
items.addAll(untrusted)
}
if (languagesWithExtensions.isNotEmpty()) {
items.addAll(languagesWithExtensions)
}
items
}
.debounce(500) // Avoid crashes due to LazyColumn rendering
.collectLatest {
state.isLoading = false
state.items = it
}
}
presenterScope.launchIO { findAvailableExtensions() }
preferences.extensionUpdatesCount().changes()
.onEach { state.updates = it }
.launchIn(presenterScope)
}
fun search(query: String?) {
presenterScope.launchIO {
_query.emit(query)
}
}
fun updateAllExtensions() {
presenterScope.launchIO {
if (state.isEmpty) return@launchIO
state.items
.mapNotNull {
when {
it !is ExtensionUiModel.Item -> null
it.extension !is Extension.Installed -> null
!it.extension.hasUpdate -> null
else -> it.extension
}
}
.forEach { updateExtension(it) }
}
}
fun installExtension(extension: Extension.Available) {
extensionManager.installExtension(extension).subscribeToInstallUpdate(extension)
}
fun updateExtension(extension: Extension.Installed) {
extensionManager.updateExtension(extension).subscribeToInstallUpdate(extension)
}
fun cancelInstallUpdateExtension(extension: Extension) {
extensionManager.cancelInstallUpdateExtension(extension)
}
private fun removeDownloadState(extension: Extension) {
_currentDownloads.update { _map ->
val map = _map.toMutableMap()
map.remove(extension.pkgName)
map
}
}
private fun addDownloadState(extension: Extension, installStep: InstallStep) {
_currentDownloads.update { _map ->
val map = _map.toMutableMap()
map[extension.pkgName] = installStep
map
}
}
private fun Observable<InstallStep>.subscribeToInstallUpdate(extension: Extension) {
this
.doOnUnsubscribe { removeDownloadState(extension) }
.subscribe(
{ installStep -> addDownloadState(extension, installStep) },
{ removeDownloadState(extension) },
)
}
fun uninstallExtension(pkgName: String) {
extensionManager.uninstallExtension(pkgName)
}
fun findAvailableExtensions() {
presenterScope.launchIO {
state.isRefreshing = true
extensionManager.findAvailableExtensions()
state.isRefreshing = false
}
}
fun trustSignature(signatureHash: String) {
extensionManager.trustSignature(signatureHash)
}
}
sealed interface ExtensionUiModel {
sealed interface Header : ExtensionUiModel {
data class Resource(@StringRes val textRes: Int) : Header
data class Text(val text: String) : Header
}
data class Item(
val extension: Extension,
val installStep: InstallStep,
) : ExtensionUiModel
}
|
apache-2.0
|
fdd6b9a95687c5e2af206c1c3ed0da6e
| 37.789954 | 118 | 0.592702 | 5.31602 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/domain/source/service/SourcePreferences.kt
|
1
|
1694
|
package eu.kanade.domain.source.service
import eu.kanade.domain.library.model.LibraryDisplayMode
import eu.kanade.domain.source.interactor.SetMigrateSorting
import eu.kanade.tachiyomi.core.preference.PreferenceStore
import eu.kanade.tachiyomi.core.preference.getEnum
import eu.kanade.tachiyomi.util.system.LocaleHelper
class SourcePreferences(
private val preferenceStore: PreferenceStore,
) {
fun sourceDisplayMode() = preferenceStore.getObject("pref_display_mode_catalogue", LibraryDisplayMode.default, LibraryDisplayMode.Serializer::serialize, LibraryDisplayMode.Serializer::deserialize)
fun enabledLanguages() = preferenceStore.getStringSet("source_languages", LocaleHelper.getDefaultEnabledLanguages())
fun disabledSources() = preferenceStore.getStringSet("hidden_catalogues", emptySet())
fun pinnedSources() = preferenceStore.getStringSet("pinned_catalogues", emptySet())
fun duplicatePinnedSources() = preferenceStore.getBoolean("duplicate_pinned_sources", false)
fun lastUsedSource() = preferenceStore.getLong("last_catalogue_source", -1)
fun showNsfwSource() = preferenceStore.getBoolean("show_nsfw_source", true)
fun migrationSortingMode() = preferenceStore.getEnum("pref_migration_sorting", SetMigrateSorting.Mode.ALPHABETICAL)
fun migrationSortingDirection() = preferenceStore.getEnum("pref_migration_direction", SetMigrateSorting.Direction.ASCENDING)
fun extensionUpdatesCount() = preferenceStore.getInt("ext_updates_count", 0)
fun trustedSignatures() = preferenceStore.getStringSet("trusted_signatures", emptySet())
fun searchPinnedSourcesOnly() = preferenceStore.getBoolean("search_pinned_sources_only", false)
}
|
apache-2.0
|
19d84eca3498a8243616972e1a996f05
| 46.055556 | 200 | 0.801063 | 4.653846 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/presentation/browse/SourcesScreen.kt
|
1
|
8109
|
package eu.kanade.presentation.browse
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PushPin
import androidx.compose.material.icons.outlined.PushPin
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.kanade.domain.source.interactor.GetRemoteManga
import eu.kanade.domain.source.model.Pin
import eu.kanade.domain.source.model.Source
import eu.kanade.presentation.browse.components.BaseSourceItem
import eu.kanade.presentation.components.EmptyScreen
import eu.kanade.presentation.components.LoadingScreen
import eu.kanade.presentation.components.ScrollbarLazyColumn
import eu.kanade.presentation.theme.header
import eu.kanade.presentation.util.horizontalPadding
import eu.kanade.presentation.util.plus
import eu.kanade.presentation.util.topPaddingValues
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.ui.browse.source.SourcesPresenter
import eu.kanade.tachiyomi.util.system.LocaleHelper
import eu.kanade.tachiyomi.util.system.toast
import kotlinx.coroutines.flow.collectLatest
@Composable
fun SourcesScreen(
presenter: SourcesPresenter,
contentPadding: PaddingValues,
onClickItem: (Source, String) -> Unit,
onClickDisable: (Source) -> Unit,
onClickPin: (Source) -> Unit,
) {
val context = LocalContext.current
when {
presenter.isLoading -> LoadingScreen()
presenter.isEmpty -> EmptyScreen(
textResource = R.string.source_empty_screen,
modifier = Modifier.padding(contentPadding),
)
else -> {
SourceList(
state = presenter,
contentPadding = contentPadding,
onClickItem = onClickItem,
onClickDisable = onClickDisable,
onClickPin = onClickPin,
)
}
}
LaunchedEffect(Unit) {
presenter.events.collectLatest { event ->
when (event) {
SourcesPresenter.Event.FailedFetchingSources -> {
context.toast(R.string.internal_error)
}
}
}
}
}
@Composable
private fun SourceList(
state: SourcesState,
contentPadding: PaddingValues,
onClickItem: (Source, String) -> Unit,
onClickDisable: (Source) -> Unit,
onClickPin: (Source) -> Unit,
) {
ScrollbarLazyColumn(
contentPadding = contentPadding + topPaddingValues,
) {
items(
items = state.items,
contentType = {
when (it) {
is SourceUiModel.Header -> "header"
is SourceUiModel.Item -> "item"
}
},
key = {
when (it) {
is SourceUiModel.Header -> it.hashCode()
is SourceUiModel.Item -> "source-${it.source.key()}"
}
},
) { model ->
when (model) {
is SourceUiModel.Header -> {
SourceHeader(
modifier = Modifier.animateItemPlacement(),
language = model.language,
)
}
is SourceUiModel.Item -> SourceItem(
modifier = Modifier.animateItemPlacement(),
source = model.source,
onClickItem = onClickItem,
onLongClickItem = { state.dialog = SourcesPresenter.Dialog(it) },
onClickPin = onClickPin,
)
}
}
}
if (state.dialog != null) {
val source = state.dialog!!.source
SourceOptionsDialog(
source = source,
onClickPin = {
onClickPin(source)
state.dialog = null
},
onClickDisable = {
onClickDisable(source)
state.dialog = null
},
onDismiss = { state.dialog = null },
)
}
}
@Composable
private fun SourceHeader(
modifier: Modifier = Modifier,
language: String,
) {
val context = LocalContext.current
Text(
text = LocaleHelper.getSourceDisplayName(language, context),
modifier = modifier
.padding(horizontal = horizontalPadding, vertical = 8.dp),
style = MaterialTheme.typography.header,
)
}
@Composable
private fun SourceItem(
modifier: Modifier = Modifier,
source: Source,
onClickItem: (Source, String) -> Unit,
onLongClickItem: (Source) -> Unit,
onClickPin: (Source) -> Unit,
) {
BaseSourceItem(
modifier = modifier,
source = source,
onClickItem = { onClickItem(source, GetRemoteManga.QUERY_POPULAR) },
onLongClickItem = { onLongClickItem(source) },
action = {
if (source.supportsLatest) {
TextButton(onClick = { onClickItem(source, GetRemoteManga.QUERY_LATEST) }) {
Text(
text = stringResource(R.string.latest),
style = LocalTextStyle.current.copy(
color = MaterialTheme.colorScheme.primary,
),
)
}
}
SourcePinButton(
isPinned = Pin.Pinned in source.pin,
onClick = { onClickPin(source) },
)
},
)
}
@Composable
private fun SourcePinButton(
isPinned: Boolean,
onClick: () -> Unit,
) {
val icon = if (isPinned) Icons.Filled.PushPin else Icons.Outlined.PushPin
val tint = if (isPinned) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onBackground
val description = if (isPinned) R.string.action_unpin else R.string.action_pin
IconButton(onClick = onClick) {
Icon(
imageVector = icon,
tint = tint,
contentDescription = stringResource(description),
)
}
}
@Composable
private fun SourceOptionsDialog(
source: Source,
onClickPin: () -> Unit,
onClickDisable: () -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
title = {
Text(text = source.visualName)
},
text = {
Column {
val textId = if (Pin.Pinned in source.pin) R.string.action_unpin else R.string.action_pin
Text(
text = stringResource(textId),
modifier = Modifier
.clickable(onClick = onClickPin)
.fillMaxWidth()
.padding(vertical = 16.dp),
)
if (source.id != LocalSource.ID) {
Text(
text = stringResource(R.string.action_disable),
modifier = Modifier
.clickable(onClick = onClickDisable)
.fillMaxWidth()
.padding(vertical = 16.dp),
)
}
}
},
onDismissRequest = onDismiss,
confirmButton = {},
)
}
sealed class SourceUiModel {
data class Item(val source: Source) : SourceUiModel()
data class Header(val language: String) : SourceUiModel()
}
|
apache-2.0
|
4bfe3a36f4f160076d51a98d3888f42c
| 32.37037 | 106 | 0.594155 | 4.90266 | false | false | false | false |
GKZX-HN/MyGithub
|
app/src/main/java/com/gkzxhn/mygithub/ui/fragment/HomeFragment.kt
|
1
|
9425
|
package com.gkzxhn.mygithub.ui.fragment
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.gkzxhn.balabala.base.BaseFragment
import com.gkzxhn.balabala.mvp.contract.BaseView
import com.gkzxhn.mygithub.R
import com.gkzxhn.mygithub.base.App
import com.gkzxhn.mygithub.bean.entity.Icon2Name
import com.gkzxhn.mygithub.bean.info.*
import com.gkzxhn.mygithub.constant.IntentConstant
import com.gkzxhn.mygithub.constant.SharedPreConstant
import com.gkzxhn.mygithub.di.module.OAuthModule
import com.gkzxhn.mygithub.extension.base64Decode2List
import com.gkzxhn.mygithub.extension.base64Encode
import com.gkzxhn.mygithub.extension.getSharedPreference
import com.gkzxhn.mygithub.extension.load
import com.gkzxhn.mygithub.mvp.presenter.HomePresenter
import com.gkzxhn.mygithub.ui.activity.*
import com.gkzxhn.mygithub.ui.adapter.AvatarListAdapter
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import com.youth.banner.loader.ImageLoader
import kotlinx.android.synthetic.main.fragment_home.*
import javax.inject.Inject
/**
* Created by 方 on 2017/10/19.
*/
class HomeFragment : BaseFragment(), BaseView {
private var trendingRepoList = arrayListOf<ItemBean>()
private var popRepoList = arrayListOf<Repo>()
private lateinit var repoWeekAdapter: AvatarListAdapter
private lateinit var popRepoAdapter: AvatarListAdapter
private lateinit var popUsersAdapter: AvatarListAdapter
@Inject lateinit var presenter: HomePresenter
override fun launchActivity(intent: Intent) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun showLoading() {
}
override fun hideLoading() {
}
override fun showMessage() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun killMyself() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun initContentView() {
setClickListener()
setRecyclerView()
presenter.getPopularUser()
val list = SharedPreConstant.USER_SP
.getSharedPreference()
.getString(SharedPreConstant.FOCUS_LANGUAGE, SharedPreConstant.DEFAULT_LANGUAGES.base64Encode())
.base64Decode2List() as List<String>
val language = if(list.isNotEmpty()) list[0] else "all"
presenter.getReposByLanguage(language)
// presenter.getTrendingUser()
presenter.getTrendingRepo()
presenter.getBanner()
}
private fun setRecyclerView() {
rv_repo_week.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
repoWeekAdapter = AvatarListAdapter(null)
rv_repo_week.adapter = repoWeekAdapter
rv_pop_repo.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
popRepoAdapter = AvatarListAdapter(null)
rv_pop_repo.adapter = popRepoAdapter
rv_pop_users.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
popUsersAdapter = AvatarListAdapter(null)
rv_pop_users.adapter = popUsersAdapter
}
private fun setClickListener() {
ll_search.setOnClickListener {
startActivity(Intent(context, SearchActivity::class.java))
}
ll_see_all1.setOnClickListener {
val data = Bundle()
data.putParcelableArrayList(IntentConstant.REPO_ENTITIES, trendingRepoList)
val intent = Intent(context, RepoListActivity::class.java)
intent.putExtra(IntentConstant.TOOLBAR_TITLE, "仓库周榜")
intent.putExtras(data)
intent.action = IntentConstant.TRENDING_REPO
startActivity(intent)
}
ll_see_all2.setOnClickListener {
val data = Bundle()
data.putParcelableArrayList(IntentConstant.REPO_ENTITIES, popRepoList)
val intent = Intent(context, PopReposActivity::class.java)
intent.putExtra(IntentConstant.TOOLBAR_TITLE, "仓库流行榜")
intent.putExtras(data)
intent.action = IntentConstant.POP_REPO
startActivity(intent)
}
ll_see_all3.setOnClickListener {
val data = Bundle()
data.putParcelableArrayList(IntentConstant.USERS, popUsersAdapter.data as ArrayList)
val intent = Intent(context, RepoListActivity::class.java)
intent.putExtras(data)
intent.putExtra(IntentConstant.TOOLBAR_TITLE, "大牛榜")
intent.action = IntentConstant.USERS
startActivity(intent)
}
}
override fun getStatusBar(): View? {
return status_view
}
override fun getToolbar(): Toolbar? {
return toolbar
}
override fun setupComponent() {
val baseComponent = App.getInstance()
.baseComponent
baseComponent
.plus(OAuthModule(this))
.inject(this)
}
override fun initView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater!!.inflate(R.layout.fragment_home, container, false)
}
fun loadRepoWeek(result: TrendingResults) {
trendingRepoList = result.items as ArrayList<ItemBean>
val list = result.items
.map { trendingItem ->
return@map Icon2Name(trendingItem.avatars[0].replace("s=40", "s=80"),
trendingItem.repo.let { return@let it.substring(it.indexOf("/") + 1) },
"repo")
}
repoWeekAdapter.setNewData(list)
repoWeekAdapter.setOnItemClickListener { adapter, view, position ->
val fullName = result.items[position].repo
val intent = Intent(context, RepoDetailActivity::class.java)
intent.putExtra(IntentConstant.FULL_NAME, fullName)
startActivity(intent)
}
}
fun loadPopUsers(result: SearchUserResult) {
val list = result.items
.map { item ->
return@map Icon2Name(item.avatar_url, item.login, "user")
}
popUsersAdapter.setNewData(list)
popUsersAdapter.setOnItemClickListener { adapter, view, position ->
val user = adapter.data[position] as Parcelable
val intent = Intent(context, UserActivity::class.java)
val bundle = Bundle()
bundle.putParcelable(IntentConstant.USER, user)
intent.putExtras(bundle)
startActivity(intent)
}
}
fun loadPopRepos(result: SearchRepoResult) {
popRepoList = result.items
val list = result.items
.map { item ->
return@map Icon2Name(item.owner.avatar_url, item.name, "user")
}
popRepoAdapter.setNewData(list)
popRepoAdapter.setOnItemClickListener { adapter, view, position ->
val repo = result.items[position]
val intent = Intent(context, RepoDetailActivity::class.java)
val bundle = Bundle()
bundle.putParcelable(IntentConstant.REPO, repo)
intent.putExtras(bundle)
startActivity(intent)
}
}
fun setBanner(srcList: List<Icon2Name>) {
//设置banner样式
banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE)
//设置图片加载器
banner.setImageLoader(GlideImageLoader())
//设置图片集合
banner.setImages(srcList)
//设置banner动画效果
banner.setBannerAnimation(Transformer.ScaleInOut)
//设置标题集合(当banner样式有显示title时)
banner.setBannerTitles(srcList.map { it.name })
//设置自动轮播,默认为true
banner.isAutoPlay(true)
//设置轮播时间
banner.setDelayTime(4000)
//设置指示器位置(当banner模式中有指示器时)
banner.setIndicatorGravity(BannerConfig.CENTER)
//banner设置方法全部调用完毕时最后调用
banner.start()
}
}
class GlideImageLoader : ImageLoader() {
override fun displayImage(context: Context, path: Any, imageView: ImageView) {
/**
注意:
1.图片加载器由自己选择,这里不限制,只是提供几种使用方法
2.返回的图片路径为Object类型,由于不能确定你到底使用的那种图片加载器,
传输的到的是什么格式,那么这种就使用Object接收和返回,你只需要强转成你传输的类型就行,
切记不要胡乱强转!
*/
imageView.load(context, (path as Icon2Name).avatarUrl!!)
imageView.setOnClickListener {
val intent = Intent(context, WebViewActivity::class.java)
intent.putExtra(IntentConstant.LINK, path.type)
intent.putExtra(IntentConstant.TITLE, path.name)
context.startActivity(intent)
}
}
}
|
gpl-3.0
|
9441ecee5e5a2c2c070f92d587fa3543
| 36.061728 | 112 | 0.666852 | 4.407734 | false | false | false | false |
exponentjs/exponent
|
packages/expo-device/android/src/main/java/expo/modules/device/DeviceModule.kt
|
2
|
6254
|
package expo.modules.device
import expo.modules.core.ExportedModule
import expo.modules.core.Promise
import expo.modules.core.interfaces.ExpoMethod
import com.facebook.device.yearclass.YearClass
import android.app.ActivityManager
import android.app.UiModeManager
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.SystemClock
import android.provider.Settings
import android.view.WindowManager
import android.util.DisplayMetrics
import java.io.File
import kotlin.math.pow
import kotlin.math.sqrt
private const val NAME = "ExpoDevice"
class DeviceModule(private val mContext: Context) : ExportedModule(mContext) {
// Keep this enum in sync with JavaScript
enum class DeviceType(val JSValue: Int) {
UNKNOWN(0),
PHONE(1),
TABLET(2),
DESKTOP(3),
TV(4);
}
override fun getName(): String {
return NAME
}
override fun getConstants(): Map<String, Any> = mapOf(
"isDevice" to (!isRunningOnGenymotion && !isRunningOnStockEmulator),
"brand" to Build.BRAND,
"manufacturer" to Build.MANUFACTURER,
"modelName" to Build.MODEL,
"designName" to Build.DEVICE,
"productName" to Build.DEVICE,
"deviceYearClass" to deviceYearClass,
"totalMemory" to run {
val memoryInfo = ActivityManager.MemoryInfo()
(mContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
memoryInfo.totalMem
},
"supportedCpuArchitectures" to run {
var supportedAbis = Build.SUPPORTED_ABIS
if (supportedAbis != null && supportedAbis.isEmpty()) {
supportedAbis = null
}
supportedAbis
},
"osName" to systemName,
"osVersion" to Build.VERSION.RELEASE,
"osBuildId" to Build.DISPLAY,
"osInternalBuildId" to Build.ID,
"osBuildFingerprint" to Build.FINGERPRINT,
"platformApiLevel" to Build.VERSION.SDK_INT,
"deviceName" to Settings.Secure.getString(mContext.contentResolver, "bluetooth_name")
)
private val deviceYearClass: Int
get() = YearClass.get(mContext)
private val systemName: String
get() {
return if (Build.VERSION.SDK_INT < 23) {
"Android"
} else {
Build.VERSION.BASE_OS.takeIf { it.isNotEmpty() } ?: "Android"
}
}
@ExpoMethod
fun getDeviceTypeAsync(promise: Promise) {
promise.resolve(getDeviceType(mContext).JSValue)
}
@ExpoMethod
fun getUptimeAsync(promise: Promise) {
promise.resolve(SystemClock.uptimeMillis().toDouble())
}
@ExpoMethod
fun getMaxMemoryAsync(promise: Promise) {
val maxMemory = Runtime.getRuntime().maxMemory()
promise.resolve(if (maxMemory != Long.MAX_VALUE) maxMemory.toDouble() else -1)
}
@ExpoMethod
fun isRootedExperimentalAsync(promise: Promise) {
var isRooted = false
val isDevice = !isRunningOnGenymotion && !isRunningOnStockEmulator
try {
val buildTags = Build.TAGS
isRooted = if (isDevice && buildTags != null && buildTags.contains("test-keys")) {
true
} else {
if (File("/system/app/Superuser.apk").exists()) {
true
} else {
isDevice && File("/system/xbin/su").exists()
}
}
} catch (se: SecurityException) {
promise.reject(
"ERR_DEVICE_ROOT_DETECTION",
"Could not access the file system to determine if the device is rooted.",
se
)
return
}
promise.resolve(isRooted)
}
@ExpoMethod
fun isSideLoadingEnabledAsync(promise: Promise) {
val enabled: Boolean = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
Settings.Global.getInt(
mContext.applicationContext.contentResolver,
Settings.Global.INSTALL_NON_MARKET_APPS,
0
) == 1
} else {
mContext.applicationContext.packageManager.canRequestPackageInstalls()
}
promise.resolve(enabled)
}
@ExpoMethod
fun getPlatformFeaturesAsync(promise: Promise) {
val allFeatures = mContext.applicationContext.packageManager.systemAvailableFeatures
val featureList = allFeatures.filterNotNull().map { it.name }
promise.resolve(featureList)
}
@ExpoMethod
fun hasPlatformFeatureAsync(feature: String, promise: Promise) {
promise.resolve(mContext.applicationContext.packageManager.hasSystemFeature(feature))
}
companion object {
private val TAG = DeviceModule::class.java.simpleName
private val isRunningOnGenymotion: Boolean
get() = Build.FINGERPRINT.contains("vbox")
private val isRunningOnStockEmulator: Boolean
get() = Build.FINGERPRINT.contains("generic")
private fun getDeviceType(context: Context): DeviceType {
// Detect TVs via UI mode (Android TVs) or system features (Fire TV).
if (context.applicationContext.packageManager.hasSystemFeature("amazon.hardware.fire_tv")) {
return DeviceType.TV
}
val uiManager = context.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager?
if (uiManager != null && uiManager.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION) {
return DeviceType.TV
}
// Find the current window manager, if none is found we can't measure the device physical size.
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager? ?: return DeviceType.UNKNOWN
// Get display metrics to see if we can differentiate phones and tablets.
val metrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metrics)
// Calculate physical size.
val widthInches = metrics.widthPixels / metrics.xdpi.toDouble()
val heightInches = metrics.heightPixels / metrics.ydpi.toDouble()
val diagonalSizeInches = sqrt(widthInches.pow(2.0) + heightInches.pow(2.0))
return if (diagonalSizeInches >= 3.0 && diagonalSizeInches <= 6.9) {
// Devices in a sane range for phones are considered to be phones.
DeviceType.PHONE
} else if (diagonalSizeInches > 6.9 && diagonalSizeInches <= 18.0) {
// Devices larger than a phone and in a sane range for tablets are tablets.
DeviceType.TABLET
} else {
// Otherwise, we don't know what device type we're on.
DeviceType.UNKNOWN
}
}
}
}
|
bsd-3-clause
|
aafbff88a1f091478daf18513869e43a
| 31.404145 | 121 | 0.695395 | 4.186078 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinInlayHintToggleAction.kt
|
2
|
4491
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.hints
import com.intellij.codeInsight.hints.*
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.util.IntentionName
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@Suppress("IntentionDescriptionNotFoundInspection")
class KotlinInlayHintToggleAction : IntentionAction, HighPriorityAction {
private val hintTypes = arrayOf(
HintType.RANGES,
HintType.PROPERTY_HINT,
HintType.LOCAL_VARIABLE_HINT,
HintType.FUNCTION_HINT,
HintType.PARAMETER_TYPE_HINT,
HintType.PARAMETER_HINT,
HintType.LAMBDA_RETURN_EXPRESSION,
HintType.LAMBDA_IMPLICIT_PARAMETER_RECEIVER,
HintType.SUSPENDING_CALL,
)
@IntentionName
private var lastOptionName = ""
override fun getText(): String = lastOptionName
override fun getFamilyName(): String = KotlinBundle.message("hints.types")
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean {
lastOptionName = ""
var element = findElement(editor, file)
while (element != null) {
for (hintType in hintTypes) {
if (!hintType.isApplicable(element)) continue
findSetting(hintType, project)?.let {
val enabled = it.second.isEnabled(hintType)
lastOptionName = if (enabled) hintType.hideDescription else hintType.showDescription
return true
}
}
element = element.parent
}
return false
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
var element = findElement(editor, file)
while(element != null) {
for (hintType in hintTypes) {
if (toggleHintSetting(hintType, project, element)) return
}
element = element.parent
}
}
private fun findElement(editor: Editor, file: PsiFile): PsiElement? {
val ktFile = file as? KtFile ?: return null
val offset = editor.caretModel.offset
return ktFile.findElementAt(offset - 1)
}
override fun startInWriteAction(): Boolean = false
}
internal fun toggleHintSetting(
hintType: HintType,
project: Project,
element: PsiElement,
state: (KotlinAbstractHintsProvider.HintsSettings) -> Boolean = { setting -> !setting.isEnabled(hintType) }
): Boolean {
if (!hintType.isApplicable(element)) return false
val hintsSettings = InlayHintsSettings.instance()
return findSetting(hintType, project, hintsSettings)?.let {
val settingsKey = it.first
val settings = it.second
val enable = state(settings)
val language = KotlinLanguage.INSTANCE
if (enable) {
InlayHintsSettings.instance().changeHintTypeStatus(settingsKey, language, true)
}
settings.enable(hintType, enable)
hintsSettings.storeSettings(settingsKey, language, settings)
refreshHints()
true
} ?: false
}
private fun findSetting(hintType: HintType, project: Project, hintsSettings: InlayHintsSettings = InlayHintsSettings.instance()):
Pair<SettingsKey<KotlinAbstractHintsProvider.HintsSettings>, KotlinAbstractHintsProvider.HintsSettings>? {
val language = KotlinLanguage.INSTANCE
val providerInfos =
InlayHintsProviderFactory.EP.extensionList
.flatMap { it.getProvidersInfo(project) }
.filter { it.language == language }
val provider = providerInfos
.firstOrNull {
val hintsProvider = it.provider as? KotlinAbstractHintsProvider ?: return@firstOrNull false
hintsProvider.isHintSupported(hintType)
}
?.provider?.safeAs<KotlinAbstractHintsProvider<KotlinAbstractHintsProvider.HintsSettings>>() ?: return null
val settingsKey = provider.key
return settingsKey to hintsSettings.findSettings(settingsKey, language, provider::createSettings)
}
|
apache-2.0
|
cd889f93c799c23fa46cc029226c690e
| 38.752212 | 129 | 0.693387 | 4.978936 | false | false | false | false |
PolymerLabs/arcs
|
java/arcs/core/storage/referencemode/BridgingOperation.kt
|
1
|
8071
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage.referencemode
import arcs.core.common.ReferenceId
import arcs.core.crdt.CrdtException
import arcs.core.crdt.CrdtOperation
import arcs.core.crdt.CrdtSet
import arcs.core.crdt.CrdtSingleton
import arcs.core.crdt.VersionMap
import arcs.core.data.RawEntity
import arcs.core.storage.RawReference
import arcs.core.storage.StorageKey
import arcs.core.storage.referencemode.BridgingOperation.AddToSet
import arcs.core.storage.referencemode.BridgingOperation.ClearSet
import arcs.core.storage.referencemode.BridgingOperation.ClearSingleton
import arcs.core.storage.referencemode.BridgingOperation.RemoveFromSet
import arcs.core.storage.referencemode.BridgingOperation.UpdateSingleton
import arcs.core.storage.toReference
/**
* Represents a bridge between the [CrdtSet]/[CrdtSingleton]'s operations from the
* [arcs.storage.ReferenceModeStore]'s `containerStore` with the client's expected
* [RefModeStoreOp]s.
*
* When the [arcs.storage.ReferenceModeStore] handles communication between external storage proxies
* and the internal containerStore, this class (and its subclasses) is used as a translation medium.
*/
sealed class BridgingOperation : CrdtOperation {
abstract val entityValue: RawEntity?
/** Represents a value added/removed from a [CrdtSet] or configured for a [CrdtSingleton]. */
abstract val referenceValue: RawReference?
/** The actual [CrdtSet] or [CrdtSingleton] operation. */
abstract val containerOp: CrdtOperation
/** The operation sent to the [arcs.storage.ReferenceModeStore]. */
abstract val refModeOp: RefModeStoreOp
/** Denotes an update to the [CrdtSingleton] managed by the store. */
data class UpdateSingleton /* internal */ constructor(
override val entityValue: RawEntity?,
override val referenceValue: RawReference?,
override val containerOp: CrdtSingleton.Operation.Update<RawReference>,
override val refModeOp: RefModeStoreOp.SingletonUpdate
) : BridgingOperation() {
override val versionMap: VersionMap = containerOp.versionMap
}
/** Denotes a clearing of the [CrdtSingleton] managed by the store. */
data class ClearSingleton /* internal */ constructor(
override val containerOp: CrdtSingleton.Operation.Clear<RawReference>,
override val refModeOp: RefModeStoreOp.SingletonClear
) : BridgingOperation() {
override val entityValue: RawEntity? = null
override val referenceValue: RawReference? = null
override val versionMap: VersionMap = containerOp.versionMap
}
/** Denotes an addition to the [CrdtSet] managed by the store. */
class AddToSet /* internal */ constructor(
override val entityValue: RawEntity?,
override val referenceValue: RawReference?,
override val containerOp: CrdtSet.Operation.Add<RawReference>,
override val refModeOp: RefModeStoreOp.SetAdd
) : BridgingOperation() {
override val versionMap: VersionMap = containerOp.versionMap
}
/** Denotes a removal from the [CrdtSet] managed by the store. */
class RemoveFromSet /* internal */ constructor(
val referenceId: ReferenceId,
override val containerOp: CrdtSet.Operation.Remove<RawReference>,
override val refModeOp: RefModeStoreOp.SetRemove
) : BridgingOperation() {
override val entityValue: RawEntity? = null
override val referenceValue: RawReference? = null
override val versionMap: VersionMap = containerOp.versionMap
}
/** Denotes a clear of the [CrdtSet] managed by the store. */
class ClearSet /* internal */ constructor(
override val containerOp: CrdtSet.Operation.Clear<RawReference>,
override val refModeOp: RefModeStoreOp.SetClear
) : BridgingOperation() {
override val entityValue: RawEntity? = null
override val referenceValue: RawReference? = null
override val versionMap: VersionMap = containerOp.versionMap
}
}
/**
* Converts a [List] of [CrdtOperation]s to a [List] of [BridgingOperation]s.
*
* Since [arcs.storage.ReferenceModeStore] only supports operations on [CrdtSingleton]s or
* [CrdtSet]s, this method will throw [CrdtException] if any member of the list is not one of those
* types of [CrdtOperation]s.
*/
suspend fun List<RefModeStoreOp>.toBridgingOps(
backingStorageKey: StorageKey,
// Callback which returns the version of the data being referenced from the backing store.
itemVersionGetter: suspend (RawEntity) -> VersionMap
): List<BridgingOperation> {
return map { it.toBridgingOp(backingStorageKey, itemVersionGetter) }
}
/**
* Converts a [CrdtOperation] from some referencable-typed operation to [BridgingOperation]
* using the provided [value] as the full data referenced in the [CrdtSet]/[CrdtSingleton].
*/
@Suppress("UNCHECKED_CAST")
fun CrdtOperation.toBridgingOp(value: RawEntity?): BridgingOperation =
when (this) {
is CrdtSet.Operation<*> ->
(this as CrdtSet.Operation<RawReference>).setToBridgingOp(value)
is CrdtSingleton.Operation<*> ->
(this as CrdtSingleton.Operation<RawReference>).singletonToBridgingOp(value)
else -> throw CrdtException("Unsupported raw entity operation")
}
/**
* Bridges the gap between a [RefModeStoreOp] and the appropriate [RawReference]-based collection
* operation.
*/
suspend fun RefModeStoreOp.toBridgingOp(
backingStorageKey: StorageKey,
// Callback which returns the version of the data being referenced from the acking store.
itemVersionGetter: suspend (RawEntity) -> VersionMap
): BridgingOperation {
return when (this) {
is RefModeStoreOp.SingletonUpdate -> {
val reference = value.toReference(backingStorageKey, itemVersionGetter(value))
UpdateSingleton(
value, reference, CrdtSingleton.Operation.Update(actor, versionMap, reference), this
)
}
is RefModeStoreOp.SingletonClear -> {
ClearSingleton(CrdtSingleton.Operation.Clear(actor, versionMap), this)
}
is RefModeStoreOp.SetAdd -> {
val reference = added.toReference(backingStorageKey, itemVersionGetter(added))
AddToSet(added, reference, CrdtSet.Operation.Add(actor, versionMap, reference), this)
}
is RefModeStoreOp.SetRemove -> {
RemoveFromSet(removed, CrdtSet.Operation.Remove(actor, versionMap, removed), this)
}
is RefModeStoreOp.SetClear -> {
ClearSet(CrdtSet.Operation.Clear(actor, versionMap), this)
}
else -> throw CrdtException("Unsupported operation: $this")
}
}
/**
* Bridges the gap between a [RawReference]-based [CrdtSingleton.Operation] and a [RefModeStoreOp],
* using the provided [newValue] as the [RawEntity].
*/
private fun CrdtSet.Operation<RawReference>.setToBridgingOp(
newValue: RawEntity?
): BridgingOperation = when (this) {
is CrdtSet.Operation.Add ->
AddToSet(
newValue,
added,
this,
RefModeStoreOp.SetAdd(actor, versionMap, requireNotNull(newValue))
)
is CrdtSet.Operation.Remove ->
RemoveFromSet(
removed,
this,
RefModeStoreOp.SetRemove(actor, versionMap, removed)
)
is CrdtSet.Operation.Clear -> ClearSet(this, RefModeStoreOp.SetClear(actor, versionMap))
is CrdtSet.Operation.FastForward ->
throw CrdtException("Unsupported reference-mode operation: FastForward.")
}
/**
* Bridges the gap between a [RawReference]-based [CrdtSingleton.Operation] and a [RefModeStoreOp],
* using the provided [newValue] as the [RawEntity].
*/
private fun CrdtSingleton.Operation<RawReference>.singletonToBridgingOp(
newValue: RawEntity?
): BridgingOperation = when (this) {
is CrdtSingleton.Operation.Update ->
UpdateSingleton(
newValue,
value,
this,
RefModeStoreOp.SingletonUpdate(actor, versionMap, requireNotNull(newValue))
)
is CrdtSingleton.Operation.Clear ->
ClearSingleton(this, RefModeStoreOp.SingletonClear(actor, versionMap))
}
|
bsd-3-clause
|
268997a176217e947a8cdcb7f77f2529
| 38.370732 | 100 | 0.751084 | 4.348599 | false | false | false | false |
android/connectivity-samples
|
CrossDeviceRockPaperScissorsKotlin/app/src/main/java/com/google/crossdevice/sample/rps/model/CodenameGenerator.kt
|
1
|
1786
|
/*
* Copyright 2022 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 com.google.crossdevice.sample.rps.model
import java.util.Random
/** Utility class to generate random Android names */
object CodenameGenerator {
private val COLORS =
arrayOf(
"Red",
"Orange",
"Yellow",
"Green",
"Blue",
"Indigo",
"Violet",
"Purple",
"Lavender",
"Fuchsia",
"Plum",
"Orchid",
"Magenta"
)
private val TREATS =
arrayOf(
"Alpha",
"Beta",
"Cupcake",
"Donut",
"Eclair",
"Froyo",
"Gingerbread",
"Honeycomb",
"Ice Cream Sandwich",
"Jellybean",
"Kit Kat",
"Lollipop",
"Marshmallow",
"Nougat",
"Oreo",
"Pie"
)
private val generator = Random()
/** Generate a random Android agent codename */
fun generate(): String {
val color = COLORS[generator.nextInt(COLORS.size)]
val treat = TREATS[generator.nextInt(TREATS.size)]
return "$color $treat"
}
}
|
apache-2.0
|
6cdc78d4de74491aac24ad53b31fa433
| 25.279412 | 75 | 0.543113 | 4.388206 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/sitecreation/misc/SiteCreationSource.kt
|
1
|
858
|
package org.wordpress.android.ui.sitecreation.misc
enum class SiteCreationSource(val label: String) {
DEEP_LINK("deep_link"),
LOGIN_EPILOGUE("login_epilogue"),
MY_SITE("my_site"),
MY_SITE_NO_SITES("my_sites_no_sites"),
NOTIFICATION("notification"),
SIGNUP_EPILOGUE("signup_epilogue"),
UNSPECIFIED("unspecified");
override fun toString() = label
companion object {
@JvmStatic
fun fromString(label: String?) = when {
DEEP_LINK.label == label -> DEEP_LINK
LOGIN_EPILOGUE.label == label -> LOGIN_EPILOGUE
MY_SITE.label == label -> MY_SITE
MY_SITE_NO_SITES.label == label -> MY_SITE_NO_SITES
NOTIFICATION.label == label -> NOTIFICATION
SIGNUP_EPILOGUE.label == label -> SIGNUP_EPILOGUE
else -> UNSPECIFIED
}
}
}
|
gpl-2.0
|
78b413f2061910e03464422e175fc691
| 32 | 63 | 0.609557 | 3.698276 | false | false | false | false |
NCBSinfo/NCBSinfo
|
app/src/main/java/com/rohitsuratekar/NCBSinfo/models/SettingsItem.kt
|
2
|
493
|
package com.rohitsuratekar.NCBSinfo.models
import com.rohitsuratekar.NCBSinfo.common.SettingsActions.VIEW_HEADER
class SettingsItem {
var icon: Int = 0
var title: String? = null
var viewType: Int = 0
var description: String? = null
var action: Int = 0
var isDisabled: Boolean = false
constructor(type: Int) {
viewType = type
}
constructor(title: String) {
this.title = title
viewType = VIEW_HEADER
}
}
|
mit
|
d61628a9abea40e88bd8386ddf371295
| 20.409091 | 69 | 0.622718 | 4.286957 | false | false | false | false |
KotlinNLP/SimpleDNN
|
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/ran/RANLayer.kt
|
1
|
3835
|
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.recurrent.ran
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.Sigmoid
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.recurrent.GatedRecurrentLayer
import com.kotlinnlp.simplednn.core.layers.models.recurrent.GatedRecurrentRelevanceHelper
import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow
import com.kotlinnlp.simplednn.core.layers.models.recurrent.RecurrentLayerUnit
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
/**
* The RAN Layer Structure.
*
* @property inputArray the input array of the layer
* @property inputType the input array type (default Dense)
* @property outputArray the output array of the layer
* @property params the parameters which connect the input to the output
* @property layersWindow the context window used for the forward and the backward
* @property activationFunction the activation function of the layer
* @property dropout the probability of dropout
*/
internal class RANLayer<InputNDArrayType : NDArray<InputNDArrayType>>(
inputArray: AugmentedArray<InputNDArrayType>,
inputType: LayerType.Input,
outputArray: AugmentedArray<DenseNDArray>,
override val params: RANLayerParameters,
layersWindow: LayersWindow,
activationFunction: ActivationFunction? = null,
dropout: Double
) : GatedRecurrentLayer<InputNDArrayType>(
inputArray = inputArray,
inputType = inputType,
outputArray = outputArray,
params = params,
layersWindow = layersWindow,
activationFunction = activationFunction,
dropout = dropout
) {
/**
*
*/
val candidate = AugmentedArray.zeros(outputArray.size)
/**
*
*/
val inputGate = RecurrentLayerUnit<InputNDArrayType>(outputArray.size)
/**
*
*/
val forgetGate = RecurrentLayerUnit<InputNDArrayType>(outputArray.size)
/**
* The helper which executes the forward
*/
override val forwardHelper = RANForwardHelper(layer = this)
/**
* The helper which executes the backward
*/
override val backwardHelper = RANBackwardHelper(layer = this)
/**
* The helper which calculates the relevance
*/
@Suppress("UNCHECKED_CAST")
override val relevanceHelper: GatedRecurrentRelevanceHelper? = if (this.denseInput)
RANRelevanceHelper(layer = this as RANLayer<DenseNDArray>)
else
null
/**
* Initialization: set the activation function of the gates
*/
init {
this.inputGate.setActivation(Sigmoid)
this.forgetGate.setActivation(Sigmoid)
if (this.activationFunction != null) {
this.outputArray.setActivation(this.activationFunction)
}
}
/**
* Set the initial hidden array.
* This method should be used when this layer is used as initial hidden state in a recurrent neural network.
*
* @param array the initial hidden array
*/
override fun setInitHidden(array: DenseNDArray) {
TODO("not implemented")
}
/**
* Get the errors of the initial hidden array.
* This method should be used only if this layer is used as initial hidden state in a recurrent neural network.
*
* @return the errors of the initial hidden array
*/
override fun getInitHiddenErrors(): DenseNDArray {
TODO("not implemented")
}
}
|
mpl-2.0
|
85ca4b4ebfff4719a9cb3bef5a305cef
| 32.060345 | 113 | 0.743416 | 4.565476 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/reader/viewmodels/ConversationNotificationsViewModel.kt
|
1
|
10033
|
package org.wordpress.android.ui.reader.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
import org.wordpress.android.datasets.wrappers.ReaderPostTableWrapper
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.reader.FollowCommentsUiStateType.DISABLED
import org.wordpress.android.ui.reader.FollowCommentsUiStateType.GONE
import org.wordpress.android.ui.reader.FollowCommentsUiStateType.LOADING
import org.wordpress.android.ui.reader.FollowCommentsUiStateType.VISIBLE_WITH_STATE
import org.wordpress.android.ui.reader.FollowConversationStatusFlags
import org.wordpress.android.ui.reader.FollowConversationUiState
import org.wordpress.android.ui.reader.ReaderFollowCommentsHandler
import org.wordpress.android.ui.reader.comments.ThreadedCommentsActionSource
import org.wordpress.android.ui.reader.comments.ThreadedCommentsActionSource.UNKNOWN
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState.Failure
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState.FlagsMappedState
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState.FollowCommentsNotAllowed
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState.FollowStateChanged
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState.Loading
import org.wordpress.android.ui.reader.usecases.ReaderCommentsFollowUseCase.FollowCommentsState.UserNotAuthenticated
import org.wordpress.android.util.map
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
class ConversationNotificationsViewModel @Inject constructor(
private val followCommentsHandler: ReaderFollowCommentsHandler,
private val readerPostTableWrapper: ReaderPostTableWrapper,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher
) : ScopedViewModel(bgDispatcher) {
private var isStarted = false
private var followStatusGetJob: Job? = null
private var followStatusSetJob: Job? = null
private val _showBottomSheetEvent = MutableLiveData<Event<ShowBottomSheetData>>()
val showBottomSheetEvent: LiveData<Event<ShowBottomSheetData>> = _showBottomSheetEvent
private val _snackbarEvents = MediatorLiveData<Event<SnackbarMessageHolder>>()
val snackbarEvents: LiveData<Event<SnackbarMessageHolder>> = _snackbarEvents
private val _updateFollowStatus = MediatorLiveData<FollowCommentsState>()
val updateFollowUiState: LiveData<FollowConversationUiState> =
_updateFollowStatus.map { state -> buildFollowCommentsUiState(state) }
private val _pushNotificationsStatusUpdate = MediatorLiveData<FollowStateChanged>()
val pushNotificationsStatusUpdate: LiveData<Event<Boolean>> =
_pushNotificationsStatusUpdate.map { state -> buildPushNotificationsUiState(state) }
private var blogId: Long = 0
private var postId: Long = 0
private var source: ThreadedCommentsActionSource = UNKNOWN
data class ShowBottomSheetData(val show: Boolean, val isReceivingNotifications: Boolean = false)
fun start(blogId: Long, postId: Long, source: ThreadedCommentsActionSource) {
if (isStarted) return
isStarted = true
this.blogId = blogId
this.postId = postId
this.source = source
_updateFollowStatus.value = FollowCommentsNotAllowed
init()
}
fun onRefresh() {
getFollowConversationStatus(false)
}
fun onFollowTapped() {
onFollowConversationClicked(true)
}
fun onUnfollowTapped() {
onFollowConversationClicked(false)
_showBottomSheetEvent.value = Event(ShowBottomSheetData(false))
}
fun onChangePushNotificationsRequest(enable: Boolean, fromSnackbar: Boolean = false) {
followStatusSetJob?.cancel()
followStatusSetJob = launch(bgDispatcher) {
followCommentsHandler.handleEnableByPushNotificationsClicked(
blogId,
postId,
enable,
source,
getSnackbarAction(fromSnackbar, enable)
)
}
}
fun onManageNotificationsTapped() {
val currentState = updateFollowUiState.value
val currentPushNotificationsValue = currentState?.flags?.isReceivingNotifications ?: false
_showBottomSheetEvent.value = Event(ShowBottomSheetData(true, currentPushNotificationsValue))
}
fun onUpdatePost(blogId: Long, postId: Long) {
this.blogId = blogId
this.postId = postId
}
fun onUserNavigateFromComments(flags: FollowConversationStatusFlags) {
_updateFollowStatus.value = FlagsMappedState(flags)
}
private fun getSnackbarAction(fromSnackbar: Boolean, askingEnable: Boolean): (() -> Unit)? {
return if (fromSnackbar) {
if (askingEnable) {
::disablePushNotificationsFromSnackbarAction
} else {
::enablePushNotificationsFromSnackbarAction
}
} else {
null
}
}
private fun enablePushNotificationsFromSnackbarAction() {
onChangePushNotificationsRequest(true, true)
}
private fun disablePushNotificationsFromSnackbarAction() {
onChangePushNotificationsRequest(false, true)
}
private fun init() {
_snackbarEvents.addSource(followCommentsHandler.snackbarEvents) { event ->
_snackbarEvents.value = event
}
_updateFollowStatus.addSource(followCommentsHandler.followStatusUpdate) { event ->
_updateFollowStatus.value = event
}
_pushNotificationsStatusUpdate.addSource(followCommentsHandler.pushNotificationsStatusUpdate) { event ->
_pushNotificationsStatusUpdate.value = event
}
getFollowConversationStatus(true)
}
private fun onFollowConversationClicked(askSubscribe: Boolean) {
followStatusSetJob?.cancel()
followStatusSetJob = launch(bgDispatcher) {
followCommentsHandler.handleFollowCommentsClicked(
blogId,
postId,
askSubscribe,
source,
if (askSubscribe) ::enablePushNotificationsFromSnackbarAction else null
)
}
}
private fun getFollowConversationStatus(isInit: Boolean) {
followStatusGetJob?.cancel()
followStatusGetJob = launch(bgDispatcher) {
val post = readerPostTableWrapper.getBlogPost(
blogId,
postId,
true
)
post?.let {
if (!post.isExternal) {
followCommentsHandler.handleFollowCommentsStatusRequest(blogId, postId, isInit)
}
}
}
}
private fun mapToStateType(followCommentsState: FollowCommentsState) = when (followCommentsState) {
Loading -> LOADING
is FollowStateChanged -> VISIBLE_WITH_STATE
is Failure, FollowCommentsNotAllowed -> DISABLED
UserNotAuthenticated -> GONE
is FlagsMappedState -> followCommentsState.flags.type
}
private fun buildFollowCommentsUiState(followCommentsState: FollowCommentsState): FollowConversationUiState {
if (followCommentsState is FlagsMappedState) {
return FollowConversationUiState(
flags = followCommentsState.flags,
onFollowTapped = if (listOf(DISABLED, LOADING).contains(followCommentsState.flags.type)) {
null
} else {
::onFollowTapped
},
onManageNotificationsTapped = ::onManageNotificationsTapped
)
} else {
val stateType = mapToStateType(followCommentsState)
val isFollowing = if (followCommentsState is FollowStateChanged) followCommentsState.isFollowing else false
return FollowConversationUiState(
FollowConversationStatusFlags(
type = stateType,
isFollowing = isFollowing,
isReceivingNotifications = if (followCommentsState is FollowStateChanged) {
followCommentsState.isReceivingNotifications
} else {
false
},
isMenuEnabled = stateType != DISABLED && stateType != LOADING,
showMenuShimmer = stateType == LOADING,
isBellMenuVisible = if (stateType != VISIBLE_WITH_STATE) false else isFollowing,
isFollowMenuVisible = when (stateType) {
DISABLED, LOADING -> true
GONE -> false
VISIBLE_WITH_STATE -> !isFollowing
}
),
onFollowTapped = if (listOf(DISABLED, LOADING).contains(stateType)) null else ::onFollowTapped,
onManageNotificationsTapped = ::onManageNotificationsTapped
)
}
}
private fun buildPushNotificationsUiState(followStateChanged: FollowStateChanged): Event<Boolean> {
return Event(followStateChanged.isReceivingNotifications)
}
override fun onCleared() {
super.onCleared()
followStatusGetJob?.cancel()
followStatusSetJob?.cancel()
}
}
|
gpl-2.0
|
9516a6ee9503e3182e1d5f6f5135a1f6
| 41.155462 | 120 | 0.680654 | 5.503566 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/test/java/org/wordpress/android/ui/mysite/cards/siteinfo/SiteInfoHeaderCardBuilderTest.kt
|
1
|
5968
|
package org.wordpress.android.ui.mysite.cards.siteinfo
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.QuickStartStore
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartExistingSiteTask
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTask
import org.wordpress.android.ui.mysite.MySiteCardAndItem.SiteInfoHeaderCard
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.SiteInfoCardBuilderParams
import org.wordpress.android.ui.mysite.cards.quickstart.QuickStartRepository
import org.wordpress.android.ui.quickstart.QuickStartType
import org.wordpress.android.viewmodel.ResourceProvider
@RunWith(MockitoJUnitRunner::class)
class SiteInfoHeaderCardBuilderTest {
@Mock lateinit var resourceProvider: ResourceProvider
@Mock lateinit var site: SiteModel
@Mock lateinit var quickStartRepository: QuickStartRepository
@Mock lateinit var quickStartType: QuickStartType
private lateinit var siteInfoHeaderCardBuilder: SiteInfoHeaderCardBuilder
@Before
fun setUp() {
whenever(quickStartRepository.quickStartType).thenReturn(quickStartType)
siteInfoHeaderCardBuilder = SiteInfoHeaderCardBuilder(resourceProvider, quickStartRepository)
}
@Test
fun `shows title quick start focus point when showUpdateSiteTitleFocusPoint is true`() {
val buildSiteInfoCard = buildSiteInfoCard(
showUpdateSiteTitleFocusPoint = true
)
assertThat(buildSiteInfoCard.showTitleFocusPoint).isTrue()
}
@Test
fun `hides title quick start focus point when showUpdateSiteTitleFocusPoint is false`() {
val buildSiteInfoCard = buildSiteInfoCard(
showUpdateSiteTitleFocusPoint = false
)
assertThat(buildSiteInfoCard.showTitleFocusPoint).isFalse()
}
@Test
fun `shows icon quick start focus point when showUploadSiteIconFocusPoint is true`() {
val buildSiteInfoCard = buildSiteInfoCard(
showUploadSiteIconFocusPoint = true
)
assertThat(buildSiteInfoCard.showIconFocusPoint).isTrue()
}
@Test
fun `hides icon quick start focus point when showUploadSiteIconFocusPoint is false`() {
val buildSiteInfoCard = buildSiteInfoCard(
showUploadSiteIconFocusPoint = false
)
assertThat(buildSiteInfoCard.showIconFocusPoint).isFalse()
}
@Test
fun `given new site QS + View Site active task, when card built, then showSubtitleFocusPoint is true`() {
val buildSiteInfoCard = buildSiteInfoCard(
showViewSiteFocusPoint = true,
isNewSiteQuickStart = true
)
assertThat(buildSiteInfoCard.showSubtitleFocusPoint).isTrue
}
@Test
fun `given new site QS + View Site not active task, when card built, then showSubtitleFocusPoint is false`() {
val buildSiteInfoCard = buildSiteInfoCard(
showViewSiteFocusPoint = false,
isNewSiteQuickStart = true
)
assertThat(buildSiteInfoCard.showSubtitleFocusPoint).isFalse
}
@Test
fun `given existing site QS + View Site active task, when card built, then showSubtitleFocusPoint is true`() {
val buildSiteInfoCard = buildSiteInfoCard(
showViewSiteFocusPoint = true,
isNewSiteQuickStart = false
)
assertThat(buildSiteInfoCard.showSubtitleFocusPoint).isTrue
}
@Test
fun `given existing site QS + View Site not active task, when card built, then showSubtitleFocusPoint is false`() {
val buildSiteInfoCard = buildSiteInfoCard(
showViewSiteFocusPoint = false,
isNewSiteQuickStart = false
)
assertThat(buildSiteInfoCard.showSubtitleFocusPoint).isFalse
}
private fun buildSiteInfoCard(
showUpdateSiteTitleFocusPoint: Boolean = false,
showViewSiteFocusPoint: Boolean = false,
showUploadSiteIconFocusPoint: Boolean = false,
isNewSiteQuickStart: Boolean = true
): SiteInfoHeaderCard {
val viewSiteTask = if (isNewSiteQuickStart) {
QuickStartNewSiteTask.VIEW_SITE
} else {
QuickStartExistingSiteTask.VIEW_SITE
}
whenever(quickStartType.getTaskFromString(QuickStartStore.QUICK_START_VIEW_SITE_LABEL))
.thenReturn(viewSiteTask)
return siteInfoHeaderCardBuilder.buildSiteInfoCard(
SiteInfoCardBuilderParams(
site = site,
showSiteIconProgressBar = showUploadSiteIconFocusPoint,
titleClick = {},
iconClick = {},
urlClick = {},
switchSiteClick = {},
setActiveTask(
showUpdateSiteTitleFocusPoint,
showViewSiteFocusPoint,
showUploadSiteIconFocusPoint,
viewSiteTask
)
)
)
}
private fun setActiveTask(
showUpdateSiteTitleFocusPoint: Boolean,
showViewSiteFocusPoint: Boolean,
showUploadSiteIconFocusPoint: Boolean,
viewSiteTask: QuickStartTask
): QuickStartTask? {
return when {
showUpdateSiteTitleFocusPoint -> QuickStartNewSiteTask.UPDATE_SITE_TITLE
showViewSiteFocusPoint -> viewSiteTask
showUploadSiteIconFocusPoint -> QuickStartNewSiteTask.UPLOAD_SITE_ICON
else -> null
}
}
}
|
gpl-2.0
|
6cd6ab7384bd4c71f9070caa24b7c227
| 37.503226 | 119 | 0.682306 | 5.212227 | false | true | false | false |
andrewoma/kommon
|
src/main/kotlin/com/github/andrewoma/kommon/util/StopWatch.kt
|
1
|
2889
|
/*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kommon.util
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.*
/**
* StopWatch is a simple timer. Multiple timings can be accumulated by calling start() and stop()
* in sequence.
*/
class StopWatch(private val currentTime: () -> Long = { System.nanoTime() }) {
private var start: Long = 0
private var elapsedNanoseconds: Long = 0
private var running: Boolean = false
fun start(): StopWatch {
check(!running) { "The stop watch is already started" }
start = currentTime()
running = true
return this
}
inline fun <R> time(f: () -> R): R {
start()
try {
return f()
} finally {
stop()
}
}
fun stop(): StopWatch {
check(running) { "The stop watch is already stopped" }
running = false
elapsedNanoseconds += currentTime() - start
return this
}
fun reset(): StopWatch {
elapsedNanoseconds = 0
running = false
return this
}
fun elapsed(unit: TimeUnit): Long {
val elapsed = if (running) elapsedNanoseconds + currentTime() - start else elapsedNanoseconds
return unit.convert(elapsed, NANOSECONDS)
}
override fun toString() = toString(MILLISECONDS)
fun toString(unit: TimeUnit, precision: Int = 3): String {
val value = elapsed(NANOSECONDS).toDouble() / NANOSECONDS.convert(1, unit)
return "%.${precision}f %s".format(value, unit.abbreviation())
}
}
fun TimeUnit.abbreviation(): String = when (this) {
NANOSECONDS -> "ns"
MICROSECONDS -> "\u03bcs"
MILLISECONDS -> "ms"
SECONDS -> "s"
MINUTES -> "m"
HOURS -> "h"
DAYS -> "d"
else -> name
}
|
mit
|
82c454a95d592e05eb499341a682b249
| 31.460674 | 101 | 0.662513 | 4.344361 | false | false | false | false |
REDNBLACK/advent-of-code2015
|
src/main/kotlin/day14/Advent14.kt
|
1
|
4564
|
package day14
import parseInput
import splitToLines
import java.lang.Math.min
import java.util.*
/**
--- Day 14: Reindeer Olympics ---
This year is the Reindeer Olympics! Reindeer can fly at high speeds, but must rest occasionally to recover their energy. Santa would like to know which of his reindeer is fastest, and so he has them race.
Reindeer can only either be flying (always at their top speed) or resting (not moving at all), and always spend whole seconds in either state.
For example, suppose you have the following Reindeer:
Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.
Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.
After one second, Comet has gone 14 km, while Dancer has gone 16 km. After ten seconds, Comet has gone 140 km, while Dancer has gone 160 km. On the eleventh second, Comet begins resting (staying at 140 km), and Dancer continues on for a total distance of 176 km. On the 12th second, both reindeer are resting. They continue to rest until the 138th second, when Comet flies for another ten seconds. On the 174th second, Dancer flies for another 11 seconds.
In this example, after the 1000th second, both reindeer are resting, and Comet is in the lead at 1120 km (poor Dancer has only gotten 1056 km by that point). So, in this situation, Comet would win (if the race ended at 1000 seconds).
Given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, what distance has the winning reindeer traveled?
--- Part Two ---
Seeing how reindeer move in bursts, Santa decides he's not pleased with the old scoring system.
Instead, at the end of each second, he awards one point to the reindeer currently in the lead. (If there are multiple reindeer tied for the lead, they each get one point.) He keeps the traditional 2503 second time limit, of course, as doing otherwise would be entirely ridiculous.
Given the example reindeer from above, after the first second, Dancer is in the lead and gets one point. He stays in the lead until several seconds into Comet's second burst: after the 140th second, Comet pulls into the lead and gets his first point. Of course, since Dancer had been in the lead for the 139 seconds before that, he has accumulated 139 points by the 140th second.
After the 1000th second, Dancer has accumulated 689 points, while poor Comet, our old champion, only has 312. So, with the new scoring system, Dancer would win (if the race ended at 1000 seconds).
Again given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, how many points does the winning reindeer have?
*/
fun main(args: Array<String>) {
val test = """
|Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.
|Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.
""".trimMargin()
val input = parseInput("day14-input.txt")
println(findWinner(test, 1000))
println(findWinner(input, 2503))
}
fun findWinner(input: String, totalTime: Int): Map<String, Pair<String, Int>?> {
val reindeers = parseReindeers(input)
tailrec fun maxPoints(counter: Int, points: HashMap<String, Int>): Pair<String, Int>? {
val allDistances = reindeers.map { it.getDistance(counter) }
val maxDistance = allDistances.maxBy { it.second }?.second
allDistances.filter { it.second == maxDistance }
.map { it.first }
.forEach { points.computeIfPresent(it, { k, v -> v + 1 }) }
if (counter == totalTime) return points.maxBy { it.value }?.toPair()
return maxPoints(counter + 1, points)
}
return mapOf(
"distance" to reindeers.map { it.getDistance(totalTime) }.maxBy { it.second },
"points" to maxPoints(1, HashMap(reindeers.map { it.name to 0 }.toMap()))
)
}
data class Reindeer(val name: String, val speed: Int, val fly: Int, val rest: Int) {
fun total() = fly + rest
fun getDistance(time: Int) = (name to speed * fly * (time / total()) + speed * min(fly, time % total()))
}
private fun parseReindeers(input: String) = input.splitToLines()
.map {
val name = it.split(" ", limit = 2).first()
val (speed, flyTime, restTime) = Regex("""(\d+)""")
.findAll(it)
.map { it.groupValues[1] }
.map(String::toInt)
.toList()
Reindeer(name = name, speed = speed, fly = flyTime, rest = restTime)
}
|
mit
|
a08fb3e5865d1a8ff7267bcd85f9f350
| 52.069767 | 455 | 0.692594 | 3.809683 | false | false | false | false |
JetBrains/teamcity-nuget-support
|
nuget-agent/src/jetbrains/buildServer/nuget/agent/serviceMessages/PublishPackageServiceMessageHandler.kt
|
1
|
5705
|
package jetbrains.buildServer.nuget.agent.serviceMessages
import jetbrains.buildServer.BuildProblemData
import jetbrains.buildServer.agent.*
import jetbrains.buildServer.log.Loggers
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
import jetbrains.buildServer.messages.serviceMessages.ServiceMessageHandler
import jetbrains.buildServer.messages.serviceMessages.ServiceMessagesRegister
import jetbrains.buildServer.nuget.common.PackageLoadException
import jetbrains.buildServer.nuget.common.index.NuGetPackageData
import jetbrains.buildServer.nuget.common.index.PackageAnalyzer
import jetbrains.buildServer.nuget.common.version.VersionUtility
import jetbrains.buildServer.nuget.feedReader.NuGetPackageAttributes.ID
import jetbrains.buildServer.nuget.feedReader.NuGetPackageAttributes.NORMALIZED_VERSION
import jetbrains.buildServer.problems.BuildProblemTypesEx
import jetbrains.buildServer.util.EventDispatcher
import jetbrains.buildServer.util.FileUtil
import jetbrains.buildServer.util.StringUtil
import org.jetbrains.annotations.NotNull
import java.io.File
import java.io.FileInputStream
import java.util.concurrent.ConcurrentHashMap
class PublishPackageServiceMessageHandler(
@NotNull private val myServiceMessagesRegister: ServiceMessagesRegister,
@NotNull private val myDispatcher: EventDispatcher<AgentLifeCycleListener>,
@NotNull private val myPackageAnalyzer: PackageAnalyzer,
@NotNull private val myPackagePublisher: NuGetPackageServiceFeedPublisher
) : ServiceMessageHandler {
private val myPackagesMap: ConcurrentHashMap<PackageKey, NuGetPackageData> = ConcurrentHashMap<PackageKey, NuGetPackageData>()
private var myBuild: AgentRunningBuild? = null
init {
myDispatcher.addListener(object: AgentLifeCycleAdapter() {
override fun buildStarted(runningBuild: AgentRunningBuild) {
myBuild = runningBuild
}
override fun beforeRunnerStart(runner: BuildRunnerContext) {
clearPackages()
}
override fun runnerFinished(runner: BuildRunnerContext, status: BuildFinishedStatus) {
publishPackages()
clearPackages()
}
override fun buildFinished(build: AgentRunningBuild, buildStatus: BuildFinishedStatus) {
myBuild = null
clearPackages()
}
})
myServiceMessagesRegister.registerHandler(MESSAGE_NAME, this)
}
override fun handle(@NotNull serviceMessage: ServiceMessage) {
val build = myBuild
if (build == null) {
Loggers.AGENT.warn("Trying to handle ${serviceMessage.asString()} service message for finished build")
return
}
if (Loggers.AGENT.isDebugEnabled) {
Loggers.AGENT.debug("Handling service message: ${serviceMessage.asString()}")
}
val logger = build.buildLogger
val path = serviceMessage.argument ?: serviceMessage.attributes.get(MESSAGE_PATH_ATTRIBUTE)
if (path.isNullOrEmpty()) {
var message = "\"$MESSAGE_PATH_ATTRIBUTE\" attribute must be a non-empty value for \"$MESSAGE_NAME\" service message"
logger.error(message)
Loggers.AGENT.warn(message)
return
}
try {
var file = File(path)
if (!file.isAbsolute) {
file = File(build.checkoutDirectory, path)
}
val keyToDataPair = readPackageInfo(file)
myPackagesMap.put(keyToDataPair.first, keyToDataPair.second)
Loggers.AGENT.debug("Service message $MESSAGE_NAME sucessfully handled")
} catch (e: Throwable) {
var message = "Could not read NuGet package. File path: $path. Message: ${e.message}"
Loggers.AGENT.warnAndDebugDetails(message, e)
var buildProblemText = "Could not read NuGet package. File path: $path."
logger.logBuildProblem(BuildProblemData.createBuildProblem(buildProblemText.hashCode().toString(), BuildProblemTypesEx.TC_BUILD_FAILURE_TYPE, buildProblemText))
}
}
public fun dispose() {
myServiceMessagesRegister.removeHandler(MESSAGE_NAME)
}
private fun readPackageInfo(file: File) : Pair<PackageKey, NuGetPackageData> {
var stream : FileInputStream? = null
try {
stream = file.inputStream()
var metadata = myPackageAnalyzer.analyzePackage(stream)
var id = metadata.getOrDefault(ID, "")
var version = metadata.getOrDefault(NORMALIZED_VERSION, "")
// Package must have id and version specified
if (StringUtil.isEmptyOrSpaces(id) || StringUtil.isEmptyOrSpaces(version)) {
throw PackageLoadException("Lack of Id or Version in NuGet package specification")
}
val key = PackageKey(id.toLowerCase(), VersionUtility.normalizeVersion(version)?.toLowerCase())
val data = NuGetPackageData(file.absolutePath, metadata)
return key to data
}
finally {
FileUtil.close(stream)
}
}
private fun clearPackages() {
myPackagesMap.clear()
}
private fun publishPackages() {
if (myPackagesMap.isEmpty()) return;
try {
myPackagePublisher.publishPackages(myPackagesMap.values)
} finally {
clearPackages()
}
}
private data class PackageKey (val name: String, val version: String?)
private companion object {
const val MESSAGE_NAME = "publishNuGetPackage"
const val MESSAGE_PATH_ATTRIBUTE = "path"
}
}
|
apache-2.0
|
1b3db4878bec8bbb9d3bb39cdeb54374
| 38.895105 | 172 | 0.687642 | 4.965187 | false | false | false | false |
ACRA/acra
|
acra-advanced-scheduler/src/main/java/org/acra/scheduler/RestartingAdministrator.kt
|
1
|
2946
|
/*
* Copyright (c) 2018
*
* 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.acra.scheduler
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.os.PersistableBundle
import com.google.auto.service.AutoService
import org.acra.builder.LastActivityManager
import org.acra.config.CoreConfiguration
import org.acra.config.ReportingAdministrator
import org.acra.config.SchedulerConfiguration
import org.acra.config.getPluginConfiguration
import org.acra.log.debug
import org.acra.log.info
import org.acra.log.warn
import org.acra.plugins.HasConfigPlugin
/**
* @author F43nd1r
* @since 07.05.18
*/
@AutoService(ReportingAdministrator::class)
class RestartingAdministrator : HasConfigPlugin(SchedulerConfiguration::class.java), ReportingAdministrator {
override fun shouldFinishActivity(context: Context, config: CoreConfiguration, lastActivityManager: LastActivityManager): Boolean {
debug { "RestartingAdministrator entry" }
if (config.getPluginConfiguration<SchedulerConfiguration>().restartAfterCrash) {
val activity = lastActivityManager.lastActivity
if (activity != null) {
debug { "Try to schedule last activity (" + activity.javaClass.name + ") for restart" }
try {
val scheduler = (context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler)
val extras = PersistableBundle()
extras.putString(EXTRA_LAST_ACTIVITY, activity.javaClass.name)
scheduler.schedule(JobInfo.Builder(1, ComponentName(context, RestartingService::class.java))
.setExtras(extras)
.setOverrideDeadline(100)
.build())
debug { "Successfully scheduled last activity (" + activity.javaClass.name + ") for restart" }
} catch (e: Exception) {
warn(e) { "Failed to schedule last activity for restart" }
}
} else {
info { "Activity restart is enabled but no activity was found. Nothing to do." }
}
}
return true
}
companion object {
const val EXTRA_LAST_ACTIVITY = "lastActivity"
const val EXTRA_ACTIVITY_RESTART_AFTER_CRASH = "restartAfterCrash"
}
}
|
apache-2.0
|
ea4425078295df7387f132606628518a
| 41.710145 | 135 | 0.681602 | 4.691083 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/mayTypeAffectAncestors.0.kt
|
5
|
701
|
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
data class A(val <caret>n: Int, val s: String)
data class B(val x: Int, val y: Int)
fun condition(a: A) = true
fun x(a: A, b: Boolean, list: List<Int>) {
val (x, y) = if (condition(a)) {
print(A(1, "").toString())
B(1, 2)
} else {
B(3, 4)
}
val (x1, y1) = if (b) {
A(1, "").apply { val (x2, y2) = this }
} else {
return
}
if (list.any { it == 0 }) {
A(1, "")
}
}
fun y1(a: A) = condition(a)
fun y2(a: A): Boolean = condition(a)
fun y3(a: A) {
condition(a)
}
// FIR_COMPARISON
// FIR_COMPARISON_WITH_DISABLED_COMPONENTS
// IGNORE_FIR_LOG
|
apache-2.0
|
c895d3dacda9e78405eff8c18ccb8e36
| 17.945946 | 52 | 0.522111 | 2.635338 | false | false | false | false |
vickychijwani/kotlin-koans-android
|
app/src/main/code/me/vickychijwani/kotlinkoans/features/common/AppBarLayoutDodgeBehavior.kt
|
1
|
2151
|
package me.vickychijwani.kotlinkoans.features.common
import android.content.Context
import android.support.design.widget.AppBarLayout
import android.support.design.widget.BottomSheetBehavior
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.support.v4.view.ViewPropertyAnimatorListener
import android.util.AttributeSet
import android.view.View
class AppBarLayoutDodgeBehavior(ctx: Context, attrs: AttributeSet)
: CoordinatorLayout.Behavior<AppBarLayout>(ctx, attrs) {
private var animating = false
override fun layoutDependsOn(parent: CoordinatorLayout, appbar: AppBarLayout, dependency: View): Boolean {
val lp = dependency.layoutParams as? CoordinatorLayout.LayoutParams
return if (lp != null) lp.behavior is BottomSheetBehavior else false
}
override fun onDependentViewChanged(parent: CoordinatorLayout, appbar: AppBarLayout, dependency: View): Boolean {
val appbarHeight = appbar.measuredHeight
if (!animating && dependency.y <= appbarHeight) {
ViewCompat.animate(appbar).withLayer()
.translationY(-appbarHeight.toFloat())
.setListener(object : ViewPropertyAnimatorListener {
override fun onAnimationEnd(view: View?) { animating = false }
override fun onAnimationCancel(view: View?) { animating = false }
override fun onAnimationStart(view: View?) { animating = true }
})
.start()
} else if (!animating && dependency.y > appbarHeight) {
ViewCompat.animate(appbar).withLayer()
.translationY(0f)
.setListener(object : ViewPropertyAnimatorListener {
override fun onAnimationEnd(view: View?) { animating = false }
override fun onAnimationCancel(view: View?) { animating = false }
override fun onAnimationStart(view: View?) { animating = true }
})
.start()
}
return false
}
}
|
mit
|
1aec35ceae6720576e0a51603437782d
| 45.76087 | 117 | 0.649 | 5.515385 | false | false | false | false |
ktorio/ktor
|
ktor-client/ktor-client-core/js/src/io/ktor/client/plugins/websocket/JsWebSocketSession.kt
|
1
|
5678
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.plugins.websocket
import io.ktor.util.*
import io.ktor.utils.io.core.*
import io.ktor.websocket.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.khronos.webgl.*
import org.w3c.dom.*
import kotlin.coroutines.*
@Suppress("CAST_NEVER_SUCCEEDS")
internal class JsWebSocketSession(
override val coroutineContext: CoroutineContext,
private val websocket: WebSocket
) : DefaultWebSocketSession {
private val _closeReason: CompletableDeferred<CloseReason> = CompletableDeferred()
private val _incoming: Channel<Frame> = Channel(Channel.UNLIMITED)
private val _outgoing: Channel<Frame> = Channel(Channel.UNLIMITED)
override val incoming: ReceiveChannel<Frame> = _incoming
override val outgoing: SendChannel<Frame> = _outgoing
override val extensions: List<WebSocketExtension<*>>
get() = emptyList()
override val closeReason: Deferred<CloseReason?> = _closeReason
override var pingIntervalMillis: Long
get() = throw WebSocketException("Websocket ping-pong is not supported in JS engine.")
set(_) = throw WebSocketException("Websocket ping-pong is not supported in JS engine.")
override var timeoutMillis: Long
get() = throw WebSocketException("Websocket timeout is not supported in JS engine.")
set(_) = throw WebSocketException("Websocket timeout is not supported in JS engine.")
override var masking: Boolean
get() = true
set(_) = throw WebSocketException("Masking switch is not supported in JS engine.")
override var maxFrameSize: Long
get() = Long.MAX_VALUE
set(_) = throw WebSocketException("Max frame size switch is not supported in Js engine.")
init {
websocket.binaryType = BinaryType.ARRAYBUFFER
websocket.addEventListener(
"message",
callback = {
val event = it.unsafeCast<MessageEvent>()
val frame: Frame = when (val data = event.data) {
is ArrayBuffer -> Frame.Binary(false, Int8Array(data).unsafeCast<ByteArray>())
is String -> Frame.Text(data)
else -> {
val error = IllegalStateException("Unknown frame type: ${event.type}")
_closeReason.completeExceptionally(error)
throw error
}
}
_incoming.trySend(frame)
}
)
websocket.addEventListener(
"error",
callback = {
val cause = WebSocketException("$it")
_closeReason.completeExceptionally(cause)
_incoming.close(cause)
_outgoing.cancel()
}
)
websocket.addEventListener(
"close",
callback = { event: dynamic ->
val reason = CloseReason(event.code as Short, event.reason as String)
_closeReason.complete(reason)
_incoming.trySend(Frame.Close(reason))
_incoming.close()
_outgoing.cancel()
}
)
launch {
_outgoing.consumeEach {
when (it.frameType) {
FrameType.TEXT -> {
val text = it.data
websocket.send(String(text))
}
FrameType.BINARY -> {
val source = it.data as Int8Array
val frameData = source.buffer.slice(
source.byteOffset,
source.byteOffset + source.byteLength
)
websocket.send(frameData)
}
FrameType.CLOSE -> {
val data = buildPacket { writeFully(it.data) }
val code = data.readShort()
val reason = data.readText()
_closeReason.complete(CloseReason(code, reason))
if (code.isReservedStatusCode()) {
websocket.close()
} else {
websocket.close(code, reason)
}
}
FrameType.PING, FrameType.PONG -> {
// ignore
}
}
}
}
coroutineContext[Job]?.invokeOnCompletion { cause ->
if (cause == null) {
websocket.close()
} else {
websocket.close(CloseReason.Codes.INTERNAL_ERROR.code, "Client failed")
}
}
}
@OptIn(InternalAPI::class)
override fun start(negotiatedExtensions: List<WebSocketExtension<*>>) {
require(negotiatedExtensions.isEmpty()) { "Extensions are not supported." }
}
override suspend fun flush() {
}
@Deprecated(
"Use cancel() instead.",
ReplaceWith("cancel()", "kotlinx.coroutines.cancel")
)
override fun terminate() {
_incoming.cancel()
_outgoing.cancel()
_closeReason.cancel("WebSocket terminated")
websocket.close()
}
@OptIn(InternalAPI::class)
private fun Short.isReservedStatusCode(): Boolean {
return CloseReason.Codes.byCode(this).let { resolved ->
@Suppress("DEPRECATION")
resolved == null || resolved == CloseReason.Codes.CLOSED_ABNORMALLY
}
}
}
|
apache-2.0
|
f257b21e9454eff5a4784d3a0edbd097
| 34.267081 | 118 | 0.550018 | 5.301587 | false | false | false | false |
linheimx/ZimuDog
|
app/src/main/java/com/linheimx/zimudog/vp/main/MainActivity.kt
|
1
|
4149
|
package com.linheimx.zimudog.vp.main
import android.Manifest
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.WindowManager
import android.widget.Toast
import com.afollestad.materialdialogs.folderselector.FolderChooserDialog
import com.linheimx.zimudog.App
import com.linheimx.zimudog.R
import com.linheimx.zimudog.utils.Utils
import com.linheimx.zimudog.vp.about.AboutFragment
import com.linheimx.zimudog.vp.search.SearchFragment
import com.tbruyelle.rxpermissions2.RxPermissions
import com.linheimx.zimudog.utils.bindView
import com.linheimx.zimudog.vp.browzimu.SdCardFragment
import es.dmoral.toasty.Toasty
import io.reactivex.functions.Consumer
import java.io.File
class MainActivity : AppCompatActivity(), FolderChooserDialog.FolderCallback {
val bottomNavigation: BottomNavigationView by bindView(R.id.bottom_navigation)
internal var _lastHitTime = System.currentTimeMillis() - 2001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
showFragment(F_SEARCH)
}
initBottomNav()
requestPermission()
}
private fun initBottomNav() {
bottomNavigation.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.navigation_search -> showFragment(F_SEARCH)
R.id.navigation_brow -> showFragment(F_BROW)
R.id.navigation_notifications -> showFragment(F_ABOUT)
}
true
}
}
override fun onBackPressed() {
val nowHitTime = System.currentTimeMillis()
if (nowHitTime - _lastHitTime <= 2000) {
finish()
} else {
Toasty.info(App.get()!!, "再按一次返回键退出", Toast.LENGTH_SHORT).show()
_lastHitTime = nowHitTime
}
}
private fun requestPermission() {
RxPermissions(this)
.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.subscribe(Consumer {
if ((!it)) {
// 未授予
Toasty.warning(App.get()!!, "读写权限未授予,字幕狗将不会正常运行,请授予其权限!", Toast.LENGTH_SHORT, true).show()
requestPermission()
} else {
Utils.init(application)
}
})
}
fun showFragment(tag: String) {
val fragmentManager = supportFragmentManager
// hidden all
if (fragmentManager.fragments != null) {
for (fragment in fragmentManager.fragments) {
if (fragment.tag != tag) {
fragmentManager.beginTransaction()
.hide(fragment)
.commit()
}
}
}
var fragment: Fragment? = fragmentManager.findFragmentByTag(tag)
if (fragment == null) {
when (tag) {
F_SEARCH -> fragment = SearchFragment()
F_BROW -> fragment = SdCardFragment()
F_ABOUT -> fragment = AboutFragment()
}
fragmentManager.beginTransaction()
.add(R.id.content, fragment, tag)
.commit()
} else {
if (fragment.isHidden) {
fragmentManager.beginTransaction()
.show(fragment)
.commit()
}
}
}
override fun onFolderSelection(dialog: FolderChooserDialog, folder: File) {
Utils.setDefaultPath(application, folder.absolutePath)
}
override fun onFolderChooserDismissed(dialog: FolderChooserDialog) {
}
companion object {
val F_SEARCH = "search"
val F_BROW = "brow"
val F_ABOUT = "about"
}
}
|
apache-2.0
|
6b0cd9c603eb6c29c590c3daec9231fa
| 30.573643 | 114 | 0.601031 | 4.638952 | false | false | false | false |
ktorio/ktor
|
ktor-http/common/src/io/ktor/http/RangesSpecifier.kt
|
1
|
2425
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http
/**
* Range specifier for partial content requests (RFC 2616 sec 14.35.1)
* @property unit range units, usually bytes
* @property ranges a list of requested ranges (could be open or closed ranges)
*/
public data class RangesSpecifier(val unit: String = RangeUnits.Bytes.unitToken, val ranges: List<ContentRange>) {
public constructor(unit: RangeUnits, ranges: List<ContentRange>) : this(unit.unitToken, ranges)
init {
require(ranges.isNotEmpty()) { "It should be at least one range" }
}
/**
* Verify ranges
*/
public fun isValid(rangeUnitPredicate: (String) -> Boolean = { it == RangeUnits.Bytes.unitToken }): Boolean =
rangeUnitPredicate(unit) && ranges.none {
when (it) {
is ContentRange.Bounded -> it.from < 0 || it.to < it.from
is ContentRange.TailFrom -> it.from < 0
is ContentRange.Suffix -> it.lastCount < 0
}
}
/**
* Resolve and merge all overlapping and neighbours ranges
* @param length content length
* @return a list of absolute long ranges
*/
public fun merge(length: Long, maxRangeCount: Int = 50): List<LongRange> {
if (ranges.size > maxRangeCount) {
return mergeToSingle(length).toList()
}
// TODO rangeMergeMaxGap
return merge(length)
}
/**
* Merges all overlapping and neighbours ranges. Currently gaps collapse is not supported but should be, one day.
*/
public fun merge(length: Long): List<LongRange> = ranges.toLongRanges(length).mergeRangesKeepOrder()
/**
* Merge all ranges into a single absolute long range
* @param length content length
*/
public fun mergeToSingle(length: Long): LongRange? {
val mapped = ranges.toLongRanges(length)
if (mapped.isEmpty()) {
return null
}
val start = mapped.minByOrNull { it.start }!!.start
val endInclusive = mapped.maxByOrNull { it.endInclusive }!!.endInclusive.coerceAtMost(length - 1)
return start..endInclusive
}
override fun toString(): String = ranges.joinToString(",", prefix = unit + "=")
private fun <T> T?.toList(): List<T> = if (this == null) emptyList() else listOf(this)
}
|
apache-2.0
|
bd6af2d4d48632e46ab27eab4d9a8bad
| 33.15493 | 118 | 0.635876 | 4.284452 | false | false | false | false |
evanchooly/kobalt
|
src/main/kotlin/com/beust/kobalt/app/remote/KobaltServer.kt
|
1
|
3196
|
package com.beust.kobalt.app.remote
import com.beust.kobalt.api.Project
import com.beust.kobalt.homeDir
import com.beust.kobalt.internal.PluginInfo
import com.beust.kobalt.misc.KFiles
import com.beust.kobalt.misc.log
import com.google.inject.Inject
import com.google.inject.assistedinject.Assisted
import java.io.File
import java.io.FileWriter
import java.lang.management.ManagementFactory
import java.util.*
import java.util.concurrent.Callable
import javax.annotation.Nullable
/**
* Launch a Kobalt server. If @param{force} is specified, a new server will be launched even if one was detected
* to be already running (from the ~/.kobalt/kobaltServer.properties file).
*
* The callbacks are used to initialize and clean up the state before and after each command, so that Kobalt's state
* can be properly reset, making the server reentrant.
*/
class KobaltServer @Inject constructor(@Assisted val force: Boolean, @Assisted @Nullable val givenPort: Int?,
@Assisted val initCallback: (String) -> List<Project>,
@Assisted val cleanUpCallback: () -> Unit,
val pluginInfo : PluginInfo) : Callable<Int> {
interface IFactory {
fun create(force: Boolean, givenPort: Int? = null,
initCallback: (String) -> List<Project>,
cleanUpCallback: () -> Unit) : KobaltServer
}
companion object {
/**
* Default response sent for calls that don't return a payload.
*/
val OK = "ok"
}
// var outgoing: PrintWriter? = null
interface IServer {
fun run(port: Int)
}
override fun call() : Int {
val port = givenPort ?: ProcessUtil.findAvailablePort(1234)
try {
if (createServerFile(port, force)) {
log(1, "KobaltServer listening on port $port")
// OldServer(initCallback, cleanUpCallback).run(port)
// JerseyServer(initCallback, cleanUpCallback).run(port)
SparkServer(initCallback, cleanUpCallback, pluginInfo).run(port)
// WasabiServer(initCallback, cleanUpCallback).run(port)
}
} catch(ex: Exception) {
ex.printStackTrace()
} finally {
// deleteServerFile()
}
return port
}
val SERVER_FILE = KFiles.joinDir(homeDir(KFiles.KOBALT_DOT_DIR, "kobaltServer.properties"))
val KEY_PORT = "port"
val KEY_PID = "pid"
private fun createServerFile(port: Int, force: Boolean) : Boolean {
if (File(SERVER_FILE).exists() && ! force) {
log(1, "Server file $SERVER_FILE already exists, is another server running?")
return false
} else {
val processName = ManagementFactory.getRuntimeMXBean().name
val pid = processName.split("@")[0]
Properties().apply {
put(KEY_PORT, port.toString())
put(KEY_PID, pid)
}.store(FileWriter(SERVER_FILE), "")
log(2, "KobaltServer created $SERVER_FILE")
return true
}
}
private fun deleteServerFile() {
log(1, "KobaltServer deleting $SERVER_FILE")
File(SERVER_FILE).delete()
}
}
|
apache-2.0
|
76c5178b7e6c5661dfbe0094f50f9d25
| 34.120879 | 116 | 0.633605 | 4.227513 | false | false | false | false |
dbrant/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/dataclient/okhttp/CacheControlInterceptor.kt
|
1
|
1658
|
package org.wikipedia.dataclient.okhttp
import okhttp3.Interceptor
import okhttp3.Response
/**
* This interceptor applies to RESPONSES after they are received from the network, but before
* they are written to cache. The goal is to manipulate the headers so that the responses would
* be readable from cache conditionally based on the app state, instead of based on what the
* server dictates.
*/
internal class CacheControlInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val rsp = chain.proceed(chain.request())
val builder = rsp.newBuilder()
if (rsp.cacheControl.mustRevalidate) {
// Override the Cache-Control header with just a max-age directive.
// Usually the server gives us a "must-revalidate" directive, which forces us to attempt
// revalidating from the network even when we're offline, which will cause offline access
// of cached data to fail. This effectively strips away "must-revalidate" so that all
// cached data will be available offline, given that we provide a "max-stale" directive
// when requesting it.
builder.header("Cache-Control", "max-age=" +
(if (rsp.cacheControl.maxAgeSeconds > 0) rsp.cacheControl.maxAgeSeconds else 0))
}
// If we're saving the current response to the offline cache, then strip away the Vary header.
if (OfflineCacheInterceptor.SAVE_HEADER_SAVE == chain.request().header(OfflineCacheInterceptor.SAVE_HEADER)) {
builder.removeHeader("Vary")
}
return builder.build()
}
}
|
apache-2.0
|
56cc98aaa8fdcc739de6644771cf2abf
| 46.371429 | 118 | 0.688179 | 4.750716 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/versions/KotlinJVMRuntimeLibraryUtil.kt
|
2
|
2602
|
// 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.versions
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.ui.Messages
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifactConstants
import org.jetbrains.kotlin.idea.configuration.BuildSystemType
import org.jetbrains.kotlin.idea.configuration.buildSystemType
import org.jetbrains.kotlin.idea.util.projectStructure.allModules
fun updateLibraries(project: Project, upToMavenVersion: String, libraries: Collection<Library>) {
if (project.allModules().any { module -> module.buildSystemType != BuildSystemType.JPS }) {
Messages.showMessageDialog(
project,
KotlinJvmBundle.message("automatic.library.version.update.for.maven.and.gradle.projects.is.currently.unsupported.please.update.your.build.scripts.manually"),
KotlinJvmBundle.message("update.kotlin.runtime.library"),
Messages.getErrorIcon()
)
return
}
libraries.asSequence()
.mapNotNull {
val lib = it as? LibraryEx ?: return@mapNotNull null
val prop = lib.properties as? RepositoryLibraryProperties ?: return@mapNotNull null
lib to prop
}
.filter { (_, prop) -> prop.groupId == KotlinArtifactConstants.KOTLIN_MAVEN_GROUP_ID }
.forEach { (lib, prop) ->
val modifiableModel = lib.modifiableModel
try {
modifiableModel.properties = RepositoryLibraryProperties(prop.groupId, prop.mavenId, upToMavenVersion)
for (orderRootType in listOf(OrderRootType.SOURCES, OrderRootType.CLASSES, OrderRootType.DOCUMENTATION)) {
modifiableModel.getUrls(orderRootType).forEach {
modifiableModel.removeRoot(it, orderRootType)
}
}
JarRepositoryManager.loadDependenciesModal(project, prop, true, true, null, null).forEach {
modifiableModel.addRoot(it.file, it.type)
}
} finally {
modifiableModel.commit()
}
}
}
|
apache-2.0
|
189da642e98ace781c6da95965577f53
| 48.09434 | 169 | 0.697925 | 4.946768 | false | false | false | false |
MarkusAmshove/Kluent
|
common/src/main/kotlin/org/amshove/kluent/ErrorCollector.kt
|
1
|
1824
|
package org.amshove.kluent
expect val errorCollector: ErrorCollector
enum class ErrorCollectionMode {
Soft, Hard
}
interface ErrorCollector {
fun getCollectionMode(): ErrorCollectionMode
fun setCollectionMode(mode: ErrorCollectionMode)
/**
* Returns the errors accumulated in the current context.
*/
fun errors(): List<Throwable>
/**
* Adds the given error to the current context.
*/
fun pushError(t: Throwable)
/**
* Clears all errors from the current context.
*/
fun clear()
}
open class BasicErrorCollector : ErrorCollector {
private val failures = mutableListOf<Throwable>()
private var mode = ErrorCollectionMode.Hard
override fun getCollectionMode(): ErrorCollectionMode = mode
override fun setCollectionMode(mode: ErrorCollectionMode) {
this.mode = mode
}
override fun pushError(t: Throwable) {
failures.add(t)
}
override fun errors(): List<Throwable> = failures.toList()
override fun clear() = failures.clear()
}
/**
* If we are in "soft assertion mode" will add this throwable to the
* list of throwables for the current execution. Otherwise will
* throw immediately.
*/
fun ErrorCollector.collectOrThrow(error: Throwable) {
when (getCollectionMode()) {
ErrorCollectionMode.Soft -> pushError(error)
ErrorCollectionMode.Hard -> throw error
}
}
/**
* The errors for the current execution are thrown as a single
* throwable.
*/
fun ErrorCollector.throwCollectedErrors() {
// set the collection mode back to the default
setCollectionMode(ErrorCollectionMode.Hard)
val failures = errors()
clear()
if (failures.isNotEmpty()) {
val t = MultiAssertionError(failures)
stacktraces.cleanStackTrace(t)
throw t
}
}
|
mit
|
31aaf5ef071e181b3e3b2f68abd59ac8
| 22.701299 | 68 | 0.685307 | 4.641221 | false | false | false | false |
ngs-doo/dsl-json
|
tests-kotlin/src/main/kotlin/com/dslplatform/json/ModelWithIgnore.kt
|
1
|
719
|
package com.dslplatform.json
//@CompiledJson
data class HasIgnoreWithDefault(
val someString: String = "some-string",
@JsonAttribute(ignore = true)val paramWithIgnoreFlag: Boolean = true) {
@JsonAttribute(ignore = true)
lateinit var stringFieldWithIgnoreFlag: String
@JsonAttribute(mandatory = true)
lateinit var stringWhichShouldBeInPlace: String
}
//@CompiledJson
data class HasIgnoreNoDefault(
val someString: String,
@JsonAttribute(ignore = true)val paramWithIgnoreFlag: Boolean) {
@JsonAttribute(ignore = true)
lateinit var stringFieldWithIgnoreFlag: String
@JsonAttribute(mandatory = true)
lateinit var stringWhichShouldBeInPlace: String
}
|
bsd-3-clause
|
cdd48959eff72dcc192a99f09291040c
| 29.347826 | 75 | 0.735744 | 4.438272 | false | false | false | false |
DreierF/MyTargets
|
shared/src/main/java/de/dreier/mytargets/shared/targets/models/NFAAIndoor5Spot.kt
|
1
|
2137
|
/*
* 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 android.graphics.PointF
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Dimension.Unit.CENTIMETER
import de.dreier.mytargets.shared.targets.decoration.CenterMarkDecorator
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import de.dreier.mytargets.shared.targets.zone.CircularZone
import de.dreier.mytargets.shared.utils.Color.DARK_GRAY
import de.dreier.mytargets.shared.utils.Color.SAPPHIRE_BLUE
import de.dreier.mytargets.shared.utils.Color.WHITE
class NFAAIndoor5Spot : TargetModelBase(
id = ID,
nameRes = R.string.nfaa_indoor_5_spot,
zones = listOf(
CircularZone(0.25f, WHITE, DARK_GRAY, 2),
CircularZone(0.5f, WHITE, DARK_GRAY, 2),
CircularZone(0.75f, SAPPHIRE_BLUE, WHITE, 2),
CircularZone(1.0f, SAPPHIRE_BLUE, WHITE, 0)
),
scoringStyles = listOf(
ScoringStyle(true, 5, 5, 4, 4),
ScoringStyle(false, 6, 6, 5, 4),
ScoringStyle(false, 7, 6, 5, 4)
),
diameters = listOf(Dimension(40f, CENTIMETER))
) {
init {
decorator = CenterMarkDecorator(DARK_GRAY, 25f, 9, true)
facePositions = listOf(
PointF(-0.6f, -0.6f),
PointF(0.6f, -0.6f),
PointF(0.0f, 0.0f),
PointF(-0.6f, 0.6f),
PointF(0.6f, 0.6f)
)
faceRadius = 0.4f
}
companion object {
const val ID = 11L
}
}
|
gpl-2.0
|
68e7e830637f6eb4c5c050e4a1dc0ce7
| 35.220339 | 72 | 0.653252 | 3.615905 | false | false | false | false |
zbeboy/ISY
|
src/main/java/top/zbeboy/isy/web/internship/release/InternshipReleaseController.kt
|
1
|
16293
|
package top.zbeboy.isy.web.internship.release
import com.alibaba.fastjson.JSON
import org.apache.commons.lang3.math.NumberUtils
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartHttpServletRequest
import top.zbeboy.isy.domain.tables.pojos.Files
import top.zbeboy.isy.domain.tables.pojos.InternshipFile
import top.zbeboy.isy.domain.tables.pojos.InternshipRelease
import top.zbeboy.isy.domain.tables.pojos.Science
import top.zbeboy.isy.service.common.FilesService
import top.zbeboy.isy.service.internship.InternshipFileService
import top.zbeboy.isy.service.internship.InternshipReleaseScienceService
import top.zbeboy.isy.service.internship.InternshipReleaseService
import top.zbeboy.isy.service.platform.UsersService
import top.zbeboy.isy.service.util.DateTimeUtils
import top.zbeboy.isy.service.util.UUIDUtils
import top.zbeboy.isy.web.bean.file.FileBean
import top.zbeboy.isy.web.bean.internship.release.InternshipReleaseBean
import top.zbeboy.isy.web.common.MethodControllerCommon
import top.zbeboy.isy.web.internship.common.InternshipMethodControllerCommon
import top.zbeboy.isy.web.util.AjaxUtils
import top.zbeboy.isy.web.util.PaginationUtils
import top.zbeboy.isy.web.vo.internship.release.InternshipReleaseAddVo
import top.zbeboy.isy.web.vo.internship.release.InternshipReleaseUpdateVo
import java.sql.Timestamp
import java.text.ParseException
import java.time.Clock
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.validation.Valid
/**
* Created by zbeboy 2017-12-18 .
**/
@Controller
open class InternshipReleaseController {
private val log = LoggerFactory.getLogger(InternshipReleaseController::class.java)
@Resource
open lateinit var internshipReleaseService: InternshipReleaseService
@Resource
open lateinit var internshipReleaseScienceService: InternshipReleaseScienceService
@Resource
open lateinit var methodControllerCommon: MethodControllerCommon
@Resource
open lateinit var internshipMethodControllerCommon: InternshipMethodControllerCommon
@Resource
open lateinit var usersService: UsersService
@Resource
open lateinit var filesService: FilesService
@Resource
open lateinit var internshipFileService: InternshipFileService
/**
* 实习发布数据
*
* @return 实习发布数据页面
*/
@RequestMapping(value = ["/web/menu/internship/release"], method = [(RequestMethod.GET)])
fun releaseData(): String {
return "web/internship/release/internship_release::#page-wrapper"
}
/**
* 获取实习发布数据
*
* @param paginationUtils 分页工具
* @return 数据
*/
@RequestMapping(value = ["/web/internship/release/data"], method = [(RequestMethod.GET)])
@ResponseBody
fun releaseDatas(paginationUtils: PaginationUtils): AjaxUtils<InternshipReleaseBean> {
val ajaxUtils = AjaxUtils.of<InternshipReleaseBean>()
val internshipReleaseBean = InternshipReleaseBean()
val commonData = methodControllerCommon.adminOrNormalData()
internshipReleaseBean.departmentId = if (StringUtils.isEmpty(commonData["departmentId"])) -1 else commonData["departmentId"]
internshipReleaseBean.collegeId = if (StringUtils.isEmpty(commonData["collegeId"])) -1 else commonData["collegeId"]
val records = internshipReleaseService.findAllByPage(paginationUtils, internshipReleaseBean)
val internshipReleaseBeens = internshipReleaseService.dealData(paginationUtils, records, internshipReleaseBean)
return ajaxUtils.success().msg("获取数据成功").listData(internshipReleaseBeens).paginationUtils(paginationUtils)
}
/**
* 实习发布添加页面
*
* @param modelMap 页面对象
* @return 实习发布添加页面
*/
@RequestMapping(value = ["/web/internship/release/add"], method = [(RequestMethod.GET)])
fun releaseAdd(modelMap: ModelMap): String {
val commonData = methodControllerCommon.adminOrNormalData()
modelMap.addAttribute("departmentId", if (StringUtils.isEmpty(commonData["departmentId"])) -1 else commonData["departmentId"])
modelMap.addAttribute("collegeId", if (StringUtils.isEmpty(commonData["collegeId"])) -1 else commonData["collegeId"])
return "web/internship/release/internship_release_add::#page-wrapper"
}
/**
* 实习发布编辑页面
*
* @param internshipReleaseId 实习发布id
* @param modelMap 页面对象
* @return 实习发布编辑页面
*/
@RequestMapping(value = ["/web/internship/release/edit"], method = [(RequestMethod.GET)])
fun releaseEdit(@RequestParam("id") internshipReleaseId: String, modelMap: ModelMap): String {
val records = internshipReleaseService.findByIdRelation(internshipReleaseId)
var internshipRelease = InternshipReleaseBean()
var sciences: List<Science> = ArrayList()
if (records.isPresent) {
internshipRelease = records.get().into(InternshipReleaseBean::class.java)
val recordResult = internshipReleaseScienceService.findByInternshipReleaseIdRelation(internshipRelease.internshipReleaseId)
if (recordResult.isNotEmpty) {
sciences = recordResult.into(Science::class.java)
}
}
modelMap.addAttribute("internshipRelease", internshipRelease)
modelMap.addAttribute("sciences", sciences)
return "web/internship/release/internship_release_edit::#page-wrapper"
}
/**
* 保存时检验标题
*
* @param title 标题
* @return true or false
*/
@RequestMapping(value = ["/web/internship/release/save/valid"], method = [(RequestMethod.POST)])
@ResponseBody
fun saveValid(@RequestParam("releaseTitle") title: String): AjaxUtils<*> {
val releaseTitle = StringUtils.trimWhitespace(title)
if (StringUtils.hasLength(releaseTitle)) {
val internshipReleases = internshipReleaseService.findByReleaseTitle(releaseTitle)
if (ObjectUtils.isEmpty(internshipReleases) && internshipReleases.isEmpty()) {
return AjaxUtils.of<Any>().success().msg("标题不重复")
}
}
return AjaxUtils.of<Any>().fail().msg("标题重复")
}
/**
* 更新时检验标题
*
* @param internshipReleaseId 实习发布id
* @param title 标题
* @return true or false
*/
@RequestMapping(value = ["/web/internship/release/update/valid"], method = [(RequestMethod.POST)])
@ResponseBody
fun updateValid(@RequestParam("internshipReleaseId") internshipReleaseId: String, @RequestParam("releaseTitle") title: String): AjaxUtils<*> {
val releaseTitle = StringUtils.trimWhitespace(title)
if (StringUtils.hasLength(releaseTitle)) {
val internshipReleases = internshipReleaseService.findByReleaseTitleNeInternshipReleaseId(releaseTitle, internshipReleaseId)
if (ObjectUtils.isEmpty(internshipReleases) && internshipReleases.isEmpty()) {
return AjaxUtils.of<Any>().success().msg("标题不重复")
}
}
return AjaxUtils.of<Any>().fail().msg("标题重复")
}
/**
* 保存
*
* @param internshipReleaseAddVo 实习
* @param bindingResult 检验
* @return true or false
*/
@RequestMapping(value = ["/web/internship/release/save"], method = [(RequestMethod.POST)])
@ResponseBody
fun save(@Valid internshipReleaseAddVo: InternshipReleaseAddVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors()) {
val internshipReleaseId = UUIDUtils.getUUID()
val teacherDistributionTime = internshipReleaseAddVo.teacherDistributionTime
val time = internshipReleaseAddVo.time
val files = internshipReleaseAddVo.files
val internshipRelease = InternshipRelease()
internshipRelease.internshipReleaseId = internshipReleaseId
internshipRelease.internshipTitle = internshipReleaseAddVo.releaseTitle
internshipRelease.releaseTime = Timestamp(Clock.systemDefaultZone().millis())
val users = usersService.getUserFromSession()
internshipRelease.username = users!!.username
internshipRelease.publisher = users.realName
saveOrUpdateTime(internshipRelease, teacherDistributionTime!!, time!!)
internshipRelease.allowGrade = internshipReleaseAddVo.grade
internshipRelease.departmentId = internshipReleaseAddVo.departmentId
internshipRelease.internshipReleaseIsDel = internshipReleaseAddVo.internshipReleaseIsDel
internshipRelease.internshipTypeId = internshipReleaseAddVo.internshipTypeId
internshipReleaseService.save(internshipRelease)
if (StringUtils.hasLength(internshipReleaseAddVo.scienceId)) {
val scienceArr = internshipReleaseAddVo.scienceId!!.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (scienceId in scienceArr) {
internshipReleaseScienceService.save(internshipReleaseId, NumberUtils.toInt(scienceId))
}
}
saveOrUpdateFiles(files, internshipReleaseId)
return AjaxUtils.of<Any>().success().msg("保存成功")
}
return AjaxUtils.of<Any>().fail().msg("保存失败")
}
/**
* 更新
*
* @param internshipReleaseUpdateVo 实习
* @param bindingResult 检验
* @return true or false
*/
@RequestMapping(value = ["/web/internship/release/update"], method = [(RequestMethod.POST)])
@ResponseBody
fun update(@Valid internshipReleaseUpdateVo: InternshipReleaseUpdateVo, bindingResult: BindingResult): AjaxUtils<*> {
if (!bindingResult.hasErrors()) {
val internshipReleaseId = internshipReleaseUpdateVo.internshipReleaseId
val teacherDistributionTime = internshipReleaseUpdateVo.teacherDistributionTime
val time = internshipReleaseUpdateVo.time
val files = internshipReleaseUpdateVo.files
val internshipRelease = internshipReleaseService.findById(internshipReleaseId!!)
internshipRelease.internshipTitle = internshipReleaseUpdateVo.releaseTitle
saveOrUpdateTime(internshipRelease, teacherDistributionTime!!, time!!)
internshipRelease.internshipReleaseIsDel = internshipReleaseUpdateVo.internshipReleaseIsDel
internshipReleaseService.update(internshipRelease)
val records = internshipFileService.findByInternshipReleaseId(internshipReleaseId)
if (records.isNotEmpty) {
internshipFileService.deleteByInternshipReleaseId(internshipReleaseId)
val internshipFiles = records.into(InternshipFile::class.java)
internshipFiles.forEach { f -> filesService.deleteById(f.fileId) }
}
saveOrUpdateFiles(files, internshipReleaseId)
return AjaxUtils.of<Any>().success().msg("保存成功")
}
return AjaxUtils.of<Any>().fail().msg("保存失败")
}
/**
* 更新实习发布状态
*
* @param internshipReleaseId 实习发布id
* @param isDel 注销参数
* @return true or false
*/
@RequestMapping(value = ["/web/internship/release/update/del"], method = [(RequestMethod.POST)])
@ResponseBody
fun updateDel(@RequestParam("internshipReleaseId") internshipReleaseId: String, @RequestParam("isDel") isDel: Byte?): AjaxUtils<*> {
val internshipRelease = internshipReleaseService.findById(internshipReleaseId)
internshipRelease.internshipReleaseIsDel = isDel
internshipReleaseService.update(internshipRelease)
return AjaxUtils.of<Any>().success().msg("更新状态成功")
}
/**
* 更新或保存时间
*
* @param internshipRelease 实习
* @param teacherDistributionTime 教师分配时间
* @param time 申请时间
*/
private fun saveOrUpdateTime(internshipRelease: InternshipRelease, teacherDistributionTime: String, time: String) {
try {
val format = "yyyy-MM-dd HH:mm:ss"
val teacherDistributionArr = DateTimeUtils.splitDateTime("至", teacherDistributionTime)
internshipRelease.teacherDistributionStartTime = DateTimeUtils.formatDateToTimestamp(teacherDistributionArr[0], format)
internshipRelease.teacherDistributionEndTime = DateTimeUtils.formatDateToTimestamp(teacherDistributionArr[1], format)
val timeArr = DateTimeUtils.splitDateTime("至", time)
internshipRelease.startTime = DateTimeUtils.formatDateToTimestamp(timeArr[0], format)
internshipRelease.endTime = DateTimeUtils.formatDateToTimestamp(timeArr[1], format)
} catch (e: ParseException) {
log.error(" format time is exception.", e)
}
}
/**
* 更新或保存文件
*
* @param files 文件json
* @param internshipReleaseId 实习id
*/
private fun saveOrUpdateFiles(files: String?, internshipReleaseId: String) {
if (StringUtils.hasLength(files)) {
val filesList = JSON.parseArray(files, Files::class.java)
for (f in filesList) {
val fileId = UUIDUtils.getUUID()
f.fileId = fileId
filesService.save(f)
val internshipFile = InternshipFile(internshipReleaseId, fileId)
internshipFileService.save(internshipFile)
}
}
}
/**
* 上传实习附件
*
* @param schoolId 学校id
* @param collegeId 院id
* @param departmentId 系id
* @param multipartHttpServletRequest 文件请求
* @return 文件信息
*/
@RequestMapping("/web/internship/release/upload/file/internship")
@ResponseBody
fun uploadFileInternship(schoolId: Int?, collegeId: Int?, @RequestParam("departmentId") departmentId: Int,
multipartHttpServletRequest: MultipartHttpServletRequest): AjaxUtils<FileBean> {
return methodControllerCommon.uploadFile(schoolId, collegeId, departmentId, multipartHttpServletRequest)
}
/**
* 删除实习附件
*
* @param filePath 文件路径
* @param request 请求
* @return true or false
*/
@RequestMapping("/web/internship/release/delete/file")
@ResponseBody
fun deleteFile(@RequestParam("filePath") filePath: String, request: HttpServletRequest): AjaxUtils<*> {
return if (methodControllerCommon.deleteFile(filePath, request)) {
AjaxUtils.of<Any>().success().msg("删除文件成功")
} else {
AjaxUtils.of<Any>().fail().msg("删除文件失败")
}
}
/**
* 删除实习附件
*
* @param filePath 文件路径
* @param fileId 文件id
* @param internshipReleaseId 实习id
* @param request 请求
* @return true or false
*/
@RequestMapping("/web/internship/release/delete/file/internship")
@ResponseBody
fun deleteFileInternship(@RequestParam("filePath") filePath: String, @RequestParam("fileId") fileId: String,
@RequestParam("internshipReleaseId") internshipReleaseId: String, request: HttpServletRequest): AjaxUtils<*> {
return internshipMethodControllerCommon.deleteFileInternship(filePath, fileId, internshipReleaseId, request)
}
}
|
mit
|
1f93a5a8c1a213cd84cb6138d86a366b
| 43.320225 | 146 | 0.694302 | 5.154198 | false | false | false | false |
elpassion/mainframer-intellij-plugin
|
src/main/kotlin/com/elpassion/mainframerplugin/action/configure/selector/ui/SelectorList.kt
|
1
|
1471
|
package com.elpassion.mainframerplugin.action.configure.selector.ui
import com.elpassion.mainframerplugin.action.configure.selector.SelectorItem
import com.intellij.ui.CheckBoxList
import com.jgoodies.common.collect.ArrayListModel
import javax.swing.JCheckBox
import javax.swing.ListModel
import javax.swing.ListSelectionModel
class SelectorList : CheckBoxList<SelectorItem>() {
init {
selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
}
var items: List<SelectorItem> = emptyList()
set(value) {
@Suppress("UNCHECKED_CAST")
model = value.asListModel() as ListModel<JCheckBox>
field = value
}
get() = field.mapIndexed { index, selectorItem -> selectorItem.copy(isSelected = isItemSelected(index)) }
@Suppress("unchecked_cast")
private val listModel get() = model as ArrayListModel<JCheckBox>
fun selectAll() {
listModel.forEachIndexed { index, checkBox ->
checkBox.isSelected = true
listModel.fireContentsChanged(index)
}
}
fun unselectAll() {
listModel.forEachIndexed { index, checkBox ->
checkBox.isSelected = false
listModel.fireContentsChanged(index)
}
}
private fun List<SelectorItem>.asListModel() = ArrayListModel(map { createCheckBox(it) })
private fun createCheckBox(item: SelectorItem) = JCheckBox(item.name).apply { isSelected = item.isSelected }
}
|
apache-2.0
|
9fd41c3a772173e1b29218b7c40bad4b
| 32.454545 | 113 | 0.693406 | 4.760518 | false | false | false | false |
cbeust/klaxon
|
src/test/kotlin/com/beust/klaxon/KlaxonTest.kt
|
1
|
14777
|
package com.beust.klaxon
import com.beust.klaxon.jackson.jackson
import org.assertj.core.api.Assertions.assertThat
import org.intellij.lang.annotations.Language
import org.testng.Assert
import org.testng.annotations.Test
import java.math.BigDecimal
import java.util.Collections.emptyMap
import java.util.regex.Pattern
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.fail
@Test
class DefaultParserTest : KlaxonBaseTest() {
override fun provideParser(): Parser =
Parser.default()
}
@Test
class JacksonParserTest : KlaxonBaseTest() {
override fun provideParser(): Parser =
Parser.jackson()
}
@Test
abstract class KlaxonBaseTest {
protected abstract fun provideParser(): Parser
private fun read(name: String): Any? {
val cls = KlaxonBaseTest::class.java
return provideParser().parse(cls.getResourceAsStream(name)!!)
}
fun generated() {
@Suppress("UNCHECKED_CAST")
val j = read("/generated.json") as JsonArray<JsonObject>
Assert.assertEquals((j[0]["name"] as JsonObject)["last"], "Olson")
}
fun simple() {
val j = read("/b.json")
val expected = json {
array(1, "abc", false)
}
assertEquals(expected, j)
}
fun basic() {
val j = read("/a.json")
val expected = json {
obj("a" to "b",
"c" to array(1, "abc", false),
"e" to obj("f" to 30, "g" to 31)
)
}
assertEquals(expected, j)
}
fun nullsParse() {
assertEquals(json {
array(1, null, obj(
"a" to 1,
"." to null
))
}, read("/nulls.json"))
}
fun nullsDsl() {
val j = json {
obj(
"1" to null,
"2" to 2
)
}
assertEquals("""{"1":null,"2":2}""", j.toJsonString())
}
fun prettyPrintObject() {
val j = json {
obj(
"a" to 1,
"b" to "text"
)
}
val expected = """{
"a": 1,
"b": "text"
}"""
val actual = j.toJsonString(true)
assertEquals(trim(expected), trim(actual))
}
fun prettyPrintEmptyObject() {
assertEquals("{}", JsonObject(emptyMap()).toJsonString(true))
}
fun prettyPrintArray() {
assertEquals("[1, 2, 3]", JsonArray(1, 2, 3).toJsonString(true))
}
fun prettyPrintNestedObjects() {
val expected = """{
"a": 1,
"obj": {
"b": 2
}
}"""
val actual = json {
obj(
"a" to 1,
"obj" to json {
obj("b" to 2)
}
)
}.toJsonString(true)
assertEquals(trim(actual), trim(expected))
}
fun canonicalJsonObject() {
val j = json {
obj(
"c" to 1,
"a" to 2,
"b" to obj(
"e" to 1,
"d" to 2
)
)
}.toJsonString(canonical = true)
val expected = """{"a":2,"b":{"d":2,"e":1},"c":1}"""
assertEquals(j, expected)
}
fun canonicalJsonNumber() {
val j = json {
obj(
"d" to 123456789.123456789,
"f" to 123456789.123456789f
)
}.toJsonString(canonical = true)
assert(Pattern.matches("\\{(\"[a-z]+\":\\d\\.\\d+E\\d+(,|}\$))+", j))
}
private fun trim(s: String) = s.replace("\n", "").replace("\r", "")
fun renderStringEscapes() {
assertEquals(""" "test\"it\n" """.trim(), valueToString("test\"it\n"))
}
fun parseStringEscapes() {
val s = "text field \"s\"\nnext line\u000cform feed\ttab\\rev solidus/solidus\bbackspace\u2018"
assertEquals(json {
obj(s to s)
}, read("/escaped.json"))
}
fun issue91WithQuotedDoubleStrings() {
val map = HashMap<String, String>()
map["whoops"] = """ Hello "world" """
val s = Klaxon().toJsonString(map)
assertThat(s).contains("\\\"world\\\"")
}
fun arrayLookup() {
val j = json {
array(
obj(
"nick" to "SuperMan",
"address" to obj("country" to "US"),
"weight" to 89.4,
"d" to 1L,
"i" to 4,
"b" to java.math.BigInteger("123456789123456789123456786")
),
obj(
"nick" to "BlackOwl",
"address" to obj("country" to "UK"),
"weight" to 75.7,
"d" to 2L,
"i" to 3,
"b" to java.math.BigInteger("123456789123456789123456787")
),
obj(
"nick" to "Anonymous",
"address" to null,
"weight" to -1.0,
"d" to 3L,
"i" to 2,
"b" to java.math.BigInteger("123456789123456789123456788")
),
obj(
"nick" to "Rocket",
"address" to obj("country" to "Russia"),
"weight" to 72.0,
"d" to 4L,
"i" to 1,
"b" to java.math.BigInteger("123456789123456789123456789")
)
)
}
assertEquals(listOf("SuperMan", "BlackOwl", "Anonymous", "Rocket"),
j.string("nick").filterNotNull())
assertEquals(listOf("US", "UK", null, "Russia"),
j.obj("address").map { it?.string("country") })
assertKlaxonEquals(JsonArray(89.4, 75.7, -1.0, 72.0), j.double("weight"))
assertKlaxonEquals(JsonArray(1L, 2L, 3L, 4L), j.long("d"))
assertKlaxonEquals(JsonArray(4, 3, 2, 1), j.int("i"))
assertKlaxonEquals(JsonArray(
java.math.BigInteger("123456789123456789123456786"),
java.math.BigInteger("123456789123456789123456787"),
java.math.BigInteger("123456789123456789123456788"),
java.math.BigInteger("123456789123456789123456789")), j.bigInt("b"))
}
private fun <T> assertKlaxonEquals(expected: List<T>, actual: JsonArray<T>) {
for (i in 0..expected.size - 1) {
assertEquals(expected.get(i), actual.get(i))
}
}
fun objectLookup() {
val j = json {
obj(
"nick" to "BlackOwl",
"address" to obj("country" to "UK"),
"weight" to 75.7,
"d" to 1L,
"true" to true
)
}
assertEquals("BlackOwl", j.string("nick"))
assertEquals(JsonObject(mapOf("country" to "UK")), j.obj("address"))
assertEquals(75.7, j.double("weight"))
assertEquals(1L, j.long("d"))
assertTrue(j.boolean("true")!!)
}
fun arrayFiltering() {
val j = json {
array(1, 2, 3, obj("a" to 1L))
}
assertEquals(listOf(1L), j.filterIsInstance<JsonObject>().map { it.long("a") })
}
fun lookupObjects() {
val j = json {
obj(
"users" to
array(
obj(
"name" to "Sergey",
"weight" to 65.0
),
obj(
"name" to "Bombshell",
"weight" to 121.0
),
null
)
)
}
assertEquals(JsonArray("Sergey", "Bombshell", null), j.lookup<String?>("/users/name"))
assertEquals(JsonArray("Sergey", "Bombshell", null), j.lookup<String?>("users.name"))
}
fun lookupArray() {
val j = json {
array(
"yo", obj("a" to 1)
)
}
assertEquals(JsonArray(null, 1), j.lookup<Int?>("a"))
}
fun lookupNestedArrays() {
val j = json {
array (
array(
array(
"yo", obj("a" to 1)
)
)
)
}
assertEquals(JsonArray(null, 1), j.lookup<Int?>("a"))
}
fun lookupSingleObject() {
val j = json {
obj("a" to 1)
}
assertEquals(1, j.lookup<Int?>("a").single())
}
fun mapChildren() {
val j = json {
array(1,2,3)
}
val result = j.mapChildrenObjectsOnly { fail("should never reach here") }
assertTrue(result.isEmpty())
}
fun mapChildrenWithNulls() {
val j = json {
array(1,2,3)
}
val result = j.mapChildren { fail("should never reach here") }
assertKlaxonEquals(listOf(null, null, null), result)
}
private fun valueToString(v: Any?, prettyPrint: Boolean = false, canonical : Boolean = false) : String =
StringBuilder().apply {
Render.renderValue(v, this, prettyPrint, canonical, 0)
}.toString()
fun renderMap() {
val map = mapOf(
"a" to 1,
"b" to "x",
"c" to null
)
assertEquals(valueToString(map), "{\"a\":1,\"b\":\"x\",\"c\":null}")
}
fun renderList() {
val list = listOf(null, 1, true, false, "a")
assertEquals(valueToString(list), "[null,1,true,false,\"a\"]")
}
data class StockEntry(
val date: String,
val close: Double,
val volume: Int,
val open: Double,
val high: Double,
val low: Double
)
fun issue77() {
val json = """
[
{
"date": "2018/01/10",
"close": 0.25,
"volume": 500000,
"open": 0.5,
"high": 0.5,
"low": 0.25
}
]
"""
Klaxon().parseArray<StockEntry>(json)
}
class PersonWitCity(val name: String, val city: City) {
class City(val name: String)
}
fun arrayParse() {
data class Child(val id: Int, val name: String)
data class Parent(val children: Array<Child>)
val array = """{
"children":[
{"id": 1, "name": "foo"},
{"id": 2, "name": "bar"}
]
}"""
val r = Klaxon().parse<Parent>(array)
with(r!!.children) {
assertThat(this[0]).isEqualTo(Child(1, "foo"))
assertThat(this[1]).isEqualTo(Child(2, "bar"))
}
}
fun nestedCollections() {
data class Root (val lists: List<List<String>>)
val result = Klaxon().parse<Root>("""
{
"lists": [["red", "green", "blue"]]
}
""")
assertThat(result).isEqualTo(Root(listOf(listOf("red", "green", "blue"))))
}
fun nested() {
val r = Klaxon().parse<PersonWitCity>("""{
"name": "John",
"city": {
"name": "San Francisco"
}
}""")
Assert.assertEquals(r?.name, "John")
Assert.assertEquals(r?.city?.name, "San Francisco")
}
fun bigDecimal() {
data class A(val data: BigDecimal)
val something = Klaxon().parse<A>("""
{"data": 0.00000001}
""")
assertThat(BigDecimal(0.00000001).compareTo(BigDecimal(something!!.data.toDouble()))).isEqualTo(0)
}
enum class Colour { Red, Green, Blue }
data class ColourHolder(val colour: Colour)
fun serializeEnum() {
val klaxon = Klaxon()
Assert.assertEquals(klaxon.toJsonString(Colour.Red), "\"Red\"")
Assert.assertEquals(klaxon.parse<ColourHolder>("{\"colour\": \"Green\"}"), ColourHolder(Colour.Green))
}
enum class ShortColour {
@Json("R")
Red,
@Json("G")
Green,
@Json("B")
Blue
}
data class ShortColourHolder(val colour: ShortColour)
fun serializeEnumWithRenames() {
val klaxon = Klaxon()
Assert.assertEquals(klaxon.toJsonString(ShortColour.Red), "\"R\"")
Assert.assertEquals(klaxon.parse<ShortColourHolder>("{\"colour\": \"G\"}"), ShortColourHolder(ShortColour.Green))
}
@Test
fun nonConstructorProperties() {
val result = Klaxon().parse<Registry>(someString)
val vendors = result?.vendor!!
assertThat("example").isEqualTo(result.name)
assertThat("example").isEqualTo(vendors[0].vendorName)
}
private class Vendor {
var vendorName : String = ""
}
@Language("json")
private val someString = """{
"name": "example",
"foo": "cool",
"boo": "stuff",
"vendor": [
{ "vendorName": "example"}
]
}"""
@Test
fun testParseRegistry() {
val result = Klaxon().parse<Registry>(someString)
val vendors = result?.vendor!!
assertEquals("example", result!!.name)
assertEquals("cool", result.foo)
assertEquals("stuff", result.boo)
assertEquals("example", vendors[0].vendorName)
}
private class Registry(val name : String,
val vendor : List<Vendor> = ArrayList()) {
var foo : String = ""
var boo : String = ""
}
fun issue153() {
abstract class FooBase(
val id: String? = null
)
class BarImpl(
val barValue: String? = null
): FooBase()
val barImpl = Klaxon()
.parse<BarImpl>("""
{
"id": "id123",
"barValue" : "value123"
}
""")
assertThat(barImpl?.barValue).isEqualTo("value123")
assertThat(barImpl?.id).isEqualTo("id123")
}
fun convertToJsonObjectTest() {
data class Employee(val name: String, val age: Int)
val jo = Klaxon().toJsonObject(Employee("Joe", 24))
assertThat(jo["age"]).isEqualTo("24")
assertThat(jo["name"]).isEqualTo("\"Joe\"")
}
}
|
apache-2.0
|
047911c75ecf301fc2d8fa7f6db06bf2
| 27.362764 | 121 | 0.46146 | 4.375777 | false | false | false | false |
paplorinc/intellij-community
|
platform/credential-store/src/kdbx/KdbxHeader.kt
|
3
|
12062
|
/*
* Copyright 2015 Jo Rabin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.credentialStore.kdbx
import com.google.common.io.LittleEndianDataInputStream
import com.google.common.io.LittleEndianDataOutputStream
import com.intellij.credentialStore.generateBytes
import com.intellij.util.ArrayUtilRt
import org.bouncycastle.crypto.engines.AESEngine
import org.bouncycastle.crypto.io.CipherInputStream
import org.bouncycastle.crypto.io.CipherOutputStream
import org.bouncycastle.crypto.modes.CBCBlockCipher
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.crypto.params.ParametersWithIV
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.security.DigestInputStream
import java.security.DigestOutputStream
import java.security.SecureRandom
import java.util.*
import java.util.zip.GZIPOutputStream
/**
* This class represents the header portion of a KeePass KDBX file or stream. The header is received in
* plain text and describes the encryption and compression of the remainder of the file.
* It is a factory for encryption and decryption streams and contains a hash of its own serialization.
* While KDBX streams are Little-Endian, data is passed to and from this class in standard Java byte order.
* @author jo
* This UUID denotes that AES Cipher is in use. No other values are known.
*/
private val AES_CIPHER = UUID.fromString("31C1F2E6-BF71-4350-BE58-05216AFC5AFF")
private const val FILE_VERSION_CRITICAL_MASK = 0xFFFF0000.toInt()
private const val SIG1 = 0x9AA2D903.toInt()
private const val SIG2 = 0xB54BFB67.toInt()
private const val FILE_VERSION_32 = 0x00030001
internal fun createProtectedStreamKey(random: SecureRandom) = random.generateBytes(32)
private object HeaderType {
const val END: Byte = 0
const val COMMENT: Byte = 1
const val CIPHER_ID: Byte = 2
const val COMPRESSION_FLAGS: Byte = 3
const val MASTER_SEED: Byte = 4
const val TRANSFORM_SEED: Byte = 5
const val TRANSFORM_ROUNDS: Byte = 6
const val ENCRYPTION_IV: Byte = 7
const val PROTECTED_STREAM_KEY: Byte = 8
const val STREAM_START_BYTES: Byte = 9
const val INNER_RANDOM_STREAM_ID: Byte = 10
}
private fun readSignature(input: LittleEndianDataInputStream): Boolean {
return input.readInt() == SIG1 && input.readInt() == SIG2
}
private fun verifyFileVersion(input: LittleEndianDataInputStream): Boolean {
return input.readInt() and FILE_VERSION_CRITICAL_MASK <= FILE_VERSION_32 and FILE_VERSION_CRITICAL_MASK
}
internal class KdbxHeader() {
constructor(inputStream: InputStream) : this() {
readKdbxHeader(inputStream)
}
constructor(random: SecureRandom) : this() {
masterSeed = random.generateBytes(32)
transformSeed = random.generateBytes(32)
encryptionIv = random.generateBytes(16)
protectedStreamKey = createProtectedStreamKey(random)
}
/**
* The ordinal 0 represents uncompressed and 1 GZip compressed
*/
enum class CompressionFlags {
NONE, GZIP
}
/**
* The ordinals represent various types of encryption that may be applied to fields within the unencrypted data
*/
enum class ProtectedStreamAlgorithm {
NONE, ARC_FOUR, SALSA_20
}
// the cipher in use
private var cipherUuid = AES_CIPHER
/* whether the data is compressed */
var compressionFlags = CompressionFlags.GZIP
private set
private var masterSeed: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
private var transformSeed: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
private var transformRounds: Long = 6000
private var encryptionIv: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
var protectedStreamKey: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
private set
private var protectedStreamAlgorithm = ProtectedStreamAlgorithm.SALSA_20
/* these bytes appear in cipher text immediately following the header */
var streamStartBytes = ByteArray(32)
private set
/* not transmitted as part of the header, used in the XML payload, so calculated
* on transmission or receipt */
var headerHash: ByteArray? = null
/**
* Create a decrypted input stream using supplied digest and this header
* apply decryption to the passed encrypted input stream
*/
fun createDecryptedStream(digest: ByteArray, inputStream: InputStream): InputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
return getDecryptedInputStream(inputStream, finalKeyDigest, encryptionIv)
}
/**
* Create an unencrypted output stream using the supplied digest and this header
* and use the supplied output stream to write encrypted data.
*/
fun createEncryptedStream(digest: ByteArray, outputStream: OutputStream): OutputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
var out = getEncryptedOutputStream(outputStream, finalKeyDigest, encryptionIv)
out.write(streamStartBytes)
out = HashedBlockOutputStream(out)
return when (compressionFlags) {
KdbxHeader.CompressionFlags.GZIP -> GZIPOutputStream(out, HashedBlockOutputStream.BLOCK_SIZE)
else -> out
}
}
private fun setCipherUuid(uuid: ByteArray) {
val b = ByteBuffer.wrap(uuid)
val incoming = UUID(b.long, b.getLong(8))
if (incoming != AES_CIPHER) {
throw IllegalStateException("Unknown Cipher UUID $incoming")
}
cipherUuid = incoming
}
/**
* Populate a KdbxHeader from the input stream supplied
*/
private fun readKdbxHeader(inputStream: InputStream) {
val digest = sha256MessageDigest()
// we do not close this stream, otherwise we lose our place in the underlying stream
val digestInputStream = DigestInputStream(inputStream, digest)
// we do not close this stream, otherwise we lose our place in the underlying stream
val input = LittleEndianDataInputStream(digestInputStream)
if (!readSignature(input)) {
throw KdbxException("Bad signature")
}
if (!verifyFileVersion(input)) {
throw IllegalStateException("File version did not match")
}
while (true) {
val headerType = input.readByte()
if (headerType == HeaderType.END) {
break
}
when (headerType) {
HeaderType.COMMENT -> readHeaderData(input)
HeaderType.CIPHER_ID -> setCipherUuid(readHeaderData(input))
HeaderType.COMPRESSION_FLAGS -> {
compressionFlags = CompressionFlags.values()[readIntHeaderData(input)]
}
HeaderType.MASTER_SEED -> masterSeed = readHeaderData(input)
HeaderType.TRANSFORM_SEED -> transformSeed = readHeaderData(input)
HeaderType.TRANSFORM_ROUNDS -> transformRounds = readLongHeaderData(input)
HeaderType.ENCRYPTION_IV -> encryptionIv = readHeaderData(input)
HeaderType.PROTECTED_STREAM_KEY -> protectedStreamKey = readHeaderData(input)
HeaderType.STREAM_START_BYTES -> streamStartBytes = readHeaderData(input)
HeaderType.INNER_RANDOM_STREAM_ID -> {
protectedStreamAlgorithm = ProtectedStreamAlgorithm.values()[readIntHeaderData(input)]
}
else -> throw IllegalStateException("Unknown File Header")
}
}
// consume length etc. following END flag
readHeaderData(input)
headerHash = digest.digest()
}
/**
* Write a KdbxHeader to the output stream supplied. The header is updated with the
* message digest of the written stream.
*/
fun writeKdbxHeader(outputStream: OutputStream) {
val messageDigest = sha256MessageDigest()
val digestOutputStream = DigestOutputStream(outputStream, messageDigest)
val output = LittleEndianDataOutputStream(digestOutputStream)
// write the magic number
output.writeInt(SIG1)
output.writeInt(SIG2)
// write a file version
output.writeInt(FILE_VERSION_32)
output.writeByte(HeaderType.CIPHER_ID.toInt())
output.writeShort(16)
val b = ByteArray(16)
val bb = ByteBuffer.wrap(b)
bb.putLong(cipherUuid.mostSignificantBits)
bb.putLong(8, cipherUuid.leastSignificantBits)
output.write(b)
output.writeByte(HeaderType.COMPRESSION_FLAGS.toInt())
output.writeShort(4)
output.writeInt(compressionFlags.ordinal)
output.writeByte(HeaderType.MASTER_SEED.toInt())
output.writeShort(masterSeed.size)
output.write(masterSeed)
output.writeByte(HeaderType.TRANSFORM_SEED.toInt())
output.writeShort(transformSeed.size)
output.write(transformSeed)
output.writeByte(HeaderType.TRANSFORM_ROUNDS.toInt())
output.writeShort(8)
output.writeLong(transformRounds)
output.writeByte(HeaderType.ENCRYPTION_IV.toInt())
output.writeShort(encryptionIv.size)
output.write(encryptionIv)
output.writeByte(HeaderType.PROTECTED_STREAM_KEY.toInt())
output.writeShort(protectedStreamKey.size)
output.write(protectedStreamKey)
output.writeByte(HeaderType.STREAM_START_BYTES.toInt())
output.writeShort(streamStartBytes.size)
output.write(streamStartBytes)
output.writeByte(HeaderType.INNER_RANDOM_STREAM_ID.toInt())
output.writeShort(4)
output.writeInt(protectedStreamAlgorithm.ordinal)
output.writeByte(HeaderType.END.toInt())
output.writeShort(0)
headerHash = digestOutputStream.messageDigest.digest()
}
}
private fun getFinalKeyDigest(key: ByteArray, masterSeed: ByteArray, transformSeed: ByteArray, transformRounds: Long): ByteArray {
val engine = AESEngine()
engine.init(true, KeyParameter(transformSeed))
// copy input key
val transformedKey = ByteArray(key.size)
System.arraycopy(key, 0, transformedKey, 0, transformedKey.size)
// transform rounds times
for (rounds in 0 until transformRounds) {
engine.processBlock(transformedKey, 0, transformedKey, 0)
engine.processBlock(transformedKey, 16, transformedKey, 16)
}
val md = sha256MessageDigest()
val transformedKeyDigest = md.digest(transformedKey)
md.update(masterSeed)
return md.digest(transformedKeyDigest)
}
/**
* Create a decrypted input stream from an encrypted one
*/
private fun getDecryptedInputStream(encryptedInputStream: InputStream, keyData: ByteArray, ivData: ByteArray): InputStream {
val keyAndIV = ParametersWithIV(KeyParameter(keyData), ivData)
val cipher = PaddedBufferedBlockCipher(CBCBlockCipher(AESEngine()))
cipher.init(false, keyAndIV)
return CipherInputStream(encryptedInputStream, cipher)
}
/**
* Create an encrypted output stream from an unencrypted output stream
*/
private fun getEncryptedOutputStream(decryptedOutputStream: OutputStream, keyData: ByteArray, ivData: ByteArray): OutputStream {
val cipher = PaddedBufferedBlockCipher(CBCBlockCipher(AESEngine()))
cipher.init(true, ParametersWithIV(KeyParameter(keyData), ivData))
return CipherOutputStream(decryptedOutputStream, cipher)
}
private fun readIntHeaderData(input: LittleEndianDataInputStream): Int {
val fieldLength = input.readShort()
if (fieldLength.toInt() != 4) {
throw IllegalStateException("Int required but length was $fieldLength")
}
return input.readInt()
}
private fun readLongHeaderData(input: LittleEndianDataInputStream): Long {
val fieldLength = input.readShort()
if (fieldLength.toInt() != 8) {
throw IllegalStateException("Long required but length was $fieldLength")
}
return input.readLong()
}
private fun readHeaderData(input: LittleEndianDataInputStream): ByteArray {
val value = ByteArray(input.readShort().toInt())
input.readFully(value)
return value
}
|
apache-2.0
|
47556802fbfafbeb46e23f91b074fdff
| 35.444109 | 130 | 0.752446 | 4.291 | false | false | false | false |
paplorinc/intellij-community
|
tools/index-tools/src/org/jetbrains/index/stubs/StubsSdkGenerator.kt
|
2
|
3064
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.index.stubs
import com.intellij.idea.IdeaTestApplication
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ui.UIUtil
import java.io.File
/**
* @author traff
*/
abstract class ProjectSdkStubsGenerator {
open fun createStubsGenerator(stubsFilePath: String): StubsGenerator = StubsGenerator("", stubsFilePath)
abstract val moduleTypeId: String
abstract fun createSdkProducer(sdkPath: String): (Project, Module) -> Sdk
open val root: String? = System.getenv("SDK_ROOT")
private val stubsFileName = "sdk-stubs"
fun buildStubs(baseDir: String) {
val app = IdeaTestApplication.getInstance()
try {
for (python in File(root).listFiles()) {
if (python.name.startsWith(".")) {
continue
}
indexSdkAndStoreSerializedStubs("${PathManager.getHomePath()}/python/testData/empty",
python.absolutePath,
"$baseDir/$stubsFileName")
}
}
catch (e: Throwable) {
e.printStackTrace()
}
finally {
UIUtil.invokeAndWaitIfNeeded(Runnable {
WriteAction.run<Throwable> {
app.dispose()
}
})
System.exit(0) //TODO: graceful shutdown
}
}
fun indexSdkAndStoreSerializedStubs(projectPath: String, sdkPath: String, stubsFilePath: String) {
val pair = openProjectWithSdk(projectPath, moduleTypeId, createSdkProducer(sdkPath))
val project = pair.first
val sdk = pair.second
try {
val roots: List<VirtualFile> = sdk!!.rootProvider.getFiles(OrderRootType.CLASSES).asList()
val stubsGenerator = createStubsGenerator(stubsFilePath)
stubsGenerator.buildStubsForRoots(roots)
}
finally {
UIUtil.invokeAndWaitIfNeeded(Runnable {
ProjectManager.getInstance().closeProject(project!!)
WriteAction.run<Throwable> {
Disposer.dispose(project)
SdkConfigurationUtil.removeSdk(sdk!!)
}
})
}
}
}
|
apache-2.0
|
31d9223c1ffb97983f2380e9caf636fa
| 30.27551 | 106 | 0.704308 | 4.492669 | false | true | false | false |
RuneSuite/client
|
api/src/main/java/org/runestar/client/api/game/UserList.kt
|
1
|
857
|
package org.runestar.client.api.game
import org.runestar.client.raw.access.XUser
import org.runestar.client.raw.access.XUserList
abstract class UserList<out T : User>(open val accessor: XUserList) : AbstractList<T?>(), RandomAccess {
override val size get() = accessor.size0
val capacity get() = accessor.capacity
val isFull get() = accessor.isFull
override fun get(index: Int): T? {
require(index in 0 until capacity)
if (index >= size) return null
val x = accessor.array[index] ?: return null
return wrap(x)
}
operator fun get(username: Username): T? {
val x = accessor.getByUsername(username.accessor) ?: return null
return wrap(x)
}
operator fun contains(username: Username) = accessor.contains(username.accessor)
protected abstract fun wrap(user: XUser) : T
}
|
mit
|
f581b79fa6478481498ac947a54fda4f
| 28.586207 | 104 | 0.68028 | 4.023474 | false | false | false | false |
indianpoptart/RadioControl
|
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/services/BackgroundJobService.kt
|
1
|
19808
|
package com.nikhilparanjape.radiocontrol.services
import android.annotation.SuppressLint
import android.app.job.JobParameters
import android.app.job.JobService
import android.content.Context
import android.content.SharedPreferences
import android.net.ConnectivityManager
import android.net.NetworkRequest
import android.text.format.DateFormat
import android.util.Log
import android.util.Log.DEBUG
import android.util.Log.INFO
import com.nikhilparanjape.radiocontrol.receivers.ConnectivityReceiver
import com.nikhilparanjape.radiocontrol.utilities.AlarmSchedulers
import com.nikhilparanjape.radiocontrol.utilities.Utilities
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.getCellStatus
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.getCurrentSsid
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.isAirplaneMode
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.isCallActive
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.isConnectedMobile
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.isConnectedWifi
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.setMobileNetworkFromLollipop
import com.nikhilparanjape.radiocontrol.utilities.Utilities.Companion.writeLog
import com.topjohnwu.superuser.Shell
import java.io.File
import java.io.IOException
import java.net.InetAddress
/**
* This service starts the BackgroundJobService as a foreground service if on Android Oreo or higher.
*
* This is the brains of the app
*
* @author Nikhil Paranjape
*
*/
@SuppressLint("SpecifyJobSchedulerIdRange")
class BackgroundJobService : JobService(), ConnectivityReceiver.ConnectivityReceiverListener {
//internal var util = Utilities() //Network and other related utilities
private var alarmUtil = AlarmSchedulers()
override fun onCreate() {
super.onCreate()
Log.i(TAG, "BackgroundJobScheduler created")
}
override fun onStartJob(params: JobParameters): Boolean {
Log.i(TAG, "Job started")
writeLog(TAG, "Job Started", applicationContext, INFO)
//Utilities.scheduleJob(applicationContext) // reschedule the job
//val sp = applicationContext.getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE)
val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(applicationContext) //General Shared Prefs for the whole app
val disabledPref = applicationContext.getSharedPreferences("disabled-networks", Context.MODE_PRIVATE) //Preferences for the Network Blocklist
//TODO Transfer to external algorithm class
//val h = HashSet(listOf("")) //Set default empty set for SSID check
val selections = prefs.getStringSet("ssid", HashSet(listOf(""))) //Gets stringset, if empty sets default
val networkAlert = prefs.getBoolean("isNetworkAlive", false) //Value for if user wants network alerts
if (isOngoingPhoneCall){
enableNetworks(prefs, params, applicationContext)
}
//Check if user wants the app on
if (prefs.getInt("isActive", 0) == 0) { //This means they DO NOT want the app enabled, or the app is disabled
Log.d(TAG, "RadioControl has been disabled")
//If the user wants to be alerted when the network is not internet reachable
if (networkAlert) { //If the user wants network alerts only
pingTask() //Run a network latency check
}
//Adds wifi signal lost log for devices that aren't rooted
if (!isConnectedWifi(applicationContext)) {
Log.d(TAG, WIFI_LOST)
writeLog(WIFI_LOST, applicationContext)
}
jobFinished(params, false) //Tell android that this job is finished and can be closed out
} else if (prefs.getInt("isActive", 0) == 1) { //This means the user DOES want the app enabled
Log.d(TAG, "Main Program Begin")
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager //Initializes the Connectivity Manager. This should only be done if the user requested the app to be active
connectivityManager.registerNetworkCallback(NetworkRequest.Builder().build(), NetworkCallbackRequest) //Registers for network callback notifications - TODO Bug reported ConnectivityManager$TooManyRequestsException
val activeNetwork = connectivityManager.activeNetworkInfo //This is used to check if the mobile network is currently off/disabled
/**^TODO refactor activeNetworkInfo to NetworkCallback API
* ConnectivityManager.NetworkCallback API
or ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties
https://stackoverflow.com/questions/53532406/activenetworkinfo-type-is-deprecated-in-api-level-28
**/
Log.d(TAG, "Status?: $activeNetwork") //Gives a run down of the current network
/** Section for on network losing status
* connectivityManager.requestNetwork(NetworkRequest.Builder().build(), object : ConnectivityManager.NetworkCallback() {}, 5000)
* **/
//Check if there is no WiFi connection && the Cell network is still not active
if (!isConnectedWifi(applicationContext) && activeNetwork == null) {
Log.d(TAG, WIFI_LOST)
writeLog(WIFI_LOST, applicationContext)
// Ensures that Airplane mode is on, or that the cell radio is off
if (isAirplaneMode(applicationContext) || !isConnectedMobile(applicationContext)) {
//Runs the alt cellular mode, otherwise, run the standard airplane mode
if (prefs.getBoolean("altRootCommand", false)) {
if (getCellStatus(applicationContext) == 1) {
val output = Shell.cmd("service call phone 27").exec()
writeLog("root accessed: $output", applicationContext)
Log.d(TAG, CELL_RADIO_ON)
writeLog(CELL_RADIO_ON, applicationContext)
jobFinished(params, false)
}
} else {
val output = Shell.cmd("settings put global airplane_mode_on 0", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false").exec()
writeLog("root accessed: $output", applicationContext)
//RootAccess.runCommands(airOffCmd3) *Here for legacy purposes
Log.d(TAG, AIRPLANE_MODE_OFF)
writeLog(AIRPLANE_MODE_OFF, applicationContext)
jobFinished(params, false)
}
}
//Here we check if the device just connected to a wifi network, as well as if airplane mode and/or the cell radio are off and/or connected respectively
} else if (isConnectedWifi(applicationContext) && !isAirplaneMode(applicationContext)) {
Log.d(TAG, "WiFi signal got")
//Checks if the currently connected SSID is in the list of disabled networks
if (!disabledPref.contains(getCurrentSsid(applicationContext))) {
Log.d(TAG, "The current SSID was not found in the disabled list")
//Checks that user is not in call
if (!isCallActive(applicationContext)) {
//Checks if the user doesn't want network alerts
if (!networkAlert) {
//Runs the cellular mode, otherwise, run default airplane mode
if (prefs.getBoolean("altRootCommand", false)) {
when {
getCellStatus(applicationContext) == 0 -> {
val output = Shell.cmd("service call phone 27").exec()
writeLog("root accessed: $output", applicationContext)
Log.d(TAG, CELL_RADIO_OFF)
writeLog(CELL_RADIO_OFF, applicationContext)
jobFinished(params, false)
}
getCellStatus(applicationContext) == 1 -> {
Log.d(TAG, "Cell Radio is already off")
jobFinished(params, false)
}
getCellStatus(applicationContext) == 2 -> {
Log.e(TAG, "Location can't be accessed, try alt method")
setMobileNetworkFromLollipop(applicationContext)
}
}
} else {
val output = Shell.cmd("settings put global airplane_mode_radios \"cell\"", "content update --uri content://settings/global --bind value:s:'cell' --where \"name='airplane_mode_radios'\"", "settings put global airplane_mode_on 1", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true").exec()
writeLog("root accessed: $output", applicationContext)
//RootAccess.runCommands(airCmd)
Log.d(TAG, AIRPLANE_MODE_ON)
writeLog(AIRPLANE_MODE_ON, applicationContext)
jobFinished(params, false)
}
} else {
pingTask()
jobFinished(params, false)
}//The user does want network alert notifications
}//Checks that user is currently in call and pauses execution till the call ends
//Waits for the active call to finish before initiating
else if (isCallActive(applicationContext)) {
//Here we want to wait for the phone call to end before closing off the cellular connection. Don't assume WiFi handoff
Log.d(TAG, "Still on the phone")
jobFinished(params, true)
/*while (isCallActive(applicationContext)) {
waitFor(2000)//Wait for call to end. TODO this is actually dangerous and should be changed as it hangs the whole app
Log.d(TAG, "waiting for call to end")
}*/
/*[Legacy Code] Waits for the active call to end, however, now it will just do a jobFinished. Idk if it works properly*/
}
} else if (selections!!.contains(getCurrentSsid(applicationContext))) {
Log.i(TAG, "The current SSID was blocked from list $selections")
writeLog("The current SSID was blocked from list $selections", applicationContext)
jobFinished(params, false)
}//Pauses because WiFi network is in the list of disabled SSIDs
}
//Handle any other event not covered above, usually something is not right, or we lack some permission, or the app is double running
else {
if (activeNetwork != null) {
Log.d(TAG, "We are connected")
} else {
//So activeNetwork has to have some value, lets see what that is
Log.e(TAG, "EGADS: $activeNetwork")
}
jobFinished(params, false)
}
//Since the code is finished, we should run the unregisterNetworkCallback
//This is to avoid hitting 100 request limit shared with registerNetworkCallback
connectivityManager.unregisterNetworkCallback(NetworkCallbackRequest)
} else {
Log.e(TAG, "Something's wrong, I can feel it")
}
Log.i(TAG, "Job completed")
jobFinished(params, false)
return true
}
private fun enableNetworks(prefs: SharedPreferences, params: JobParameters, context: Context){
// Ensures that Airplane mode is on, or that the cell radio is off
if (isAirplaneMode(context) || !isConnectedMobile(context)) {
//Runs the alt cellular mode, otherwise, run the standard airplane mode
if (prefs.getBoolean("altRootCommand", false)) {
if (getCellStatus(context) == 1) {
val output = Shell.cmd("service call phone 27").exec()
writeLog("root accessed: $output", context)
Log.d(TAG, CELL_RADIO_ON)
writeLog(CELL_RADIO_ON, context)
jobFinished(params, false)
}
} else {
val output = Shell.cmd("settings put global airplane_mode_on 0", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false").exec()
writeLog("root accessed: $output", context)
//RootAccess.runCommands(airOffCmd3) *Here for legacy purposes
Log.d(TAG, AIRPLANE_MODE_OFF)
writeLog(AIRPLANE_MODE_OFF, context)
jobFinished(params, false)
}
}
}
/**
* Write a private log for the Statistics Activity
*
* Sets the date in yyyy-MM-dd HH:mm:ss format
*
* This method always requires appropriate context
*
* @param data The data to be written to the log file radiocontrol.log
* @param c context allows access to application-specific resources and classes
*/
private fun writeLog(data: String, c: Context) {
val preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(c)
if (preferences.getBoolean("enableLogs", false)) {
try {
val h = DateFormat.format("yyyy-MM-dd HH:mm:ss", System.currentTimeMillis()).toString()
val log = File(c.filesDir, "radiocontrol.log")
if (!log.exists()) {
log.createNewFile() // Create a log file if it does not exist
}
val logPath = "radiocontrol.log"
val string = "\n$h: $data"
val fos = c.openFileOutput(logPath, Context.MODE_APPEND)
fos.write(string.toByteArray()) // Writes the current string to a bytearray into the path radiocontrol.log
fos.close()
} catch (e: IOException) {
Log.d(TAG, "There was an error saving the log: $e")
}
}
}
/**
* Checks latency to CloudFlare
*
* This method always requires application context
*
*/
private fun pingTask() {
try {
//Wait for network to be connected fully
/*while (!isConnected(applicationContext)) {
//Thread.sleep(1000)
}*/
//Fix this, as it causes a hang when wifi is disconnected and the app is on airplane mode(Only if Internet Test is active)
/*if (!isConnected(applicationContext)){
waitFor(5000)
}*/ //Commented out because address.isReachable has a timeout of 5 seconds
val address = InetAddress.getByName("1.1.1.1")
val reachable = address.isReachable(5000)
Log.d(TAG, "Reachable?: $reachable")
//val sp = applicationContext.getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE)
val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(applicationContext)
val alertPriority = prefs.getBoolean("networkPriority", false)//Setting for network notifier
val alertSounds = prefs.getBoolean("networkSound", false)
val alertVibrate = prefs.getBoolean("networkVibrate", false)
if (prefs.getInt("isActive", 0) == 0) {
//If the connection can't reach Google
if (!reachable) {
Utilities.sendNote(applicationContext, applicationContext.getString(com.nikhilparanjape.radiocontrol.R.string.not_connected_alert), alertVibrate, alertSounds, alertPriority)
writeLog("Not connected to the internet", applicationContext)
}
} else if (prefs.getInt("isActive", 0) == 1) {
//If the connection can't reach Google
if (!reachable) {
Utilities.sendNote(applicationContext, applicationContext.getString(com.nikhilparanjape.radiocontrol.R.string.not_connected_alert), alertVibrate, alertSounds, alertPriority)
writeLog("Not connected to the internet", applicationContext)
} else {
//Runs the cellular mode
if (prefs.getBoolean("altRootCommand", false)) {
val output = Shell.cmd("service call phone 27").exec()
Utilities.writeLog("root accessed: $output", applicationContext)
alarmUtil.scheduleRootAlarm(applicationContext)
Log.d(TAG, "Cell Radio has been turned off")
writeLog("Cell radio has been turned off", applicationContext)
} else if (!prefs.getBoolean("altRootCommand", false)) {
val output = Shell.cmd("settings put global airplane_mode_radios \"cell\"", "content update --uri content://settings/global --bind value:s:'cell' --where \"name='airplane_mode_radios'\"", "settings put global airplane_mode_on 1", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true").exec()
Utilities.writeLog("root accessed: $output", applicationContext)
//RootAccess.runCommands(airCmd)
Log.d(TAG, "Airplane mode has been turned on")
writeLog("Airplane mode has been turned on", applicationContext)
}
}
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
private fun waitFor(timer: Long) { // It's complaining that the timer is always 1000. Like, ok, but what if it isn't? Didn't think if that did you
try {
Thread.sleep(timer)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
override fun onStopJob(params: JobParameters): Boolean {
return true
}
companion object {
object NetworkCallbackRequest : ConnectivityManager.NetworkCallback()
const val TAG = "RadioControl-JobSrv"
/*private const val PRIVATE_PREF = "prefs"*/
var isOngoingPhoneCall = false
private const val WIFI_LOST = "WiFi signal LOST"
const val CELL_RADIO_ON = "Cell Radio has been turned on"
const val CELL_RADIO_OFF = "Cell Radio has been turned on"
const val AIRPLANE_MODE_OFF = "Airplane mode has been turned off"
const val AIRPLANE_MODE_ON = "Airplane mode has been turned on"
}
}
|
gpl-3.0
|
64c429845a92d6163e9f67707b681570
| 53.640449 | 340 | 0.591074 | 5.273695 | false | false | false | false |
Atsky/haskell-idea-plugin
|
plugin/src/org/jetbrains/haskell/HaskellProjectComponent.kt
|
1
|
2212
|
package org.jetbrains.haskell
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleType
import org.jetbrains.haskell.module.HaskellModuleType
import org.jetbrains.cabal.CabalInterface
import com.intellij.util.ui.UIUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.options.ShowSettingsUtil
import org.jetbrains.haskell.config.HaskellConfigurable
import com.intellij.openapi.module.Module
import java.io.File
import org.jetbrains.haskell.util.deleteRecursive
import org.jetbrains.haskell.util.OSUtil
import org.jetbrains.haskell.external.GhcMod
import com.intellij.openapi.roots.ProjectRootManager
import org.jetbrains.haskell.sdk.HaskellSdkType
class HaskellProjectComponent(val project: Project) : ProjectComponent {
companion object {
val GHC_PATH_NOT_FOUND = "ghc not found in PATH. It can cause issues."+
" Please spicify haskell SDK for project."
}
fun invokeInUI(block: () -> Unit) {
UIUtil.invokeAndWaitIfNeeded(object : Runnable {
override fun run() {
block()
}
})
}
fun getHaskellModules(): List<Module> {
val moduleManager = ModuleManager.getInstance(project)!!
return moduleManager.modules.filter { ModuleType.get(it) == HaskellModuleType.INSTANCE }
}
override fun projectOpened() {
if (!getHaskellModules().isEmpty()) {
val paths = System.getenv("PATH")!!.split(File.pathSeparator.toRegex()).toTypedArray().toMutableList()
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk != null && sdk.sdkType is HaskellSdkType) {
paths.add(sdk.homePath + File.separator + "bin")
}
if (OSUtil.isMac) {
paths.add("/usr/local/bin")
}
}
}
override fun projectClosed() {
}
override fun getComponentName(): String {
return "HaskellProjectComponent"
}
override fun initComponent() {
}
override fun disposeComponent() {
}
}
|
apache-2.0
|
82f6e319c4a4cd39c1fefdda788d8a94
| 30.6 | 114 | 0.683092 | 4.570248 | false | false | false | false |
tiarebalbi/okhttp
|
okhttp-brotli/src/main/kotlin/okhttp3/brotli/internal/brotli.kt
|
4
|
1545
|
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.brotli.internal
import okhttp3.Response
import okhttp3.ResponseBody.Companion.asResponseBody
import okhttp3.internal.http.promisesBody
import okio.GzipSource
import okio.buffer
import okio.source
import org.brotli.dec.BrotliInputStream
fun uncompress(response: Response): Response {
if (!response.promisesBody()) {
return response
}
val body = response.body ?: return response
val encoding = response.header("Content-Encoding") ?: return response
val decompressedSource = when {
encoding.equals("br", ignoreCase = true) ->
BrotliInputStream(body.source().inputStream()).source().buffer()
encoding.equals("gzip", ignoreCase = true) ->
GzipSource(body.source()).buffer()
else -> return response
}
return response.newBuilder()
.removeHeader("Content-Encoding")
.removeHeader("Content-Length")
.body(decompressedSource.asResponseBody(body.contentType(), -1))
.build()
}
|
apache-2.0
|
35db0ec6ffa11007532ff58b2877868d
| 32.586957 | 75 | 0.733981 | 4.142091 | false | false | false | false |
allotria/intellij-community
|
platform/elevation/client/testSrc/com/intellij/execution/process/mediator/rt/MediatedProcessTestMain.kt
|
3
|
1620
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.process.mediator.rt
import java.util.*
import kotlin.system.exitProcess
class MediatedProcessTestMain {
object True {
@JvmStatic
fun main(args: Array<String>) {
exitProcess(0)
}
}
object False {
@JvmStatic
fun main(args: Array<String>) {
exitProcess(42)
}
}
object Loop {
@JvmStatic
fun main(args: Array<String>) {
while (true) {
Thread.sleep(500)
}
}
}
object Echo {
@JvmStatic
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val printToStderr = args.isNotEmpty() && args[0] == "with_stderr"
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
println(line)
if (printToStderr) {
System.err.println(line)
}
}
}
}
object StreamInterruptor {
@JvmStatic
fun main(args: Array<String>) {
try {
System.out.close()
System.err.close()
System.`in`.close()
} catch (e: Exception) {
exitProcess(-1)
}
catch (e: Exception) {
exitProcess(-1)
}
while (true) {
Thread.sleep(500)
}
}
}
object TestClosedStream {
@JvmStatic
fun main(args: Array<String>) {
Thread.sleep(1500)
if (System.`in`.read() != -1) {
exitProcess(42)
}
// System.out and System.err (write -> flush) work even output stream is closed
}
}
}
|
apache-2.0
|
14ce091d2a350721085fb4973d33a2bf
| 19.782051 | 140 | 0.572222 | 3.793911 | false | false | false | false |
Skatteetaten/boober
|
src/test/kotlin/no/skatteetaten/aurora/boober/feature/AuroraAzureApimSubPartTest.kt
|
1
|
11322
|
package no.skatteetaten.aurora.boober.feature
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import assertk.assertThat
import io.mockk.every
import io.mockk.mockk
import no.skatteetaten.aurora.boober.feature.azure.AzureFeature
import no.skatteetaten.aurora.boober.service.CantusService
import no.skatteetaten.aurora.boober.service.ImageMetadata
import no.skatteetaten.aurora.boober.service.MultiApplicationValidationException
import no.skatteetaten.aurora.boober.utils.AbstractMultiFeatureTest
class AuroraAzureApimSubPartTest : AbstractMultiFeatureTest() {
override val features: List<Feature>
get() = listOf(
AzureFeature(cantusService, "0", "ldap://default", "http://jwks")
)
private val cantusService: CantusService = mockk()
@BeforeEach
fun setupMock() {
every {
cantusService.getImageMetadata(
"no_skatteetaten_aurora", "clinger", "0"
)
} returns
ImageMetadata(
"docker.registry/no_skatteetaten_aurora/clinger",
"0",
"sha:1234567"
)
}
@Test
fun `if minimal AuroraAzureApim is configured nothing goes wrong`() {
val (_, auroraAzureApp) = generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path/to/api",
"versions" : {
"v1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 1
)
assertThat(auroraAzureApp).auroraResourceCreatedByTarget(AzureFeature::class.java)
.auroraResourceMatchesFile("aurora-azure-apim.json")
}
@Test
fun `if multiple api versions are created`() {
val (_, auroraApimV1, auroraApimV2) = generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path/to/api",
"versions" : {
"v1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
},
"v2" : {
"enabled" : true,
"openApiUrl" : "https://openapi2",
"serviceUrl" : "https://service2"
},
"v3" : {
"enabled" : false,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 2
)
assertThat(auroraApimV1).auroraResourceCreatedByTarget(AzureFeature::class.java)
.auroraResourceMatchesFile("aurora-azure-apim.json")
assertThat(auroraApimV2).auroraResourceCreatedByTarget(AzureFeature::class.java)
.auroraResourceMatchesFile("aurora-azure-apim-v2.json")
}
@Test
fun `if policies are filtered, added and sorted`() {
val (_, auroraApim) = generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path/to/api",
"versions" : {
"v1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service",
"policies" : {
"policy2": {
"enabled": true,
"parameters": {
"param1": "value1",
"param2": "value2"
}
},
"policy1": {
"enabled": true
},
"policy3": {
"enabled": false
}
}
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 1
)
assertThat(auroraApim).auroraResourceCreatedByTarget(AzureFeature::class.java)
.auroraResourceMatchesFile("aurora-azure-apim-with-policies.json")
}
@Test
fun `if policies must be a list`() {
Assertions.assertThrows(MultiApplicationValidationException::class.java) {
generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path/to/api",
"versions" : {
"v1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service",
"policies" : "awsome policy"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 1
)
}
}
@Test
fun `if AuroraAzureApim is disabled, no resource is created`() {
val (_) = generateResources(
"""{
"azure" : {
"apim": {
"enabled" : false,
"apiName" : "super-api",
"path" : "/path/to/api",
"versions" : {
"v1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 0
)
}
@Test
fun `if version is disabled, no resource is created`() {
val (_) = generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path/to/api",
"versions" : {
"v1" : {
"enabled" : false,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 0
)
}
@Test
fun `invalid path gives error`() {
Assertions.assertThrows(MultiApplicationValidationException::class.java) {
generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/should/not/end/with/slash/",
"versions" : {
"v1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 1
)
}
}
@Test
fun `invalid version gives error`() {
Assertions.assertThrows(MultiApplicationValidationException::class.java) {
generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path",
"versions" : {
"version1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 1
)
}
}
@Test
fun `invalid openApiUrl gives error`() {
Assertions.assertThrows(MultiApplicationValidationException::class.java) {
generateResources(
"""{
"azure" : {
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path",
"v1" : {
"version1" : {
"enabled" : true,
"openApiUrl" : "openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 1
)
}
}
@Test
fun `4 elements configured, azureapp, clinger sidecar, managed route and azureapim`() {
val (_, _, _, auroraApim) = generateResources(
"""{
"azure": {
"azureAppFqdn": "saksmappa.amutv.skead.no",
"groups": [],
"jwtToStsConverter": {
"jwksUrl": "http://login-microsoftonline-com.app2ext.sikker-prod.skead.no/common/discovery/keys",
"enabled": true,
"version": "0"
},
"apim": {
"enabled" : true,
"apiName" : "super-api",
"path" : "/path/to/api",
"versions" : {
"v1" : {
"enabled" : true,
"openApiUrl" : "https://openapi",
"serviceUrl" : "https://service"
}
}
}
}
}""",
createEmptyDeploymentConfig(), createdResources = 3
)
assertThat(auroraApim).auroraResourceCreatedByTarget(AzureFeature::class.java)
.auroraResourceMatchesFile("aurora-azure-apim.json")
}
}
|
apache-2.0
|
8f4bdb1b31725428ecc2b8e8b7cbed9b
| 34.161491 | 115 | 0.38147 | 5.474855 | false | false | false | false |
allotria/intellij-community
|
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/entities/TestEntities.kt
|
2
|
13613
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.entities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.EntityDataDelegation
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlListProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlNullableProperty
import com.intellij.workspaceModel.storage.impl.indices.VirtualFileUrlProperty
import com.intellij.workspaceModel.storage.impl.references.ManyToOne
import com.intellij.workspaceModel.storage.impl.references.MutableManyToOne
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
internal data class SampleEntitySource(val name: String) : EntitySource
internal object MySource : EntitySource {
override fun toString(): String = "MySource"
}
internal object AnotherSource : EntitySource {
override fun toString(): String = "AnotherSource"
}
internal object MyDummyParentSource : DummyParentEntitySource {
override fun toString(): String = "DummyParent"
}
// ---------------------------------------
internal class SampleEntityData : WorkspaceEntityData<SampleEntity>() {
var booleanProperty: Boolean = false
lateinit var stringProperty: String
lateinit var stringListProperty: List<String>
lateinit var fileProperty: VirtualFileUrl
lateinit var myData: MyConcreteImpl
override fun createEntity(snapshot: WorkspaceEntityStorage): SampleEntity {
return SampleEntity(booleanProperty, stringProperty, stringListProperty, fileProperty, myData).also { addMetaData(it, snapshot) }
}
}
internal class SampleEntity(
val booleanProperty: Boolean,
val stringProperty: String,
val stringListProperty: List<String>,
val fileProperty: VirtualFileUrl,
val myData: MyConcreteImpl,
) : WorkspaceEntityBase()
internal class ModifiableSampleEntity : ModifiableWorkspaceEntityBase<SampleEntity>() {
var booleanProperty: Boolean by EntityDataDelegation()
var stringProperty: String by EntityDataDelegation()
var stringListProperty: List<String> by EntityDataDelegation()
var fileProperty: VirtualFileUrl by EntityDataDelegation()
var myData: MyConcreteImpl by EntityDataDelegation()
}
abstract class MyData(val myData: MyContainer)
class MyConcreteImpl(myData: MyContainer) : MyData(myData) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MyConcreteImpl) return false
return this.myData == other.myData
}
override fun hashCode(): Int {
return this.myData.hashCode()
}
}
data class MyContainer(val info: String)
internal fun WorkspaceEntityStorageDiffBuilder.addSampleEntity(stringProperty: String,
source: EntitySource = SampleEntitySource("test"),
booleanProperty: Boolean = false,
stringListProperty: MutableList<String> = ArrayList(),
virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManagerImpl(),
fileProperty: VirtualFileUrl = virtualFileManager.fromUrl("file:///tmp"),
info: String = ""
): SampleEntity {
return addEntity(ModifiableSampleEntity::class.java, source) {
this.booleanProperty = booleanProperty
this.stringProperty = stringProperty
this.stringListProperty = stringListProperty
this.fileProperty = fileProperty
this.myData = MyConcreteImpl(MyContainer(info))
}
}
// ---------------------------------------
internal class SecondSampleEntityData : WorkspaceEntityData<SecondSampleEntity>() {
var intProperty: Int = -1
override fun createEntity(snapshot: WorkspaceEntityStorage): SecondSampleEntity {
return SecondSampleEntity(intProperty).also { addMetaData(it, snapshot) }
}
}
internal class SecondSampleEntity(
val intProperty: Int
) : WorkspaceEntityBase()
internal class ModifiableSecondSampleEntity : ModifiableWorkspaceEntityBase<SecondSampleEntity>() {
var intProperty: Int by EntityDataDelegation()
}
// ---------------------------------------
internal class SourceEntityData : WorkspaceEntityData<SourceEntity>() {
lateinit var data: String
override fun createEntity(snapshot: WorkspaceEntityStorage): SourceEntity {
return SourceEntity(data).also { addMetaData(it, snapshot) }
}
}
internal class SourceEntity(val data: String) : WorkspaceEntityBase()
internal class ModifiableSourceEntity : ModifiableWorkspaceEntityBase<SourceEntity>() {
var data: String by EntityDataDelegation()
}
internal fun WorkspaceEntityStorageBuilder.addSourceEntity(data: String,
source: EntitySource): SourceEntity {
return addEntity(ModifiableSourceEntity::class.java, source) {
this.data = data
}
}
// ---------------------------------------
internal class ChildSourceEntityData : WorkspaceEntityData<ChildSourceEntity>() {
lateinit var data: String
override fun createEntity(snapshot: WorkspaceEntityStorage): ChildSourceEntity {
return ChildSourceEntity(data).also { addMetaData(it, snapshot) }
}
}
internal class ChildSourceEntity(val data: String) : WorkspaceEntityBase() {
val parent: SourceEntity by ManyToOne.NotNull(SourceEntity::class.java)
}
internal class ModifiableChildSourceEntity : ModifiableWorkspaceEntityBase<ChildSourceEntity>() {
var data: String by EntityDataDelegation()
var parent: SourceEntity by MutableManyToOne.NotNull(ChildSourceEntity::class.java, SourceEntity::class.java)
}
// ---------------------------------------
internal class ChildSampleEntityData : WorkspaceEntityData<ChildSampleEntity>() {
lateinit var data: String
override fun createEntity(snapshot: WorkspaceEntityStorage): ChildSampleEntity {
return ChildSampleEntity(data).also { addMetaData(it, snapshot) }
}
}
internal class ChildSampleEntity(
val data: String
) : WorkspaceEntityBase() {
val parent: SampleEntity? by ManyToOne.Nullable(SampleEntity::class.java)
}
internal class ModifiableChildSampleEntity : ModifiableWorkspaceEntityBase<ChildSampleEntity>() {
var data: String by EntityDataDelegation()
var parent: SampleEntity? by MutableManyToOne.Nullable(ChildSampleEntity::class.java, SampleEntity::class.java)
}
internal fun WorkspaceEntityStorageBuilder.addChildSampleEntity(stringProperty: String,
parent: SampleEntity?,
source: EntitySource = SampleEntitySource("test")): ChildSampleEntity {
return addEntity(ModifiableChildSampleEntity::class.java, source) {
this.data = stringProperty
this.parent = parent
}
}
internal class PersistentIdEntityData : WorkspaceEntityData.WithCalculablePersistentId<PersistentIdEntity>() {
lateinit var data: String
override fun createEntity(snapshot: WorkspaceEntityStorage): PersistentIdEntity {
return PersistentIdEntity(data).also { addMetaData(it, snapshot) }
}
override fun persistentId(): LinkedListEntityId = LinkedListEntityId(data)
}
internal class PersistentIdEntity(val data: String) : WorkspaceEntityWithPersistentId, WorkspaceEntityBase() {
override fun persistentId(): LinkedListEntityId = LinkedListEntityId(data)
}
internal class ModifiablePersistentIdEntity : ModifiableWorkspaceEntityBase<PersistentIdEntity>() {
var data: String by EntityDataDelegation()
}
internal fun WorkspaceEntityStorageBuilder.addPersistentIdEntity(data: String,
source: EntitySource = SampleEntitySource("test")): PersistentIdEntity {
return addEntity(ModifiablePersistentIdEntity::class.java, source) {
this.data = data
}
}
internal class VFUEntityData : WorkspaceEntityData<VFUEntity>() {
lateinit var data: String
lateinit var fileProperty: VirtualFileUrl
override fun createEntity(snapshot: WorkspaceEntityStorage): VFUEntity {
return VFUEntity(data, fileProperty).also { addMetaData(it, snapshot) }
}
}
internal class VFUWithTwoPropertiesEntityData : WorkspaceEntityData<VFUWithTwoPropertiesEntity>() {
lateinit var data: String
lateinit var fileProperty: VirtualFileUrl
lateinit var secondFileProperty: VirtualFileUrl
override fun createEntity(snapshot: WorkspaceEntityStorage): VFUWithTwoPropertiesEntity {
return VFUWithTwoPropertiesEntity(data, fileProperty, secondFileProperty).also { addMetaData(it, snapshot) }
}
}
internal class NullableVFUEntityData : WorkspaceEntityData<NullableVFUEntity>() {
lateinit var data: String
var fileProperty: VirtualFileUrl? = null
override fun createEntity(snapshot: WorkspaceEntityStorage): NullableVFUEntity {
return NullableVFUEntity(data, fileProperty).also { addMetaData(it, snapshot) }
}
}
internal class ListVFUEntityData : WorkspaceEntityData<ListVFUEntity>() {
lateinit var data: String
lateinit var fileProperty: List<VirtualFileUrl>
override fun createEntity(snapshot: WorkspaceEntityStorage): ListVFUEntity {
return ListVFUEntity(data, fileProperty).also { addMetaData(it, snapshot) }
}
}
internal class VFUEntity(val data: String, val fileProperty: VirtualFileUrl) : WorkspaceEntityBase()
internal class VFUWithTwoPropertiesEntity(val data: String,
val fileProperty: VirtualFileUrl,
val secondFileProperty: VirtualFileUrl) : WorkspaceEntityBase()
internal class NullableVFUEntity(val data: String, val fileProperty: VirtualFileUrl?) : WorkspaceEntityBase()
internal class ListVFUEntity(val data: String, val fileProperty: List<VirtualFileUrl>) : WorkspaceEntityBase()
internal class ModifiableVFUEntity : ModifiableWorkspaceEntityBase<VFUEntity>() {
var data: String by EntityDataDelegation()
var fileProperty: VirtualFileUrl by VirtualFileUrlProperty()
}
internal class ModifiableVFUWithTwoPropertiesEntity : ModifiableWorkspaceEntityBase<VFUWithTwoPropertiesEntity>() {
var data: String by EntityDataDelegation()
var fileProperty: VirtualFileUrl by VirtualFileUrlProperty()
var secondFileProperty: VirtualFileUrl by VirtualFileUrlProperty()
}
internal class ModifiableNullableVFUEntity : ModifiableWorkspaceEntityBase<NullableVFUEntity>() {
var data: String by EntityDataDelegation()
var fileProperty: VirtualFileUrl? by VirtualFileUrlNullableProperty()
}
internal class ModifiableListVFUEntity : ModifiableWorkspaceEntityBase<ListVFUEntity>() {
var data: String by EntityDataDelegation()
var fileProperty: List<VirtualFileUrl> by VirtualFileUrlListProperty()
}
internal fun WorkspaceEntityStorageBuilder.addVFUEntity(data: String,
fileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")): VFUEntity {
return addEntity(ModifiableVFUEntity::class.java, source) {
this.data = data
this.fileProperty = virtualFileManager.fromUrl(fileUrl)
}
}
internal fun WorkspaceEntityStorageBuilder.addVFU2Entity(data: String,
fileUrl: String,
secondFileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")): VFUWithTwoPropertiesEntity {
return addEntity(ModifiableVFUWithTwoPropertiesEntity::class.java, source) {
this.data = data
this.fileProperty = virtualFileManager.fromUrl(fileUrl)
this.secondFileProperty = virtualFileManager.fromUrl(secondFileUrl)
}
}
internal fun WorkspaceEntityStorageBuilder.addNullableVFUEntity(data: String,
fileUrl: String?,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")): NullableVFUEntity {
return addEntity(ModifiableNullableVFUEntity::class.java, source) {
this.data = data
if (fileUrl != null) this.fileProperty = virtualFileManager.fromUrl(fileUrl)
}
}
internal fun WorkspaceEntityStorageBuilder.addListVFUEntity(data: String,
fileUrl: List<String>,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")): ListVFUEntity {
return addEntity(ModifiableListVFUEntity::class.java, source) {
this.data = data
this.fileProperty = fileUrl.map { virtualFileManager.fromUrl(it) }
}
}
|
apache-2.0
|
00e04bf478ef3ffa4224809de4305e08
| 43.34202 | 140 | 0.705869 | 6.079946 | false | false | false | false |
allotria/intellij-community
|
python/src/com/jetbrains/python/console/PydevConsoleCommunicationClient.kt
|
3
|
6196
|
// 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.jetbrains.python.console
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.project.Project
import com.jetbrains.python.PyBundle
import com.jetbrains.python.console.protocol.PythonConsoleBackendService
import com.jetbrains.python.console.protocol.PythonConsoleFrontendService
import com.jetbrains.python.console.transport.client.TNettyClientTransport
import com.jetbrains.python.console.transport.server.TNettyServer
import com.jetbrains.python.debugger.PyDebugValueExecutionService
import org.apache.thrift.protocol.TBinaryProtocol
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* This is [PydevConsoleCommunication] where Python Console backend acts like a
* server and IDE acts like a client.
*
* Python Console [Process] is expected to be already started. It is passed as
* [_pythonConsoleProcess] property.
*/
class PydevConsoleCommunicationClient(project: Project,
private val host: String, private val port: Int,
private val _pythonConsoleProcess: Process) : PydevConsoleCommunication(project) {
private var server: TNettyServer? = null
/**
* Thrift RPC client for sending messages to the server.
*
* Guarded by [stateLock].
*/
private var client: PythonConsoleBackendServiceDisposable? = null
private val clientTransport: TNettyClientTransport = TNettyClientTransport(host, port)
private val stateLock: Lock = ReentrantLock()
private val stateChanged: Condition = stateLock.newCondition()
/**
* Initial non-thread safe [PythonConsoleBackendService.Client].
*
* Guarded by [stateLock].
*/
private var initialPythonConsoleClient: PythonConsoleBackendService.Iface? = null
/**
* Guarded by [stateLock].
*/
private var isClosed = false
/**
* Establishes connection to Python Console backend listening at
* [host]:[port].
*/
fun connect() {
ApplicationManager.getApplication().executeOnPooledThread {
try {
clientTransport.open()
}
catch (e: Exception) {
LOG.warn(e)
stateLock.withLock {
isClosed = true
stateChanged.signalAll()
}
return@executeOnPooledThread
}
val clientProtocol = TBinaryProtocol(clientTransport)
val client = PythonConsoleBackendService.Client(clientProtocol)
val serverTransport = clientTransport.serverTransport
val serverHandler = createPythonConsoleFrontendHandler()
val serverProcessor = PythonConsoleFrontendService.Processor<PythonConsoleFrontendService.Iface>(serverHandler)
val server = TNettyServer(serverTransport, serverProcessor)
stateLock.withLock {
if (isClosed) throw ProcessCanceledException()
this.server = server
initialPythonConsoleClient = client
stateChanged.signalAll()
}
ApplicationManager.getApplication().executeOnPooledThread { server.serve() }
val executionService = PyDebugValueExecutionService.getInstance(myProject)
executionService.sessionStarted(this)
addFrameListener { executionService.cancelSubmittedTasks(this@PydevConsoleCommunicationClient) }
}
}
override fun getPythonConsoleBackendClient(): PythonConsoleBackendServiceDisposable {
stateLock.withLock {
while (!isClosed && _pythonConsoleProcess.isAlive) {
// if `client` is set just return it
client?.let {
return it
}
val initialPythonConsoleClient = initialPythonConsoleClient
if (initialPythonConsoleClient != null) {
val newClient = synchronizedPythonConsoleClient(PydevConsoleCommunication::class.java.classLoader,
initialPythonConsoleClient, _pythonConsoleProcess)
client = newClient
return newClient
}
else {
stateChanged.await()
}
}
if (!_pythonConsoleProcess.isAlive) {
throw PyConsoleProcessFinishedException(_pythonConsoleProcess.exitValue())
}
throw CommunicationClosedException()
}
}
override fun closeCommunication(): Future<*> {
stateLock.withLock {
try {
isClosed = true
}
finally {
stateChanged.signalAll()
}
}
// `client` cannot be assigned after `isClosed` is set
val progressIndicator: ProgressIndicator? = ProgressIndicatorProvider.getInstance().progressIndicator
// if client exists then try to gracefully `close()` it
try {
client?.apply {
progressIndicator?.text2 = PyBundle.message("debugger.sending.close.message")
close()
dispose()
}
}
catch (e: Exception) {
// ignore exceptions on `client` shutdown
}
_pythonConsoleProcess.let {
progressIndicator?.text2 = PyBundle.message("debugger.waiting.to.finish")
// TODO move under the future!
try {
do {
progressIndicator?.checkCanceled()
}
while (!it.waitFor(500, TimeUnit.MILLISECONDS))
}
catch (e: InterruptedException) {
Thread.currentThread().interrupt()
}
}
// explicitly close Netty client
clientTransport.close()
// we know that in this case `server.stop()` would do almost nothing
return server?.stop() ?: CompletableFuture.completedFuture(null)
}
override fun isCommunicationClosed(): Boolean = stateLock.withLock { isClosed }
companion object {
private val LOG: Logger = Logger.getInstance(Logger::class.java)
}
}
|
apache-2.0
|
5fc8d525b45c92d29616fde5666042f4
| 31.610526 | 140 | 0.705617 | 5.103789 | false | false | false | false |
Kotlin/kotlinx.coroutines
|
kotlinx-coroutines-core/native/src/Builders.kt
|
1
|
4439
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:OptIn(ExperimentalContracts::class)
package kotlinx.coroutines
import kotlinx.cinterop.*
import platform.posix.*
import kotlin.contracts.*
import kotlin.coroutines.*
import kotlin.native.concurrent.*
/**
* Runs new coroutine and **blocks** current thread _interruptibly_ until its completion.
* This function should not be used from coroutine. It is designed to bridge regular blocking code
* to libraries that are written in suspending style, to be used in `main` functions and in tests.
*
* The default [CoroutineDispatcher] for this builder in an implementation of [EventLoop] that processes continuations
* in this blocked thread until the completion of this coroutine.
* See [CoroutineDispatcher] for the other implementations that are provided by `kotlinx.coroutines`.
*
* When [CoroutineDispatcher] is explicitly specified in the [context], then the new coroutine runs in the context of
* the specified dispatcher while the current thread is blocked. If the specified dispatcher implements [EventLoop]
* interface and this `runBlocking` invocation is performed from inside of the this event loop's thread, then
* this event loop is processed using its [processNextEvent][EventLoop.processNextEvent] method until coroutine completes.
*
* If this blocked thread is interrupted (see [Thread.interrupt]), then the coroutine job is cancelled and
* this `runBlocking` invocation throws [InterruptedException].
*
* See [newCoroutineContext] for a description of debugging facilities that are available for newly created coroutine.
*
* @param context context of the coroutine. The default value is an implementation of [EventLoop].
* @param block the coroutine code.
*/
public actual fun <T> runBlocking(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
val contextInterceptor = context[ContinuationInterceptor]
val eventLoop: EventLoop?
val newContext: CoroutineContext
if (contextInterceptor == null) {
// create or use private event loop if no dispatcher is specified
eventLoop = ThreadLocalEventLoop.eventLoop
newContext = GlobalScope.newCoroutineContext(context + eventLoop)
} else {
// See if context's interceptor is an event loop that we shall use (to support TestContext)
// or take an existing thread-local event loop if present to avoid blocking it (but don't create one)
eventLoop = (contextInterceptor as? EventLoop)?.takeIf { it.shouldBeProcessedFromContext() }
?: ThreadLocalEventLoop.currentOrNull()
newContext = GlobalScope.newCoroutineContext(context)
}
val coroutine = BlockingCoroutine<T>(newContext, eventLoop)
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
return coroutine.joinBlocking()
}
private class BlockingCoroutine<T>(
parentContext: CoroutineContext,
private val eventLoop: EventLoop?
) : AbstractCoroutine<T>(parentContext, true, true) {
private val joinWorker = Worker.current
override val isScopedCoroutine: Boolean get() = true
override fun afterCompletion(state: Any?) {
// wake up blocked thread
if (joinWorker != Worker.current) {
// Unpark waiting worker
joinWorker.executeAfter(0L, {}) // send an empty task to unpark the waiting event loop
}
}
@Suppress("UNCHECKED_CAST")
fun joinBlocking(): T {
try {
eventLoop?.incrementUseCount()
while (true) {
var parkNanos: Long
// Workaround for bug in BE optimizer that cannot eliminate boxing here
if (eventLoop != null) {
parkNanos = eventLoop.processNextEvent()
} else {
parkNanos = Long.MAX_VALUE
}
// note: processNextEvent may lose unpark flag, so check if completed before parking
if (isCompleted) break
joinWorker.park(parkNanos / 1000L, true)
}
} finally { // paranoia
eventLoop?.decrementUseCount()
}
// now return result
val state = state.unboxState()
(state as? CompletedExceptionally)?.let { throw it.cause }
return state as T
}
}
|
apache-2.0
|
556b90ff88b15c36257e81bc01f524ff
| 43.838384 | 122 | 0.695652 | 4.932222 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.