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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aosp-mirror/platform_frameworks_support | navigation/safe-args-gradle-plugin/src/main/kotlin/androidx/navigation/safeargs/gradle/SafeArgsPlugin.kt | 1 | 2919 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.safeargs.gradle
import com.android.build.gradle.AppExtension
import com.android.build.gradle.api.BaseVariant
import groovy.util.XmlSlurper
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File
private const val PLUGIN_DIRNAME = "navigation-args"
internal const val GENERATED_PATH = "generated/source/$PLUGIN_DIRNAME"
internal const val INTERMEDIATES_PATH = "intermediates/$PLUGIN_DIRNAME"
@Suppress("unused")
class SafeArgsPlugin : Plugin<Project> {
override fun apply(project: Project) {
val appExtension = project.extensions.findByType(AppExtension::class.java)
?: throw GradleException("safeargs plugin must be used with android plugin")
appExtension.applicationVariants.all { variant ->
val task = project.tasks.create("generateSafeArgs${variant.name.capitalize()}",
ArgumentsGenerationTask::class.java) { task ->
task.rFilePackage = variant.rFilePackage()
task.applicationId = variant.applicationId
task.navigationFiles = navigationFiles(variant)
task.outputDir = File(project.buildDir, "$GENERATED_PATH/${variant.dirName}")
task.incrementalFolder = File(project.buildDir,
"$INTERMEDIATES_PATH/${variant.dirName}")
task.variantName = variant.name
}
variant.registerJavaGeneratingTask(task, task.outputDir)
}
}
}
private fun navigationFiles(variant: BaseVariant) = variant.sourceSets
.flatMap { it.resDirectories }
.mapNotNull {
File(it, "navigation").let { navFolder ->
if (navFolder.exists() && navFolder.isDirectory) navFolder else null
}
}
.flatMap { navFolder -> navFolder.listFiles().asIterable() }
.groupBy { file -> file.name }
.map { entry -> entry.value.last() }
private fun BaseVariant.rFilePackage(): String {
val mainSourceSet = sourceSets.find { it.name == "main" }
val sourceSet = mainSourceSet ?: sourceSets[0]
val manifest = sourceSet.manifestFile
val parsed = XmlSlurper(false, false).parse(manifest)
return parsed.getProperty("@package").toString()
} | apache-2.0 | 474d960e3c120e5777b3c9544ce73cac | 40.714286 | 93 | 0.685851 | 4.456489 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/view/LoginScreen.kt | 1 | 7614 | package koma.gui.view
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.*
import javafx.scene.effect.DropShadow
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.layout.GridPane
import javafx.scene.layout.Priority
import javafx.scene.paint.Color
import javafx.scene.text.Text
import javafx.util.StringConverter
import koma.controller.requests.account.login.onClickLogin
import koma.gui.view.window.preferences.PreferenceWindow
import koma.koma_app.AppData
import koma.koma_app.AppStore
import koma.koma_app.appState
import koma.matrix.UserId
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import link.continuum.desktop.database.KDataStore
import link.continuum.desktop.database.KeyValueStore
import link.continuum.desktop.gui.*
import link.continuum.desktop.util.debugAssertUiThread
import mu.KotlinLogging
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import org.controlsfx.control.MaskerPane
import org.controlsfx.control.decoration.Decoration
import org.controlsfx.control.textfield.TextFields
import org.controlsfx.validation.Severity
import org.controlsfx.validation.ValidationMessage
import org.controlsfx.validation.ValidationSupport
import org.controlsfx.validation.Validator
import org.controlsfx.validation.decoration.GraphicValidationDecoration
private val logger = KotlinLogging.logger {}
/**
* Created by developer on 2017/6/21.
*/
class LoginScreen(
private val keyValueStore: KeyValueStore,
private val deferredAppData : Deferred<AppData>,
private val mask: MaskerPane
) {
private val scope = MainScope()
val root = VBox()
var userId = ComboBox<UserId>().apply {
promptText = "@user:matrix.org"
isEditable = true
converter = object : StringConverter<UserId>() {
override fun toString(u: UserId?): String? =u?.str
override fun fromString(string: String?): UserId? = string?.let { UserId(it) }
}
}
var serverCombo: TextField = TextFields.createClearableTextField().apply {
promptText = "https://matrix.org"
}
var password: PasswordField = TextFields.createClearablePasswordField()
private val prefWin by lazy { PreferenceWindow(keyValueStore.proxyList) }
private val validation = ValidationSupport().apply {
validationDecorator = object: GraphicValidationDecoration(){
override fun createDecorationNode(message: ValidationMessage?): Node {
val graphic = if (Severity.ERROR === message?.getSeverity()) createErrorNode() else createWarningNode()
graphic.style = "-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.8), 10, 0, 0, 0);"
val label = Label()
label.setGraphic(graphic)
label.setTooltip(createTooltip(message))
label.setAlignment(Pos.TOP_CENTER)
return label
}
override fun createRequiredDecorations(target: Control?): MutableCollection<Decoration> {
return mutableListOf()
}
}
}
private var job: Job? = null
private var httpClient: OkHttpClient? = null
fun start(httpClient: OkHttpClient) {
debugAssertUiThread()
this.httpClient = httpClient
root.isDisable = false
val recentUsers = keyValueStore.getRecentUsers()
userId.itemsProperty().get().setAll(recentUsers)
userId.selectionModel.selectFirst()
}
init {
val grid = GridPane()
with(grid) {
vgap = 10.0
hgap = 10.0
padding = Insets(5.0)
add(Text("Username"), 0, 0)
add(userId, 1, 0)
add(Text("Server"), 0, 1)
add(serverCombo, 1,1)
add(Text("Password"), 0, 2)
password = PasswordField()
add(password, 1, 2)
// TODO not updated in real time when editing
validation.registerValidator(userId, Validator.createPredicateValidator({ p0: UserId? ->
p0 ?: return@createPredicateValidator true
return@createPredicateValidator p0.user.isNotBlank() && p0.server.isNotBlank()
}, "User ID should be of the form @user:matrix.org"))
validation.registerValidator(serverCombo, Validator.createPredicateValidator({ s: String? ->
s?.let { it.toHttpUrlOrNull() } != null
}, "Server should be a valid HTTP/HTTPS URL"))
}
with(root) {
isDisable = true
addEventFilter(KeyEvent.KEY_PRESSED) {
if (it.code == KeyCode.ESCAPE && mask.isVisible) {
job?.let { scope.launch(Dispatchers.Default) { it.cancel() } }
logger.debug { "cancelling login"}
mask.text = "Cancelling"
scope.launch {
delay(500)
mask.isVisible = false
}
it.consume()
}
}
background = whiteBackGround
val buts = HBox(10.0).apply {
button("Options") {
action { prefWin.openModal(owner = JFX.primaryStage) }
}
hbox {
HBox.setHgrow(this, Priority.ALWAYS)
}
button("Login") {
isDefaultButton = true
this.disableProperty().bind(validation.invalidProperty())
action {
mask.text = "Signing in"
mask.isVisible = true
job = scope.launch {
val c = httpClient ?: return@launch
val d = appState.store
onClickLogin(
c,
deferredAppData,
userId.value,
password.text,
serverCombo.text,
keyValueStore
)
}
}
}
}
stackpane {
children.addAll(
StackPane().apply {
effect = DropShadow(59.0, Color.GRAY)
background = whiteBackGround
},
VBox(10.0).apply {
padding = Insets(10.0)
background = whiteBackGround
children.addAll(grid, buts)
})
}
}
val userInput = Channel<String>(Channel.CONFLATED)
userId.editor.textProperty().addListener { _, _, newValue ->
userInput.offer(newValue)
}
scope.launch {
for (u in userInput) {
val a = suggestedServerAddr(keyValueStore, UserId(u))
if (userId.isFocused || serverCombo.text.isBlank()) {
serverCombo.text = a
}
}
}
}
}
private fun suggestedServerAddr(keyValueStore: KeyValueStore,
userId: UserId
): String {
val sn = userId.server
if (sn.isBlank()) return "https://matrix.org"
keyValueStore.serverToAddress.get(sn)?.let { return it }
return "https://$sn"
} | gpl-3.0 | 69191fe10eedfefedf6e0ebd74b41fe3 | 37.654822 | 119 | 0.569871 | 5.039047 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/optional/CustomMutationRateGene.kt | 1 | 6936 | package org.evomaster.core.search.gene.optional
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.problem.util.ParamUtil
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.root.CompositeFixedGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.impact.impactinfocollection.value.DisruptiveGeneImpact
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.MutationWeightControl
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* A wrapper for a gene that has a major, disruptive impact on the whole chromosome.
* As such, it should be mutated only with low probability.
* Can also be used for genes that might have little to no impact on phenotype, so mutating them
* would be just a waste
*
* @param probability of the gene can be mutated. 0 means it is impossible to mutate,
* whereas 1 means can always be mutated
* @param searchPercentageActive for how long the gene can be mutated. After this percentage [0.0,1.0] of time has passed,
* then we prevent mutations to it (ie probability is set to 0 automatically).
* By default, it is used during whole search (ie, 1.0).
*/
class CustomMutationRateGene<out T>(
name: String,
val gene: T,
var probability: Double,
var searchPercentageActive: Double = 1.0
) : CompositeFixedGene(name, gene)
where T : Gene {
init {
if (probability < 0 || probability > 1) {
throw IllegalArgumentException("Invalid probability value: $probability")
}
if(searchPercentageActive < 0 || searchPercentageActive > 1){
throw IllegalArgumentException("Invalid searchPercentageActive value: $searchPercentageActive")
}
if (gene is CustomMutationRateGene<*>) {
throw IllegalArgumentException("Cannot have a recursive disruptive gene")
}
}
companion object{
private val log: Logger = LoggerFactory.getLogger(CustomMutationRateGene::class.java)
}
override fun <T> getWrappedGene(klass: Class<T>) : T? where T : Gene{
if(this.javaClass == klass){
return this as T
}
return gene.getWrappedGene(klass)
}
fun preventMutation(){
probability = 0.0
}
override fun isLocallyValid() : Boolean{
return getViewOfChildren().all { it.isLocallyValid() }
}
override fun copyContent(): Gene {
return CustomMutationRateGene(name, gene.copy(), probability, searchPercentageActive)
}
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
gene.randomize(randomness, tryToForceNewValue)
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
) : Boolean {
/*
This is a bit convoluted... but this gene is rather special.
Whether it can be mutated is based on a probability, so it is not deterministic.
Applying "shallow mutate" here actually means not mutating...
So, the "higher" probability of mutate, the "lower" the probability of shallow mutate
*/
return randomness.nextBoolean(1 - probability)
}
/**
* mutation of inside gene in DisruptiveGene is based on the probability.
* If not mutating internal gene, then shallow does nothing
*/
override fun shallowMutate(randomness: Randomness, apc: AdaptiveParameterControl, mwc: MutationWeightControl, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo?): Boolean {
// do nothing, but still not crash EM. this is an expected behaviour, see customShouldApplyShallowMutation
return true
}
override fun adaptiveSelectSubsetToMutate(randomness: Randomness, internalGenes: List<Gene>, mwc: MutationWeightControl, additionalGeneMutationInfo: AdditionalGeneMutationInfo): List<Pair<Gene, AdditionalGeneMutationInfo?>> {
if (additionalGeneMutationInfo.impact != null && additionalGeneMutationInfo.impact is DisruptiveGeneImpact){
if (internalGenes.size != 1 || !internalGenes.contains(gene))
throw IllegalStateException("mismatched input: the internalGenes should only contain gene")
return listOf(gene to additionalGeneMutationInfo.copyFoInnerGene(additionalGeneMutationInfo.impact.geneImpact, gene))
}
throw IllegalArgumentException("impact is null or not DisruptiveGeneImpact")
}
override fun getValueAsPrintableString(previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean): String {
return gene.getValueAsPrintableString(previousGenes, mode, targetFormat)
}
override fun getValueAsRawString(): String {
return gene.getValueAsRawString()
}
override fun isMutable() = probability > 0 && gene.isMutable()
override fun isPrintable() = gene.isPrintable()
override fun copyValueFrom(other: Gene) {
if (other !is CustomMutationRateGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
this.gene.copyValueFrom(other.gene)
this.probability = other.probability
this.searchPercentageActive = other.searchPercentageActive
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is CustomMutationRateGene<*>) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
/**
* Not sure if probability is part of the
* value for this gene
*/
return this.gene.containsSameValueAs(other.gene)
&& this.probability == other.probability
&& this.searchPercentageActive == other.searchPercentageActive
}
override fun getVariableName() = gene.getVariableName()
override fun mutationWeight(): Double {
return 1.0 + gene.mutationWeight() * probability
}
override fun possiblySame(gene: Gene): Boolean {
return gene is CustomMutationRateGene<*> && gene.name == this.name && this.gene.possiblySame((gene as CustomMutationRateGene<T>).gene)
}
override fun bindValueBasedOn(gene: Gene): Boolean {
return ParamUtil.getValueGene(this).bindValueBasedOn(ParamUtil.getValueGene(gene))
}
} | lgpl-3.0 | daaf35664927ca31ba86ce633c72f07f | 41.042424 | 274 | 0.709198 | 5.103753 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/inspections/unsafeIterators/IntFloatMap.kt | 1 | 614 | package main
import com.badlogic.gdx.utils.IntFloatMap
@Suppress("UNUSED_VARIABLE", "UNCHECKED_CAST")
class IntFloatMapTest {
private val map = IntFloatMap()
companion object {
var map2: IntFloatMap? = null
}
internal fun test() {
<warning>map.keys()</warning>.hasNext()
<warning>map.entries()</warning>.iterator()
map2 = map
val iterator1 = <warning>map.iterator()</warning>
val keys = <warning>map2?.keys()</warning>
val entries = <warning>map2?.entries()</warning>
val values = <warning>map2?.values()</warning>
val keys2 = IntFloatMap.Keys(map2)
}
}
| apache-2.0 | 7c965133e4ab0ffb833a77241d127695 | 17.606061 | 53 | 0.661238 | 3.633136 | false | true | false | false |
mbenz95/hangman | src/TerminalBuffer.kt | 1 | 1921 |
class TerminalBuffer(val width: Int, val height: Int) {
val buffer: Array<CharArray> = array2dOfChar(height, width)
init {
// init with spaces
clear()
}
fun present() {
clearTerminal()
for ((r,row) in buffer.withIndex()) {
for ((c, char) in row.withIndex()) {
print(char)
}
println()
}
System.out.flush()
}
fun clear() {
for ((r,row) in buffer.withIndex()) {
for ((c, char) in row.withIndex()) {
buffer[r][c] = ' '
}
}
}
fun clearLine(row: Int) {
for ((c, col) in buffer[row].withIndex()) {
buffer[row][c] = ' '
}
}
fun insertAt(row: Int, col: Int, buff: Array<CharArray>) {
if (buffer.isEmpty() || buffer[0].isEmpty())
return
if (row + buff.size >= buffer.size || col + buff[0].size >= buffer[0].size)
throw IllegalArgumentException("The buffer doesn't fit on the screen") // todo crop buffer instead
// insert buf in buffer
for (currRow in 0..buff.size - 1) {
for (currCol in 0..buff[0].size - 1) {
buffer[currRow + row][currCol + col] = buff[currRow][currCol]
}
}
}
fun insertAt(row: Int, col: Int, lines: Array<String>) {
// todo input validation
for (currRow in 0..lines.size - 1) {
writeAt(row + currRow, col, lines[currRow])
}
}
fun writeAt(row: Int, col: Int, str: String) {
var currRow = row
var currCol = col
for ((i,c) in str.withIndex()) {
// go to new line if string contains linebreak
if (c == '\n') {
currRow++
currCol = col - (i + 1)
continue
}
buffer[currRow][currCol+i] = c
}
}
}
| mit | 5928cb04cec5f27325ea79a37efdadc8 | 26.442857 | 110 | 0.475273 | 3.85743 | false | false | false | false |
misty000/kotlinfx | kotlinfx-core/src/main/kotlin/kotlinfx/kalium/Kalium.kt | 2 | 2931 | package kotlinfx.kalium
import javafx.beans.value.ObservableValue
import javafx.beans.value.WritableValue
import javafx.beans.property.Property
import javafx.scene.Node
import javafx.scene.control.ComboBoxBase
import javafx.scene.control.TextInputControl
import javafx.scene.control.ProgressBar
import javafx.scene.control.ProgressIndicator
import javafx.scene.control.Slider
import java.util.Observable
import javafx.scene.control.Label
import javafx.scene.shape.Rectangle
import javafx.scene.paint.Paint
import javafx.scene.shape.Shape
private var enclosing: Pair<Any, String>? = null
private val calcMap: MutableMap<Pair<Any, String>, () -> Unit> = hashMapOf()
// To not set redundant listeners
private var isConstruction = false
private val listenerMap: MutableMap<Pair<Any, String>, MutableSet<Any>> = hashMapOf()
public class V<T>(private var value: T) {
val callbacks: MutableList<() -> Unit> = arrayListOf()
fun invoke(): T {
if (enclosing != null &&
(isConstruction || !listenerMap.containsKey(enclosing) || !listenerMap.get(enclosing)!!.contains(this))) {
val e = enclosing!!
listenerMap.getOrPut(e) { hashSetOf() } .add(this)
callbacks.add { calcMap.get(e)!!() }
}
return value
}
fun u(newValue: T) {
value = newValue
for (callback in callbacks) {
callback()
}
}
}
public class K<T>(private val calc: () -> T) {
init {
val e = Pair(this, "K")
calcMap.put(e, {})
isConstruction = true; enclosing = e; calc(); enclosing = null; isConstruction = false
}
val callbacks: MutableList<() -> Unit> = arrayListOf()
fun invoke(): T {
if (enclosing != null &&
(isConstruction || !listenerMap.containsKey(enclosing) || !listenerMap.get(enclosing)!!.contains(this))) {
val e = enclosing!!
listenerMap.getOrPut(e) { hashSetOf() } .add(this)
callbacks.add { calcMap.get(e)!!() }
}
return calc()
}
}
fun template<T>(name: String, f: (() -> T)?, thiz: Any, property: ObservableValue<T>): T {
if (f == null) {
if (enclosing != null &&
(isConstruction || !listenerMap.containsKey(enclosing) || !listenerMap.get(enclosing)!!.contains(thiz))) {
val e = enclosing!!
listenerMap.getOrPut(e) { hashSetOf() } .add(thiz)
property.addListener { v: Any?, o: Any?, n: Any? -> calcMap.get(e)!!() }
}
}
else {
if (property is WritableValue<*>) {
[suppress("UNCHECKED_CAST", "NAME_SHADOWING")]
val property = property as WritableValue<T>
val e = Pair(thiz, name)
val g = { enclosing = e; property.setValue(f()); enclosing = null }
calcMap.put(e, g)
isConstruction = true; g(); isConstruction = false
}
}
return property.getValue()!!
}
| mit | bbd59d30b3c543623ce50283d0a20fb2 | 31.932584 | 114 | 0.618219 | 4.015068 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/feature-layer-selection/src/main/java/com/esri/arcgisruntime/sample/featurelayerselection/MainActivity.kt | 1 | 5853 | /*
* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.featurelayerselection
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.Feature
import com.esri.arcgisruntime.data.ServiceFeatureTable
import com.esri.arcgisruntime.geometry.Envelope
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.featurelayerselection.databinding.ActivityMainBinding
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val TAG: String = MainActivity::class.java.simpleName
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create service feature table and a feature layer from it
val serviceFeatureTable = ServiceFeatureTable(getString(R.string.gdp_per_capita_url))
val featureLayer = FeatureLayer(serviceFeatureTable)
// create a map with the streets base map type
val streetsMap = ArcGISMap(BasemapStyle.ARCGIS_STREETS).apply {
// add the feature layer to the map's operational layers
operationalLayers.add(featureLayer)
}
mapView.let {
// set the map to be displayed in the layout's map view
it.map = streetsMap
// set an initial view point
it.setViewpoint(
Viewpoint(
Envelope(
-1131596.019761,
3893114.069099,
3926705.982140,
7977912.461790,
SpatialReferences.getWebMercator()
)
)
)
// give any item selected on the map view a red selection halo
it.selectionProperties.color = Color.RED
// set an on touch listener on the map view
it.onTouchListener = object : DefaultMapViewOnTouchListener(this, it) {
override fun onSingleTapConfirmed(motionEvent: MotionEvent): Boolean {
// clear the previous selection
featureLayer.clearSelection()
// get the point that was tapped and convert it to a point in map coordinates
val tappedPoint =
android.graphics.Point(
motionEvent.x.roundToInt(),
motionEvent.y.roundToInt()
)
// set a tolerance for accuracy of returned selections from point tapped
val tolerance = 25.0
val identifyLayerResultFuture =
mapView.identifyLayerAsync(featureLayer, tappedPoint, tolerance, false, -1)
identifyLayerResultFuture.addDoneListener {
try {
val identifyLayerResult = identifyLayerResultFuture.get()
// get the elements in the selection that are features
val features = identifyLayerResult.elements.filterIsInstance<Feature>()
// add the features to the current feature layer selection
featureLayer.selectFeatures(features)
// make a toast to show the number of features selected
Toast.makeText(
applicationContext,
"${features.size} features selected",
Toast.LENGTH_SHORT
).show()
} catch (e: Exception) {
val errorMessage = "Select feature failed: " + e.message
Log.e(TAG, errorMessage)
Toast.makeText(applicationContext, errorMessage, Toast.LENGTH_LONG)
.show()
}
}
return super.onSingleTapConfirmed(motionEvent)
}
}
}
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 17e6bebdc5e6d0427abbf8bb8b1d2570 | 39.93007 | 99 | 0.608748 | 5.490619 | false | false | false | false |
interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/DekkerAlgorithm.kt | 1 | 10216 | /*
* Copyright (c) 2015 The Interedition Development Group.
*
* This file is part of CollateX.
*
* CollateX 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.
*
* CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.interedition.collatex.dekker
import eu.interedition.collatex.CollationAlgorithm
import eu.interedition.collatex.Token
import eu.interedition.collatex.VariantGraph
import eu.interedition.collatex.Witness
import eu.interedition.collatex.dekker.island.Island
import eu.interedition.collatex.dekker.island.IslandCollection
import eu.interedition.collatex.dekker.island.IslandConflictResolver
import eu.interedition.collatex.dekker.token_index.TokenIndex
import eu.interedition.collatex.dekker.token_index.TokenIndexToMatches
import eu.interedition.collatex.matching.EqualityTokenComparator
import eu.interedition.collatex.util.StreamUtil
import eu.interedition.collatex.util.VariantGraphRanking
import java.util.*
import java.util.logging.Level
import java.util.stream.Collectors
class DekkerAlgorithm @JvmOverloads constructor(private val comparator: Comparator<Token> = EqualityTokenComparator()) : CollationAlgorithm.Base(), InspectableCollationAlgorithm {
var tokenIndex: TokenIndex? = null
// tokens are mapped to vertices by their position in the token array
@JvmField
var vertex_array: Array<VariantGraph.Vertex?>? = null
private val phraseMatchDetector: PhraseMatchDetector
private val transpositionDetector: TranspositionDetector
// for debugging purposes only
private var allPossibleIslands: Set<Island>? = null
private var preferredIslands: List<Island>? = null
private var phraseMatches: List<List<Match>>? = null
private var transpositions: MutableList<List<Match>>? = null
private var mergeTranspositions = false
// The algorithm contains two phases:
// 1) Matching phase
// This phase is implemented using a token array -> suffix array -> LCP array -> LCP intervals
//
// 2) Alignment phase
// This phase uses a priority queue and looks at overlap between possible matches to find the optimal alignment and moves
override fun collate(graph: VariantGraph, witnesses: List<Iterable<Token>>) {
// phase 1: matching phase
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Building token index from the tokens of all witnesses")
}
tokenIndex = TokenIndex(comparator, witnesses)
tokenIndex!!.prepare()
// phase 2: alignment phase
vertex_array = arrayOfNulls(tokenIndex!!.token_array!!.size)
var firstWitness = true
for (tokens in witnesses) {
val witness = StreamUtil.stream(tokens)
.findFirst()
.map { obj: Token -> obj.witness }
.orElseThrow { IllegalArgumentException("Empty witness") }
// first witness has a fast path
if (firstWitness) {
super.merge(graph, tokens, emptyMap())
updateTokenToVertexArray(tokens, witness)
firstWitness = false
continue
}
// align second, third, fourth witness etc.
if (LOG.isLoggable(Level.FINER)) {
LOG.log(Level.FINER, "{0} + {1}: {2} vs. {3}", arrayOf(graph, witness, graph.vertices(), tokens))
}
// Phase 2a: Gather matches from the token index
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "{0} + {1}: Gather matches between variant graph and witness from token index", arrayOf(graph, witness))
}
allPossibleIslands = TokenIndexToMatches.createMatches(tokenIndex!!, vertex_array!!, graph, tokens)
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "{0} + {1}: Aligning witness and graph", arrayOf(graph, witness))
}
// Phase 2b: do the actual alignment
val resolver = IslandConflictResolver(IslandCollection(allPossibleIslands))
preferredIslands = resolver.createNonConflictingVersion().islands
// we need to convert the islands into Map<Token, Vertex> for further processing
val alignments: MutableMap<Token, VariantGraph.Vertex> = HashMap()
for (island in preferredIslands!!.listIterator()) {
for (c in island) {
alignments[c.match.token!!] = c.match.vertex
}
}
if (LOG.isLoggable(Level.FINER)) {
for ((key, value) in alignments) {
LOG.log(Level.FINER, "{0} + {1}: Aligned token (incl transposed): {2} = {3}", arrayOf(graph, witness, value, key))
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "{0} + {1}: Detect phrase matches", arrayOf(graph, witness))
}
// Phase 2c: detect phrases and transpositions
phraseMatches = phraseMatchDetector.detect(alignments, graph, tokens)
if (LOG.isLoggable(Level.FINER)) {
for (phraseMatch in phraseMatches!!.listIterator()) {
LOG.log(Level.FINER, "{0} + {1}: Phrase match: {2}", arrayOf(graph, witness, phraseMatch))
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "{0} + {1}: Detect transpositions", arrayOf(graph, witness))
}
transpositions = transpositionDetector.detect(phraseMatches, graph)
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "transpositions:{0}", transpositions)
}
if (LOG.isLoggable(Level.FINER)) {
for (transposition in transpositions!!.listIterator()) {
LOG.log(Level.FINER, "{0} + {1}: Transposition: {2}", arrayOf(graph, witness, transposition))
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "{0} + {1}: Determine aligned tokens by filtering transpositions", arrayOf(graph, witness))
}
// Filter out transposed tokens from aligned tokens
for (transposedPhrase in transpositions!!.listIterator()) {
for (match in transposedPhrase) {
alignments.remove(match.token)
}
}
if (LOG.isLoggable(Level.FINER)) {
for ((key, value) in alignments) {
LOG.log(Level.FINER, "{0} + {1}: Alignment: {2} = {3}", arrayOf(graph, witness, value, key))
}
}
// Phase 2d: and merge
merge(graph, tokens, alignments)
// we filter out small transposed phrases over large distances
val falseTranspositions: MutableList<List<Match>> = ArrayList()
// rank the variant graph
val ranking = VariantGraphRanking.of(graph)
for (transposedPhrase in transpositions!!.listIterator()) {
val match = transposedPhrase[0]
val v1 = witnessTokenVertices[match.token]
val v2 = match.vertex
val distance = Math.abs(ranking.apply(v1) - ranking.apply(v2)) - 1
if (distance > transposedPhrase.size * 3) {
falseTranspositions.add(transposedPhrase)
}
}
transpositions!!.removeAll(falseTranspositions)
// merge transpositions
if (mergeTranspositions) {
mergeTranspositions(graph, transpositions)
}
updateTokenToVertexArray(tokens, witness)
if (LOG.isLoggable(Level.FINER)) {
LOG.log(Level.FINER, "!{0}: {1}", arrayOf(graph, StreamUtil.stream(graph.vertices()).map { obj: VariantGraph.Vertex -> obj.toString() }.collect(Collectors.joining(", "))))
}
}
}
private fun updateTokenToVertexArray(tokens: Iterable<Token>, witness: Witness) {
// we need to update the token -> vertex map
// that information is stored in protected map
var tokenPosition = tokenIndex!!.getStartTokenPositionForWitness(witness)
for (token in tokens) {
val vertex = witnessTokenVertices[token]
vertex_array!![tokenPosition] = vertex
tokenPosition++
}
}
override fun collate(graph: VariantGraph, tokens: Iterable<Token>) {
throw RuntimeException("Progressive alignment is not supported!")
}
override fun getPhraseMatches(): List<List<Match>> {
return Collections.unmodifiableList(phraseMatches)
}
override fun getTranspositions(): List<List<Match>> {
return Collections.unmodifiableList(transpositions)
}
fun getAllPossibleIslands(): Set<Island> {
return Collections.unmodifiableSet(allPossibleIslands)
}
fun getPreferredIslands(): List<Island> {
return Collections.unmodifiableList(preferredIslands)
}
/*
* This check disables transposition rendering in the variant
* graph when the variant graph contains more then two witnesses.
* Transposition detection is done in a progressive manner
* (witness by witness). When viewing the resulting graph
* containing the variation for all witnesses
* the detected transpositions can look strange, since segments
* may have split into smaller or larger parts.
*/
override fun setMergeTranspositions(b: Boolean) {
mergeTranspositions = b
}
init {
phraseMatchDetector = PhraseMatchDetector()
transpositionDetector = TranspositionDetector()
}
} | gpl-3.0 | fa064de620445373e73ac2fc99220174 | 43.229437 | 187 | 0.633516 | 4.532387 | false | false | false | false |
meddlepal/openbaseball | src/main/kotlin/openbaseball/Config.kt | 1 | 529 | package openbaseball
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonUnwrapped
import openbaseball.vertx.Config
data class ServerConfig(
@JsonProperty("port") val port: Int = 5000,
@JsonProperty("host") val host: String = "0.0.0.0") : Config
data class ApiConfig(
@JsonProperty
@JsonUnwrapped
val server: ServerConfig = ServerConfig(port = 52689, host = "0.0.0.0")) : Config
data class OpenBaseballConfig(@JsonProperty("api") val api: ApiConfig) : Config
| agpl-3.0 | 061724753f8003784d75324568d9f915 | 30.117647 | 85 | 0.746692 | 3.805755 | false | true | false | false |
passsy/CompositeAndroid | generator/src/main/kotlin/types/Activity.kt | 1 | 8399 | package types
import inPath
import parse.parseJavaFile
import writer.writeComposite
import writer.writeDelegate
import writer.writeInterface
import writer.writePlugin
import java.io.File
private val outPath = "../activity/src/main/java/com/pascalwelsch/compositeandroid/"
fun main(args: Array<String>) {
generateActivity()
}
fun generateActivity() {
var activity = parseJavaFile(File("$inPath/BlueprintActivity.java"))
// filter methods with special implementations
val filteredMethods = activity.methods
.filterNot { it.name.contains("NonConfigurationInstance") }
activity = activity.copy(methods = filteredMethods)
writeComposite(outPath,
activity,
"activity",
"CompositeActivity",
"AppCompatActivity implements ICompositeActivity",
delegateClassName = "ActivityDelegate",
pluginClassName = "ActivityPlugin",
transform = replaceExtraData,
additionalImports = """
|import android.support.v4.app.SupportActivity;
|import android.support.v7.app.ActionBarDrawerToggle;
|import android.support.v7.app.ActionBarDrawerToggle.Delegate;
|import android.support.v4.app.SupportActivity.ExtraData;
""".replaceIndentByMargin(),
addCodeToClass = activity_custom_nonConfigurationInstance_handling)
writeDelegate(outPath,
activity,
"activity",
"ActivityDelegate",
"ICompositeActivity",
"ActivityPlugin",
extends = "AbstractDelegate<ICompositeActivity, ActivityPlugin>",
transform = replaceExtraData,
additionalImports = """
|import java.util.ListIterator;
|import android.support.v4.app.SupportActivity;
|import android.support.v7.app.ActionBarDrawerToggle;
|import android.support.v7.app.ActionBarDrawerToggle.Delegate;
|import android.support.v4.app.SupportActivity.ExtraData;
""".replaceIndentByMargin(),
addCodeToClass = delegate_custom_nonConfigurationInstance_handling)
writePlugin(outPath,
"Activity",
activity,
"activity",
"ActivityPlugin",
extends = "AbstractPlugin<CompositeActivity, ActivityDelegate>",
transform = replaceExtraData,
additionalImports = """
|import android.support.v4.app.SupportActivity;
|import android.support.v4.app.SupportActivity.ExtraData;
""".replaceIndentByMargin(),
addCodeToClass = plugin_custom_nonConfigurationInstance_handling)
writeInterface(outPath,
activity,
"activity",
"ICompositeActivity",
"LayoutInflater.Factory2, Window.Callback, KeyEvent.Callback, View.OnCreateContextMenuListener, ComponentCallbacks2, ActivityCompat.OnRequestPermissionsResultCallback, AppCompatCallback, ActionBarDrawerToggle.DelegateProvider",
addCodeToClass = interface_custom_nonConfigurationInstance_handling,
transform = replaceExtraData,
additionalImports = """
|import android.content.*;
|import android.support.v4.app.ActivityCompat;
|import android.support.v4.app.Fragment;
|import android.support.v4.app.FragmentManager;
|import android.support.v4.app.LoaderManager;
|import android.support.v4.app.SharedElementCallback;
|import android.support.v4.app.SupportActivity;
|import android.support.v7.app.*;
|import android.support.v7.app.ActionBarDrawerToggle.Delegate;
|import android.support.v4.app.SupportActivity.ExtraData;
""".replaceIndentByMargin())
}
val replaceExtraData: (String) -> String = {
it.replace(" ExtraData", " SupportActivity.ExtraData")
.replace("(ExtraData)", "(SupportActivity.ExtraData)")
.replace("<ExtraData", "<SupportActivity.ExtraData")
}
val interface_custom_nonConfigurationInstance_handling = """
|Object getLastNonConfigurationInstance();
|
|Object getLastCustomNonConfigurationInstance();
|
|Object onRetainCustomNonConfigurationInstance();
|
|Object getLastCompositeCustomNonConfigurationInstance();
|
|Object onRetainCompositeCustomNonConfigurationInstance();
""".replaceIndentByMargin(" ")
val activity_custom_nonConfigurationInstance_handling = """
|/**
| * Use {@link #getLastCompositeCustomNonConfigurationInstance()} instead. This is used internally
| * @see AppCompatActivity#getLastNonConfigurationInstance()
| */
|@Nullable
|@Override
|final public Object getLastNonConfigurationInstance() {
| return super.getLastNonConfigurationInstance();
|}
|
|/**
| * Use {@link #getLastCompositeCustomNonConfigurationInstance()} instead. This is used internally
| * @see AppCompatActivity#getLastCustomNonConfigurationInstance()
| */
|@Override
|final public Object getLastCustomNonConfigurationInstance() {
| return super.getLastCustomNonConfigurationInstance();
|}
|
|/**
| * use {@link #onRetainCompositeCustomNonConfigurationInstance()} instead. This is used integrally
| */
|@Override
|final public Object onRetainCustomNonConfigurationInstance() {
| return delegate.onRetainNonConfigurationInstance();
|}
|
|/**
| * @return see {@link #AppCompatActivity#getLastCustomNonConfigurationInstance()}
| */
|public Object getLastCompositeCustomNonConfigurationInstance() {
| return delegate.getLastCompositeCustomNonConfigurationInstance();
|}
|
|/**
| * save any object over configuration changes, get it with {@link #getLastCompositeCustomNonConfigurationInstance()}
| * @return see {@link #AppCompatActivity#onRetainCustomNonConfigurationInstance()}
| */
|public Object onRetainCompositeCustomNonConfigurationInstance() {
| return null;
|}
""".replaceIndentByMargin(" ")
val delegate_custom_nonConfigurationInstance_handling = """
|
|public Object getLastCompositeCustomNonConfigurationInstance() {
| final Object nci = getOriginal().getLastCustomNonConfigurationInstance();
| if (nci instanceof NonConfigurationInstanceWrapper) {
| final NonConfigurationInstanceWrapper all = (NonConfigurationInstanceWrapper) nci;
| return all.getSuperNonConfigurationInstance();
| }
| return null;
|}
|
|public Object getLastNonConfigurationInstance(final String key) {
| final Object nci = getOriginal().getLastCustomNonConfigurationInstance();
| if (nci instanceof NonConfigurationInstanceWrapper) {
| final NonConfigurationInstanceWrapper all = (NonConfigurationInstanceWrapper) nci;
| return all.getPluginNonConfigurationInstance(key);
| }
| return null;
|}
|
|public Object onRetainNonConfigurationInstance() {
| final NonConfigurationInstanceWrapper all = new NonConfigurationInstanceWrapper(
| getOriginal().onRetainCompositeCustomNonConfigurationInstance());
| for (final ActivityPlugin plugin : mPlugins) {
| final CompositeNonConfigurationInstance pluginNci = plugin
| .onRetainNonConfigurationInstance();
| if (pluginNci != null) {
| all.putPluginNonConfigurationInstance(pluginNci);
| }
| }
| return all;
|}
""".replaceIndentByMargin(" ")
val plugin_custom_nonConfigurationInstance_handling = """
|
|public Object getLastNonConfigurationInstance(final String key) {
| return getCompositeDelegate().getLastNonConfigurationInstance(key);
|}
|
|public CompositeNonConfigurationInstance onRetainNonConfigurationInstance() {
| return null;
|}
""".replaceIndentByMargin(" ") | apache-2.0 | 21aa5cfe7a2f3d2cc0b5ab3bcca84404 | 41.639594 | 239 | 0.647696 | 5.165437 | false | true | false | false |
deltaDNA/android-smartads-sdk | provider-chartboost/src/test/java/com/deltadna/android/sdk/ads/provider/chartboost/DelegateTest.kt | 1 | 7304 | /*
* Copyright (c) 2017 deltaDNA Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.deltadna.android.sdk.ads.provider.chartboost
import com.chartboost.sdk.Model.CBError
import com.deltadna.android.sdk.ads.bindings.AdRequestResult
import com.deltadna.android.sdk.ads.bindings.AdShowResult
import com.deltadna.android.sdk.ads.bindings.MediationAdapter
import com.deltadna.android.sdk.ads.bindings.MediationListener
import com.nhaarman.mockito_kotlin.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class DelegateTest {
private val interstitialAdapter = mock<MediationAdapter>()
private val interstitialListener = mock<MediationListener>()
private val rewardedAdapter = mock<MediationAdapter>()
private val rewardedListener = mock<MediationListener>()
private var uut = Delegate()
@Before
fun before() {
uut = Delegate()
}
@After
fun after() {
reset( interstitialAdapter,
interstitialListener,
rewardedAdapter,
rewardedListener)
}
@Test
fun listenersUnset() {
uut.setInterstitial(interstitialListener, interstitialAdapter)
uut.setRewarded(rewardedListener, rewardedAdapter)
uut.setInterstitial(null, null)
uut.setRewarded(null, null)
uut.didCacheInterstitial("")
uut.didFailToLoadInterstitial("", CBError.CBImpressionError.NO_AD_FOUND)
uut.didDisplayInterstitial("")
uut.didClickInterstitial("")
uut.didCloseInterstitial("")
uut.didCacheRewardedVideo("")
uut.didFailToLoadRewardedVideo("", CBError.CBImpressionError.NO_AD_FOUND)
uut.didDisplayRewardedVideo("")
uut.didClickRewardedVideo("")
uut.didCompleteRewardedVideo("", 0)
uut.didCloseRewardedVideo("")
verifyZeroInteractions(interstitialListener)
verifyZeroInteractions(rewardedListener)
}
@Test
fun interstitial() {
uut.setInterstitial(interstitialListener, interstitialAdapter)
uut.didCacheInterstitial("")
uut.didDisplayInterstitial("")
uut.didClickInterstitial("")
uut.didCloseInterstitial("")
inOrder(interstitialListener) {
verify(interstitialListener).onAdLoaded(same(interstitialAdapter))
verify(interstitialListener).onAdShowing(same(interstitialAdapter))
verify(interstitialListener).onAdClicked(same(interstitialAdapter))
verify(interstitialListener).onAdClosed(
same(interstitialAdapter),
eq(true))
}
}
@Test
fun interstitialFailed() {
uut.setInterstitial(interstitialListener, interstitialAdapter)
uut.didFailToLoadInterstitial("", CBError.CBImpressionError.NO_AD_FOUND)
verify(interstitialListener).onAdFailedToLoad(
same(interstitialAdapter),
eq(AdRequestResult.NoFill),
any())
}
@Test
fun interstitialLoadedCalledTwice() {
uut.setInterstitial(interstitialListener, interstitialAdapter)
uut.didCacheInterstitial("")
uut.didDisplayInterstitial("")
uut.didCacheInterstitial("")
verify(interstitialListener).onAdLoaded(same(interstitialAdapter))
verify(interstitialListener).onAdShowing(same(interstitialAdapter))
verifyNoMoreInteractions(interstitialAdapter)
}
@Test
fun interstitialFailedToShow() {
uut.setInterstitial(interstitialListener, interstitialAdapter)
uut.didCacheInterstitial("")
uut.didFailToLoadInterstitial("", CBError.CBImpressionError.NO_HOST_ACTIVITY)
verify(interstitialListener).onAdLoaded(same(interstitialAdapter))
verify(interstitialListener).onAdFailedToShow(
same(interstitialAdapter),
eq(AdShowResult.ERROR))
}
@Test
fun rewardedWithoutReward() {
uut.setRewarded(rewardedListener, rewardedAdapter)
uut.didCacheRewardedVideo("")
uut.didDisplayRewardedVideo("")
uut.didClickRewardedVideo("")
uut.didCloseRewardedVideo("")
inOrder(rewardedListener) {
verify(rewardedListener).onAdLoaded(same(rewardedAdapter))
verify(rewardedListener).onAdShowing(same(rewardedAdapter))
verify(rewardedListener).onAdClicked(same(rewardedAdapter))
verify(rewardedListener).onAdClosed(
same(rewardedAdapter),
eq(false))
}
}
@Test
fun rewardedWithReward() {
uut.setRewarded(rewardedListener, rewardedAdapter)
uut.didCacheRewardedVideo("")
uut.didDisplayRewardedVideo("")
uut.didClickRewardedVideo("")
uut.didCompleteRewardedVideo("", 0)
uut.didCloseRewardedVideo("")
inOrder(rewardedListener) {
verify(rewardedListener).onAdLoaded(same(rewardedAdapter))
verify(rewardedListener).onAdShowing(same(rewardedAdapter))
verify(rewardedListener).onAdClicked(same(rewardedAdapter))
verify(rewardedListener).onAdClosed(
same(rewardedAdapter),
eq(true))
}
}
@Test
fun rewardedFailed() {
uut.setRewarded(rewardedListener, rewardedAdapter)
uut.didFailToLoadRewardedVideo("", CBError.CBImpressionError.NO_AD_FOUND)
verify(rewardedListener).onAdFailedToLoad(
same(rewardedAdapter),
eq(AdRequestResult.NoFill),
any())
}
@Test
fun rewardedLoadedCalledTwice() {
uut.setRewarded(rewardedListener, rewardedAdapter)
uut.didCacheRewardedVideo("")
uut.didDisplayRewardedVideo("")
uut.didCacheRewardedVideo("")
verify(rewardedListener).onAdLoaded(same(rewardedAdapter))
verify(rewardedListener).onAdShowing(same(rewardedAdapter))
verifyNoMoreInteractions(rewardedAdapter)
}
@Test
fun rewardedFailedToShow() {
uut.setRewarded(rewardedListener, rewardedAdapter)
uut.didCacheRewardedVideo("")
uut.didFailToLoadRewardedVideo("", CBError.CBImpressionError.NO_HOST_ACTIVITY)
verify(rewardedListener).onAdLoaded(same(rewardedAdapter))
verify(rewardedListener).onAdFailedToShow(
same(rewardedAdapter),
eq(AdShowResult.ERROR))
}
}
| apache-2.0 | e0dd4d2ab0e55972a6d265ed4a50450f | 33.947368 | 86 | 0.660871 | 5.016484 | false | true | false | false |
RP-Kit/RPKit | bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/TrackCommand.kt | 1 | 4870 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.essentials.bukkit.command
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.essentials.bukkit.RPKEssentialsBukkit
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.tracking.bukkit.tracking.RPKTrackingService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class TrackCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (!sender.hasPermission("rpkit.essentials.command.track")) {
sender.sendMessage(plugin.messages["no-permission-track"])
return true
}
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["track-usage"])
return true
}
val bukkitPlayer = plugin.server.getPlayer(args[0])
if (bukkitPlayer == null) {
sender.sendMessage(plugin.messages["track-invalid-player"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val trackingService = Services[RPKTrackingService::class.java]
if (trackingService == null) {
sender.sendMessage(plugin.messages["no-tracking-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character-other"])
return true
}
trackingService.isTrackable(character).thenAccept { isTrackable ->
if (!isTrackable) {
sender.sendMessage(plugin.messages["track-invalid-untrackable"])
bukkitPlayer.sendMessage(plugin.messages["track-untrackable-notification", mapOf(
"player" to sender.name
)])
return@thenAccept
}
plugin.server.scheduler.runTask(plugin, Runnable {
val itemRequirement = plugin.config.getItemStack("track-command.item-requirement")
if (itemRequirement != null && !bukkitPlayer.inventory.containsAtLeast(itemRequirement, itemRequirement.amount)) {
sender.sendMessage(plugin.messages["track-invalid-item", mapOf(
"amount" to itemRequirement.amount.toString(),
"type" to itemRequirement.type.toString().lowercase().replace('_', ' ')
)])
return@Runnable
}
val maximumDistance = plugin.config.getInt("track-command.maximum-distance")
val distanceSquared = bukkitPlayer.location.distanceSquared(sender.location)
if (maximumDistance >= 0 && distanceSquared > maximumDistance * maximumDistance) {
sender.sendMessage(plugin.messages["track-invalid-distance"])
return@Runnable
}
sender.compassTarget = bukkitPlayer.location
sender.sendMessage(plugin.messages["track-valid", mapOf(
"player" to minecraftProfile.name,
"character" to if (character.isNameHidden) "[HIDDEN]" else character.name
)])
})
}
return true
}
}
| apache-2.0 | 70681ccb1b945080476902aa39517cb4 | 44.514019 | 130 | 0.644353 | 5.078206 | false | false | false | false |
weisterjie/FamilyLedger | app/src/main/java/ycj/com/familyledger/ui/KBaseActivity.kt | 1 | 2295 | package ycj.com.familyledger.ui
import android.app.Dialog
import android.graphics.drawable.BitmapDrawable
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.widget.TextView
import org.jetbrains.anko.find
import ycj.com.familyledger.R
/**
* @author: ycj
* @date: 2017-06-12 18:43
* @version V1.0 <>
*/
abstract class KBaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
initView()
initListener()
initialize()
}
abstract fun initialize()
abstract fun initView()
abstract fun initListener()
private var dialog: Dialog? = null
fun showLoading() {
hideLoading()
dialog = Dialog(this)
dialog?.show()
val wind = dialog?.window
dialog?.setCanceledOnTouchOutside(true)
dialog?.setCancelable(true)
wind?.setBackgroundDrawable(BitmapDrawable())
val attri = wind?.attributes
attri?.alpha = 1.0F//alpha在0.0f到1.0f之间。1.0完全不透明,0.0f完全透明
attri?.dimAmount = 0.4f//dimAmount在0.0f和1.0f之间,0.0f完全不暗,1.0f全暗
wind?.attributes = attri
val dialogView = LayoutInflater.from(this).inflate(R.layout.layout_loading_dialog, null)
wind?.setContentView(dialogView)
}
fun hideLoading() {
if (dialog != null) {
dialog?.dismiss()
dialog = null
}
}
fun showTips(msg: String, callback: OnTipsCallBack) {
val dialog = Dialog(this)
dialog.show()
val wind = dialog.window
wind.setBackgroundDrawable(BitmapDrawable())
val dialogView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_tips, null)
val tvTips = dialogView.find<TextView>(R.id.tv_tips_dialog)
tvTips.text = msg
dialogView.find<TextView>(R.id.btn_ok_dialog).setOnClickListener {
callback.positiveClick()
dialog.dismiss()
}
dialogView.find<TextView>(R.id.btn_cancel_dialog).setOnClickListener {
dialog.dismiss()
}
wind.setContentView(dialogView)
}
interface OnTipsCallBack {
fun positiveClick()
}
} | apache-2.0 | 2fbd80b6a3d8d977a6f25992fb6f8320 | 28.116883 | 96 | 0.648371 | 4.142329 | false | false | false | false |
siosio/kotlin-jsr352-jsl | src/main/kotlin/siosio/jsr352/jsl/ChunkStep.kt | 1 | 2469 | package siosio.jsr352.jsl
import javax.batch.api.chunk.*
class ChunkStep(
val name: String,
nextStep: String? = null,
allowStartIfComplete: Boolean = false
) : Step(name, nextStep, allowStartIfComplete), Verifier {
var itemCount: Int = 10
var timeLimit: Int = 0
var skipLimit: Int? = null
var retryLimit: Int? = null
var reader: Item<out ItemReader>? = null
var processor: Item<out ItemProcessor>? = null
var writer: Item<out ItemWriter>? = null
inline fun <reified T : ItemReader> reader() {
reader<T> {}
}
inline fun <reified T : ItemReader> reader(body: Item<out ItemReader>.() -> Unit) {
val readerClass = T::class
verifyNamedAnnotation(readerClass)
val item = Item("reader", readerClass)
item.body()
this.reader = item
}
inline fun <reified T : ItemProcessor> processor() {
processor<T> {}
}
inline fun <reified T : ItemProcessor> processor(body: Item<out ItemProcessor>.() -> Unit) {
val processorClass = T::class
verifyNamedAnnotation(processorClass)
val item = Item("processor", processorClass)
item.body()
this.processor = item
}
inline fun <reified T : ItemWriter> writer() {
writer<T> {}
}
inline fun <reified T : ItemWriter> writer(body: Item<out ItemWriter>.() -> Unit) {
val writerClass = T::class
verifyNamedAnnotation(writerClass)
val item = Item("writer", writerClass)
item.body()
this.writer = item
}
override fun buildBody(): String {
verify()
val xml = StringBuilder()
xml.append("<chunk item-count='$itemCount' time-limit='$timeLimit' ${buildSkipLimit()} ${buildRetryLimit()}>")
xml.append(reader!!.buildItem())
processor?.let {
xml.append(it.buildItem())
}
xml.append(writer!!.buildItem())
xml.append("</chunk>")
return xml.toString()
}
private fun buildSkipLimit() =
skipLimit?.let {
"skip-limit='$skipLimit'"
} ?: ""
private fun buildRetryLimit() =
retryLimit?.let {
"retry-limit='$retryLimit'"
} ?: ""
private fun verify() {
if (reader == null) {
throw IllegalStateException("reader mut be set.")
}
if (writer == null) {
throw IllegalStateException("writer mut be set.")
}
}
}
| mit | 6b14e9cc6c2a5a73a3e979df1898e925 | 27.056818 | 118 | 0.583637 | 4.184746 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/guilds/dashboard/GuildDashboard.kt | 1 | 1313 | package net.perfectdreams.spicymorenitta.routes.guilds.dashboard
import kotlinx.html.DIV
import kotlinx.html.InputType
import kotlinx.html.div
import kotlinx.html.input
import kotlinx.html.js.onChangeFunction
import kotlinx.html.label
import org.w3c.dom.HTMLInputElement
fun DIV.createToggle(title: String, subText: String? = null, id: String? = null, isChecked: Boolean = false, onChange: ((Boolean) -> (Boolean))? = null) {
div(classes = "toggleable-wrapper") {
div(classes = "information") {
div {
+ title
}
if (subText != null) {
div(classes = "sub-text") {
+ subText
}
}
}
label("switch") {
attributes["for"] = id ?: "checkbox"
input(InputType.checkBox) {
attributes["id"] = id ?: "checkbox"
if (isChecked) {
attributes["checked"] = "true"
}
onChangeFunction = {
val target = it.target as HTMLInputElement
val result = onChange?.invoke(target.checked) ?: target.checked
target.checked = result
}
}
div(classes = "slider round") {}
}
}
} | agpl-3.0 | 15adc25689176a85c006b0fc7a9a72a7 | 28.2 | 154 | 0.519421 | 4.656028 | false | false | false | false |
chrsep/Kingfish | app/src/main/java/com/directdev/portal/features/resources/ResourcesRecyclerAdapter.kt | 1 | 3951 | package com.directdev.portal.features.resources
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.crashlytics.android.Crashlytics
import com.directdev.portal.R
import com.directdev.portal.models.ResModel
import com.directdev.portal.models.ResResourcesModel
import kotlinx.android.synthetic.main.item_resources.view.*
import org.jetbrains.anko.downloadManager
import org.jetbrains.anko.layoutInflater
class ResourcesRecyclerAdapter(
val context: Context,
val data: List<String>,
val resources: ResModel) :
androidx.recyclerview.widget.RecyclerView.Adapter<ResourcesRecyclerAdapter.ViewHolder>() {
override fun getItemCount() = data.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(context.layoutInflater.inflate(R.layout.item_resources, parent, false))
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val outlines = resources.resources.filter { it.courseOutlineTopicID == data[position] }
holder.bindData(context, outlines, resources)
}
class ViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
@SuppressLint("ResourceType")
fun bindData(ctx: Context, item: List<ResResourcesModel>, resources: ResModel) {
if (item.isEmpty()) return
itemView.resSession.text = "Meeting " + item[0].sessionIDNUM
itemView.resTopic.text = item[0].courseOutlineTopic
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
itemView.presentationDownload.backgroundTintList = ColorStateList
.valueOf(Color.parseColor(ctx.getString(R.color.colorAccent)))
}
} catch (e: NoSuchMethodError) {
}
itemView.presentationDownload.setOnClickListener {
val selectedDownload = resources.path.filter {
it.mediaTypeId == "01" && it.courseOutlineTopicID == item[0].courseOutlineTopicID
}
if (selectedDownload.isEmpty()) return@setOnClickListener
try {
val path = (selectedDownload[0].path
+ selectedDownload[0].location
+ "/"
+ selectedDownload[0].filename)
.replace("\\", "/")
.replace(" ", "%20")
Log.d("Path", path)
ctx.downloadManager.enqueue(DownloadManager.Request(Uri.parse(path))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setTitle(item[0].courseOutlineTopic))
} catch (e: IllegalArgumentException) {
// Needed to know what changed when downloading slides
Crashlytics.log(selectedDownload.toString())
val path = "https://newcontent.binus.ac.id/data_content/" + (selectedDownload[0].path
+ "/"
+ selectedDownload[0].location
+ "/"
+ selectedDownload[0].filename)
.replace("\\", "/")
.replace(" ", "%20")
ctx.downloadManager.enqueue(DownloadManager.Request(Uri.parse(path))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setTitle(item[0].courseOutlineTopic))
}
}
}
}
} | gpl-3.0 | f112184bc73153a74c7176a03c422f8c | 47.195122 | 115 | 0.604404 | 5.185039 | false | false | false | false |
shyiko/ktlint | ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/MaxLineLengthRuleTest.kt | 1 | 4253 | package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.core.api.FeatureInAlphaState
import com.pinterest.ktlint.test.EditorConfigTestRule
import com.pinterest.ktlint.test.diffFileLint
import com.pinterest.ktlint.test.lint
import java.io.File
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
@OptIn(FeatureInAlphaState::class)
class MaxLineLengthRuleTest {
@get:Rule
val editorConfigTestRule = EditorConfigTestRule()
@Test
fun testLint() {
assertThat(
MaxLineLengthRule().diffFileLint(
"spec/max-line-length/lint.kt.spec",
userData = mapOf("max_line_length" to "80")
)
).isEmpty()
}
@Test
fun testErrorSuppression() {
assertThat(
MaxLineLengthRule().lint(
"""
fun main(vaaaaaaaaaaaaaaaaaaaaaaar: String) { // ktlint-disable max-line-length
println("teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeext")
/* ktlint-disable max-line-length */
println("teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeext")
}
""".trimIndent(),
userData = mapOf("max_line_length" to "40")
)
).isEqualTo(
listOf(
LintError(2, 1, "max-line-length", "Exceeded max line length (40)")
)
)
}
@Test
fun testErrorSuppressionOnTokensBetweenBackticks() {
val testFile = ignoreBacktickedIdentifier()
assertThat(
MaxLineLengthRule().lint(
testFile.absolutePath,
"""
@Test
fun `Some too long test description between backticks`() {
println("teeeeeeeeeeeeeeeeeeeeeeeext")
}
""".trimIndent(),
userData = mapOf(
"max_line_length" to "40"
)
)
).isEqualTo(
listOf(
// Note that no error was generated on line 2 with the long fun name but on another line
LintError(3, 1, "max-line-length", "Exceeded max line length (40)")
)
)
}
@Test
fun testReportLongLinesAfterExcludingTokensBetweenBackticks() {
assertThat(
MaxLineLengthRule().lint(
"""
@ParameterizedTest
fun `Some too long test description between backticks`(looooooooongParameterName: String) {
println("teeeeeeeeext")
}
""".trimIndent(),
userData = mapOf("max_line_length" to "40")
)
).isEqualTo(
listOf(
LintError(2, 1, "max-line-length", "Exceeded max line length (40)")
)
)
}
@Test
fun testLintOff() {
assertThat(
MaxLineLengthRule().diffFileLint(
"spec/max-line-length/lint-off.kt.spec",
userData = mapOf("max_line_length" to "off")
)
).isEmpty()
}
@Test
fun testRangeSearch() {
for (i in 0 until 10) {
assertThat(RangeTree((0..i).asSequence().toList()).query(Int.MIN_VALUE, Int.MAX_VALUE).toString())
.isEqualTo((0..i).asSequence().toList().toString())
}
assertThat(RangeTree(emptyList()).query(1, 5).toString()).isEqualTo("[]")
assertThat(RangeTree((5 until 10).asSequence().toList()).query(1, 5).toString()).isEqualTo("[]")
assertThat(RangeTree((5 until 10).asSequence().toList()).query(3, 7).toString()).isEqualTo("[5, 6]")
assertThat(RangeTree((5 until 10).asSequence().toList()).query(7, 12).toString()).isEqualTo("[7, 8, 9]")
assertThat(RangeTree((5 until 10).asSequence().toList()).query(10, 15).toString()).isEqualTo("[]")
assertThat(RangeTree(listOf(1, 5, 10)).query(3, 4).toString()).isEqualTo("[]")
}
private fun ignoreBacktickedIdentifier(): File = editorConfigTestRule
.writeToEditorConfig(
mapOf(MaxLineLengthRule.ignoreBackTickedIdentifierProperty.type to true.toString())
)
}
| mit | b4c2cf2ad81720bf9118c2d3a56da656 | 34.14876 | 112 | 0.563837 | 4.617807 | false | true | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/echo.kt | 1 | 1882 | /*
* Copyright 2016 Karl Tauber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Echo
import org.apache.tools.ant.types.Resource
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.echo(
message: String? = null,
file: String? = null,
output: String? = null,
append: Boolean? = null,
level: EchoLevel? = null,
encoding: String? = null,
force: Boolean? = null,
nested: (KEcho.() -> Unit)? = null)
{
Echo().execute("echo") { task ->
if (message != null)
task.setMessage(message)
if (file != null)
task.setFile(project.resolveFile(file))
if (output != null)
task.setOutput(Resource(output))
if (append != null)
task.setAppend(append)
if (level != null)
task.setLevel(Echo.EchoLevel().apply { this.value = level.value })
if (encoding != null)
task.setEncoding(encoding)
if (force != null)
task.setForce(force)
if (nested != null)
nested(KEcho(task))
}
}
class KEcho(val component: Echo) {
operator fun String.unaryPlus() = component.addText(this)
}
enum class EchoLevel(val value: String) { ERROR("error"), WARN("warn"), WARNING("warning"), INFO("info"), VERBOSE("verbose"), DEBUG("debug") }
| apache-2.0 | d93ab02b5f35f9d6261e827f3a0db459 | 30.366667 | 142 | 0.636557 | 3.675781 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/search/MultiselectSearchEngineListPreference.kt | 1 | 2464 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.search
import android.content.Context
import android.util.AttributeSet
import android.widget.CompoundButton
import androidx.preference.PreferenceViewHolder
import org.mozilla.focus.R
import org.mozilla.focus.ext.tryAsActivity
class MultiselectSearchEngineListPreference(context: Context, attrs: AttributeSet) :
SearchEngineListPreference(context, attrs) {
override val itemResId: Int
get() = R.layout.search_engine_checkbox_button
val checkedEngineIds: Set<String>
get() {
val engineIdSet = HashSet<String>()
for (i in 0 until searchEngineGroup!!.childCount) {
val engineButton = searchEngineGroup!!.getChildAt(i) as CompoundButton
if (engineButton.isChecked) {
engineIdSet.add(engineButton.tag as String)
}
}
return engineIdSet
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
bindEngineCheckboxesToMenu()
}
override fun updateDefaultItem(defaultButton: CompoundButton) {
defaultButton.isClickable = false
// Showing the default engine as disabled requires a StateListDrawable, but since there
// is no state_clickable and state_enabled seems to require a default drawable state,
// use state_activated instead to designate the default search engine.
defaultButton.isActivated = true
}
// Whenever an engine is checked or unchecked, we notify the menu
private fun bindEngineCheckboxesToMenu() {
for (i in 0 until searchEngineGroup!!.childCount) {
val engineButton = searchEngineGroup!!.getChildAt(i) as CompoundButton
engineButton.setOnCheckedChangeListener { _, _ ->
val context = context
context.tryAsActivity()?.invalidateOptionsMenu()
}
}
}
fun atLeastOneEngineChecked(): Boolean {
for (i in 0 until searchEngineGroup!!.childCount) {
val engineButton = searchEngineGroup!!.getChildAt(i) as CompoundButton
if (engineButton.isChecked) {
return true
}
}
return false
}
}
| mpl-2.0 | df21d19f1ab72c2b093b08cdae3926ba | 36.333333 | 95 | 0.665179 | 5.059548 | false | false | false | false |
square/leakcanary | shark-hprof/src/main/java/shark/StreamingHprofReader.kt | 2 | 12321 | package shark
import java.io.File
import okio.Source
import shark.HprofRecordTag.CLASS_DUMP
import shark.HprofRecordTag.HEAP_DUMP
import shark.HprofRecordTag.HEAP_DUMP_END
import shark.HprofRecordTag.HEAP_DUMP_INFO
import shark.HprofRecordTag.HEAP_DUMP_SEGMENT
import shark.HprofRecordTag.INSTANCE_DUMP
import shark.HprofRecordTag.LOAD_CLASS
import shark.HprofRecordTag.OBJECT_ARRAY_DUMP
import shark.HprofRecordTag.PRIMITIVE_ARRAY_DUMP
import shark.HprofRecordTag.PRIMITIVE_ARRAY_NODATA
import shark.HprofRecordTag.ROOT_DEBUGGER
import shark.HprofRecordTag.ROOT_FINALIZING
import shark.HprofRecordTag.ROOT_INTERNED_STRING
import shark.HprofRecordTag.ROOT_JAVA_FRAME
import shark.HprofRecordTag.ROOT_JNI_GLOBAL
import shark.HprofRecordTag.ROOT_JNI_LOCAL
import shark.HprofRecordTag.ROOT_JNI_MONITOR
import shark.HprofRecordTag.ROOT_MONITOR_USED
import shark.HprofRecordTag.ROOT_NATIVE_STACK
import shark.HprofRecordTag.ROOT_REFERENCE_CLEANUP
import shark.HprofRecordTag.ROOT_STICKY_CLASS
import shark.HprofRecordTag.ROOT_THREAD_BLOCK
import shark.HprofRecordTag.ROOT_THREAD_OBJECT
import shark.HprofRecordTag.ROOT_UNKNOWN
import shark.HprofRecordTag.ROOT_UNREACHABLE
import shark.HprofRecordTag.ROOT_VM_INTERNAL
import shark.HprofRecordTag.STACK_FRAME
import shark.HprofRecordTag.STACK_TRACE
import shark.HprofRecordTag.STRING_IN_UTF8
import shark.PrimitiveType.Companion.REFERENCE_HPROF_TYPE
import shark.PrimitiveType.INT
import shark.StreamingHprofReader.Companion.readerFor
/**
* Reads the entire content of a Hprof source in one fell swoop.
* Call [readerFor] to obtain a new instance.
*/
class StreamingHprofReader private constructor(
private val sourceProvider: StreamingSourceProvider,
private val header: HprofHeader
) {
/**
* Obtains a new source to read all hprof records from and calls [listener] back for each record
* that matches one of the provided [recordTags].
*
* @return the number of bytes read from the source
*/
@Suppress("ComplexMethod", "LongMethod", "NestedBlockDepth")
fun readRecords(
recordTags: Set<HprofRecordTag>,
listener: OnHprofRecordTagListener
): Long {
return sourceProvider.openStreamingSource().use { source ->
val reader = HprofRecordReader(header, source)
reader.skip(header.recordsPosition)
// Local ref optimizations
val intByteSize = INT.byteSize
val identifierByteSize = reader.sizeOf(REFERENCE_HPROF_TYPE)
while (!source.exhausted()) {
// type of the record
val tag = reader.readUnsignedByte()
// number of microseconds since the time stamp in the header
reader.skip(intByteSize)
// number of bytes that follow and belong to this record
val length = reader.readUnsignedInt()
when (tag) {
STRING_IN_UTF8.tag -> {
if (STRING_IN_UTF8 in recordTags) {
listener.onHprofRecord(STRING_IN_UTF8, length, reader)
} else {
reader.skip(length)
}
}
LOAD_CLASS.tag -> {
if (LOAD_CLASS in recordTags) {
listener.onHprofRecord(LOAD_CLASS, length, reader)
} else {
reader.skip(length)
}
}
STACK_FRAME.tag -> {
if (STACK_FRAME in recordTags) {
listener.onHprofRecord(STACK_FRAME, length, reader)
} else {
reader.skip(length)
}
}
STACK_TRACE.tag -> {
if (STACK_TRACE in recordTags) {
listener.onHprofRecord(STACK_TRACE, length, reader)
} else {
reader.skip(length)
}
}
HEAP_DUMP.tag, HEAP_DUMP_SEGMENT.tag -> {
val heapDumpStart = reader.bytesRead
var previousTag = 0
var previousTagPosition = 0L
while (reader.bytesRead - heapDumpStart < length) {
val heapDumpTagPosition = reader.bytesRead
val heapDumpTag = reader.readUnsignedByte()
when (heapDumpTag) {
ROOT_UNKNOWN.tag -> {
if (ROOT_UNKNOWN in recordTags) {
listener.onHprofRecord(ROOT_UNKNOWN, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_JNI_GLOBAL.tag -> {
if (ROOT_JNI_GLOBAL in recordTags) {
listener.onHprofRecord(ROOT_JNI_GLOBAL, -1, reader)
} else {
reader.skip(identifierByteSize + identifierByteSize)
}
}
ROOT_JNI_LOCAL.tag -> {
if (ROOT_JNI_LOCAL in recordTags) {
listener.onHprofRecord(ROOT_JNI_LOCAL, -1, reader)
} else {
reader.skip(identifierByteSize + intByteSize + intByteSize)
}
}
ROOT_JAVA_FRAME.tag -> {
if (ROOT_JAVA_FRAME in recordTags) {
listener.onHprofRecord(ROOT_JAVA_FRAME, -1, reader)
} else {
reader.skip(identifierByteSize + intByteSize + intByteSize)
}
}
ROOT_NATIVE_STACK.tag -> {
if (ROOT_NATIVE_STACK in recordTags) {
listener.onHprofRecord(ROOT_NATIVE_STACK, -1, reader)
} else {
reader.skip(identifierByteSize + intByteSize)
}
}
ROOT_STICKY_CLASS.tag -> {
if (ROOT_STICKY_CLASS in recordTags) {
listener.onHprofRecord(ROOT_STICKY_CLASS, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_THREAD_BLOCK.tag -> {
if (ROOT_THREAD_BLOCK in recordTags) {
listener.onHprofRecord(ROOT_THREAD_BLOCK, -1, reader)
} else {
reader.skip(identifierByteSize + intByteSize)
}
}
ROOT_MONITOR_USED.tag -> {
if (ROOT_MONITOR_USED in recordTags) {
listener.onHprofRecord(ROOT_MONITOR_USED, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_THREAD_OBJECT.tag -> {
if (ROOT_THREAD_OBJECT in recordTags) {
listener.onHprofRecord(ROOT_THREAD_OBJECT, -1, reader)
} else {
reader.skip(identifierByteSize + intByteSize + intByteSize)
}
}
ROOT_INTERNED_STRING.tag -> {
if (ROOT_INTERNED_STRING in recordTags) {
listener.onHprofRecord(ROOT_INTERNED_STRING, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_FINALIZING.tag -> {
if (ROOT_FINALIZING in recordTags) {
listener.onHprofRecord(ROOT_FINALIZING, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_DEBUGGER.tag -> {
if (ROOT_DEBUGGER in recordTags) {
listener.onHprofRecord(ROOT_DEBUGGER, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_REFERENCE_CLEANUP.tag -> {
if (ROOT_REFERENCE_CLEANUP in recordTags) {
listener.onHprofRecord(ROOT_REFERENCE_CLEANUP, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_VM_INTERNAL.tag -> {
if (ROOT_VM_INTERNAL in recordTags) {
listener.onHprofRecord(ROOT_VM_INTERNAL, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
ROOT_JNI_MONITOR.tag -> {
if (ROOT_JNI_MONITOR in recordTags) {
listener.onHprofRecord(ROOT_JNI_MONITOR, -1, reader)
} else {
reader.skip(identifierByteSize + intByteSize + intByteSize)
}
}
ROOT_UNREACHABLE.tag -> {
if (ROOT_UNREACHABLE in recordTags) {
listener.onHprofRecord(ROOT_UNREACHABLE, -1, reader)
} else {
reader.skip(identifierByteSize)
}
}
CLASS_DUMP.tag -> {
if (CLASS_DUMP in recordTags) {
listener.onHprofRecord(CLASS_DUMP, -1, reader)
} else {
reader.skipClassDumpRecord()
}
}
INSTANCE_DUMP.tag -> {
if (INSTANCE_DUMP in recordTags) {
listener.onHprofRecord(INSTANCE_DUMP, -1, reader)
} else {
reader.skipInstanceDumpRecord()
}
}
OBJECT_ARRAY_DUMP.tag -> {
if (OBJECT_ARRAY_DUMP in recordTags) {
listener.onHprofRecord(OBJECT_ARRAY_DUMP, -1, reader)
} else {
reader.skipObjectArrayDumpRecord()
}
}
PRIMITIVE_ARRAY_DUMP.tag -> {
if (PRIMITIVE_ARRAY_DUMP in recordTags) {
listener.onHprofRecord(PRIMITIVE_ARRAY_DUMP, -1, reader)
} else {
reader.skipPrimitiveArrayDumpRecord()
}
}
PRIMITIVE_ARRAY_NODATA.tag -> {
throw UnsupportedOperationException("$PRIMITIVE_ARRAY_NODATA cannot be parsed")
}
HEAP_DUMP_INFO.tag -> {
if (HEAP_DUMP_INFO in recordTags) {
listener.onHprofRecord(HEAP_DUMP_INFO, -1, reader)
} else {
reader.skipHeapDumpInfoRecord()
}
}
else -> throw IllegalStateException(
"Unknown tag ${
"0x%02x".format(
heapDumpTag
)
} at $heapDumpTagPosition after ${
"0x%02x".format(
previousTag
)
} at $previousTagPosition"
)
}
previousTag = heapDumpTag
previousTagPosition = heapDumpTagPosition
}
}
HEAP_DUMP_END.tag -> {
if (HEAP_DUMP_END in recordTags) {
listener.onHprofRecord(HEAP_DUMP_END, length, reader)
}
}
else -> {
reader.skip(length)
}
}
}
reader.bytesRead
}
}
companion object {
/**
* Creates a [StreamingHprofReader] for the provided [hprofFile]. [hprofHeader] will be read from
* [hprofFile] unless you provide it.
*/
fun readerFor(
hprofFile: File,
hprofHeader: HprofHeader = HprofHeader.parseHeaderOf(hprofFile)
): StreamingHprofReader {
val sourceProvider = FileSourceProvider(hprofFile)
return readerFor(sourceProvider, hprofHeader)
}
/**
* Creates a [StreamingHprofReader] that will call [StreamingSourceProvider.openStreamingSource]
* on every [readRecords] to obtain a [Source] to read the hprof data from. Before reading the
* hprof records, [StreamingHprofReader] will skip [HprofHeader.recordsPosition] bytes.
*/
fun readerFor(
hprofSourceProvider: StreamingSourceProvider,
hprofHeader: HprofHeader = hprofSourceProvider.openStreamingSource()
.use { HprofHeader.parseHeaderOf(it) }
): StreamingHprofReader {
return StreamingHprofReader(hprofSourceProvider, hprofHeader)
}
}
}
| apache-2.0 | 350809380070c32b580de5fd0737716a | 35.669643 | 101 | 0.536401 | 4.852698 | false | false | false | false |
JayNewstrom/ScreenSwitcher | sample-core/src/main/java/screenswitchersample/core/screen/BaseScreen.kt | 1 | 2960 | package screenswitchersample.core.screen
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import com.jaynewstrom.concrete.Concrete
import com.jaynewstrom.concrete.ConcreteBlock
import com.jaynewstrom.concrete.ConcreteWall
import com.jaynewstrom.screenswitcher.Screen
import com.jaynewstrom.screenswitcher.ScreenSwitcherState
import screenswitchersample.core.components.PassthroughComponent
import screenswitchersample.core.leak.LeakWatcher
import screenswitchersample.core.view.inflate
private const val LEAK_WATCHER_DESCRIPTION = "Screen Has Been Removed"
abstract class BaseScreen<C> : Screen {
private var state: BaseScreenState<C>? = null
protected abstract fun createWallManager(screenSwitcherState: ScreenSwitcherState): ScreenWallManager<C>
@LayoutRes protected abstract fun layoutId(): Int
protected abstract fun bindView(view: View, component: C)
final override fun createView(hostView: ViewGroup, screenSwitcherState: ScreenSwitcherState): View {
val state = state
val screenWall: ConcreteWall<C>
if (state == null) {
val parentWall = Concrete.findWall<ConcreteWall<PassthroughComponent>>(hostView.context)
val wallManager = createWallManager(screenSwitcherState)
screenWall = wallManager.createScreenWall(parentWall)
val leakWatcher = parentWall.component.leakWatcher
this.state = BaseScreenState(screenWall, leakWatcher, wallManager)
} else {
screenWall = state.screenWall
}
return hostView.inflate(layoutId(), context = screenWall.createContext(hostView.context))
}
final override fun bindView(view: View) {
bindView(view, state!!.screenWall.component)
}
final override fun destroyScreen(associatedView: View) {
val state = state!!
val component = state.screenWall.component
state.screenWall.destroy()
state.leakWatcher.watch(this, LEAK_WATCHER_DESCRIPTION)
state.leakWatcher.watch(associatedView, LEAK_WATCHER_DESCRIPTION)
state.leakWatcher.watch(component, LEAK_WATCHER_DESCRIPTION)
}
override fun transition(): Screen.Transition = DefaultScreenTransition
}
private data class BaseScreenState<C>(
val screenWall: ConcreteWall<C>,
val leakWatcher: LeakWatcher,
val wallManager: ScreenWallManager<C>
)
interface ScreenWallManager<C> {
fun createScreenWall(parentWall: ConcreteWall<PassthroughComponent>): ConcreteWall<C>
}
class DefaultScreenWallManager<C>(
private val blockFactory: (parentComponent: PassthroughComponent) -> ConcreteBlock<C>,
private val initializationAction: ((wall: ConcreteWall<C>) -> Unit)? = null
) : ScreenWallManager<C> {
override fun createScreenWall(parentWall: ConcreteWall<PassthroughComponent>): ConcreteWall<C> {
return parentWall.stack(blockFactory(parentWall.component), initializationAction)
}
}
| apache-2.0 | 5cbc2d02d88ba5725827ca91141b39f6 | 39 | 108 | 0.753716 | 4.560863 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/preferences/PreferenceManager.kt | 1 | 5553 | /*
* Copyright 2022, Lawnchair
*
* 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.lawnchair.preferences
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import app.lawnchair.LawnchairLauncher
import app.lawnchair.font.FontCache
import app.lawnchair.util.isOnePlusStock
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.model.DeviceGridState
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.util.MainThreadInitializedObject
class PreferenceManager private constructor(private val context: Context) : BasePreferenceManager(context) {
private val idp get() = InvariantDeviceProfile.INSTANCE.get(context)
private val reloadIcons = { idp.onPreferencesChanged(context) }
private val reloadGrid: () -> Unit = { idp.onPreferencesChanged(context) }
private val recreate = {
LawnchairLauncher.instance?.recreateIfNotScheduled()
Unit
}
val iconPackPackage = StringPref("pref_iconPackPackage", "", reloadIcons)
val allowRotation = BoolPref("pref_allowRotation", false)
val wrapAdaptiveIcons = BoolPref("prefs_wrapAdaptive", false, reloadIcons)
val addIconToHome = BoolPref("pref_add_icon_to_home", true)
val hotseatColumns = IntPref("pref_hotseatColumns", 4, reloadGrid)
val workspaceColumns = IntPref("pref_workspaceColumns", 4)
val workspaceRows = IntPref("pref_workspaceRows", 5)
val folderRows = IdpIntPref("pref_folderRows", { numFolderRows }, reloadGrid)
val drawerOpacity = FloatPref("pref_drawerOpacity", 1F, recreate)
val coloredBackgroundLightness = FloatPref("pref_coloredBackgroundLightness", 0.9F, reloadIcons)
val feedProvider = StringPref("pref_feedProvider", "")
val launcherTheme = StringPref("pref_launcherTheme", "system")
val overrideWindowCornerRadius = BoolPref("pref_overrideWindowCornerRadius", false, recreate)
val windowCornerRadius = IntPref("pref_windowCornerRadius", 80, recreate)
val autoLaunchRoot = BoolPref("pref_autoLaunchRoot", false)
val wallpaperScrolling = BoolPref("pref_wallpaperScrolling", true)
val enableDebugMenu = BoolPref("pref_enableDebugMenu", false)
val customAppName = object : MutableMapPref<ComponentKey, String>("pref_appNameMap", reloadGrid) {
override fun flattenKey(key: ComponentKey) = key.toString()
override fun unflattenKey(key: String) = ComponentKey.fromString(key)!!
override fun flattenValue(value: String) = value
override fun unflattenValue(value: String) = value
}
private val fontCache = FontCache.INSTANCE.get(context)
val fontWorkspace = FontPref("pref_workspaceFont", fontCache.uiText, recreate)
val fontHeading = FontPref("pref_fontHeading", fontCache.uiRegular, recreate)
val fontHeadingMedium = FontPref("pref_fontHeadingMedium", fontCache.uiMedium, recreate)
val fontBody = FontPref("pref_fontBody", fontCache.uiText, recreate)
val fontBodyMedium = FontPref("pref_fontBodyMedium", fontCache.uiTextMedium, recreate)
val deviceSearch = BoolPref("device_search", true, recreate)
val searchResultShortcuts = BoolPref("pref_searchResultShortcuts", true)
val searchResultPeople = BoolPref("pref_searchResultPeople", true)
val searchResultPixelTips = BoolPref("pref_searchResultPixelTips", false)
val searchResultSettings = BoolPref("pref_searchResultSettings", false)
val themedIcons = BoolPref("themed_icons", false)
val drawerThemedIcons = BoolPref("drawer_themed_icons", false, recreate)
val hotseatQsbCornerRadius = FloatPref("pref_hotseatQsbCornerRadius", 1F, recreate)
val recentsActionScreenshot = BoolPref("pref_recentsActionScreenshot", !isOnePlusStock)
val recentsActionShare = BoolPref("pref_recentsActionShare", isOnePlusStock)
val recentsActionLens = BoolPref("pref_recentsActionLens", true)
val recentsActionClearAll = BoolPref("pref_clearAllAsAction", false)
val recentsTranslucentBackground = BoolPref("pref_recentsTranslucentBackground", false, recreate)
init {
sp.registerOnSharedPreferenceChangeListener(this)
migratePrefs(CURRENT_VERSION) { oldVersion ->
if (oldVersion < 2) {
val gridState = DeviceGridState(context).toProtoMessage()
if (gridState.hotseatCount != -1) {
val colsAndRows = gridState.gridSize.split(",")
workspaceColumns.set(colsAndRows[0].toInt())
workspaceRows.set(colsAndRows[1].toInt())
hotseatColumns.set(gridState.hotseatCount)
}
}
}
}
companion object {
private const val CURRENT_VERSION = 2
@JvmField
val INSTANCE = MainThreadInitializedObject(::PreferenceManager)
@JvmStatic
fun getInstance(context: Context) = INSTANCE.get(context)!!
}
}
@Composable
fun preferenceManager() = PreferenceManager.getInstance(LocalContext.current)
| gpl-3.0 | 7dcdd4aca6529e01485745b90e8472f3 | 47.286957 | 108 | 0.736719 | 4.358713 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/mesh/FlatMeshTriangle.kt | 1 | 1709 | package net.dinkla.raytracer.objects.mesh
import net.dinkla.raytracer.hits.Hit
import net.dinkla.raytracer.math.MathUtils
import net.dinkla.raytracer.math.Normal
import net.dinkla.raytracer.math.Ray
class FlatMeshTriangle : MeshTriangle {
constructor(mesh: Mesh) : super(mesh) {}
constructor(mesh: Mesh, i0: Int, i1: Int, i2: Int) : super(mesh, i0, i1, i2) {}
override fun hit(ray: Ray, sr: Hit): Boolean {
val v0 = mesh.vertices[index0]
val v1 = mesh.vertices[index1]
val v2 = mesh.vertices[index2]
val a = v0.x - v1.x
val b = v0.x - v2.x
val c = ray.direction.x
val d = v0.x - ray.origin.x
val e = v0.y - v1.y
val f = v0.y - v2.y
val g = ray.direction.y
val h = v0.y - ray.origin.y
val i = v0.z - v1.z
val j = v0.z - v2.z
val k = ray.direction.z
val l = v0.z - ray.origin.z
val m = f * k - g * j
val n = h * k - g * l
val p = f * l - h * j
val q = g * i - e * k
val s = e * j - f * i
val invDenom = 1.0 / (a * m + b * q + c * s)
val e1 = d * m - b * n - c * p
val beta = e1 * invDenom
if (beta < 0.0)
return false
val r = e * l - h * i
val e2 = a * n + d * q + c * r
val gamma = e2 * invDenom
if (gamma < 0.0)
return false
if (beta + gamma > 1.0)
return false
val e3 = a * p - b * r + d * s
val t = e3 * invDenom
if (t < MathUtils.K_EPSILON)
return false
sr.t = t
assert(normal != null)
sr.normal = normal ?: Normal.ZERO
return true
}
}
| apache-2.0 | 18ed7bbb9af0e2b2f7ccb4e3d6c1dc32 | 23.768116 | 83 | 0.49093 | 3.030142 | false | false | false | false |
mbarta/scr-redesign | app/src/main/java/me/barta/stayintouch/ui/views/ScrTabLayout.kt | 1 | 1851 | package me.barta.stayintouch.ui.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import com.google.android.material.tabs.TabLayout
import me.barta.stayintouch.R
import me.barta.stayintouch.common.utils.animateTextSize
import me.barta.stayintouch.common.utils.getFontSize
class ScrTabLayout : TabLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun addTab(tab: Tab, setSelected: Boolean) {
val tabViewText = View.inflate(context, R.layout.scr_tab_textview, null) as TextView
tabViewText.text = tab.text
tab.customView = tabViewText
super.addTab(tab, setSelected)
}
init {
addOnTabSelectedListener(
object : OnTabSelectedListener {
override fun onTabSelected(tab: Tab?) {
val textView = tab?.customView as? TextView
textView?.animateTextSize(resources.getFontSize(R.dimen.tab_text_size),
resources.getFontSize(R.dimen.tab_text_selected_size),
200)
}
override fun onTabUnselected(tab: Tab?) {
val textView = tab?.customView as? TextView
textView?.animateTextSize(resources.getFontSize(R.dimen.tab_text_selected_size),
resources.getFontSize(R.dimen.tab_text_size),
200)
}
override fun onTabReselected(tab: Tab?) {
}
})
}
}
| mit | f92e416c0f2e4064aa40110b1a15c8ed | 35.294118 | 111 | 0.605078 | 4.734015 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/androidTest/java/org/wordpress/android/fluxc/mocked/MockedStack_EditorThemeStoreTest.kt | 2 | 12813 | package org.wordpress.android.fluxc.mocked
import android.os.Bundle
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.junit.Assert
import org.junit.Test
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.TestUtils
import org.wordpress.android.fluxc.generated.EditorThemeActionBuilder
import org.wordpress.android.fluxc.model.EditorTheme
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.module.ResponseMockingInterceptor
import org.wordpress.android.fluxc.module.ResponseMockingInterceptor.InterceptorMode.STICKY
import org.wordpress.android.fluxc.store.EditorThemeStore
import org.wordpress.android.fluxc.store.EditorThemeStore.FetchEditorThemePayload
import org.wordpress.android.fluxc.store.EditorThemeStore.OnEditorThemeChanged
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.inject.Inject
class MockedStack_EditorThemeStoreTest : MockedStack_Base() {
@Inject lateinit var dispatcher: Dispatcher
@Inject lateinit var interceptor: ResponseMockingInterceptor
@Inject lateinit var editorThemeStore: EditorThemeStore
private lateinit var countDownLatch: CountDownLatch
private lateinit var site: SiteModel
private lateinit var payload: FetchEditorThemePayload
private lateinit var payloadWithGSS: FetchEditorThemePayload
private var editorTheme: EditorTheme? = null
override fun setUp() {
super.setUp()
mMockedNetworkAppComponent.inject(this)
dispatcher.register(this)
editorTheme = null
site = SiteModel()
site.setIsWPCom(true)
site.softwareVersion = "5.8"
payload = FetchEditorThemePayload(site)
payloadWithGSS = FetchEditorThemePayload(site, true)
countDownLatch = CountDownLatch(1)
}
@Test
fun testFetchEditorThemeSuccess() {
interceptor.respondWith("editor-theme-custom-elements-success-response.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(payload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// Validate Callback
assertNotEmpty(editorTheme)
// Validate Cache
val cachedTheme = editorThemeStore.getEditorThemeForSite(site)
assertNotEmpty(cachedTheme)
// Validate Bundle
val themeBundle = editorTheme!!.themeSupport.toBundle()
assertNotEmpty(themeBundle)
}
@Test
fun testUnsupportedFetchEditorThemeSuccess() {
interceptor.respondWith("editor-theme-unsupported-response.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(payload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// Validate Callback
assertEmpty(editorTheme)
// Validate Cache
val cachedTheme = editorThemeStore.getEditorThemeForSite(site)
assertEmpty(cachedTheme)
// Validate Bundle
val themeBundle = editorTheme!!.themeSupport.toBundle()
assertEmpty(themeBundle)
}
@Test
fun testFetchEditorThemeInvalidFormat() {
interceptor.respondWith(JsonObject())
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(payload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// Validate Callback
assertEmpty(editorTheme)
// Validate Cache
val cachedTheme = editorThemeStore.getEditorThemeForSite(site)
assertEmpty(cachedTheme)
}
@Test
fun testFetchEditorThemeEmptyResultFormat() {
interceptor.respondWith(JsonArray())
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(payload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// Validate Callback
assertEmpty(editorTheme)
// Validate Cache
val cachedTheme = editorThemeStore.getEditorThemeForSite(site)
assertEmpty(cachedTheme)
}
@Test
fun testInvalidFetchEditorThemeSuccess() {
interceptor.respondWith("editor-theme-invalid-response.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(payload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// Validate Callback
assertEmpty(editorTheme)
// Validate Cache
val cachedTheme = editorThemeStore.getEditorThemeForSite(site)
assertEmpty(cachedTheme)
// Validate Bundle
val themeBundle = editorTheme!!.themeSupport.toBundle()
assertEmpty(themeBundle)
}
@Test
fun testGlobalStylesSettingsOffSuccess() {
interceptor.respondWith("global-styles-off-success.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(payloadWithGSS))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// Validate Callback
assertNotEmpty(editorTheme)
// Validate Cache
val cachedTheme = editorThemeStore.getEditorThemeForSite(site)
assertNotEmpty(cachedTheme)
// Validate Bundle
val themeBundle = editorTheme!!.themeSupport.toBundle()
assertNotEmpty(themeBundle)
}
@Test
fun testGlobalStylesSettingsFullSuccess() {
interceptor.respondWith("global-styles-full-success.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(payloadWithGSS))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// Validate Callback
assertEmpty(editorTheme)
Assert.assertNotNull(editorTheme?.themeSupport?.rawStyles)
// Validate Cache
val cachedTheme = editorThemeStore.getEditorThemeForSite(site)
assertEmpty(cachedTheme)
Assert.assertNotNull(cachedTheme?.themeSupport?.rawStyles)
// Validate Bundle
val themeBundle = editorTheme!!.themeSupport.toBundle()
assertEmpty(themeBundle)
val styles = themeBundle.getString("rawStyles")
val features = themeBundle.getString("rawFeatures")
Assert.assertNotNull(styles)
Assert.assertNotNull(features)
}
@Test
fun testEditorSettingsUrl() {
val wordPressPayload = payloadWithGSS.apply {
site.softwareVersion = "5.8"
site.setIsWPCom(true)
}
interceptor.respondWith("global-styles-full-success.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(wordPressPayload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
val id = payloadWithGSS.site.siteId
val expectedUrl = "https://public-api.wordpress.com/wp-block-editor/v1/sites/$id/settings"
interceptor.assertExpectedUrl(expectedUrl)
}
@Test
fun testEditorSettingsOldUrl() {
val wordPressPayload = payloadWithGSS.apply {
site.softwareVersion = "5.7"
site.setIsWPCom(true)
}
interceptor.respondWith("editor-theme-custom-elements-success-response.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(wordPressPayload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
val id = payloadWithGSS.site.siteId
val expectedUrl = "https://public-api.wordpress.com/wp/v2/sites/$id/themes"
interceptor.assertExpectedUrl(expectedUrl)
}
@Test
fun testEditorSettingsRetryUrl() {
val wordPressPayload = payloadWithGSS.apply {
site.softwareVersion = "5.8"
site.setIsWPCom(true)
}
interceptor.respondWithError(JsonObject(), 404)
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(wordPressPayload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// In case of failure we call the theme endpoint
val id = payloadWithGSS.site.siteId
val expectedUrl = "https://public-api.wordpress.com/wp/v2/sites/$id/themes"
interceptor.assertExpectedUrl(expectedUrl)
}
@Test
fun testEditorSettingsOrgUrl() {
val wordPressPayload = payloadWithGSS.apply {
site.softwareVersion = "5.8"
site.url = "https://test.com"
site.setIsWPCom(false)
}
interceptor.respondWith("global-styles-full-success.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(wordPressPayload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
val expectedUrl = "https://test.com/wp-json/wp-block-editor/v1/settings"
interceptor.assertExpectedUrl(expectedUrl)
}
@Test
fun testEditorSettingsOldOrgUrl() {
val wordPressPayload = payloadWithGSS.apply {
site.softwareVersion = "5.7"
site.url = "https://test.com"
site.setIsWPCom(false)
}
interceptor.respondWith("editor-theme-custom-elements-success-response.json")
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(wordPressPayload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
val expectedUrl = "https://test.com/wp-json/wp/v2/themes"
interceptor.assertExpectedUrl(expectedUrl)
}
@Test
fun testEditorSettingsRetryOrgUrl() {
val wordPressPayload = payloadWithGSS.apply {
site.softwareVersion = "5.8"
site.url = "https://test.com"
site.setIsWPCom(false)
}
interceptor.respondWithError(JsonObject(), 404, STICKY)
dispatcher.dispatch(EditorThemeActionBuilder.newFetchEditorThemeAction(wordPressPayload))
// See onEditorThemeChanged for the latch's countdown to fire.
Assert.assertTrue(countDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), MILLISECONDS))
// In case of failure we call the theme endpoint
val expectedUrl = "https://test.com/wp-json/wp/v2/themes"
interceptor.assertExpectedUrl(expectedUrl)
}
private fun ResponseMockingInterceptor.assertExpectedUrl(expectedUrl: String) =
Assert.assertTrue(lastRequestUrl.startsWith(expectedUrl))
private fun assertNotEmpty(theme: EditorTheme?) {
Assert.assertFalse(theme?.themeSupport?.colors.isNullOrEmpty())
Assert.assertFalse(theme?.themeSupport?.gradients.isNullOrEmpty())
}
private fun assertEmpty(theme: EditorTheme?) {
Assert.assertTrue(theme?.themeSupport?.colors == null)
Assert.assertTrue(theme?.themeSupport?.gradients == null)
}
private fun assertEmpty(theme: Bundle) {
val colors = theme.getSerializable("colors")
val gradients = theme.getSerializable("gradients")
Assert.assertTrue(colors == null)
Assert.assertTrue(gradients == null)
}
private fun assertNotEmpty(theme: Bundle) {
val colors = theme.getSerializable("colors") as ArrayList<*>
val gradients = theme.getSerializable("gradients") as ArrayList<*>
Assert.assertFalse(colors.isNullOrEmpty())
Assert.assertFalse(gradients.isNullOrEmpty())
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
fun onEditorThemeChanged(event: OnEditorThemeChanged) {
if (event.isError) {
countDownLatch.countDown()
}
editorTheme = event.editorTheme
countDownLatch.countDown()
}
}
| gpl-2.0 | 69b09f4955a338cd5d7945e5383b4f06 | 38.183486 | 100 | 0.713572 | 4.7263 | false | true | false | false |
Kotlin/dokka | core/src/main/kotlin/utilities/json.kt | 1 | 1650 | package org.jetbrains.dokka.utilities
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import java.io.File
import com.fasterxml.jackson.core.type.TypeReference as JacksonTypeReference
private val objectMapper = run {
val module = SimpleModule().apply {
addSerializer(FileSerializer)
}
jacksonObjectMapper()
.registerModule(module)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}
@PublishedApi
internal class TypeReference<T> private constructor(
internal val jackson: JacksonTypeReference<T>
) {
companion object {
internal inline operator fun <reified T> invoke(): TypeReference<T> = TypeReference(jacksonTypeRef())
}
}
@PublishedApi
internal fun toJsonString(value: Any): String = objectMapper.writeValueAsString(value)
@PublishedApi
internal inline fun <reified T : Any> parseJson(json: String): T = parseJson(json, TypeReference())
@PublishedApi
internal fun <T : Any> parseJson(json: String, typeReference: TypeReference<T>): T =
objectMapper.readValue(json, typeReference.jackson)
private object FileSerializer : StdScalarSerializer<File>(File::class.java) {
override fun serialize(value: File, g: JsonGenerator, provider: SerializerProvider) {
g.writeString(value.path)
}
}
| apache-2.0 | 94288648732b0cb79283c414f0e6d2ba | 34.869565 | 109 | 0.781818 | 4.483696 | false | false | false | false |
mattak/KotlinMoment | src/test/kotlin/me/mattak/moment/OperatorsTest.kt | 1 | 1988 | package me.mattak.moment
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
/**
* Test for Operators
* Created by mattak on 15/09/27.
*/
public class OperatorsTest {
@Test
fun moment_minus_moment() {
val m1 = Moment()
val m2 = m1.add(Duration(1))
assertEquals(1, (m2 - m1).interval.toInt())
}
@Test
fun moment_plus_duration() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
calendar.set(2015, 0, 1, 0, 0, 0)
val m1 = Moment(calendar.time, calendar.timeZone)
val m2 = m1 + Duration(1000)
assertEquals("2015-01-01 00:00:01", m2.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun moment_minus_duration() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
calendar.set(2015, 0, 1, 0, 0, 1)
val m1 = Moment(calendar.time, calendar.timeZone)
val m2 = m1 - Duration(1000)
assertEquals("2015-01-01 00:00:00", m2.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun duration_plus_moment() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
calendar.set(2015, 0, 1, 0, 0, 0)
val m1 = Moment(calendar.time, calendar.timeZone)
val m2 = Duration(1000) + m1
assertEquals("2015-01-01 00:00:01", m2.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun duration_minus_moment() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
calendar.set(2015, 0, 1, 0, 0, 1)
val m1 = Moment(calendar.time, calendar.timeZone)
val m2 = Duration(1000) - m1
assertEquals("2015-01-01 00:00:00", m2.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun duration_plus_duration() {
val d = Duration(1) + Duration(2)
assertEquals(3, d.interval.toInt())
}
@Test
fun duration_minus_duration() {
val d = Duration(2) - Duration(1)
assertEquals(1, d.interval.toInt())
}
} | apache-2.0 | bc9c7017f0985d81e34266d516e7463d | 29.136364 | 77 | 0.601107 | 3.346801 | false | true | false | false |
mattak/KotlinMoment | src/test/kotlin/me/mattak/moment/MomentTest.kt | 1 | 11125 | package me.mattak.moment
import org.junit.Test
import org.junit.Assert.*
import java.util.*
/**
* MomentTest.kt
* Created by mattak on 15/09/22.
*/
public class MomentTest {
@Test
fun init() {
val defaultDate = Date()
val defaultTimeZone = TimeZone.getDefault()
val defaultLocale = Locale.getDefault()
val m1 = Moment()
assertTrue(m1.date.after(defaultDate) || m1.date.equals(defaultDate))
assertTrue(m1.timeZone.equals(defaultTimeZone))
assertTrue(m1.locale.equals(defaultLocale))
val m2 = Moment(defaultDate, defaultTimeZone, defaultLocale)
assertTrue(m2.date.after(defaultDate) || m2.date.equals(defaultDate))
assertTrue(m2.timeZone.equals(defaultTimeZone))
assertTrue(m2.locale.equals(defaultLocale))
}
@Test
fun year() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.year, calendar.get(Calendar.YEAR))
}
@Test
fun month() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.month, calendar.get(Calendar.MONTH) + 1)
}
@Test
fun day() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.day, calendar.get(Calendar.DAY_OF_MONTH))
}
@Test
fun hour() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 23, 59, 59)
val date = calendar.time
val m = Moment(date)
assertEquals(m.hour, calendar.get(Calendar.HOUR_OF_DAY))
}
@Test
fun minute() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.minute, calendar.get(Calendar.MINUTE))
}
@Test
fun second() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.second, calendar.get(Calendar.SECOND))
}
@Test
fun millisecond() {
val calendar = Calendar.getInstance()
calendar.timeInMillis = 1442922588569
val date = calendar.time
val m = Moment(date)
assertEquals(m.millisecond, calendar.get(Calendar.MILLISECOND))
}
@Test
fun weekday() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.weekday, calendar.get(Calendar.DAY_OF_WEEK))
}
@Test
fun weekdayName() {
val calendar = Calendar.getInstance(Locale.ENGLISH)
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date, locale = Locale.ENGLISH)
assertEquals(m.weekdayName, "Sunday")
}
@Test
fun weekdayOrdinal() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.weekdayOrdinal, calendar.get(Calendar.WEEK_OF_MONTH))
}
@Test
fun weekdayOfYear() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.weekOfYear, calendar.get(Calendar.WEEK_OF_YEAR))
}
@Test
fun quarter() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date = calendar.time
val m = Moment(date)
assertEquals(m.quarter, 1)
}
@Test
fun epoch() {
val calendar = Calendar.getInstance()
calendar.timeInMillis = 123456789
val date = calendar.time
val m = Moment(date)
assertEquals(m.epoch, 123456)
}
@Test
fun get() {
val calendar = Calendar.getInstance()
calendar.timeInMillis = 123456789
val m1 = Moment(calendar.time)
assertEquals(m1.get(TimeUnit.MILLISECONDS), 789)
calendar.set(2015, 0, 1, 0, 0, 0)
val m2 = Moment(calendar.time)
assertEquals(0, m2.get(TimeUnit.SECONDS))
assertEquals(0, m2.get(TimeUnit.MINUTES))
assertEquals(0, m2.get(TimeUnit.HOURS))
assertEquals(1, m2.get(TimeUnit.DAYS))
assertEquals(1, m2.get(TimeUnit.MONTHS))
assertEquals(1, m2.get(TimeUnit.QUARTERS))
assertEquals(2015, m2.get(TimeUnit.YEARS))
}
@Test
fun format() {
val calendar = Calendar.getInstance()
calendar.set(2015, 0, 1, 0, 0, 0)
val m = Moment(calendar.time)
assertEquals("2015-01-01 00:00:00", m.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun add() {
val calendar = Calendar.getInstance()
calendar.set(2015, 0, 1, 0, 0, 0)
var m = Moment(calendar.time)
assertEquals("2015-01-01 00:00:00", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(1, TimeUnit.SECONDS)
assertEquals("2015-01-01 00:00:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(1, TimeUnit.MINUTES)
assertEquals("2015-01-01 00:01:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(1, TimeUnit.HOURS)
assertEquals("2015-01-01 01:01:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(1, TimeUnit.DAYS)
assertEquals("2015-01-02 01:01:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(1, TimeUnit.MONTHS)
assertEquals("2015-02-02 01:01:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(1, TimeUnit.QUARTERS)
assertEquals("2015-05-02 01:01:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(1, TimeUnit.YEARS)
assertEquals("2016-05-02 01:01:01", m.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun add_duration() {
val calendar = Calendar.getInstance()
calendar.set(2015, 0, 1, 0, 0, 0)
var m = Moment(calendar.time)
assertEquals("2015-01-01 00:00:00", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.add(Duration(1000))
assertEquals("2015-01-01 00:00:01", m.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun subtract() {
val calendar = Calendar.getInstance()
calendar.set(2015, 0, 1, 0, 0, 1)
var m = Moment(calendar.time)
assertEquals("2015-01-01 00:00:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.subtract(1, TimeUnit.SECONDS)
assertEquals("2015-01-01 00:00:00", m.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun subtract_duration() {
val calendar = Calendar.getInstance()
calendar.set(2015, 0, 1, 0, 0, 1)
var m = Moment(calendar.time)
assertEquals("2015-01-01 00:00:01", m.format("yyyy-MM-dd HH:mm:ss"))
m = m.subtract(Duration(1000))
assertEquals("2015-01-01 00:00:00", m.format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun isCloseTo() {
val calendar = Calendar.getInstance()
calendar.set(2015, 0, 1, 0, 0, 1)
var m0 = Moment(calendar.time)
calendar.set(2015, 0, 1, 0, 1, 0)
var m1 = Moment(calendar.time)
assertTrue(m0.isCloseTo(m1, 60000))
assertTrue(m0.isCloseTo(m1, 59999))
}
@Test
fun startOf() {
val calendar = Calendar.getInstance()
calendar.set(2015, 11, 31, 23, 59, 59)
var m = Moment(calendar.time)
assertEquals("2015-12-31 23:59:59", m.format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-12-31 23:59:59", m.startOf(TimeUnit.MILLISECONDS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-12-31 23:59:59", m.startOf(TimeUnit.SECONDS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-12-31 23:59:00", m.startOf(TimeUnit.MINUTES).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-12-31 23:00:00", m.startOf(TimeUnit.HOURS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-12-31 00:00:00", m.startOf(TimeUnit.DAYS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-12-01 00:00:00", m.startOf(TimeUnit.MONTHS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-10-01 00:00:00", m.startOf(TimeUnit.QUARTERS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-01-01 00:00:00", m.startOf(TimeUnit.YEARS).format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun endOf() {
val calendar = Calendar.getInstance()
calendar.set(2015, 0, 1, 0, 0, 0)
var m = Moment(calendar.time)
assertEquals("2015-01-01 00:00:00", m.format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-01-01 00:00:00", m.endOf(TimeUnit.MILLISECONDS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-01-01 00:00:00", m.endOf(TimeUnit.SECONDS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-01-01 00:00:59", m.endOf(TimeUnit.MINUTES).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-01-01 00:59:59", m.endOf(TimeUnit.HOURS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-01-01 23:59:59", m.endOf(TimeUnit.DAYS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-01-31 23:59:59", m.endOf(TimeUnit.MONTHS).format("yyyy-MM-dd HH:mm:ss"))
assertEquals("2015-12-31 23:59:59", m.endOf(TimeUnit.YEARS).format("yyyy-MM-dd HH:mm:ss"))
}
@Test
fun intervalSince() {
val calendar = Calendar.getInstance()
calendar.timeInMillis = 1442922588000
val date1 = calendar.time
calendar.timeInMillis = 1442922588001
val date2 = calendar.time
val m1 = Moment(date1)
val m2 = Moment(date2)
assertEquals(0, m1.intervalSince(m1).interval)
assertEquals(1, m2.intervalSince(m1).interval)
assertEquals(-1, m1.intervalSince(m2).interval)
}
@Test
fun equals() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date1 = calendar.time
val date2 = calendar.time
calendar.set(2015, 1, 2, 0, 0, 0)
val date3 = calendar.time
val m1 = Moment(date1)
val m2 = Moment(date2)
val m3 = Moment(date3)
assertTrue(m1.equals(m1))
assertTrue(m1.equals(m2))
assertFalse(m1.equals(m3))
assertFalse(m1.equals("hoge"))
}
@Test
fun compareTo() {
val calendar = Calendar.getInstance()
calendar.set(2015, 1, 1, 0, 0, 0)
val date1 = calendar.time
calendar.set(2015, 1, 2, 0, 0, 0)
val date2 = calendar.time
val m1 = Moment(date1)
val m2 = Moment(date2)
assertTrue(m2.compareTo(m2) == 0)
assertTrue(m2.compareTo(m1) > 0)
assertTrue(m1.compareTo(m2) < 0)
}
@Test
fun _toString() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
calendar.set(2015, 0, 1, 0, 0, 0)
assertEquals("2015-01-01 00:00:00 +0000", Moment(calendar.time, TimeZone.getTimeZone("UTC")).toString())
}
} | apache-2.0 | f9b8c72d3b3164912f1553ac1b6568b7 | 31.91716 | 112 | 0.594966 | 3.371212 | false | true | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/web/FrostWebViewClients.kt | 1 | 10826 | /*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.web
import android.graphics.Bitmap
import android.graphics.Color
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import ca.allanwang.kau.utils.ctxCoroutine
import ca.allanwang.kau.utils.withAlpha
import com.pitchedapps.frost.db.CookieDao
import com.pitchedapps.frost.db.currentCookie
import com.pitchedapps.frost.db.updateMessengerCookie
import com.pitchedapps.frost.enums.ThemeCategory
import com.pitchedapps.frost.facebook.FACEBOOK_BASE_COM
import com.pitchedapps.frost.facebook.FbCookie
import com.pitchedapps.frost.facebook.FbItem
import com.pitchedapps.frost.facebook.HTTPS_MESSENGER_COM
import com.pitchedapps.frost.facebook.MESSENGER_THREAD_PREFIX
import com.pitchedapps.frost.facebook.WWW_FACEBOOK_COM
import com.pitchedapps.frost.facebook.formattedFbUrl
import com.pitchedapps.frost.injectors.CssAsset
import com.pitchedapps.frost.injectors.CssHider
import com.pitchedapps.frost.injectors.InjectorContract
import com.pitchedapps.frost.injectors.JsActions
import com.pitchedapps.frost.injectors.JsAssets
import com.pitchedapps.frost.injectors.ThemeProvider
import com.pitchedapps.frost.injectors.jsInject
import com.pitchedapps.frost.prefs.Prefs
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.isExplicitIntent
import com.pitchedapps.frost.utils.isFacebookUrl
import com.pitchedapps.frost.utils.isFbCookie
import com.pitchedapps.frost.utils.isImageUrl
import com.pitchedapps.frost.utils.isIndirectImageUrl
import com.pitchedapps.frost.utils.isMessengerUrl
import com.pitchedapps.frost.utils.launchImageActivity
import com.pitchedapps.frost.utils.startActivityForUri
import com.pitchedapps.frost.views.FrostWebView
import kotlinx.coroutines.launch
/**
* Created by Allan Wang on 2017-05-31.
*
* Collection of webview clients
*/
/** The base of all webview clients Used to ensure that resources are properly intercepted */
open class BaseWebViewClient : WebViewClient() {
override fun shouldInterceptRequest(
view: WebView,
request: WebResourceRequest
): WebResourceResponse? = view.shouldFrostInterceptRequest(request)
}
/** The default webview client */
open class FrostWebViewClient(val web: FrostWebView) : BaseWebViewClient() {
protected val fbCookie: FbCookie
get() = web.fbCookie
protected val prefs: Prefs
get() = web.prefs
protected val themeProvider: ThemeProvider
get() = web.themeProvider
// protected val refresh: SendChannel<Boolean> = web.parent.refreshChannel
protected val isMain = web.parent.baseEnum != null
/** True if current url supports refresh. See [doUpdateVisitedHistory] for updates */
internal var urlSupportsRefresh: Boolean = true
override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
super.doUpdateVisitedHistory(view, url, isReload)
urlSupportsRefresh = urlSupportsRefresh(url)
web.parent.swipeAllowedByPage = urlSupportsRefresh
view.jsInject(JsAssets.AUTO_RESIZE_TEXTAREA.maybe(prefs.autoExpandTextBox), prefs = prefs)
v { "History $url; refresh $urlSupportsRefresh" }
}
private fun urlSupportsRefresh(url: String?): Boolean {
if (url == null) return false
if (url.isMessengerUrl) return false
if (!url.isFacebookUrl) return true
if (url.contains("soft=composer")) return false
if (url.contains("sharer.php") || url.contains("sharer-dialog.php")) return false
return true
}
protected inline fun v(crossinline message: () -> Any?) = L.v { "web client: ${message()}" }
/** Main injections for facebook content */
protected open val facebookJsInjectors: List<InjectorContract> =
listOf(
// CssHider.CORE,
CssHider.HEADER,
CssHider.COMPOSER.maybe(!prefs.showComposer),
CssHider.STORIES.maybe(!prefs.showStories),
CssHider.PEOPLE_YOU_MAY_KNOW.maybe(!prefs.showSuggestedFriends),
CssHider.SUGGESTED_GROUPS.maybe(!prefs.showSuggestedGroups),
CssHider.SUGGESTED_POSTS.maybe(!prefs.showSuggestedPosts),
themeProvider.injector(ThemeCategory.FACEBOOK),
CssHider.NON_RECENT.maybe(
(web.url?.contains("?sk=h_chr") ?: false) && prefs.aggressiveRecents
),
CssHider.ADS,
CssHider.POST_ACTIONS.maybe(!prefs.showPostActions),
CssHider.POST_REACTIONS.maybe(!prefs.showPostReactions),
CssAsset.FullSizeImage.maybe(prefs.fullSizeImage),
JsAssets.DOCUMENT_WATCHER,
JsAssets.HORIZONTAL_SCROLLING,
JsAssets.AUTO_RESIZE_TEXTAREA.maybe(prefs.autoExpandTextBox),
JsAssets.CLICK_A,
JsAssets.CONTEXT_A,
JsAssets.MEDIA,
JsAssets.SCROLL_STOP,
)
private fun WebView.facebookJsInject() {
jsInject(*facebookJsInjectors.toTypedArray(), prefs = prefs)
}
private fun WebView.messengerJsInject() {
jsInject(themeProvider.injector(ThemeCategory.MESSENGER), prefs = prefs)
}
override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
if (url == null) return
v { "loading $url ${web.settings.userAgentString}" }
// refresh.offer(true)
}
private fun injectBackgroundColor() {
web.setBackgroundColor(
when {
isMain -> Color.TRANSPARENT
web.url.isFacebookUrl -> themeProvider.bgColor.withAlpha(255)
else -> Color.WHITE
}
)
}
override fun onPageCommitVisible(view: WebView, url: String?) {
super.onPageCommitVisible(view, url)
injectBackgroundColor()
when {
url.isFacebookUrl -> {
v { "FB Page commit visible" }
view.facebookJsInject()
}
url.isMessengerUrl -> {
v { "Messenger Page commit visible" }
view.messengerJsInject()
}
else -> {
// refresh.offer(false)
}
}
}
override fun onPageFinished(view: WebView, url: String?) {
url ?: return
v { "finished $url" }
if (!url.isFacebookUrl && !url.isMessengerUrl) {
// refresh.offer(false)
return
}
onPageFinishedActions(url)
}
internal open fun onPageFinishedActions(url: String) {
if (url.startsWith("${FbItem.MESSAGES.url}/read/") && prefs.messageScrollToBottom) {
web.pageDown(true)
}
injectAndFinish()
}
// Temp open
internal open fun injectAndFinish() {
v { "page finished reveal" }
// refresh.offer(false)
injectBackgroundColor()
when {
web.url.isFacebookUrl -> {
web.jsInject(
JsActions.LOGIN_CHECK,
JsAssets.TEXTAREA_LISTENER,
JsAssets.HEADER_BADGES.maybe(isMain),
prefs = prefs
)
web.facebookJsInject()
}
web.url.isMessengerUrl -> {
web.messengerJsInject()
}
}
}
open fun handleHtml(html: String?) {
L.d { "Handle Html" }
}
open fun emit(flag: Int) {
L.d { "Emit $flag" }
}
/**
* Helper to format the request and launch it returns true to override the url returns false if we
* are already in an overlaying activity
*/
private fun launchRequest(request: WebResourceRequest): Boolean {
v { "Launching url: ${request.url}" }
return web.requestWebOverlay(request.url.toString())
}
private fun launchImage(url: String, text: String? = null, cookie: String? = null): Boolean {
v { "Launching image: $url" }
web.context.launchImageActivity(url, text, cookie)
if (web.canGoBack()) web.goBack()
return true
}
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
v { "Url loading: ${request.url}" }
val path = request.url?.path ?: return super.shouldOverrideUrlLoading(view, request)
v { "Url path $path" }
val url = request.url.toString()
if (url.isExplicitIntent) {
view.context.startActivityForUri(request.url)
return true
}
if (path.startsWith("/composer/")) {
return launchRequest(request)
}
if (url.isIndirectImageUrl) {
return launchImage(url.formattedFbUrl, cookie = fbCookie.webCookie)
}
if (url.isImageUrl) {
return launchImage(url.formattedFbUrl)
}
if (prefs.linksInDefaultApp && view.context.startActivityForUri(request.url)) {
return true
}
// Convert desktop urls to mobile ones
if (url.contains("https://www.facebook.com") && urlSupportsRefresh(url)) {
view.loadUrl(url.replace(WWW_FACEBOOK_COM, FACEBOOK_BASE_COM))
return true
}
return super.shouldOverrideUrlLoading(view, request)
}
}
private const val EMIT_THEME = 0b1
private const val EMIT_ID = 0b10
private const val EMIT_COMPLETE = EMIT_THEME or EMIT_ID
private const val EMIT_FINISH = 0
class FrostWebViewClientMessenger(web: FrostWebView) : FrostWebViewClient(web) {
override fun onPageFinished(view: WebView, url: String?) {
super.onPageFinished(view, url)
messengerCookieCheck(url!!)
}
private val cookieDao: CookieDao
get() = web.cookieDao
private var hasCookie = fbCookie.messengerCookie.isFbCookie
/**
* Check cookie changes. Unlike fb checks, we will continuously poll for cookie changes during
* loading. There is no lifecycle association between messenger login and facebook login, so we'll
* try to be smart about when to check for state changes.
*
* From testing, it looks like this is called after redirects. We can therefore classify no login
* as pointing to messenger.com, and login as pointing to messenger.com/t/[thread id]
*/
private fun messengerCookieCheck(url: String?) {
if (url?.startsWith(HTTPS_MESSENGER_COM) != true) return
val shouldHaveCookie = url.startsWith(MESSENGER_THREAD_PREFIX)
L._d { "Messenger client: $url $shouldHaveCookie" }
if (shouldHaveCookie == hasCookie) return
hasCookie = shouldHaveCookie
web.context.ctxCoroutine.launch {
cookieDao.updateMessengerCookie(
prefs.userId,
if (shouldHaveCookie) fbCookie.messengerCookie else null
)
L._d { "New cookie ${cookieDao.currentCookie(prefs)?.toSensitiveString()}" }
}
}
}
| gpl-3.0 | a6003aad38df2a1229caa348b33117dd | 34.263844 | 100 | 0.71513 | 4.01409 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/ui/files/FilesUploadDialogFragment.kt | 1 | 2403 | package com.etesync.syncadapter.ui.files
import android.app.Dialog
import android.app.ProgressDialog
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.support.v4.app.DialogFragment
import com.etesync.syncadapter.R
class FilesUploadDialogFragment : DialogFragment() {
private lateinit var fileUri: Uri
private var timeLimit: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fileUri = arguments!!.getParcelable(KEY_FILE_URI)!!
timeLimit = arguments!!.getInt(KEY_TIME_LIMIT)
UploadFile().execute()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val progress = ProgressDialog(context)
progress.setTitle(getString(R.string.uploading_files))
progress.setMessage(getString(R.string.please_wait))
progress.isIndeterminate = true
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
progress.setCanceledOnTouchOutside(false)
isCancelable = false
return progress
}
private inner class UploadFile : AsyncTask<Void, Int, Void>() {
override fun doInBackground(vararg voids: Void): Void? {
// TODO(talh): need to call UploadFile only after the dialog is created
Thread.sleep(1000)
publishProgress(10)
Thread.sleep(1000)
publishProgress(90)
Thread.sleep(2000)
return null
}
override fun onPostExecute(result: Void) {
dismiss()
if (activity is UploadFileCallbacks) {
(activity as UploadFileCallbacks).onUpload("FILE_URL")
}
}
override fun onProgressUpdate(vararg values: Int?) {
(dialog as ProgressDialog).progress = values[0]!!
}
}
interface UploadFileCallbacks {
fun onUpload(url: String)
}
companion object {
private val KEY_FILE_URI = "fileUri"
private val KEY_TIME_LIMIT = "timeLimit"
fun newInstance(uri: Uri, timeLimit: Int): FilesUploadDialogFragment {
val frag = FilesUploadDialogFragment()
val args = Bundle(2)
args.putParcelable(KEY_FILE_URI, uri)
args.putInt(KEY_TIME_LIMIT, timeLimit)
frag.arguments = args
return frag
}
}
}
| gpl-3.0 | a6d3e962c46da1299aa70119c2133542 | 30.618421 | 83 | 0.643779 | 4.825301 | false | false | false | false |
yyued/CodeX-UIKit-Android | library/src/main/java/com/yy/codex/uikit/UIConstraint.kt | 1 | 13268 | package com.yy.codex.uikit
import android.content.res.TypedArray
import net.objecthunter.exp4j.ExpressionBuilder
/**
* Created by cuiminghui on 2017/1/4.
*/
class UIConstraint {
enum class LayoutRelate {
RelateToGroup,
RelateToPrevious
}
var disabled = false
var alignmentRelate = LayoutRelate.RelateToGroup
var centerHorizontally = false
var centerVertically = false
var sizeRelate = LayoutRelate.RelateToGroup
var width: String? = null
var height: String? = null
var pinRelate = LayoutRelate.RelateToGroup
var top: String? = null
var left: String? = null
var right: String? = null
var bottom: String? = null
private var needsLayout = true
private var lastSuperviewFrame = CGRect(0.0, 0.0, 0.0, 0.0)
private var lastPreviousViewFrame = CGRect(0.0, 0.0, 0.0, 0.0)
fun setNeedsLayout() {
needsLayout = true
}
fun requestFrame(myView: UIView, superView: UIView?, previousView: UIView?): CGRect {
if (disabled) {
return myView.frame
}
if (superView != null && lastSuperviewFrame == superView.frame &&
previousView != null && lastPreviousViewFrame == previousView.frame &&
!needsLayout) {
return myView.frame
}
needsLayout = false
lastSuperviewFrame = superView?.frame ?: CGRect(0.0, 0.0, 0.0, 0.0)
lastPreviousViewFrame = previousView?.frame ?: CGRect(0.0, 0.0, 0.0, 0.0)
var x = java.lang.Double.NaN
var y = java.lang.Double.NaN
var mx = java.lang.Double.NaN
var my = java.lang.Double.NaN
var cx = java.lang.Double.NaN
var cy = java.lang.Double.NaN
var w = java.lang.Double.NaN
var h = java.lang.Double.NaN
var xorw = false
var yorh = false
if (width is String) {
val formula = width as String
if (sizeRelate == LayoutRelate.RelateToPrevious) {
w = requestValue(0.0, previousView?.frame?.size?.width ?: 0.0, formula)
} else {
w = requestValue(0.0, superView?.frame?.size?.width ?: 0.0, formula)
}
} else {
val iSize = myView.intrinsicContentSize()
if (iSize.width > 0.0) {
w = Math.ceil(iSize.width)
}
}
if (height is String) {
val formula = height as String
if (sizeRelate == LayoutRelate.RelateToPrevious) {
h = requestValue(0.0, previousView?.frame?.size?.height ?: 0.0, formula)
} else {
h = requestValue(0.0, superView?.frame?.size?.height ?: 0.0, formula)
}
} else {
if (width != null && !java.lang.Double.isNaN(w)) {
myView.maxWidth = w
}
val iSize = myView.intrinsicContentSize()
if (iSize.height > 0.0) {
h = Math.ceil(iSize.height)
}
}
if (centerHorizontally && alignmentRelate == LayoutRelate.RelateToGroup) {
cx = if (superView != null) superView.frame.size.width / 2.0 else 0.0
} else if (centerHorizontally && alignmentRelate == LayoutRelate.RelateToPrevious) {
cx = previousView?.center?.x ?: 0.0
}
if (centerVertically && alignmentRelate == LayoutRelate.RelateToGroup) {
cy = if (superView != null) superView.frame.size.height / 2.0 else 0.0
} else if (centerVertically && alignmentRelate == LayoutRelate.RelateToPrevious) {
cy = previousView?.center?.y ?: 0.0
}
if (top is String) {
val formula = top as String
var t = 0.0
if (pinRelate == LayoutRelate.RelateToGroup) {
t = requestValue(0.0, superView?.frame?.size?.height ?: 0.0, formula)
} else if (pinRelate == LayoutRelate.RelateToPrevious) {
t = requestValue(0.0, previousView?.frame?.size?.height ?: 0.0, formula)
if (previousView != null) {
t = previousView.frame.origin.y + t
}
}
if (centerVertically) {
cy += t
} else {
y = t
}
}
if (bottom is String) {
val formula = bottom as String
var t = 0.0
if (pinRelate == LayoutRelate.RelateToGroup) {
t = requestValue(0.0, superView?.frame?.size?.height ?: 0.0, formula)
} else if (pinRelate == LayoutRelate.RelateToPrevious) {
t = requestValue(0.0, previousView?.frame?.size?.height ?: 0.0, formula)
if (previousView != null) {
t = previousView.frame.origin.y + previousView.frame.size.height - t
}
}
if (centerVertically) {
cy -= t
} else if (pinRelate == LayoutRelate.RelateToPrevious) {
y = t
yorh = true
} else {
my = t
}
}
if (left is String) {
val formula = left as String
var t = 0.0
if (pinRelate == LayoutRelate.RelateToGroup) {
t = requestValue(0.0, superView?.frame?.size?.width ?: 0.0, formula)
} else if (pinRelate == LayoutRelate.RelateToPrevious) {
t = requestValue(0.0, previousView?.frame?.size?.width ?: 0.0, formula)
if (previousView != null) {
t = previousView.frame.origin.x + t
}
}
if (centerHorizontally) {
cx += t
} else {
x = t
}
}
if (right is String) {
val formula = right as String
var t = 0.0
if (pinRelate == LayoutRelate.RelateToGroup) {
t = requestValue(0.0, superView?.frame?.size?.width ?: 0.0, formula)
} else if (pinRelate == LayoutRelate.RelateToPrevious) {
t = requestValue(0.0, previousView?.frame?.size?.width ?: 0.0, formula)
if (previousView != null) {
t = previousView.frame.origin.x + previousView.frame.size.width - t
}
}
if (centerHorizontally) {
cx -= t
} else if (pinRelate == LayoutRelate.RelateToPrevious) {
x = t
xorw = true
} else {
mx = t
}
}
var newFrame = CGRect(
if (!java.lang.Double.isNaN(cx)) cx else if (!java.lang.Double.isNaN(x)) x else 0.0,
if (!java.lang.Double.isNaN(cy)) cy else if (!java.lang.Double.isNaN(y)) y else 0.0,
if (!java.lang.Double.isNaN(w)) w else 0.0,
if (!java.lang.Double.isNaN(h)) h else 0.0
)
if (!java.lang.Double.isNaN(cx)) {
newFrame = newFrame.setX(newFrame.origin.x - newFrame.size.width / 2.0)
}
if (!java.lang.Double.isNaN(cy)) {
newFrame = newFrame.setY(newFrame.origin.y - newFrame.size.height / 2.0)
}
if (!java.lang.Double.isNaN(mx) && java.lang.Double.isNaN(x)) {
if (pinRelate == LayoutRelate.RelateToGroup) {
newFrame = newFrame.setX((superView?.frame?.size?.width ?: 0.0) - mx - newFrame.size.width)
} else {
newFrame = newFrame.setX((previousView?.frame?.size?.width ?: 0.0) - mx - newFrame.size.width)
}
}
if (!java.lang.Double.isNaN(my) && java.lang.Double.isNaN(y)) {
if (pinRelate == LayoutRelate.RelateToGroup) {
newFrame = newFrame.setY((superView?.frame?.size?.height ?: 0.0) - my - newFrame.size.height)
} else {
newFrame = newFrame.setY((previousView?.frame?.size?.height ?: 0.0) - my - newFrame.size.height)
}
}
if (!java.lang.Double.isNaN(mx) && !java.lang.Double.isNaN(x)) {
if (pinRelate == LayoutRelate.RelateToGroup) {
newFrame = newFrame.setWidth((superView?.frame?.size?.width ?: 0.0) - mx - x)
} else {
newFrame = newFrame.setWidth((previousView?.frame?.size?.width ?: 0.0) - mx - (x - (previousView?.frame?.origin?.x ?: 0.0)))
}
}
if (!java.lang.Double.isNaN(my) && !java.lang.Double.isNaN(y)) {
if (pinRelate == LayoutRelate.RelateToGroup) {
newFrame = newFrame.setHeight((superView?.frame?.size?.height ?: 0.0) - my - y)
} else {
newFrame = newFrame.setHeight((previousView?.frame?.size?.height ?: 0.0) - my - (y - (previousView?.frame?.origin?.y ?: 0.0)))
}
}
if (xorw) {
newFrame = newFrame.setX(newFrame.origin.x - newFrame.size.width)
}
if (yorh) {
newFrame = newFrame.setY(newFrame.origin.y - newFrame.size.height)
}
if (java.lang.Double.isNaN(newFrame.origin.x)) {
newFrame = newFrame.setX(0.0)
}
if (java.lang.Double.isNaN(newFrame.origin.y)) {
newFrame = newFrame.setY(0.0)
}
if (java.lang.Double.isNaN(newFrame.size.width)) {
newFrame = newFrame.setWidth(0.0)
}
if (java.lang.Double.isNaN(newFrame.size.height)) {
newFrame = newFrame.setHeight(0.0)
}
return newFrame
}
fun requestValue(origin: Double, length: Double, formula: String): Double {
var formula = formula
formula = formula.replace("%", "/100.0*" + length)
try {
val e = ExpressionBuilder(formula).build()
return e.evaluate() + origin
} catch (e: Exception) {
return 0.0
}
}
fun sizeCanFit(): Boolean {
return !centerHorizontally && !centerHorizontally && width == null && height == null &&
top != null && left != null && bottom != null && right != null
}
companion object {
fun create(attributes: TypedArray): UIConstraint? {
if (attributes.getBoolean(R.styleable.UIView_constraint_enabled, false)) {
val constraint = UIConstraint()
when (attributes.getInt(R.styleable.UIView_constraint_alignmentRelate, 0)) {
0 -> constraint.alignmentRelate = LayoutRelate.RelateToGroup
1 -> constraint.alignmentRelate = LayoutRelate.RelateToPrevious
}
constraint.centerHorizontally = attributes.getBoolean(R.styleable.UIView_constraint_centerHorizontally, false)
constraint.centerVertically = attributes.getBoolean(R.styleable.UIView_constraint_centerVertically, false)
when (attributes.getInt(R.styleable.UIView_constraint_sizeRelate, 0)) {
0 -> constraint.sizeRelate = LayoutRelate.RelateToGroup
1 -> constraint.sizeRelate = LayoutRelate.RelateToPrevious
}
constraint.width = attributes.getString(R.styleable.UIView_constraint_width)
constraint.height = attributes.getString(R.styleable.UIView_constraint_height)
when (attributes.getInt(R.styleable.UIView_constraint_pinRelate, 0)) {
0 -> constraint.pinRelate = LayoutRelate.RelateToGroup
1 -> constraint.pinRelate = LayoutRelate.RelateToPrevious
}
constraint.top = attributes.getString(R.styleable.UIView_constraint_top)
constraint.left = attributes.getString(R.styleable.UIView_constraint_left)
constraint.bottom = attributes.getString(R.styleable.UIView_constraint_bottom)
constraint.right = attributes.getString(R.styleable.UIView_constraint_right)
return constraint
}
return null
}
fun center(): UIConstraint {
val constraint = UIConstraint()
constraint.centerHorizontally = true
constraint.centerVertically = true
return constraint
}
fun full(): UIConstraint {
val constraint = UIConstraint()
constraint.centerHorizontally = true
constraint.centerVertically = true
constraint.width = "100%"
constraint.height = "100%"
return constraint
}
fun horizonStack(idx: Int, total: Int): UIConstraint {
val step = (100 / total)
val current = step * idx
val constraint = UIConstraint()
constraint.left = "$current%"
constraint.width = "$step%"
constraint.top = "0"
constraint.height = "100%"
return constraint
}
fun verticalStack(idx: Int, total: Int): UIConstraint {
val step = (100 / total)
val current = step * idx
val constraint = UIConstraint()
constraint.top = "$current%"
constraint.height = "$step%"
constraint.left = "0"
constraint.width = "100%"
return constraint
}
}
}
| gpl-3.0 | e98002dbf927b46a8add552179114b6b | 40.333333 | 142 | 0.542358 | 4.142367 | false | false | false | false |
TimePath/java-xplaf | src/main/kotlin/com/timepath/plaf/x/filechooser/AWTFileChooser.kt | 1 | 1929 | package com.timepath.plaf.x.filechooser
import com.timepath.plaf.OS
import com.timepath.plaf.mac.OSXProps
import java.awt.FileDialog
import java.io.File
import java.io.FilenameFilter
import java.util.logging.Logger
/**
* @author TimePath
*/
public class AWTFileChooser : BaseFileChooser() {
override fun choose(): Array<File>? {
if (OS.isMac()) {
OSXProps.setFileDialogDirectoryMode(isDirectoryMode())
}
val fd = FileDialog(parent, dialogTitle)
fd.setFilenameFilter(object : FilenameFilter {
override fun accept(dir: File, name: String): Boolean {
for (ef in filters) {
for (e in ef.getExtensions()) {
if (dir.getName().endsWith(e)) {
return true
}
}
}
return false
}
})
if (directory != null) {
fd.setDirectory(directory!!.getPath())
}
if (fileName != null) {
fd.setFile(fileName)
}
if (isDirectoryMode()) {
if (!OS.isMac()) {
LOG.warning("Using AWT for directory selection on non mac system - not ideal")
}
fd.setFilenameFilter(object : FilenameFilter {
override fun accept(dir: File, name: String): Boolean {
return File(dir, name).isDirectory()
}
})
}
fd.setMode(if (isSaveDialog()) FileDialog.SAVE else FileDialog.LOAD)
fd.setVisible(true)
if ((fd.getDirectory() == null) || (fd.getFile() == null)) {
// cancelled
return null
}
return array(File(fd.getDirectory() + File.pathSeparator + fd.getFile()))
}
companion object {
private val LOG = Logger.getLogger(javaClass<AWTFileChooser>().getName())
}
}
| artistic-2.0 | 0f0d8831bd271984f0667bd7590ecb61 | 30.622951 | 94 | 0.533955 | 4.637019 | false | false | false | false |
pacien/tincapp | app/src/main/java/org/pacien/tincapp/context/AppPaths.kt | 1 | 3290 | /*
* Tinc App, an Android binding and user interface for the tinc mesh VPN daemon
* Copyright (C) 2017-2020 Pacien TRAN-GIRARD
*
* 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 <https://www.gnu.org/licenses/>.
*/
package org.pacien.tincapp.context
import java.io.File
import java.io.FileNotFoundException
/**
* @author pacien
*
* @implNote Logs and PID files are stored in the cache directory for automatic collection.
*/
object AppPaths {
private const val APP_LOG_DIR = "log"
private const val APP_TINC_RUNTIME_DIR = "run"
private const val APP_TINC_NETWORKS_DIR = "networks"
private const val TINCD_BIN = "libtincd.so"
private const val TINC_BIN = "libtinc.so"
private const val APPLOG_FILE = "tincapp.log"
private const val CRASHFLAG_FILE = "crash.flag"
private const val LOGFILE_FORMAT = "tinc.%s.log"
private const val PIDFILE_FORMAT = "tinc.%s.pid"
private const val NET_CONF_FILE = "network.conf"
private const val NET_TINC_CONF_FILE = "tinc.conf"
private const val NET_HOSTS_DIR = "hosts"
private const val NET_INVITATION_FILE = "invitation-data"
const val NET_DEFAULT_ED25519_PRIVATE_KEY_FILE = "ed25519_key.priv"
const val NET_DEFAULT_RSA_PRIVATE_KEY_FILE = "rsa_key.priv"
private val context by lazy { App.getContext() }
private fun cacheDir() = context.cacheDir!!
private fun binDir() = File(context.applicationInfo.nativeLibraryDir)
fun runtimeDir() = withDir(File(cacheDir(), APP_TINC_RUNTIME_DIR))
fun logDir() = withDir(File(cacheDir(), APP_LOG_DIR))
fun confDir() = withDir(File(context.filesDir!!, APP_TINC_NETWORKS_DIR))
fun confDir(netName: String) = File(confDir(), netName)
fun hostsDir(netName: String) = File(confDir(netName), NET_HOSTS_DIR)
fun netConfFile(netName: String) = File(confDir(netName), NET_CONF_FILE)
fun tincConfFile(netName: String) = File(confDir(netName), NET_TINC_CONF_FILE)
fun invitationFile(netName: String) = File(confDir(netName), NET_INVITATION_FILE)
fun logFile(netName: String) = File(logDir(), String.format(LOGFILE_FORMAT, netName))
fun pidFile(netName: String) = File(runtimeDir(), String.format(PIDFILE_FORMAT, netName))
fun appLogFile() = File(logDir(), APPLOG_FILE)
fun crashFlagFile() = File(cacheDir(), CRASHFLAG_FILE)
fun existing(f: File) = f.apply { if (!exists()) throw FileNotFoundException(f.absolutePath) }
fun withDir(f: File) = f.apply { if (!exists()) mkdirs() }
fun defaultEd25519PrivateKeyFile(netName: String) = File(confDir(netName), NET_DEFAULT_ED25519_PRIVATE_KEY_FILE)
fun defaultRsaPrivateKeyFile(netName: String) = File(confDir(netName), NET_DEFAULT_RSA_PRIVATE_KEY_FILE)
fun tincd() = File(binDir(), TINCD_BIN)
fun tinc() = File(binDir(), TINC_BIN)
}
| gpl-3.0 | a1431b77a9bfe24c812c561d266d65d7 | 42.289474 | 114 | 0.731003 | 3.485169 | false | false | false | false |
Yubyf/QuoteLock | app/src/main/java/com/crossbowffs/quotelock/modules/natune/NatuneQuoteModule.kt | 1 | 1523 | package com.crossbowffs.quotelock.modules.natune
import android.content.ComponentName
import android.content.Context
import com.crossbowffs.quotelock.R
import com.crossbowffs.quotelock.api.QuoteData
import com.crossbowffs.quotelock.api.QuoteModule
import com.crossbowffs.quotelock.api.QuoteModule.Companion.CHARACTER_TYPE_LATIN
import com.crossbowffs.quotelock.utils.downloadUrl
import org.jsoup.Jsoup
class NatuneQuoteModule : QuoteModule {
override fun getDisplayName(context: Context): String {
return context.getString(R.string.module_natune_name)
}
override fun getConfigActivity(context: Context): ComponentName? {
return null
}
override fun getMinimumRefreshInterval(context: Context): Int {
return 0
}
override fun requiresInternetConnectivity(context: Context): Boolean {
return true
}
@Suppress("BlockingMethodInNonBlockingContext")
@Throws(Exception::class)
override suspend fun getQuote(context: Context): QuoteData {
val html = "https://natune.net/zitate/Zufalls5".downloadUrl()
val document = Jsoup.parse(html)
val quoteLi = document.select(".quotes > li").first()
val quoteText = quoteLi.getElementsByClass("quote_text").first().text()
val quoteAuthor = quoteLi.getElementsByClass("quote_author").first().text()
return QuoteData(quoteText = quoteText, quoteSource = "", quoteAuthor = quoteAuthor)
}
override val characterType: Int
get() = CHARACTER_TYPE_LATIN
} | mit | 949ff96658c4997007bbec5bda916361 | 35.285714 | 92 | 0.732764 | 4.414493 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/model/Widget.kt | 1 | 11600 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.model
import android.content.SharedPreferences
import android.net.Uri
import android.os.Parcelable
import kotlin.math.abs
import kotlin.math.max
import kotlinx.parcelize.Parcelize
import org.json.JSONException
import org.json.JSONObject
import org.openhab.habdroid.util.appendQueryParameter
import org.openhab.habdroid.util.forEach
import org.openhab.habdroid.util.getChartScalingFactor
import org.openhab.habdroid.util.map
import org.openhab.habdroid.util.optBooleanOrNull
import org.openhab.habdroid.util.optStringOrFallback
import org.openhab.habdroid.util.optStringOrNull
import org.openhab.habdroid.util.shouldRequestHighResChart
import org.w3c.dom.Node
@Parcelize
data class Widget(
val id: String,
val parentId: String?,
private val rawLabel: String,
val icon: IconResource?,
val state: ParsedState?,
val type: Type,
val url: String?,
val item: Item?,
val linkedPage: LinkedPage?,
val mappings: List<LabeledValue>,
val encoding: String?,
val iconColor: String?,
val labelColor: String?,
val valueColor: String?,
val refresh: Int,
val minValue: Float,
val maxValue: Float,
val step: Float,
val period: String,
val service: String,
val legend: Boolean?,
val forceAsItem: Boolean,
val switchSupport: Boolean,
val height: Int,
val visibility: Boolean
) : Parcelable {
val label get() = rawLabel.split("[", "]")[0].trim()
val stateFromLabel: String? get() = rawLabel.split("[", "]").getOrNull(1)?.trim()
val mappingsOrItemOptions get() =
if (mappings.isEmpty() && item?.options != null) item.options else mappings
@Suppress("unused")
enum class Type {
Chart,
Colorpicker,
Default,
Frame,
Group,
Image,
Mapview,
Selection,
Setpoint,
Slider,
Switch,
Text,
Video,
Webview,
Unknown
}
fun toChartUrl(
prefs: SharedPreferences,
width: Int,
height: Int = width / 2,
chartTheme: CharSequence?,
density: Int,
forcedPeriod: String = period,
forcedLegend: Boolean? = legend
): String? {
item ?: return null
val actualDensity = density.toFloat() / prefs.getChartScalingFactor()
val resDivider = if (prefs.shouldRequestHighResChart()) 1 else 2
val chartUrl = Uri.Builder()
.path("chart")
.appendQueryParameter(if (item.type === Item.Type.Group && !forceAsItem) "groups" else "items", item.name)
.appendQueryParameter("dpi", actualDensity.toInt() / resDivider)
.appendQueryParameter("period", forcedPeriod)
if (service.isNotEmpty()) {
chartUrl.appendQueryParameter("service", service)
}
if (chartTheme != null) {
chartUrl.appendQueryParameter("theme", chartTheme.toString())
}
if (forcedLegend != null) {
chartUrl.appendQueryParameter("legend", forcedLegend)
}
if (width > 0) {
chartUrl.appendQueryParameter("w", width / resDivider)
chartUrl.appendQueryParameter("h", height / resDivider)
}
return chartUrl.toString()
}
companion object {
@Throws(JSONException::class)
fun updateFromEvent(source: Widget, eventPayload: JSONObject): Widget {
val item = Item.updateFromEvent(source.item, eventPayload.optJSONObject("item"))
val iconName = eventPayload.optStringOrFallback("icon", source.icon?.icon)
val icon = iconName.toOH2WidgetIconResource(item, source.type, source.mappings.isNotEmpty())
return Widget(
id = source.id,
parentId = source.parentId,
rawLabel = eventPayload.optString("label", source.label),
icon = icon,
state = determineWidgetState(eventPayload.optStringOrNull("state"), item),
type = source.type,
url = source.url,
item = item,
linkedPage = source.linkedPage,
mappings = source.mappings,
encoding = source.encoding,
iconColor = source.iconColor,
labelColor = eventPayload.optStringOrNull("labelcolor"),
valueColor = eventPayload.optStringOrNull("valuecolor"),
refresh = source.refresh,
minValue = source.minValue,
maxValue = source.maxValue,
step = source.step,
period = source.period,
service = source.service,
legend = source.legend,
forceAsItem = source.forceAsItem,
switchSupport = source.switchSupport,
height = source.height,
visibility = eventPayload.optBoolean("visibility", source.visibility)
)
}
internal fun sanitizeRefreshRate(refresh: Int) = if (refresh in 1..99) 100 else refresh
internal fun sanitizePeriod(period: String?) = if (period.isNullOrEmpty()) "D" else period
internal fun sanitizeMinMaxStep(min: Float, max: Float, step: Float) =
Triple(min, max(min, max), abs(step))
internal fun determineWidgetState(state: String?, item: Item?): ParsedState? {
return state.toParsedState(item?.state?.asNumber?.format) ?: item?.state
}
}
}
fun String?.toWidgetType(): Widget.Type {
if (this != null) {
try {
return Widget.Type.valueOf(this)
} catch (e: IllegalArgumentException) {
// fall through
}
}
return Widget.Type.Unknown
}
fun Node.collectWidgets(parent: Widget?): List<Widget> {
var item: Item? = null
var linkedPage: LinkedPage? = null
var id: String? = null
var label: String? = null
var icon: String? = null
var url: String? = null
var period = ""
var service = ""
var encoding: String? = null
var iconColor: String? = null
var labelColor: String? = null
var valueColor: String? = null
var switchSupport = false
var type = Widget.Type.Unknown
var minValue = 0f
var maxValue = 100f
var step = 1f
var refresh = 0
var height = 0
val mappings = ArrayList<LabeledValue>()
val childWidgetNodes = ArrayList<Node>()
childNodes.forEach { node ->
when (node.nodeName) {
"item" -> item = node.toItem()
"linkedPage" -> linkedPage = node.toLinkedPage()
"widget" -> childWidgetNodes.add(node)
"type" -> type = node.textContent.toWidgetType()
"widgetId" -> id = node.textContent
"label" -> label = node.textContent
"icon" -> icon = node.textContent
"url" -> url = node.textContent
"minValue" -> minValue = node.textContent.toFloat()
"maxValue" -> maxValue = node.textContent.toFloat()
"step" -> step = node.textContent.toFloat()
"refresh" -> refresh = node.textContent.toInt()
"period" -> period = node.textContent
"service" -> service = node.textContent
"height" -> height = node.textContent.toInt()
"iconcolor" -> iconColor = node.textContent
"valuecolor" -> valueColor = node.textContent
"labelcolor" -> labelColor = node.textContent
"encoding" -> encoding = node.textContent
"switchSupport" -> switchSupport = node.textContent?.toBoolean() == true
"mapping" -> {
var mappingCommand = ""
var mappingLabel = ""
node.childNodes.forEach { childNode ->
when (childNode.nodeName) {
"command" -> mappingCommand = childNode.textContent
"label" -> mappingLabel = childNode.textContent
}
}
mappings.add(LabeledValue(mappingCommand, mappingLabel))
}
else -> {}
}
}
val finalId = id ?: return emptyList()
val (actualMin, actualMax, actualStep) = Widget.sanitizeMinMaxStep(minValue, maxValue, step)
val widget = Widget(
id = finalId,
parentId = parent?.id,
rawLabel = label.orEmpty(),
icon = icon.toOH1IconResource(),
state = item?.state,
type = type,
url = url,
item = item,
linkedPage = linkedPage,
mappings = mappings,
encoding = encoding,
iconColor = iconColor,
labelColor = labelColor,
valueColor = valueColor,
refresh = Widget.sanitizeRefreshRate(refresh),
minValue = actualMin,
maxValue = actualMax,
step = actualStep,
period = Widget.sanitizePeriod(period),
service = service,
legend = null,
forceAsItem = false, // forceAsItem was added in openHAB 3, so no support for openHAB 1 required.
switchSupport = switchSupport,
height = height,
visibility = true
)
val childWidgets = childWidgetNodes.map { node -> node.collectWidgets(widget) }.flatten()
return listOf(widget) + childWidgets
}
@Throws(JSONException::class)
fun JSONObject.collectWidgets(parent: Widget?): List<Widget> {
val mappings = if (has("mappings")) {
getJSONArray("mappings").map { obj -> obj.toLabeledValue("command", "label") }
} else {
emptyList()
}
val item = optJSONObject("item")?.toItem()
val type = getString("type").toWidgetType()
val icon = optStringOrNull("icon")
val (minValue, maxValue, step) = Widget.sanitizeMinMaxStep(
optDouble("minValue", 0.0).toFloat(),
optDouble("maxValue", 100.0).toFloat(),
optDouble("step", 1.0).toFloat()
)
val widget = Widget(
id = getString("widgetId"),
parentId = parent?.id,
rawLabel = optString("label", ""),
icon = icon.toOH2WidgetIconResource(item, type, mappings.isNotEmpty()),
state = Widget.determineWidgetState(optStringOrNull("state"), item),
type = type,
url = optStringOrNull("url"),
item = item,
linkedPage = optJSONObject("linkedPage").toLinkedPage(),
mappings = mappings,
encoding = optStringOrNull("encoding"),
iconColor = optStringOrNull("iconcolor"),
labelColor = optStringOrNull("labelcolor"),
valueColor = optStringOrNull("valuecolor"),
refresh = Widget.sanitizeRefreshRate(optInt("refresh")),
minValue = minValue, maxValue = maxValue, step = step,
period = Widget.sanitizePeriod(optString("period")),
service = optString("service", ""),
legend = optBooleanOrNull("legend"),
forceAsItem = optBoolean("forceAsItem", false),
switchSupport = optBoolean("switchSupport", false),
height = optInt("height"),
visibility = optBoolean("visibility", true)
)
val result = arrayListOf(widget)
val childWidgetJson = optJSONArray("widgets")
childWidgetJson?.forEach { obj -> result.addAll(obj.collectWidgets(widget)) }
return result
}
| epl-1.0 | 9a9ba37634a6510f9da2f6659a29ac27 | 34.913313 | 118 | 0.608793 | 4.534793 | false | false | false | false |
vovagrechka/k2php | k2php/src/k2php/gen.kt | 1 | 48566 | package k2php
import org.jetbrains.kotlin.js.backend.ast.JsVisitor
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.JsNumberLiteral.JsDoubleLiteral
import org.jetbrains.kotlin.js.backend.ast.JsNumberLiteral.JsIntLiteral
import org.jetbrains.kotlin.js.backend.ast.JsVars.JsVar
import org.jetbrains.kotlin.js.util.TextOutput
import gnu.trove.THashSet
import org.jetbrains.kotlin.backend.jvm.codegen.psiElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.js.backend.JsConstructExpressionVisitor
import org.jetbrains.kotlin.js.backend.JsFirstExpressionVisitor
import org.jetbrains.kotlin.js.backend.JsPrecedenceVisitor
import org.jetbrains.kotlin.js.backend.JsRequiresSemiVisitor
import org.jetbrains.kotlin.js.translate.utils.name
import org.jetbrains.kotlin.js.util.TextOutputImpl
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.annotations.argumentValue
import org.jetbrains.kotlin.resolve.constants.BooleanValue
import org.jetbrains.kotlin.resolve.constants.StringValue
import java.util.*
import photlin.*
open class JsToStringGenerationVisitor2(out:TextOutput): JsVisitor() {
protected var needSemi = true
private var lineBreakAfterBlock = true
/**
* "Global" blocks are either the global block of a fragment, or a block
* nested directly within some other global block. This definition matters
* because the statements designated by statementEnds and statementStarts are
* those that appear directly within these global blocks.
*/
private val globalBlocks = THashSet<JsBlock>()
val p:TextOutput
init{
p = out
}
override fun visitSingleLineComment(x: JsSingleLineComment) {
p.print("// ${x.text}\n")
}
override fun visitPHPPlainCodeExpression(x: PHPPlainCodeExpression) {
p.print(x.spewCode())
}
override fun visitArrayAccess(x:JsArrayAccess) {
printPair(x, x.getArrayExpression())
leftSquare()
accept(x.getIndexExpression())
rightSquare()
}
override fun visitArray(x: JsArrayLiteral) {
printDebugTag(x)
fun fuck(gen: JsToStringGenerationVisitor2) {
gen.p.print("array(")
gen.printExpressions(x.getExpressions())
gen.p.print(")")
}
fuck(this)
}
private fun printExpressions(expressions:List<JsExpression>) {
var notFirst = false
for ((expressionIndex, expression) in expressions.withIndex())
{
notFirst = sepCommaOptSpace(notFirst) && !(expression is JsDocComment)
val isEnclosed = parenPushIfCommaExpression(expression)
// if (expression.debugTag == "1646") {
// "break on me"
// }
if (expression is JsArrayLiteral || expression.valueParameterDescriptor?.type?.typeName == "kotlin.Array") {
pizdavalue(byReference = expression !is JsArrayLiteral) {gen-> gen.accept(expression)}
} else {
accept(expression)
}
if (isEnclosed)
{
rightParen()
}
}
}
private fun pizdavalue(byReference: Boolean = false, fuck: (JsToStringGenerationVisitor2) -> Unit) {
val tag = DebugGlobal.nextDebugTag()
if (tag == DebugGlobal.breakOnPizdavalue) {
"break on me"
}
val varName = "pizdavalue" + tag
val out = TextOutputImpl()
val generator = JsToStringGenerationVisitor2(out)
fuck(generator)
val eq = when {
byReference -> "=&"
else -> "="
}
printLineAbove("\$$varName $eq ${out.out};")
p.print("\$$varName")
}
override fun visitBinaryExpression(binaryOperation: JsBinaryOperation) {
val operator = binaryOperation.getOperator()
val arg1 = binaryOperation.getArg1()
val isExpressionEnclosed = parenPush(binaryOperation, arg1, !operator.isLeftAssociative())
accept(arg1)
if (operator.isKeyword())
{
_parenPopOrSpace(binaryOperation, arg1, !operator.isLeftAssociative())
}
else if (operator !== JsBinaryOperator.COMMA)
{
if (isExpressionEnclosed)
{
rightParen()
}
spaceOpt()
}
printDebugTag(binaryOperation)
if (binaryOperation.elvis) {
p.print("?:")
} else {
p.print(run {
val type = arg1.kotlinTypeName
if (type == "kotlin.String") {
if (operator.symbol == "+") return@run "."
if (operator.symbol == "+=") return@run ".="
}
return@run operator.symbol
})
}
// if (operator.symbol == "=") {
// if (binaryOperation.arg2.kotlinTypeName == "kotlin.Array") {
// p.print("&")
// }
// }
val arg2 = binaryOperation.getArg2()
val isParenOpened:Boolean
if (operator === JsBinaryOperator.COMMA)
{
isParenOpened = false
spaceOpt()
}
else if (arg2 is JsBinaryOperation && (arg2 as JsBinaryOperation).getOperator() === JsBinaryOperator.AND)
{
spaceOpt()
leftParen()
isParenOpened = true
}
else
{
if (spaceCalc(operator, arg2))
{
isParenOpened = _parenPushOrSpace(binaryOperation, arg2, operator.isLeftAssociative())
}
else
{
spaceOpt()
isParenOpened = parenPush(binaryOperation, arg2, operator.isLeftAssociative())
}
}
accept(arg2)
if (isParenOpened)
{
rightParen()
}
}
override fun visitBlock(x:JsBlock) {
printJsBlock(x, true)
}
override fun visitPHPClass(x: PHPClass) {
printAnnotations(x.classDescriptor, x)
val fuckingName = escapeIdent(x.className.ident)
p.print("class $fuckingName ")
x.classDescriptor.phpSuperPrototypeNameRef?.let {
val superClassName = (it.qualifier as JsNameRef).ident
p.print("extends ${escapeIdent(superClassName)} ")
}
blockOpen()
x.statements.forEach {accept(it); newlineOpt()}
blockClose()
p.newline()
p.print("\$$fuckingName = new stdClassWithPhotlinProps(); // Fuck...")
p.newline()
}
private fun printAnnotations(x: Annotated, node: JsNode) {
val annotations = x.annotations
if (!annotations.isEmpty()) {
p.print("/**")
for (ann in annotations) {
val annAnnotations = ann.type.constructor.declarationDescriptor?.annotations
if (annAnnotations != null) {
val emitAnnotationAsPHPCommentAnnotation = annAnnotations.find {
it.type.typeName == "photlin.EmitAnnotationAsPHPComment"
}
if (emitAnnotationAsPHPCommentAnnotation != null) {
val annotationTypeName = ann.type.typeName ?: wtf("0afd9e3c-b8f5-4cef-8d82-45de409b8e6a")
val nameArgValue = emitAnnotationAsPHPCommentAnnotation.argumentValue("name") as String
val phpName = when (nameArgValue) {
"" -> annotationTypeName.substringAfterLast(".")
else -> nameArgValue
}
p.print(" @" + phpName)
if (ann.allValueArguments.isNotEmpty()) {
p.print("(")
for ((key, value) in ann.allValueArguments) {
p.print(key.name.asString())
p.print("=")
when (value) {
is StringValue -> {
p.print(phpString(value.value, forceDoubleQuote = true))
}
is BooleanValue -> {
p.print(value.value.toString())
}
else -> imf("7a2b3251-0044-4b96-a9c4-5ca3cbabe207")
}
}
p.print(")")
}
}
}
}
p.print(" **/ ")
}
}
override fun visitBoolean(x:JsLiteral.JsBooleanLiteral) {
if (x.getValue())
{
p.print(CHARS_TRUE)
}
else
{
p.print(CHARS_FALSE)
}
}
override fun visitBreak(x:JsBreak) {
p.print(CHARS_BREAK)
continueOrBreakLabel(x)
}
override fun visitContinue(x:JsContinue) {
p.print(CHARS_CONTINUE)
continueOrBreakLabel(x)
}
private fun continueOrBreakLabel(x:JsContinue) {
val label = x.getLabel()
if (label != null && label.getIdent() != null)
{
space()
p.print("1") // XXX PHP...
// p.print(escapeIdent(label.getIdent()))
}
}
override fun visitCase(x:JsCase) {
p.print(CHARS_CASE)
space()
accept(x.getCaseExpression())
_colon()
newlineOpt()
printSwitchMemberStatements(x)
}
private fun printSwitchMemberStatements(x:JsSwitchMember) {
p.indentIn()
for (stmt in x.getStatements())
{
needSemi = true
accept(stmt)
if (needSemi)
{
semi()
}
newlineOpt()
}
p.indentOut()
needSemi = false
}
override fun visitCatch(x: JsCatch) {
spaceOpt()
p.print(CHARS_CATCH)
spaceOpt()
leftParen()
// val catchParam = ShitToShit.attrs(x).catchParam
// if (catchParam != null) {
// p.print(catchParam.typeReference!!.text + " $")
// }
accept(x.typeExpression)
p.print(" $")
nameDef(x.parameter.name)
// Optional catch condition.
//
val catchCond = x.condition
if (catchCond != null)
{
space()
_if()
space()
accept(catchCond)
}
rightParen()
spaceOpt()
accept(x.body)
}
override fun visitConditional(x:JsConditional) {
// Associativity: for the then and else branches, it is safe to insert
// another
// ternary expression, but if the test expression is a ternary, it should
// get parentheses around it.
printPair(x, x.getTestExpression(), true)
spaceOpt()
p.print('?')
spaceOpt()
printPair(x, x.getThenExpression())
spaceOpt()
_colon()
spaceOpt()
printPair(x, x.getElseExpression())
}
private fun printPair(parent:JsExpression, expression:JsExpression, wrongAssoc:Boolean = false) {
val isNeedParen = parenCalc(parent, expression, wrongAssoc)
if (isNeedParen)
{
leftParen()
}
accept(expression)
if (isNeedParen)
{
rightParen()
}
}
override fun visitDebugger(x:JsDebugger) {
p.print(CHARS_DEBUGGER)
}
override fun visitDefault(x:JsDefault) {
p.print(CHARS_DEFAULT)
_colon()
printSwitchMemberStatements(x)
}
override fun visitWhile(x:JsWhile) {
_while()
spaceOpt()
leftParen()
accept(x.getCondition())
rightParen()
nestedPush(x.getBody())
accept(x.getBody())
nestedPop(x.getBody())
}
override fun visitDoWhile(x:JsDoWhile) {
p.print(CHARS_DO)
nestedPush(x.getBody())
accept(x.getBody())
nestedPop(x.getBody())
if (needSemi)
{
semi()
newlineOpt()
}
else
{
spaceOpt()
needSemi = true
}
_while()
spaceOpt()
leftParen()
accept(x.getCondition())
rightParen()
}
override fun visitEmpty(x:JsEmpty) {}
override fun visitExpressionStatement(x:JsExpressionStatement) {
val surroundWithParentheses = JsFirstExpressionVisitor.exec(x)
if (surroundWithParentheses)
{
leftParen()
}
val expr = x.expression
if (expr is JsFunction) {
expr.shouldPrintName = true
}
accept(expr)
if (surroundWithParentheses)
{
rightParen()
}
}
override fun visitFor(x: JsFor) {
_for()
spaceOpt()
leftParen()
// The init expressions or var decl.
//
if (x.getInitExpression() != null)
{
accept(x.getInitExpression())
}
else if (x.getInitVars() != null)
{
accept(x.getInitVars())
}
semi()
// The loop test.
//
if (x.getCondition() != null)
{
spaceOpt()
accept(x.getCondition())
}
semi()
// The incr expression.
//
if (x.getIncrementExpression() != null)
{
spaceOpt()
accept(x.getIncrementExpression())
}
rightParen()
nestedPush(x.getBody())
accept(x.getBody())
nestedPop(x.getBody())
}
override fun visitForIn(x:JsForIn) {
wtf("visitForIn 7cd8a5a3-136d-4a4a-bfd4-78502e2dd11c")
// _for()
// spaceOpt()
// leftParen()
// if (x.getIterVarName() != null)
// {
// printVar()
// space()
// nameDef(x.getIterVarName())
// if (x.getIterExpression() != null)
// {
// spaceOpt()
// assignment()
// spaceOpt()
// accept(x.getIterExpression())
// }
// }
// else
// {
// // Just a name ref.
// //
// accept(x.getIterExpression())
// }
// space()
// p.print(CHARS_IN)
// space()
// accept(x.getObjectExpression())
// rightParen()
// nestedPush(x.getBody())
// accept(x.getBody())
// nestedPop(x.getBody())
}
override fun visitFunction(x: JsFunction) {
val shouldDumpBodyToContainer = x.declarationDescriptor?.annotations
?.any {it.type.typeName == "photlin.PHPDumpBodyToContainer"}
?: false
if (!shouldDumpBodyToContainer) {
printDebugTag(x)
p.print(CHARS_FUNCTION)
if (x.declarationDescriptor != null) {
val functionDescriptor = x.declarationDescriptor as? FunctionDescriptor
?: wtf("19b83dc5-1876-4a36-a82a-7feb392655d8")
if (functionDescriptor.returnType?.typeName == "kotlin.Array") {
p.print("&")
}
}
space()
if (x.getName() != null && x.shouldPrintName)
{
nameOf(x)
}
leftParen()
var notFirst = false
for (element in x.getParameters())
{
val param = element as JsParameter
notFirst = sepCommaOptSpace(notFirst)
accept(param)
}
rightParen()
space()
if (x.useNames.isNotEmpty()) {
p.print("use (")
for ((i, nameRef) in x.useNames.withIndex()) {
if (i > 0) p.print(", ")
if (isByRefShit(nameRef)) p.print("&")
p.print("$" + escapeIdent(nameRef.ident))
}
p.print(")")
}
lineBreakAfterBlock = false
}
accept(x.getBody())
needSemi = true
}
override fun visitIf(x:JsIf) {
_if()
spaceOpt()
leftParen()
accept(x.getIfExpression())
rightParen()
var thenStmt = x.getThenStatement()
var elseStatement = x.getElseStatement()
// @fucking if-then-else printing
thenStmt = JsBlock(thenStmt)
elseStatement = JsBlock(elseStatement)
if (elseStatement != null && thenStmt is JsIf && (thenStmt as JsIf).getElseStatement() == null)
{
thenStmt = JsBlock(thenStmt)
}
nestedPush(thenStmt)
accept(thenStmt)
nestedPop(thenStmt)
if (elseStatement != null)
{
if (needSemi)
{
semi()
newlineOpt()
}
else
{
spaceOpt()
needSemi = true
}
p.print(CHARS_ELSE)
val elseIf = elseStatement is JsIf
if (!elseIf)
{
nestedPush(elseStatement)
}
else
{
space()
}
accept(elseStatement)
if (!elseIf)
{
nestedPop(elseStatement)
}
}
}
// override fun visitPHPVarRef(varRef: PHPVarRef) {
// printDebugTag(varRef)
// p.print("$" + escapeDollar(varRef.getIdent()))
// }
override fun visitPHPGlobalVarRef(varRef: PHPGlobalVarRef) {
printDebugTag(varRef)
p.print("\$GLOBALS['" + escapeIdent(varRef.getIdent()) + "']")
}
// override fun visitPHPFieldRef(x: PHPFieldRef) {
// accept(x.receiver)
// p.print("->${x.fieldName}")
// }
override fun visitPHPMethodCall(call: PHPMethodCall) {
accept(call.receiver)
printDebugTag(call, spaceBefore = true)
p.print("->${call.methodName}")
leftParen()
printExpressions(call.arguments)
rightParen()
}
override fun visitPHPStaticMethodCall(call: PHPStaticMethodCall) {
p.print("${call.className}::${call.methodName}")
leftParen()
printExpressions(call.arguments)
rightParen()
}
// override fun visitPHPInvocation(invocation: PHPInvocation) {
//// val c = invocation.callee
// accept(invocation.callee)
//
// leftParen()
// printExpressions(invocation.arguments)
// rightParen()
// }
override fun visitInvocation(invocation: JsInvocation) {
printDebugTag(invocation)
val callee = invocation.qualifier
if (callee is JsNameRef) {
if (callee.qualifier?.kotlinTypeName == "kotlin.String") {
"break on me"
val builtInFunction = when (callee.ident) {
"charCodeAt" -> "Kotlin::charCodeAt"
"substring" -> "Kotlin::substring"
"split" -> "pizdasplit"
else -> wtf("d140179a-26b4-4726-bd6d-be69c62f42ed callee.ident = ${callee.ident}")
// else -> "pizdunishka"
}
p.print("$builtInFunction(")
accept(callee.qualifier)
p.print(", ")
printExpressions(invocation.arguments)
p.print(")")
return
}
accept(callee)
// printPair(invocation, callee)
} else {
pizdavalue {gen-> gen.accept(callee)}
}
leftParen()
printExpressions(invocation.arguments)
rightParen()
}
override fun visitLabel(x:JsLabel) {
nameOf(x)
_colon()
spaceOpt()
accept(x.getStatement())
}
override fun visitNameRef(nameRef: JsNameRef) {
printDebugTag(nameRef)
if (nameRef.suppressWarnings)
p.print("@")
exhaustive=when (nameRef.kind) {
PHPNameRefKind.STRING_LITERAL -> {
if (nameRef.qualifier != null) {
wtf("STRING_LITERAL with qualifier 210ac0a8-eaf1-44fe-933f-4e78a7cf07a6")
}
p.print("'" + escapeIdent(nameRef.ident) + "'")
return
}
PHPNameRefKind.GLOBAL_VAR -> {
if (nameRef.qualifier != null) {
wtf("GLOBALVAR with qualifier 1325766c-29a4-44f9-b773-428a4f097e84")
}
p.print("\$GLOBALS['" + escapeIdent(nameRef.getIdent()) + "']")
}
PHPNameRefKind.VAR -> {
if (nameRef.qualifier != null) {
wtf("VAR with qualifier 562283b3-071e-4fac-bcae-6be7f2fbc1ba")
}
p.print("$" + escapeIdent(nameRef.ident))
return
}
PHPNameRefKind.FIELD -> {
val qualifier = nameRef.qualifier
if (qualifier != null) {
if (nameRef.qualifier?.kotlinTypeName == "kotlin.String") {
val builtInFunction = when (nameRef.ident) {
"length" -> "strlen"
else -> wtf("39e634a3-a9c7-4cef-bc57-01bd2e4ae195 nameRef.ident = ${nameRef.ident}")
}
p.print("$builtInFunction(")
accept(nameRef.qualifier)
p.print(")")
return
}
}
accept(nameRef.qualifier)
p.print("->${escapeIdent(nameRef.ident)}")
return
}
PHPNameRefKind.STATIC -> {
accept(nameRef.qualifier)
p.print("::${escapeIdent(nameRef.ident)}")
return
}
PHPNameRefKind.LAMBDA,
PHPNameRefKind.LAMBDA_CREATOR -> {
val varName = "pizda_" + DebugGlobal.nextDebugTag()
// if (varName == "pizda_3485") {
// "break on me"
// }
val crappyPHPLambda = StringBuilder()-{s->
s.append("function(")
val callableDescriptor = nameRef.callableDescriptor ?: wtf("ddb4e1a5-457a-4d51-b5d5-b999247e0b07")
val paramDescriptors = when (nameRef.kind) {
PHPNameRefKind.LAMBDA_CREATOR -> nameRef.additionalArgDescriptors ?: listOf()
else -> callableDescriptor.valueParameters + (nameRef.additionalArgDescriptors ?: listOf())
}
for ((i, valueParameter) in paramDescriptors.withIndex()) {
if (i > 0)
s.append(", ")
if (valueParameter is ValueDescriptor) {
if (valueParameter.type.typeName == "kotlin.Array")
s.append("&")
}
s.append("\$p$i")
}
s.append(") {")
s.append("return ${escapeIdent(nameRef.ident)}(")
for (i in 0..paramDescriptors.lastIndex) {
if (i > 0)
s.append(", ")
s.append("\$p$i")
}
s.append(");")
s.append("}")
}
printLineAbove("\$$varName = $crappyPHPLambda;")
p.print("\$$varName")
return
}
PHPNameRefKind.DUNNO -> {
val qualifier = nameRef.qualifier
if (qualifier != null)
{
if (nameRef.qualifier?.kotlinTypeName == "kotlin.String") {
val builtInFunction = when (nameRef.ident) {
"length" -> "strlen"
else -> wtf("3c1a8c8c-4fe0-4d8b-bd4f-2bcab38a84f5 nameRef.ident = ${nameRef.ident}")
}
p.print("$builtInFunction(")
accept(nameRef.qualifier)
p.print(")")
return
}
var enclose:Boolean
if (qualifier is JsLiteral.JsValueLiteral)
{
// "42.foo" is not allowed, but "(42).foo" is.
enclose = qualifier is JsNumberLiteral
}
else
{
enclose = parenCalc(nameRef, qualifier, false)
}
if (qualifier !is JsNameRef)
enclose = false
if (enclose)
{
leftParen()
}
if (qualifier !is JsNameRef) {
// "break on me"
pizdavalue {gen-> gen.accept(qualifier)}
} else {
accept(qualifier)
}
if (enclose)
{
rightParen()
}
p.print("->")
}
p.maybeIndent()
beforeNodePrinted(nameRef)
p.print(escapeIdent(nameRef.ident))
}
}
}
private fun printLineAbove(s: String) {
try {
val out = (p as TextOutputImpl).out
var index = out.length - 1
while (out[index] != '\n' && index > 0) {
--index
}
if (out[index] == '\r' && index > 0)
--index
out.insert(index, "\n$s")
} catch(e: StringIndexOutOfBoundsException) {
"break on me"
throw e
}
}
private fun printDebugTag(shit: AbstractNode, spaceBefore: Boolean = false) {
val debugTag = shit.debugTag
if (debugTag != null) {
if (debugTag == DebugGlobal.breakOnDebugTag) {
"break on me"
}
// val mappedFrom = shit.mappedFromDebugTag?.let {"<$it>"} ?: ""
val mappedFrom = ""
p.printTagged(spaceBefore.ifOrEmpty{" "} + debugTag + mappedFrom + "@")
}
}
fun escapeIdent(s: String): String {
// PHP reserved words and alike
if (s == "die") return "die__photlin_umri_skotina"
if (s == "const") return "const__photlin_konstantinovich"
if (s == "split") return "split__photlin_v_zhopu_zalit"
return s.replace("$", "__dollar__")
}
protected fun beforeNodePrinted(node:JsNode) {}
override fun visitNew(x: JsNew) {
printDebugTag(x)
p.print(CHARS_NEW)
space()
val constructorExpression = x.getConstructorExpression()
val needsParens = JsConstructExpressionVisitor.exec(constructorExpression)
if (needsParens)
{
leftParen()
}
accept(constructorExpression)
if (needsParens)
{
rightParen()
}
leftParen()
printExpressions(x.getArguments())
rightParen()
}
override fun visitNull(x:JsNullLiteral) {
printDebugTag(x)
p.print(CHARS_NULL)
}
override fun visitInt(x:JsIntLiteral) {
p.print(x.value)
}
override fun visitDouble(x:JsDoubleLiteral) {
p.print(x.value)
}
override fun visitObjectLiteral(objectLiteral: JsObjectLiteral) {
printDebugTag(objectLiteral)
if (objectLiteral.propertyInitializers.isEmpty()) {
p.print("new stdClassWithPhotlinProps()")
} else {
// imf("Generate non-empty object literal 653f3b11-ea9c-4f14-9b41-7d17a44c2d0d")
p.print("array(")
if (objectLiteral.isMultiline)
{
p.indentIn()
}
var notFirst = false
for (item in objectLiteral.propertyInitializers)
{
if (notFirst)
{
p.print(',')
}
if (objectLiteral.isMultiline)
{
newlineOpt()
}
else if (notFirst)
{
spaceOpt()
}
notFirst = true
val labelExpr = item.labelExpr
// labels can be either string, integral, or decimal literals
p.print("'")
if (labelExpr is JsNameRef)
{
p.print((labelExpr as JsNameRef).ident)
}
else if (labelExpr is JsStringLiteral)
{
p.print((labelExpr as JsStringLiteral).value)
}
else
{
accept(labelExpr)
}
p.print("'")
p.print(" => ")
// _colon()
space()
val valueExpr = item.valueExpr
val wasEnclosed = parenPushIfCommaExpression(valueExpr)
accept(valueExpr)
if (wasEnclosed)
{
rightParen()
}
}
if (objectLiteral.isMultiline())
{
p.indentOut()
newlineOpt()
}
p.print(')')
}
}
fun isByRefShit(node: JsNode): Boolean {
return node.kotlinTypeName == "kotlin.Array"
}
override fun visitParameter(x: JsParameter) {
printDebugTag(x)
if (isByRefShit(x)) {
p.print("&")
}
p.print("$" + escapeIdent(x.name.ident))
}
override fun visitPostfixOperation(x:JsPostfixOperation) {
val op = x.getOperator()
val arg = x.getArg()
// unary operators always associate correctly (I think)
printPair(x, arg)
p.print(op.getSymbol())
}
override fun visitPrefixOperation(x:JsPrefixOperation) {
val op = x.getOperator()
p.print(op.getSymbol())
val arg = x.getArg()
if (spaceCalc(op, arg))
{
space()
}
// unary operators always associate correctly (I think)
printPair(x, arg)
}
override fun visitProgram(x:JsProgram) {
p.print("<JsProgram>")
}
override fun visitProgramFragment(x:JsProgramFragment) {
p.print("<JsProgramFragment>")
}
override fun visitRegExp(x:JsRegExp) {
slash()
p.print(x.getPattern())
slash()
val flags = x.getFlags()
if (flags != null)
{
p.print(flags)
}
}
override fun visitReturn(x:JsReturn) {
printDebugTag(x)
p.print(CHARS_RETURN)
val expr = x.getExpression()
if (expr != null)
{
space()
accept(expr)
}
}
override fun visitString(x:JsStringLiteral) {
p.print(phpString(x.value, forceDoubleQuote = true))
}
override fun visit(x:JsSwitch) {
p.print(CHARS_SWITCH)
spaceOpt()
leftParen()
accept(x.getExpression())
rightParen()
spaceOpt()
blockOpen()
acceptList(x.getCases())
blockClose()
}
override fun visitThis(x:JsLiteral.JsThisRef) {
p.print(CHARS_THIS)
}
override fun visitThrow(x: JsThrow) {
printDebugTag(x)
p.print(CHARS_THROW)
space()
accept(x.expression)
}
override fun visitTry(x:JsTry) {
p.print(CHARS_TRY)
spaceOpt()
accept(x.getTryBlock())
acceptList(x.getCatches())
val finallyBlock = x.getFinallyBlock()
if (finallyBlock != null)
{
p.print(CHARS_FINALLY)
spaceOpt()
accept(finallyBlock)
}
}
override fun visit(v: JsVar) {
v.propertyDescriptor?.let {printAnnotations(it, v)}
v.visibility?.let {p.print("$it ")}
printDebugTag(v)
p.print("$" + escapeIdent(v.name.ident))
val initExpr = v.initExpression
if (initExpr != null) {
spaceOpt()
// if (v.debugTag == DebugGlobal.breakOnDebugTag) {
// "break on me"
// }
assignment(byRef = isByRefShit(v) && initExpr is JsNameRef)
spaceOpt()
val isEnclosed = parenPushIfCommaExpression(initExpr)
accept(initExpr)
if (isEnclosed)
{
rightParen()
}
}
}
override fun visitVars(vars: JsVars) {
space()
var sep = false
for (v in vars)
{
if (sep)
{
if (vars.isMultiline)
{
newlineOpt()
}
spaceOpt()
}
else
{
sep = true
}
accept(v)
p.print(';')
}
}
override fun visitDocComment(comment:JsDocComment) {
val asSingleLine = comment.getTags().size === 1
if (!asSingleLine)
{
newlineOpt()
}
p.print("/**")
if (asSingleLine)
{
space()
}
else
{
p.newline()
}
var notFirst = false
for (entry in comment.getTags().entries)
{
if (notFirst)
{
p.newline()
p.print(' ')
p.print('*')
}
else
{
notFirst = true
}
p.print('@')
p.print(entry.key)
val value = entry.value
if (value != null)
{
space()
if (value is CharSequence)
{
p.print(value as CharSequence)
}
else
{
visitNameRef(value as JsNameRef)
}
}
if (!asSingleLine)
{
p.newline()
}
}
if (asSingleLine)
{
space()
}
else
{
newlineOpt()
}
p.print('*')
p.print('/')
if (asSingleLine)
{
spaceOpt()
}
}
protected fun newlineOpt() {
if (!p.isCompact())
{
p.newline()
}
// @debug
// val breakOnLine = 37
// if (p.line == breakOnLine - 1) {
// "break on me"
// }
}
protected fun printJsBlock(x:JsBlock, _finalNewline:Boolean) {
var finalNewline = _finalNewline
if (!lineBreakAfterBlock)
{
finalNewline = false
lineBreakAfterBlock = true
}
val needBraces = !x.isGlobalBlock()
if (needBraces)
{
blockOpen()
}
val iterator = x.getStatements().iterator()
while (iterator.hasNext())
{
val isGlobal = x.isGlobalBlock() || globalBlocks.contains(x)
val statement = iterator.next()
if (statement is JsEmpty)
{
continue
}
needSemi = true
var stmtIsGlobalBlock = false
if (isGlobal)
{
if (statement is JsBlock)
{
// A block inside a global block is still considered global
stmtIsGlobalBlock = true
globalBlocks.add(statement as JsBlock)
}
}
val commentedOut = statement is AbstractNode && statement.commentedOut
if (commentedOut) p.print("/*")
accept(statement)
if (commentedOut) p.print("*/")
if (stmtIsGlobalBlock)
{
globalBlocks.remove(statement)
}
if (needSemi)
{
/*
* Special treatment of function declarations: If they are the only item in a
* statement (i.e. not part of an assignment operation), just give them
* a newline instead of a semi.
*/
val functionStmt = statement is JsExpressionStatement && (statement as JsExpressionStatement).getExpression() is JsFunction
/*
* Special treatment of the last statement in a block: only a few
* statements at the end of a block require semicolons.
*/
val lastStatement = !iterator.hasNext() && needBraces && !JsRequiresSemiVisitor.exec(statement)
if (functionStmt)
{
if (lastStatement)
{
newlineOpt()
}
else
{
p.newline()
}
}
else
{
if (lastStatement)
{
p.printOpt(';')
}
else
{
semi()
}
newlineOpt()
}
}
}
if (needBraces)
{
// _blockClose() modified
p.indentOut()
p.print('}')
if (finalNewline)
{
newlineOpt()
}
}
needSemi = false
}
private fun assignment(byRef: Boolean) {
p.print('=')
if (byRef) p.print('&')
}
private fun blockClose() {
p.indentOut()
p.print('}')
newlineOpt()
}
private fun blockOpen() {
p.print('{')
p.indentIn()
newlineOpt()
}
private fun _colon() {
p.print(':')
}
private fun _for() {
p.print(CHARS_FOR)
}
private fun _if() {
p.print(CHARS_IF)
}
private fun leftParen() {
p.print('(')
}
private fun leftSquare() {
p.print('[')
}
private fun nameDef(name: JsName) {
// printDebugTag(name)
p.print(escapeIdent(name.ident))
}
private fun nameOf(hasName: HasName) {
nameDef(hasName.name)
}
private fun nestedPop(statement:JsStatement):Boolean {
val pop = !(statement is JsBlock)
if (pop)
{
p.indentOut()
}
return pop
}
private fun nestedPush(statement:JsStatement):Boolean {
val push = !(statement is JsBlock)
if (push)
{
newlineOpt()
p.indentIn()
}
else
{
spaceOpt()
}
return push
}
private fun _parenPopOrSpace(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val doPop = parenCalc(parent, child, wrongAssoc)
if (doPop)
{
rightParen()
}
else
{
space()
}
return doPop
}
private fun parenPush(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val doPush = parenCalc(parent, child, wrongAssoc)
if (doPush)
{
leftParen()
}
return doPush
}
private fun parenPushIfCommaExpression(x:JsExpression):Boolean {
val doPush = x is JsBinaryOperation && (x as JsBinaryOperation).getOperator() === JsBinaryOperator.COMMA
if (doPush)
{
leftParen()
}
return doPush
}
private fun _parenPushOrSpace(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val doPush = parenCalc(parent, child, wrongAssoc)
if (doPush)
{
leftParen()
}
else
{
space()
}
return doPush
}
private fun rightParen() {
p.print(')')
}
private fun rightSquare() {
p.print(']')
}
private fun semi() {
p.print(';')
}
private fun sepCommaOptSpace(sep:Boolean):Boolean {
if (sep)
{
p.print(',')
spaceOpt()
}
return true
}
private fun slash() {
p.print('/')
}
private fun space() {
p.print(' ')
}
private fun spaceOpt() {
p.printOpt(' ')
}
private fun printVar() {
p.print(CHARS_VAR)
}
private fun _while() {
p.print(CHARS_WHILE)
}
companion object {
private val CHARS_BREAK = "break".toCharArray()
private val CHARS_CASE = "case".toCharArray()
private val CHARS_CATCH = "catch".toCharArray()
private val CHARS_CONTINUE = "continue".toCharArray()
private val CHARS_DEBUGGER = "debugger".toCharArray()
private val CHARS_DEFAULT = "default".toCharArray()
private val CHARS_DO = "do".toCharArray()
private val CHARS_ELSE = "else".toCharArray()
private val CHARS_FALSE = "false".toCharArray()
private val CHARS_FINALLY = "finally".toCharArray()
private val CHARS_FOR = "for".toCharArray()
private val CHARS_FUNCTION = "function".toCharArray()
private val CHARS_IF = "if".toCharArray()
private val CHARS_IN = "in".toCharArray()
private val CHARS_NEW = "new".toCharArray()
private val CHARS_NULL = "NULL".toCharArray()
private val CHARS_RETURN = "return".toCharArray()
private val CHARS_SWITCH = "switch".toCharArray()
private val CHARS_THIS = "this".toCharArray()
private val CHARS_THROW = "throw".toCharArray()
private val CHARS_TRUE = "true".toCharArray()
private val CHARS_TRY = "try".toCharArray()
private val CHARS_VAR = "var".toCharArray()
private val CHARS_WHILE = "while".toCharArray()
private val HEX_DIGITS = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
fun javaScriptString(value:String):CharSequence {
return phpString(value, false)
}
/**
* Generate JavaScript code that evaluates to the supplied string. Adapted
* from {@link org.mozilla.javascript.ScriptRuntime#escapeString(String)}
* . The difference is that we quote with either " or ' depending on
* which one is used less inside the string.
*/
fun phpString(chars: CharSequence, forceDoubleQuote: Boolean = false):CharSequence {
val n = chars.length
var quoteCount = 0
var aposCount = 0
for (i in 0..n - 1)
{
when (chars.get(i)) {
'"' -> ++quoteCount
'\'' -> ++aposCount
}
}
val result = StringBuilder(n + 16)
val quoteChar = if ((quoteCount < aposCount || forceDoubleQuote)) '"' else '\''
result.append(quoteChar)
for (i in 0..n - 1)
{
val c = chars.get(i)
if (' ' <= c && c <= '~' && c != quoteChar && c != '\\' && c != '$')
{
// an ordinary print character (like C isprint())
result.append(c)
continue
}
var escape = -1
when (c) {
'\b' -> escape = 'b'.toInt()
// '\f' -> escape = 'f'
'\n' -> escape = 'n'.toInt()
'\r' -> escape = 'r'.toInt()
'\t' -> escape = 't'.toInt()
'"' -> escape = '"'.toInt()
'\'' -> escape = '\''.toInt()
'\\' -> escape = '\\'.toInt()
'$' -> escape = '$'.toInt()
}// only reach here if == quoteChar
// only reach here if == quoteChar
if (escape >= 0)
{
// an \escaped sort of character
result.append('\\')
result.append(escape.toChar())
}
else
{
val hexSize:Int
if (c.toInt() < 256)
{
// 2-digit hex
result.append("\\x")
hexSize = 2
}
else
{
// Unicode.
result.append("\\u")
hexSize = 4
}
// append hexadecimal form of ch left-padded with 0
var shift = (hexSize - 1) * 4
while (shift >= 0)
{
val digit = 0xf and (c.toInt() shr shift)
result.append(HEX_DIGITS[digit])
shift -= 4
}
}
}
result.append(quoteChar)
escapeClosingTags(result)
return result
}
/**
* Escapes any closing XML tags embedded in <code>str</code>, which could
* potentially cause a parse failure in a browser, for example, embedding a
* closing <code><script></code> tag.
*
* @param str an unescaped literal; May be null
*/
private fun escapeClosingTags(str:StringBuilder) {
if (str == null)
{
return
}
var index = 0
while (true) {
index = str.indexOf("</", index)
if (index == -1) break
str.insert(index + 1, '\\')
}
}
private fun parenCalc(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val parentPrec = JsPrecedenceVisitor.exec(parent)
val childPrec = JsPrecedenceVisitor.exec(child)
return parentPrec > childPrec || parentPrec == childPrec && wrongAssoc
}
/**
* Decide whether, if <code>op</code> is printed followed by <code>arg</code>,
* there needs to be a space between the operator and expression.
*
* @return <code>true</code> if a space needs to be printed
*/
private fun spaceCalc(op:JsOperator, arg:JsExpression):Boolean {
if (op.isKeyword())
{
return true
}
if (arg is JsBinaryOperation)
{
val binary = arg as JsBinaryOperation
/*
* If the binary operation has a higher precedence than op, then it won't
* be parenthesized, so check the first argument of the binary operation.
*/
return binary.getOperator().getPrecedence() > op.getPrecedence() && spaceCalc(op, binary.getArg1())
}
if (arg is JsPrefixOperation)
{
val op2 = (arg as JsPrefixOperation).getOperator()
return (op === JsBinaryOperator.SUB || op === JsUnaryOperator.NEG) && (op2 === JsUnaryOperator.DEC || op2 === JsUnaryOperator.NEG) || (op === JsBinaryOperator.ADD && op2 === JsUnaryOperator.INC)
}
if (arg is JsNumberLiteral && (op === JsBinaryOperator.SUB || op === JsUnaryOperator.NEG))
{
if (arg is JsIntLiteral)
{
return (arg as JsIntLiteral).value < 0
}
else
{
assert(arg is JsDoubleLiteral)
return (arg as JsDoubleLiteral).value < 0
}
}
return false
}
}
}
| apache-2.0 | d9d57dec901a13bf9936f28b673fa981 | 29.973214 | 210 | 0.483198 | 4.644353 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/sorter/GeekRatingSorter.kt | 1 | 705 | package com.boardgamegeek.sorter
import android.content.Context
import androidx.annotation.StringRes
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
import java.text.DecimalFormat
class GeekRatingSorter(context: Context) : RatingSorter(context) {
@StringRes
public override val typeResId = R.string.collection_sort_type_geek_rating
@StringRes
override val descriptionResId = R.string.collection_sort_geek_rating
override fun sort(items: Iterable<CollectionItemEntity>) = items.sortedByDescending { it.geekRating }
override val displayFormat = DecimalFormat("0.000")
override fun getRating(item: CollectionItemEntity) = item.geekRating
}
| gpl-3.0 | f91ea29566df4fc354d091f1bc540eb2 | 32.571429 | 105 | 0.797163 | 4.462025 | false | false | false | false |
PrivacyStreams/PrivacyStreams | privacystreams-app/src/main/java/io/github/privacystreams/app/NavActivity.kt | 2 | 3088 | package io.github.privacystreams.app
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import io.github.privacystreams.app.db.PStreamCollectService
class NavActivity : AppCompatActivity() {
companion object {
val NAV_ID_KEY = "navId"
val DEFAULT_NAV_ID = R.id.nav_data
val LOG_TAG = "NavActivity"
}
var navId = DEFAULT_NAV_ID
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
loadFragment(item.itemId)
true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nav)
val toolbar : Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
PStreamCollectService.start(this)
val navigation : BottomNavigationView = findViewById(R.id.navigation)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
onNewIntent(intent)
}
override fun onNewIntent(intent: Intent) {
val bundle = intent.extras
if (bundle != null)
navId = bundle.getInt(NAV_ID_KEY, navId)
loadFragment(navId)
}
private fun loadFragment(navId: Int) {
val fragmentManager = fragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
when (navId) {
R.id.nav_timeline -> {
this.setTitle(R.string.timeline)
}
R.id.nav_market -> {
this.setTitle(R.string.market)
}
R.id.nav_notification -> {
this.setTitle(R.string.notification)
}
R.id.nav_account -> {
this.setTitle(R.string.account)
}
R.id.nav_data -> {
this.setTitle(R.string.data)
val fragment = ManageDataFragment()
fragmentTransaction.replace(R.id.content, fragment)
}
}
fragmentTransaction.commit()
val navigation : BottomNavigationView = findViewById(R.id.navigation)
navigation.menu.findItem(navId).isChecked = true
this.navId = navId
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.nav_bar, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
| apache-2.0 | e693d5de28a287eab7e8b35794c418c8 | 31.166667 | 115 | 0.641192 | 4.700152 | false | false | false | false |
binaryfoo/emv-bertlv | src/main/java/io/github/binaryfoo/decoders/DOLParser.kt | 1 | 695 | package io.github.binaryfoo.decoders
import io.github.binaryfoo.tlv.Tag
import java.nio.ByteBuffer
import java.util.*
/**
* DOL = Data Object List = A description of some data a receiver would like.
*
* Each element in the list is a tag and a length the receiver would like the value encoded on.
*/
class DOLParser {
fun parse(dol: ByteArray): List<DOLElement> {
val elements = ArrayList<DOLElement>()
val buffer = ByteBuffer.wrap(dol)
while (buffer.hasRemaining()) {
val tag = Tag.parse(buffer)
val length = buffer.get()
elements.add(DOLElement(tag, length.toInt()))
}
return elements
}
data class DOLElement(val tag: Tag, val length: Int)
}
| mit | feeeaf8f1e55fe3fa51f7ee5ab98df83 | 25.730769 | 95 | 0.693525 | 3.777174 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/autocomplete/AutocompleteSettingsFragment.kt | 1 | 1874 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.autocomplete
import android.content.SharedPreferences
import android.os.Bundle
import org.mozilla.focus.R
import org.mozilla.focus.settings.BaseSettingsFragment
import org.mozilla.focus.telemetry.TelemetryWrapper
/**
* Settings UI for configuring autocomplete.
*/
class AutocompleteSettingsFragment : BaseSettingsFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
override fun onCreatePreferences(p0: Bundle?, p1: String?) {
addPreferencesFromResource(R.xml.autocomplete)
}
override fun onResume() {
super.onResume()
val updater = activity as BaseSettingsFragment.ActionBarUpdater
updater.updateTitle(R.string.preference_subitem_autocomplete)
updater.updateIcon(R.drawable.ic_back)
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onPreferenceTreeClick(preference: android.support.v7.preference.Preference?): Boolean {
preference?.let {
if (it.key == getString(R.string.pref_key_screen_custom_domains)) {
navigateToFragment(AutocompleteListFragment())
}
}
return super.onPreferenceTreeClick(preference)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == null || sharedPreferences == null) {
return
}
TelemetryWrapper.settingsEvent(key, sharedPreferences.all[key].toString())
}
}
| mpl-2.0 | 861ac1ea6f3e27b28662ca88514e7a8b | 34.358491 | 113 | 0.720918 | 5.051213 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/readers/MeasurementConsumerReader.kt | 1 | 4045 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers
import com.google.cloud.spanner.Struct
import kotlinx.coroutines.flow.singleOrNull
import org.wfanet.measurement.common.identity.ExternalId
import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient
import org.wfanet.measurement.gcloud.spanner.appendClause
import org.wfanet.measurement.gcloud.spanner.getBytesAsByteString
import org.wfanet.measurement.gcloud.spanner.getProtoEnum
import org.wfanet.measurement.gcloud.spanner.getProtoMessage
import org.wfanet.measurement.internal.kingdom.Certificate
import org.wfanet.measurement.internal.kingdom.MeasurementConsumer
class MeasurementConsumerReader : SpannerReader<MeasurementConsumerReader.Result>() {
data class Result(val measurementConsumer: MeasurementConsumer, val measurementConsumerId: Long)
override val baseSql: String =
"""
SELECT
MeasurementConsumers.MeasurementConsumerId,
MeasurementConsumers.ExternalMeasurementConsumerId,
MeasurementConsumers.MeasurementConsumerDetails,
MeasurementConsumers.MeasurementConsumerDetailsJson,
MeasurementConsumerCertificates.ExternalMeasurementConsumerCertificateId,
Certificates.CertificateId,
Certificates.SubjectKeyIdentifier,
Certificates.NotValidBefore,
Certificates.NotValidAfter,
Certificates.RevocationState,
Certificates.CertificateDetails
FROM MeasurementConsumers
JOIN MeasurementConsumerCertificates USING (MeasurementConsumerId)
JOIN Certificates USING (CertificateId)
"""
.trimIndent()
override suspend fun translate(struct: Struct): Result =
Result(buildMeasurementConsumer(struct), struct.getLong("MeasurementConsumerId"))
private fun buildMeasurementConsumer(struct: Struct): MeasurementConsumer =
MeasurementConsumer.newBuilder()
.apply {
externalMeasurementConsumerId = struct.getLong("ExternalMeasurementConsumerId")
details =
struct.getProtoMessage("MeasurementConsumerDetails", MeasurementConsumer.Details.parser())
certificate = buildCertificate(struct)
}
.build()
suspend fun readByExternalMeasurementConsumerId(
readContext: AsyncDatabaseClient.ReadContext,
externalMeasurementConsumerId: ExternalId,
): Result? {
return fillStatementBuilder {
appendClause("WHERE ExternalMeasurementConsumerId = @externalMeasurementConsumerId")
bind("externalMeasurementConsumerId").to(externalMeasurementConsumerId.value)
appendClause("LIMIT 1")
}
.execute(readContext)
.singleOrNull()
}
// TODO(uakyol) : Move this function to CertificateReader when it is implemented.
private fun buildCertificate(struct: Struct): Certificate =
Certificate.newBuilder()
.apply {
externalMeasurementConsumerId = struct.getLong("ExternalMeasurementConsumerId")
externalCertificateId = struct.getLong("ExternalMeasurementConsumerCertificateId")
subjectKeyIdentifier = struct.getBytesAsByteString("SubjectKeyIdentifier")
notValidBefore = struct.getTimestamp("NotValidBefore").toProto()
notValidAfter = struct.getTimestamp("NotValidAfter").toProto()
revocationState =
struct.getProtoEnum("RevocationState", Certificate.RevocationState::forNumber)
details = struct.getProtoMessage("CertificateDetails", Certificate.Details.parser())
}
.build()
}
| apache-2.0 | 5bada9b97f43b0439fce0d058b7d277b | 43.450549 | 100 | 0.775278 | 5.400534 | false | false | false | false |
debop/debop4k | debop4k-spring/src/main/kotlin/debop4k/spring/beans/BeanUtilx.kt | 1 | 4675 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("BeanUtilx")
package debop4k.spring.beans
import org.springframework.beans.*
import org.springframework.core.MethodParameter
import java.beans.PropertyDescriptor
import java.beans.PropertyEditor
import java.lang.reflect.Constructor
import java.lang.reflect.Method
/**
* 해당 수형의 인스턴스를 기본 생성자를 이용해 생성합니다
*/
@Throws(BeanInstantiationException::class)
fun <T> Class<T>.instantiate(): T = BeanUtils.instantiate(this)
/**
* 해당 수형의 인스턴스를 기본 생성자를 이용해 생성합니다
*/
@Throws(BeanInstantiationException::class)
fun <T> Class<T>.instantiateClass(): T = BeanUtils.instantiateClass(this)
@Throws(BeanInstantiationException::class)
fun <T> Constructor<T>.instanticateClass(vararg args: Any): T = BeanUtils.instantiateClass(this, *args)
@Throws(BeanInstantiationException::class)
fun <T> Class<*>.instantiateClass(assignableTo: Class<T>): T = BeanUtils.instantiateClass(this, assignableTo)
fun Class<*>.findMethod(methodName: String, vararg paramTypes: Class<*>): Method
= BeanUtils.findMethod(this, methodName, *paramTypes)
fun Class<*>.findMethodWithMinimalParameters(methodName: String): Method
= BeanUtils.findMethodWithMinimalParameters(this, methodName)
fun Array<Method>.findMethodWithMinimalParameters(methodName: String): Method
= BeanUtils.findMethodWithMinimalParameters(this, methodName)
fun Class<*>.findDeclaredMethodWithMinimalParameters(methodName: String): Method
= BeanUtils.findDeclaredMethodWithMinimalParameters(this, methodName)
fun String.resolveSignature(clazz: Class<*>): Method = BeanUtils.resolveSignature(this, clazz)
fun Class<*>.getPropertyDescriptors(): Array<PropertyDescriptor>
= BeanUtils.getPropertyDescriptors(this)
fun Class<*>.getPropertyDescriptor(propertyName: String): PropertyDescriptor
= BeanUtils.getPropertyDescriptor(this, propertyName)
fun Method.findPropertyForMethod(): PropertyDescriptor
= BeanUtils.findPropertyForMethod(this)
fun Method.findPropertyForMethod(clazz: Class<*>): PropertyDescriptor
= BeanUtils.findPropertyForMethod(this, clazz)
fun Class<*>.findEditorByConvention(): PropertyEditor
= BeanUtils.findEditorByConvention(this)
fun String.findPropertyType(vararg beanClasses: Class<*>): Class<*>
= BeanUtils.findPropertyType(this, *beanClasses)
fun PropertyDescriptor.getWriteMethodParameter(): MethodParameter
= BeanUtils.getWriteMethodParameter(this)
fun Class<*>.isSimpleProperty(): Boolean = BeanUtils.isSimpleProperty(this)
fun Class<*>.isSimpleValueType(): Boolean = BeanUtils.isSimpleValueType(this)
@Throws(BeansException::class)
fun Any.copyProperties(target: Any): Unit = BeanUtils.copyProperties(this, target)
@Throws(BeansException::class)
fun Any.copyProperties(target: Any, vararg ignoredProperties: String): Unit
= BeanUtils.copyProperties(this, target, *ignoredProperties)
@Throws(BeansException::class)
fun Any.copyProperties(target: Any, editable: Class<*>): Unit
= BeanUtils.copyProperties(this, target, editable)
//@Throws(BeansException::class)
//fun Any.copyProperties(target: Any, editable: Class<*>, vararg ignoredProperties:String): Unit
// = BeanUtils.copyProperties(this, target, editable, *ignoredProperties)
fun String.getPropertyName(): String = PropertyAccessorUtils.getPropertyName(this)
fun String.isNestedOrIndexedProperty(): Boolean = PropertyAccessorUtils.isNestedOrIndexedProperty(this)
fun String.getFirstNestedPropertySeparatorIndex(): Int
= PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(this)
fun String.getLastNestedPropertySeparatorIndex(): Int
= PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(this)
fun String.matchesProperty(propertyPath: String): Boolean
= PropertyAccessorUtils.matchesProperty(this, propertyPath)
fun String.canonicalPropertyName(): String = PropertyAccessorUtils.canonicalPropertyName(this)
fun Array<String>.canonicalPropertyNames(): Array<String>
= PropertyAccessorUtils.canonicalPropertyNames(this)
| apache-2.0 | 9ed453d94dec7f8febe21885e83543bc | 38.474138 | 109 | 0.792094 | 4.200917 | false | false | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/events/UserInfo.kt | 1 | 1520 | package io.rover.sdk.core.events
import io.rover.sdk.core.data.domain.Attributes
import io.rover.sdk.core.data.graphql.operations.data.encodeJson
import io.rover.sdk.core.data.graphql.operations.data.toAttributesHash
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.platform.LocalStorage
import org.json.JSONObject
class UserInfo(
localStorage: LocalStorage
) : UserInfoInterface {
private val store = localStorage.getKeyValueStorageFor(STORAGE_CONTEXT_IDENTIFIER)
override fun update(builder: (attributes: HashMap<String, Any>) -> Unit) {
val mutableDraft = HashMap(currentUserInfo)
builder(mutableDraft)
currentUserInfo = mutableDraft
}
override fun clear() {
currentUserInfo = hashMapOf()
}
override var currentUserInfo: Attributes = try {
val currentAttributesJson = store[USER_INFO_KEY]
when (currentAttributesJson) {
null -> hashMapOf()
else -> JSONObject(store[USER_INFO_KEY]).toAttributesHash()
}
} catch (throwable: Throwable) {
log.w("Corrupted local user info, ignoring and starting fresh. Cause: ${throwable.message}")
hashMapOf()
}
private set(value) {
field = value
store[USER_INFO_KEY] = value.encodeJson().toString()
log.v("Stored new user info.")
}
companion object {
private const val STORAGE_CONTEXT_IDENTIFIER = "user-info"
private const val USER_INFO_KEY = "user-info"
}
} | apache-2.0 | 27fc47801f9a66e421b3ad27438b6b9e | 33.568182 | 101 | 0.675 | 4.198895 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/treefarm/VanillaTree.kt | 1 | 1125 | package net.ndrei.teslapoweredthingies.machines.treefarm
import net.minecraft.block.state.IBlockState
import net.minecraft.init.Blocks
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by CF on 2017-07-07.
*/
class VanillaTree : ITreeFactory {
override fun getHarvestableLog(world: World, pos: BlockPos, block: IBlockState): ITreeLogWrapper? {
return if ((block.block === Blocks.LOG || block.block === Blocks.LOG2))
VanillaTreeLog(world, pos)
else
null
}
override fun getHarvestableLeaf(world: World, pos: BlockPos, block: IBlockState): ITreeLeafWrapper? {
return if ((block.block === Blocks.LEAVES || block.block === Blocks.LEAVES2))
VanillaTreeLeaf(world, pos)
else
null
}
override fun getPlantableSapling(stack: ItemStack): ITreeSaplingWrapper? {
if (!stack.isEmpty && stack.item === Item.getItemFromBlock(Blocks.SAPLING)) {
return VanillaSapling(stack)
}
return null
}
}
| mit | 41cf64f837df10c9292bc696032f92d4 | 32.088235 | 105 | 0.678222 | 3.961268 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/utils/NotificationUtils.kt | 1 | 3028 | package com.quickblox.sample.chat.kotlin.utils
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.RingtoneManager
import android.os.Build
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
private const val CHANNEL_ONE_ID = "com.quickblox.samples.ONE"// The id of the channel.
private const val CHANNEL_ONE_NAME = "Channel One"
object NotificationUtils {
fun showNotification(context: Context, activityClass: Class<out Activity>, title: String,
message: String, @DrawableRes icon: Int, notificationId: Int) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannelIfNotExist(notificationManager)
}
val notification = buildNotification(context, activityClass, title, message, icon)
notificationManager.notify(notificationId, notification)
}
@RequiresApi(api = Build.VERSION_CODES.O)
private fun createChannelIfNotExist(notificationManager: NotificationManager) {
if (notificationManager.getNotificationChannel(CHANNEL_ONE_ID) == null) {
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel = NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, importance)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.BLUE
notificationChannel.setShowBadge(true)
notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.createNotificationChannel(notificationChannel)
}
}
private fun buildNotification(context: Context, activityClass: Class<out Activity>,
title: String, message: String, @DrawableRes icon: Int): Notification {
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
return NotificationCompat.Builder(context, CHANNEL_ONE_ID)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(buildContentIntent(context, activityClass, message))
.build()
}
private fun buildContentIntent(context: Context, activityClass: Class<out Activity>, message: String): PendingIntent {
val intent = Intent(context, activityClass)
intent.putExtra(EXTRA_FCM_MESSAGE, message)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
var intentFlag = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
intentFlag = PendingIntent.FLAG_IMMUTABLE
}
return PendingIntent.getActivity(context, 0, intent, intentFlag)
}
} | bsd-3-clause | 48364f9874148fc1c42613297c04861c | 45.6 | 122 | 0.701453 | 5.238754 | false | false | false | false |
GeoffreyMetais/vlc-android | application/moviepedia/src/main/java/org/videolan/moviepedia/Helpers.kt | 1 | 2607 | package org.videolan.moviepedia
import android.content.Context
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.moviepedia.database.models.MediaMetadata
import org.videolan.moviepedia.database.models.getYear
fun getHeaderMoviepedia(context: Context?, sort: Int, item: MediaMetadata?, aboveItem: MediaMetadata?) = if (context !== null && item != null) when (sort) {
Medialibrary.SORT_DEFAULT,
Medialibrary.SORT_FILENAME,
Medialibrary.SORT_ALPHA -> {
val letter = if (item.title.isEmpty() || !Character.isLetter(item.title[0])) "#" else item.title.substring(0, 1).toUpperCase()
if (aboveItem == null) letter
else {
val previous = if (aboveItem.title.isEmpty() || !Character.isLetter(aboveItem.title[0])) "#" else aboveItem.title.substring(0, 1).toUpperCase()
letter.takeIf { it != previous }
}
}
// SORT_DURATION -> {
// val length = item.getLength()
// val lengthCategory = length.lengthToCategory()
// if (aboveItem == null) lengthCategory
// else {
// val previous = aboveItem.getLength().lengthToCategory()
// lengthCategory.takeIf { it != previous }
// }
// }
Medialibrary.SORT_RELEASEDATE -> {
val year = item.getYear()
if (aboveItem == null) year
else {
val previous = aboveItem.getYear()
year.takeIf { it != previous }
}
}
// SORT_LASTMODIFICATIONDATE -> {
// val timestamp = (item as MediaWrapper).lastModified
// val category = getTimeCategory(timestamp)
// if (aboveItem == null) getTimeCategoryString(context, category)
// else {
// val prevCat = getTimeCategory((aboveItem as MediaWrapper).lastModified)
// if (prevCat != category) getTimeCategoryString(context, category) else null
// }
// }
// SORT_ARTIST -> {
// val artist = (item as MediaWrapper).artist ?: ""
// if (aboveItem == null) artist
// else {
// val previous = (aboveItem as MediaWrapper).artist ?: ""
// artist.takeIf { it != previous }
// }
// }
// SORT_ALBUM -> {
// val album = (item as MediaWrapper).album ?: ""
// if (aboveItem == null) album
// else {
// val previous = (aboveItem as MediaWrapper).album ?: ""
// album.takeIf { it != previous }
// }
// }
else -> null
} else null | gpl-2.0 | cb0a856c21b15b97acd9371f7d8f76ac | 40.396825 | 156 | 0.564634 | 4.294893 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/settings/video/VideoSettingsViewModel.kt | 1 | 2748 | package com.quickblox.sample.conference.kotlin.presentation.screens.settings.video
import android.os.Bundle
import com.quickblox.sample.conference.kotlin.R
import com.quickblox.sample.conference.kotlin.domain.DomainCallback
import com.quickblox.sample.conference.kotlin.domain.chat.ChatManager
import com.quickblox.sample.conference.kotlin.domain.settings.SettingsManager
import com.quickblox.sample.conference.kotlin.domain.settings.entities.CallSettingsEntity
import com.quickblox.sample.conference.kotlin.domain.user.UserManager
import com.quickblox.sample.conference.kotlin.presentation.LiveData
import com.quickblox.sample.conference.kotlin.presentation.resources.ResourcesManager
import com.quickblox.sample.conference.kotlin.presentation.screens.base.BaseViewModel
import com.quickblox.users.model.QBUser
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
@HiltViewModel
class VideoSettingsViewModel @Inject constructor(private val settingsManager: SettingsManager, resourcesManager: ResourcesManager,
userManager: UserManager, private val chatManager: ChatManager) : BaseViewModel() {
val liveData = LiveData<Pair<Int, Any?>>()
var currentUser: QBUser? = null
private set
var callSettings: CallSettingsEntity? = null
private set
private val resolutions = arrayListOf<Pair<String, Int>>()
init {
resolutions.add(Pair(resourcesManager.get().getString(R.string.HD), 0))
resolutions.add(Pair(resourcesManager.get().getString(R.string.VGA), 1))
resolutions.add(Pair(resourcesManager.get().getString(R.string.QVGA), 2))
callSettings = settingsManager.loadCallSettings()
currentUser = userManager.getCurrentUser()
}
override fun onStartView() {
if (!chatManager.isLoggedInChat()) {
loginToChat()
}
}
override fun onStopApp() {
chatManager.destroyChat()
}
private fun loginToChat() {
currentUser?.let {
chatManager.loginToChat(it, object : DomainCallback<Unit, Exception> {
override fun onSuccess(result: Unit, bundle: Bundle?) {
// empty
}
override fun onError(error: Exception) {
// empty
}
})
} ?: run {
liveData.setValue(Pair(ViewState.SHOW_LOGIN_SCREEN, null))
}
}
fun getResolutions(): List<Pair<String, Int>> {
return resolutions
}
override fun onPauseView() {
callSettings?.let { settingsManager.saveCallSettings(it) }
}
} | bsd-3-clause | 673b78720c0582b8759aeb7c85b57197 | 36.643836 | 132 | 0.691664 | 4.711835 | false | false | false | false |
sys1yagi/mastodon4j | mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/entity/Attachment.kt | 1 | 713 | package com.sys1yagi.mastodon4j.api.entity
import com.google.gson.annotations.SerializedName
/**
* see more https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#attachment
*/
class Attachment(
@SerializedName("id") val id: Long = 0L,
@SerializedName("type") val type: String = Type.Image.value,
@SerializedName("url") val url: String = "",
@SerializedName("remote_url") val remoteUrl: String? = null,
@SerializedName("preview_url") val previewUrl: String = "",
@SerializedName("text_url") val textUrl: String? = null) {
enum class Type(val value: String) {
Image("image"),
Video("video"),
Gifv("gifv")
}
}
| mit | 5b6e0735b121821ce54429d54ce071de | 34.65 | 98 | 0.645161 | 3.732984 | false | false | false | false |
Light-Team/ModPE-IDE-Source | languages/language-shell/src/main/kotlin/com/brackeys/ui/language/shell/styler/ShellStyler.kt | 1 | 8636 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.language.shell.styler
import android.util.Log
import com.brackeys.ui.language.base.model.SyntaxScheme
import com.brackeys.ui.language.base.span.StyleSpan
import com.brackeys.ui.language.base.span.SyntaxHighlightSpan
import com.brackeys.ui.language.base.styler.LanguageStyler
import com.brackeys.ui.language.base.utils.StylingResult
import com.brackeys.ui.language.base.utils.StylingTask
import com.brackeys.ui.language.shell.lexer.ShellLexer
import com.brackeys.ui.language.shell.lexer.ShellToken
import java.io.IOException
import java.io.StringReader
import java.util.regex.Pattern
class ShellStyler private constructor() : LanguageStyler {
companion object {
private const val TAG = "ShellStyler"
private val METHOD = Pattern.compile("(\\w+\\s*\\w*)\\(\\)\\s*\\{")
private var shellStyler: ShellStyler? = null
fun getInstance(): ShellStyler {
return shellStyler ?: ShellStyler().also {
shellStyler = it
}
}
}
private var task: StylingTask? = null
override fun execute(sourceCode: String, syntaxScheme: SyntaxScheme): List<SyntaxHighlightSpan> {
val syntaxHighlightSpans = mutableListOf<SyntaxHighlightSpan>()
val sourceReader = StringReader(sourceCode)
val lexer = ShellLexer(sourceReader)
val matcher = METHOD.matcher(sourceCode)
matcher.region(0, sourceCode.length)
while (matcher.find()) {
val styleSpan = StyleSpan(syntaxScheme.methodColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, matcher.start(), matcher.end())
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
while (true) {
try {
when (lexer.advance()) {
ShellToken.INTEGER_LITERAL,
ShellToken.DOUBLE_LITERAL -> {
val styleSpan = StyleSpan(syntaxScheme.numberColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
ShellToken.BREAK,
ShellToken.CASE,
ShellToken.CONTINUE,
ShellToken.ECHO,
ShellToken.ESAC,
ShellToken.EVAL,
ShellToken.ELIF,
ShellToken.ELSE,
ShellToken.EXIT,
ShellToken.EXEC,
ShellToken.EXPORT,
ShellToken.DONE,
ShellToken.DO,
ShellToken.FI,
ShellToken.FOR,
ShellToken.IN,
ShellToken.FUNCTION,
ShellToken.IF,
ShellToken.SET,
ShellToken.SELECT,
ShellToken.SHIFT,
ShellToken.TRAP,
ShellToken.THEN,
ShellToken.ULIMIT,
ShellToken.UMASK,
ShellToken.UNSET,
ShellToken.UNTIL,
ShellToken.WAIT,
ShellToken.WHILE,
ShellToken.LET,
ShellToken.LOCAL,
ShellToken.READ,
ShellToken.READONLY,
ShellToken.RETURN,
ShellToken.TEST -> {
val styleSpan = StyleSpan(syntaxScheme.keywordColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
ShellToken.TRUE,
ShellToken.FALSE -> {
val styleSpan = StyleSpan(syntaxScheme.langConstColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
ShellToken.MULTEQ,
ShellToken.DIVEQ,
ShellToken.MODEQ,
ShellToken.PLUSEQ,
ShellToken.MINUSEQ,
ShellToken.SHIFT_RIGHT_EQ,
ShellToken.SHIFT_LEFT_EQ,
ShellToken.BIT_AND_EQ,
ShellToken.BIT_OR_EQ,
ShellToken.BIT_XOR_EQ,
ShellToken.NOTEQ,
ShellToken.EQEQ,
ShellToken.REGEXP,
ShellToken.GTEQ,
ShellToken.LTEQ,
ShellToken.PLUS_PLUS,
ShellToken.MINUS_MINUS,
ShellToken.EXPONENT,
ShellToken.BANG,
ShellToken.TILDE,
ShellToken.PLUS,
ShellToken.MINUS,
ShellToken.MULT,
ShellToken.DIV,
ShellToken.MOD,
ShellToken.SHIFT_LEFT,
ShellToken.SHIFT_RIGHT,
ShellToken.LT,
ShellToken.GT,
ShellToken.AND_AND,
ShellToken.OR_OR,
ShellToken.AND,
ShellToken.XOR,
ShellToken.OR,
ShellToken.DOLLAR,
ShellToken.EQ,
ShellToken.BACKTICK,
ShellToken.QUEST,
ShellToken.COLON,
ShellToken.LPAREN,
ShellToken.RPAREN,
ShellToken.LBRACE,
ShellToken.RBRACE,
ShellToken.LBRACK,
ShellToken.RBRACK,
ShellToken.EVAL_CONTENT -> {
val styleSpan = StyleSpan(syntaxScheme.operatorColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
ShellToken.SEMICOLON,
ShellToken.COMMA,
ShellToken.DOT -> {
continue // skip
}
ShellToken.SHEBANG,
ShellToken.COMMENT -> {
val styleSpan = StyleSpan(syntaxScheme.commentColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
ShellToken.DOUBLE_QUOTED_STRING,
ShellToken.SINGLE_QUOTED_STRING -> {
val styleSpan = StyleSpan(syntaxScheme.stringColor)
val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd)
syntaxHighlightSpans.add(syntaxHighlightSpan)
}
ShellToken.IDENTIFIER,
ShellToken.WHITESPACE,
ShellToken.BAD_CHARACTER -> {
continue
}
ShellToken.EOF -> {
break
}
}
} catch (e: IOException) {
Log.e(TAG, e.message, e)
break
}
}
return syntaxHighlightSpans
}
override fun enqueue(sourceCode: String, syntaxScheme: SyntaxScheme, stylingResult: StylingResult) {
task?.cancelTask()
task = StylingTask(
doAsync = { execute(sourceCode, syntaxScheme) },
onSuccess = stylingResult
)
task?.executeTask()
}
override fun cancel() {
task?.cancelTask()
task = null
}
} | apache-2.0 | eab45447e38110879b5e1619fc8e68b8 | 39.172093 | 114 | 0.523969 | 5.291667 | false | false | false | false |
BjoernPetersen/JMusicBot | src/main/kotlin/net/bjoernpetersen/musicbot/api/plugin/NamedPlugin.kt | 1 | 1362 | package net.bjoernpetersen.musicbot.api.plugin
import net.bjoernpetersen.musicbot.spi.plugin.Plugin
import net.bjoernpetersen.musicbot.spi.plugin.UserFacing
import kotlin.reflect.KClass
/**
* Static, serializable representation of a [user-facing][UserFacing] plugin.
*
* @param id the qualified name of the plugin's [ID base][IdBase]
* @param name the plugin's [subject][UserFacing.subject]
*/
data class NamedPlugin<out T>(
val id: String,
val name: String
) where T : Plugin, T : UserFacing {
/**
* Convenience constructor to create an instance using the ID base class.
*
* @param idClass ID base class
* @param name the plugin's [subject][UserFacing.subject]
*/
constructor(idClass: KClass<out T>, name: String) : this(idClass.java.name, name)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is NamedPlugin<*>) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
}
/**
* Creates a NamedPlugin for this plugin instance. Only works for active plugins (with ID).
*/
fun <T> T.toNamedPlugin(): NamedPlugin<T> where T : Plugin, T : UserFacing {
val id = id.qualifiedName
val subject = subject
return NamedPlugin(id = id, name = subject)
}
| mit | 5ce7bedb4e7967c7c38a73345199afaf | 27.978723 | 91 | 0.673275 | 3.880342 | false | false | false | false |
michalkowol/kotlin-spring-boot-template | src/main/kotlin/com/michalkowol/errors.kt | 1 | 1614 | package com.michalkowol
import java.io.PrintWriter
import java.io.StringWriter
import java.net.HttpURLConnection.*
import java.util.*
internal interface ServerError {
val status: Int
val code: String
val id: UUID
val message: String?
}
internal class NotFound(
override val message: String,
override val status: Int = HTTP_NOT_FOUND,
override val code: String = "NF",
override val id: UUID = UUID.randomUUID()
) : ServerError
internal class InternalServerError(
override val message: String?,
val stackTrace: String? = null,
override val status: Int = HTTP_INTERNAL_ERROR,
override val code: String = "IE",
override val id: UUID = UUID.randomUUID()
) : ServerError {
companion object {
fun create(ex: Exception): InternalServerError {
return InternalServerError(ex.message, Errors.extractStackTrace(ex))
}
}
}
internal class BadRequest(
override val message: String,
override val status: Int = HTTP_BAD_REQUEST,
override val code: String = "BR",
override val id: UUID = UUID.randomUUID()
) : ServerError
internal class NotFoundException(override val message: String, cause: Throwable? = null) : RuntimeException(message, cause)
internal class BadRequestException(override val message: String, cause: Throwable? = null) : RuntimeException(message, cause)
private object Errors {
internal fun extractStackTrace(throwable: Throwable): String {
val errorMsgWriter = StringWriter()
throwable.printStackTrace(PrintWriter(errorMsgWriter))
return errorMsgWriter.toString()
}
}
| isc | 0dd79d876a6b197155b12d6e9bc83ab3 | 28.888889 | 125 | 0.713135 | 4.39782 | false | false | false | false |
whoww/SneakPeek | app/src/main/java/de/sneakpeek/ui/main/fragment/StatisticsFragment.kt | 1 | 6512 | package de.sneakpeek.ui.main.fragment
import android.app.Activity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IValueFormatter
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import de.sneakpeek.R
import de.sneakpeek.data.SneakPeekDatabaseHelper
import de.sneakpeek.util.inflate
import de.sneakpeek.util.resolveColor
import kotlinx.android.synthetic.main.fragment_statistics.*
class StatisticsFragment : Fragment() {
private val actual_movies: TextView by lazy { fragment_statistics_actual_movies }
private val studios_number: TextView by lazy { fragment_statistics_studios_number }
private val total_predictions: TextView by lazy { fragment_statistics_total_predictions }
private val unique_predictions: TextView by lazy { fragment_statistics_unique_predictions }
private val statistics_chart: LineChart by lazy { fragment_statistics_chart }
private val graphColor by lazy { (context as Activity).theme.resolveColor(R.attr.graphColor) }
private val graphColorAccumulated by lazy { (context as Activity).theme.resolveColor(R.attr.graphColorAccumulated) }
private val textColor by lazy { (context as Activity).theme.resolveColor(R.attr.graphTextColor) }
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return container?.inflate(R.layout.fragment_statistics)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupChart()
}
fun setupChart() {
val (stats, statistics) = calcStatistic()
if (statistics.numberOfMovies == -1) {
return
}
actual_movies.text = "${statistics.numberOfMovies}"
studios_number.text = "${statistics.numberOfStudios}"
total_predictions.text = "${statistics.numberOfPredictions}"
unique_predictions.text = "${statistics.numberOfUniquePredictions}"
val entries = stats.map { it.toFloat() / statistics.numberOfMovies }.mapIndexed { index, i -> Entry(index.toFloat() + 1, i) }
val dataSet = LineDataSet(entries, getString(R.string.statistic_fragment_distribution_description));
dataSet.valueFormatter = IValueFormatter { value, _, _, _ -> String.format("%.1f%%", value * 100) }
dataSet.color = graphColor
dataSet.setCircleColor(graphColor)
dataSet.valueTextColor = textColor
var sum = 0
val accumulated = IntArray(entries.size)
for (i in 0..entries.lastIndex) {
sum += stats[i]
accumulated[i] = sum
}
val cumulativeDistribution = accumulated.map { it.toFloat() / statistics.numberOfMovies }.mapIndexed { index, i -> Entry(index.toFloat() + 1, i) }
val dataSetCumulative = LineDataSet(cumulativeDistribution, getString(R.string.statistic_fragment_cumulative_distribution_description))
dataSetCumulative.valueFormatter = IValueFormatter { value, _, _, _ -> String.format("%.1f%%", value * 100) }
dataSetCumulative.color = graphColorAccumulated
dataSetCumulative.setCircleColor(graphColorAccumulated)
dataSetCumulative.valueTextColor = textColor
statistics_chart.xAxis?.position = XAxis.XAxisPosition.BOTTOM
statistics_chart.xAxis?.isGranularityEnabled = true
statistics_chart.xAxis?.granularity = 1f
statistics_chart.xAxis?.mAxisMaximum = stats.size.toFloat()
statistics_chart.axisRight?.isEnabled = false
statistics_chart.xAxis?.labelCount = 15
statistics_chart.xAxis.textColor = textColor
statistics_chart.axisLeft.textColor = textColor
statistics_chart.legend?.isEnabled = true
statistics_chart.legend?.isWordWrapEnabled = true
statistics_chart.legend?.textSize = 14f
statistics_chart.legend?.textColor = textColor
val dataSets = ArrayList<ILineDataSet>()
dataSets.add(dataSet)
dataSets.add(dataSetCumulative)
statistics_chart.data = LineData(dataSets)
statistics_chart.description?.isEnabled = false
statistics_chart.invalidate()
}
/**
* Returns an array with the number of correct predictions and the number of sneaks
*/
private fun calcStatistic(): Pair<IntArray, SneakStatistics> {
val predictions = SneakPeekDatabaseHelper.GetInstance(context).getMoviePredictions().reversed()
val actualMovies = SneakPeekDatabaseHelper.GetInstance(context).getActualMovies()
if (actualMovies.isEmpty()) {
return Pair(kotlin.IntArray(0), SneakStatistics())
}
val correctPrediction = IntArray(predictions.map { it.movies.size }.max() ?: 15)
val datasetSize = Math.min(actualMovies.lastIndex, predictions.lastIndex)
for (i in 0..datasetSize) {
val prediction = predictions[i]
val movie = actualMovies[i]
var indexOfCorrectPrediction = prediction.movies.find { it.title == movie.title }?.position ?: -1
indexOfCorrectPrediction -= 1
if (indexOfCorrectPrediction != -2) {
correctPrediction[indexOfCorrectPrediction] += 1
}
}
val numberOfStudios = SneakPeekDatabaseHelper.GetInstance(context).getStudios().size
val numberOfPredictions = predictions.map { it.movies }.map { it.size }.sum()
val numberOfUniquePredictions = predictions.flatMap { it.movies }.distinctBy { it.title }.size
return Pair(correctPrediction,
SneakStatistics(datasetSize, numberOfStudios, numberOfPredictions, numberOfUniquePredictions))
}
companion object {
fun newInstance(): StatisticsFragment {
return StatisticsFragment()
}
}
data class SneakStatistics(val numberOfMovies: Int = -1,
val numberOfStudios: Int = -1,
val numberOfPredictions: Int = -1,
val numberOfUniquePredictions: Int = -1)
} | mit | 1ffa0610b2b1bcaf808dee3687da82b7 | 41.292208 | 154 | 0.697942 | 4.631579 | false | false | false | false |
isuPatches/WiseFy | wisefy/src/androidTest/java/com/isupatches/wisefy/GetFrequencyTests.kt | 1 | 6469 | package com.isupatches.wisefy
import android.net.wifi.WifiInfo
import android.os.Build
import com.isupatches.wisefy.callbacks.GetFrequencyCallbacks
import com.isupatches.wisefy.constants.MISSING_PARAMETER
import com.isupatches.wisefy.internal.base.BaseInstrumentationTest
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Assume
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.after
import org.mockito.Mockito.mock
import org.mockito.Mockito.timeout
import org.mockito.Mockito.verify
/**
* Tests the ability to retrieve a network's frequency.
*
* @author Patches
* @since 3.0
*/
internal class GetFrequencyTests : BaseInstrumentationTest() {
@Before
fun setup() {
Assume.assumeTrue(
"Can only run on API Level 21 or newer",
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
)
}
@Test
fun sync_getFrequency_currentNetwork_failure() {
mockWiseFyPrechecksUtil.getFrequency_success()
mockWiseFyPrechecksUtil.getCurrentNetwork_success()
mockNetworkUtil.currentNetwork_null()
assertEquals(null, wisefy.getFrequency())
verificationUtil.triedToGetCurrentNetwork()
}
@Test
fun sync_getFrequency_currentNetwork_success() {
mockWiseFyPrechecksUtil.getFrequency_success()
mockWiseFyPrechecksUtil.getCurrentNetwork_success()
val wifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
val frequency = wisefy.getFrequency()
if (frequency != null) {
assertEquals(TEST_NETWORK_FREQUENCY_24GHZ.toLong(), frequency.toLong())
verificationUtil.triedToGetCurrentNetwork()
verify(wifiInfo, timeout(VERIFICATION_SUCCESS_TIMEOUT)).frequency
} else {
fail()
}
}
@Test
fun sync_getFrequency_failure_prechecks() {
mockWiseFyPrechecksUtil.getFrequency_failure()
assertEquals(null, wisefy.getFrequency())
verificationUtil.didNotTryToGetCurrentNetwork()
}
@Test
fun async_getFrequency_currentNetwork_failure() {
mockWiseFyPrechecksUtil.getFrequency_success()
mockWiseFyPrechecksUtil.getCurrentNetwork_success()
mockNetworkUtil.currentNetwork_null()
val mockCallbacks = mock(GetFrequencyCallbacks::class.java)
wisefy.getFrequency(mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).failureGettingFrequency()
verificationUtil.triedToGetCurrentNetwork()
}
@Test
fun async_getFrequency_currentNetwork_failure_nullCallback() {
mockWiseFyPrechecksUtil.getFrequency_success()
mockWiseFyPrechecksUtil.getCurrentNetwork_success()
mockNetworkUtil.currentNetwork_null()
nullCallbackUtil.callGetFrequency()
verificationUtil.triedToGetCurrentNetwork()
}
@Test
fun async_getFrequency_currentNetwork_success() {
mockWiseFyPrechecksUtil.getFrequency_success()
mockWiseFyPrechecksUtil.getCurrentNetwork_success()
val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
val mockCallbacks = mock(GetFrequencyCallbacks::class.java)
wisefy.getFrequency(mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
verificationUtil.triedToGetCurrentNetwork()
verify(mockWifiInfo, timeout(VERIFICATION_SUCCESS_TIMEOUT)).frequency
}
@Test
fun async_getFrequency_currentNetwork_success_nullCallback() {
mockWiseFyPrechecksUtil.getFrequency_success()
mockWiseFyPrechecksUtil.getCurrentNetwork_success()
mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
nullCallbackUtil.callGetFrequency()
verificationUtil.triedToGetCurrentNetwork()
}
@Test
fun async_getFrequency_failure_prechecks() {
mockWiseFyPrechecksUtil.getFrequency_failure()
val mockCallbacks = mock(GetFrequencyCallbacks::class.java)
wisefy.getFrequency(mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER)
verificationUtil.didNotTryToGetCurrentNetwork()
}
@Test
fun async_getFrequency_failure_prechecks_nullCallback() {
mockWiseFyPrechecksUtil.getFrequency_failure()
nullCallbackUtil.callGetFrequency()
verificationUtil.didNotTryToGetCurrentNetwork()
}
@Test
fun sync_getFrequency_networkProvided_failure() {
mockNetworkUtil.currentNetwork_null()
assertEquals(null, wisefy.getFrequency(null as? WifiInfo?))
}
@Test
fun sync_getFrequency_networkProvided_success() {
val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
val frequency = wisefy.getFrequency(mockWifiInfo)
if (frequency != null) {
assertEquals(TEST_NETWORK_FREQUENCY_24GHZ.toLong(), frequency.toLong())
} else {
fail()
}
}
@Test
fun async_getFrequency_networkProvided_failure() {
mockNetworkUtil.currentNetwork_null()
val mockCallbacks = mock(GetFrequencyCallbacks::class.java)
wisefy.getFrequency(null, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER)
}
@Test
fun async_getFrequency_networkProvided_failure_nullCallback() {
mockNetworkUtil.currentNetwork_null()
nullCallbackUtil.callGetFrequency_networkProvided(null)
}
@Test
fun async_getFrequency_networkProvided_success() {
val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
val mockCallbacks = mock(GetFrequencyCallbacks::class.java)
wisefy.getFrequency(mockWifiInfo, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
verify(mockWifiInfo, timeout(VERIFICATION_SUCCESS_TIMEOUT)).frequency
}
@Test
fun async_getFrequency_networkProvided_success_nullCallback() {
val mockWifiInfo = mockNetworkUtil.networkWithFrequency(TEST_NETWORK_FREQUENCY_24GHZ)
nullCallbackUtil.callGetFrequency_networkProvided(mockWifiInfo)
verify(mockWifiInfo, after(VERIFICATION_FAILURE_TIMEOUT).times(0)).frequency
}
}
| apache-2.0 | f1f960c0c982ef3f13640e56957e7960 | 37.505952 | 117 | 0.728242 | 4.991512 | false | true | false | false |
mayank408/susi_android | app/src/main/java/org/fossasia/susi/ai/settings/SettingsActivity.kt | 1 | 2245 | package org.fossasia.susi.ai.settings
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.helper.Constant
import org.fossasia.susi.ai.helper.PrefManager
import org.fossasia.susi.ai.login.LoginActivity
import android.content.Intent
import org.fossasia.susi.ai.chat.ChatActivity
import org.fossasia.susi.ai.settings.contract.ISettingsPresenter
import org.fossasia.susi.ai.settings.contract.ISettingsView
/**
* <h1>The Settings activity.</h1>
* <h2>This activity is used to set Preferences into the app.</h2>
*
* Created by mayanktripathi on 07/07/17.
*/
class SettingsActivity : AppCompatActivity(), ISettingsView {
var settingsPresenter: ISettingsPresenter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (PrefManager.getTheme() == Constant.DARK) {
setTheme(R.style.PreferencesThemeDark)
} else {
setTheme(R.style.PreferencesThemeLight)
}
setContentView(R.layout.activity_settings)
}
override fun showAlert(activity: FragmentActivity) {
val builder = AlertDialog.Builder(activity)
builder.setTitle(Constant.CHANGE_SERVER)
builder.setMessage(Constant.SERVER_CHANGE_PROMPT)
.setCancelable(false)
.setNegativeButton(Constant.CANCEL, null)
.setPositiveButton(activity.getString(R.string.ok)) { dialog, _ ->
settingsPresenter?.deleteMsg()
val intent = Intent(activity, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
activity.startActivity(intent)
dialog.dismiss()
}
val alert = builder.create()
alert.show()
}
override fun onBackPressed() {
super.finish()
val intent = Intent(this@SettingsActivity, ChatActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
}
| apache-2.0 | 13a83abd20696597f1a71a90c1d60850 | 35.209677 | 99 | 0.685969 | 4.367704 | false | false | false | false |
Devifish/ReadMe | app/src/main/java/cn/devifish/readme/view/module/bookshelf/BookshelfFragment.kt | 1 | 1373 | package cn.devifish.readme.view.module.bookshelf
import android.support.v7.widget.GridLayoutManager
import android.view.View
import cn.devifish.readme.R
import cn.devifish.readme.view.adapter.BookshelfRecyclerAdapter
import cn.devifish.readme.view.base.MainPageFragment
import kotlinx.android.synthetic.main.page_bookshelf_main.view.*
/**
* Created by zhang on 2017/6/3.
* 书架Fragment
*/
class BookshelfFragment : MainPageFragment() {
private val title = "书架"
private val adapter: BookshelfRecyclerAdapter = BookshelfRecyclerAdapter()
override fun bindLayout(): Int = R.layout.page_bookshelf_main
override fun getTitle(): String = this.title
override fun initVar() {}
override fun initView(view: View) {
view.refresh.setOnRefreshListener(this)
view.refresh.setColorSchemeResources(
android.R.color.holo_blue_light,
android.R.color.holo_orange_light,
android.R.color.holo_green_light,
android.R.color.holo_red_light)
view.rv_bookshelf.layoutManager = GridLayoutManager(context, 3)
view.rv_bookshelf.adapter = adapter
adapter.setOnItemClickListener(this)
}
override fun onRefresh() {}
override fun onItemClick(view: View, position: Int) {
}
override fun onItemLongClick(view: View, position: Int) {
}
} | apache-2.0 | ff97b5639758d7a9ac7a461f324fcabb | 29.355556 | 78 | 0.705495 | 4.187117 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/MandateTextUI.kt | 1 | 944 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.stripe.android.ui.core.paymentsColors
@Composable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun MandateTextUI(
element: MandateTextElement
) {
Text(
text = stringResource(element.stringResId, element.merchantName ?: ""),
style = MaterialTheme.typography.body2,
color = MaterialTheme.paymentsColors.subtitle,
modifier = Modifier
.padding(vertical = 8.dp)
.semantics(mergeDescendants = true) {} // makes it a separate accessibile item
)
}
| mit | db7f45a0dda9d9c2674d3dedbbf13f13 | 33.962963 | 90 | 0.768008 | 4.35023 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/tasks/TaskLisenerCustomAdapter.kt | 1 | 3913 | package com.github.jk1.ytplugin.tasks
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.timeTracker.OnTaskSwitchingTimerDialog
import com.github.jk1.ytplugin.timeTracker.OpenActiveTaskSelection
import com.github.jk1.ytplugin.timeTracker.TrackerNotification
import com.github.jk1.ytplugin.timeTracker.actions.SaveTrackerAction
import com.github.jk1.ytplugin.timeTracker.actions.StartTrackerAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import com.intellij.tasks.LocalTask
import com.intellij.tasks.TaskListener
import com.github.jk1.ytplugin.logger
class TaskListenerCustomAdapter(override val project: Project) : TaskListener, ComponentAware {
private val note = "To start using time tracking please select active task on the toolbar" +
" or by pressing Shift + Alt + T"
private val trackerNote = TrackerNotification()
override fun taskDeactivated(task: LocalTask) {
try {
taskManagerComponent.getActiveYouTrackTask()
} catch (e: NoActiveYouTrackTaskException) {
logger.debug(e)
if (timeTrackerComponent.isAutoTrackingEnabled || timeTrackerComponent.isManualTrackingEnabled) {
trackerNote.notifyWithHelper(note, NotificationType.INFORMATION, OpenActiveTaskSelection())
}
}
}
override fun taskActivated(task: LocalTask) {
try {
// split cases of vcs commit and branch switching in manual/none mode
if (!timeTrackerComponent.isAutoTrackingEnabled) {
if (timeTrackerComponent.isRunning){
timeTrackerComponent.pause("Work timer paused")
}
val savedTimeStorage = ComponentAware.of(project).spentTimePerTaskStorage
savedTimeStorage.setSavedTimeForLocalTask(timeTrackerComponent.issueId, timeTrackerComponent.timeInMills)
timeTrackerComponent.resetTimeOnly()
timeTrackerComponent.updateIdOnTaskSwitching()
}
timeTrackerComponent.isAutoTrackingTemporaryDisabled = false
// do not start auto tracking in case of invalid task
try {
taskManagerComponent.getActiveYouTrackTask()
StartTrackerAction().startAutomatedTracking(project, timeTrackerComponent)
} catch (e: NoActiveYouTrackTaskException) {
timeTrackerComponent.stop()
logger.info("Task ${ComponentAware.of(project).taskManagerComponent.getActiveTask().id} is not valid")
}
logger.debug("Switch from: ${spentTimePerTaskStorage.getSavedTimeForLocalTask(timeTrackerComponent.issueId)}")
if (spentTimePerTaskStorage.getSavedTimeForLocalTask(task.id) > 0){
OnTaskSwitchingTimerDialog(project, taskManagerComponent.getActiveYouTrackRepository()).show()
}
} catch (e: NoYouTrackRepositoryException){
logger.debug(e)
}
}
override fun taskAdded(task: LocalTask) {
// the second and third conditions are required for the post on vcs commit functionality - it is disabled in manual tracking
// mode, but taskAdded triggers on git action 9with the same task) and thus timer is stopped even in manual mode.
// However, we still want to post/save time on task switching in manual mode so saveTime call is also triggered there
if (timeTrackerComponent.isRunning && timeTrackerComponent.isAutoTrackingEnabled &&
combineTaskIdAndSummary(taskManagerComponent.getActiveTask()) != task.summary) {
SaveTrackerAction().saveTimer(project, taskManagerComponent.getActiveTask().id)
}
}
private fun combineTaskIdAndSummary(task: LocalTask) = "${task.id} ${task.summary}"
override fun taskRemoved(task: LocalTask) {
}
} | apache-2.0 | 686358e2aa9c34fb7efb2f8a50fe3538 | 43.477273 | 132 | 0.706108 | 4.842822 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/SetMutableIntention.kt | 2 | 1586 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsRefLikeType
import org.rust.lang.core.psi.RsTypeReference
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.isRef
import org.rust.lang.core.psi.ext.mutability
/**
* Set reference mutable
*
* ```
* &type
* ```
*
* to this:
*
* ```
* &mut type
* ```
*/
open class SetMutableIntention : RsElementBaseIntentionAction<SetMutableIntention.Context>() {
override fun getText() = "Set reference mutable"
override fun getFamilyName() = text
open val mutable = true
data class Context(
val refType: RsRefLikeType,
val referencedType: RsTypeReference
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val refType = element.ancestorStrict<RsRefLikeType>() ?: return null
if (!refType.isRef) return null
val referencedType = refType.typeReference ?: return null
if (refType.mutability.isMut == mutable) return null
return Context(refType, referencedType)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val newType = RsPsiFactory(project).createReferenceType(ctx.referencedType.text, mutable)
ctx.refType.replace(newType)
}
}
| mit | 0d5ee6c0a2053902c2a8e453653f1def | 27.836364 | 105 | 0.715006 | 4.098191 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/psi/ProcMacroAttributeTest.kt | 2 | 12653 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.intellij.lang.annotations.Language
import org.rust.*
import org.rust.ide.experiments.RsExperiments.ATTR_PROC_MACROS
import org.rust.ide.experiments.RsExperiments.DERIVE_PROC_MACROS
import org.rust.ide.experiments.RsExperiments.EVALUATE_BUILD_SCRIPTS
import org.rust.ide.experiments.RsExperiments.PROC_MACROS
import org.rust.lang.core.psi.ProcMacroAttributeTest.TestProcMacroAttribute.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.stubs.RsAttrProcMacroOwnerStub
import org.rust.stdext.singleOrFilter
/**
* A test for detecting proc macro attributes on items. See [ProcMacroAttribute]
*/
@ProjectDescriptor(WithProcMacroRustProjectDescriptor::class)
@WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, PROC_MACROS)
class ProcMacroAttributeTest : RsTestBase() {
fun `test inline mod`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
mod foo {}
""", Attr("attr_as_is", 0))
fun `test mod declaration is not a macro`() = checkNotAProcMacroOwner("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
mod foo;
""")
fun `test fn`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
fn foo() {}
""", Attr("attr_as_is", 0))
fun `test const`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
const C: i32 = 0;
""", Attr("attr_as_is", 0))
fun `test static`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
static S: i32 = 0;
""", Attr("attr_as_is", 0))
fun `test struct`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
struct S;
""", Attr("attr_as_is", 0))
fun `test union`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
union U {}
""", Attr("attr_as_is", 0))
fun `test enum`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
enum E {}
""", Attr("attr_as_is", 0))
fun `test trait`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
trait T {}
""", Attr("attr_as_is", 0))
fun `test trait alias`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
trait T = Foo;
""", Attr("attr_as_is", 0))
fun `test type alias`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
type T = i32;
""", Attr("attr_as_is", 0))
fun `test impl`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
impl Foo {}
""", Attr("attr_as_is", 0))
fun `test use`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
use foo::bar;
""", Attr("attr_as_is", 0))
fun `test extern block`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
extern {}
""", Attr("attr_as_is", 0))
fun `test extern crate`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
extern crate foo;
""", Attr("attr_as_is", 0))
fun `test macro_rules`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
macro_rules! foo {}
""", Attr("attr_as_is", 0))
fun `test macro 2`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
macro foo() {}
""", Attr("attr_as_is", 0))
fun `test macro call`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
foo!();
""", Attr("attr_as_is", 0))
fun `test enum variant is not a macro`() = checkNotAProcMacroOwner("""
use test_proc_macros::attr_as_is;
enum E { #[attr_as_is] A }
""")
fun `test type parameter is not a macro`() = checkNotAProcMacroOwner("""
use test_proc_macros::attr_as_is;
fn foo<#[attr_as_is] T>() {}
""")
fun `test struct field is not a macro`() = checkNotAProcMacroOwner("""
use test_proc_macros::attr_as_is;
struct S {
#[attr_as_is]
field: i32
}
""")
fun `test code block is not a macro`() = checkNotAProcMacroOwner("""
use test_proc_macros::attr_as_is;
fn foo() {
#[attr_as_is]
{
};
}
""")
fun `test empty attr is not a macro`() = doTest("""
#[()]
struct S;
""", None)
fun `test built-in attribute is not a macro`() = doTest("""
#[allow()]
struct S;
""", None)
fun `test inner attribute is not a macro`() = doTest("""
use test_proc_macros::attr_as_is;
fn foo() {
#![attr_as_is]
}
""", None)
fun `test rustfmt is not a macro 1`() = doTest("""
#[rustfmt::foo]
struct S;
""", None)
fun `test rustfmt is not a macro 2`() = doTest("""
#[rustfmt::foo::bar]
struct S;
""", None)
fun `test clippy is not a macro 1`() = doTest("""
#[clippy::foo]
struct S;
""", None)
fun `test clippy is not a macro 2`() = doTest("""
#[clippy::foo::bar]
struct S;
""", None)
fun `test derive`() = doTest("""
#[derive(Foo)]
struct S;
""", Derive)
fun `test macro before derive`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
#[derive(Foo)]
struct S;
""", Attr("attr_as_is", 0))
fun `test attr after derive is not a macro`() = doTest("""
use test_proc_macros::attr_as_is;
#[derive(Foo)]
#[attr_as_is]
struct S;
""", Derive)
fun `test 1 built-int attribute before macro`() = doTest("""
use test_proc_macros::attr_as_is;
#[allow()]
#[attr_as_is]
struct S;
""", Attr("attr_as_is", 1))
fun `test 2 built-int attribute before macro`() = doTest("""
use test_proc_macros::attr_as_is;
#[allow()]
#[allow()]
#[attr_as_is]
struct S;
""", Attr("attr_as_is", 2))
fun `test built-int attribute after macro`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
#[allow()]
struct S;
""", Attr("attr_as_is", 0))
fun `test only first attr is actually a macros`() = doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
#[attr_as_is]
struct S;
""", Attr("attr_as_is", 0))
@MockAdditionalCfgOptions("intellij_rust")
fun `test enabled cfg_attr is accounted 1`() = doTest("""
use test_proc_macros::attr_as_is;
#[cfg_attr(intellij_rust, attr_as_is)]
struct S;
""", Attr("attr_as_is", 0))
@MockAdditionalCfgOptions("intellij_rust")
fun `test enabled cfg_attr is accounted 2`() = doTest("""
use test_proc_macros::attr_as_is;
#[cfg_attr(intellij_rust, allow(), attr_as_is)]
struct S;
""", Attr("attr_as_is", 1))
@MockAdditionalCfgOptions("intellij_rust")
fun `test enabled cfg_attr is accounted 3`() = doTest("""
use test_proc_macros::attr_as_is;
#[cfg_attr(intellij_rust, allow())]
#[attr_as_is]
struct S;
""", Attr("attr_as_is", 1))
@MockAdditionalCfgOptions("intellij_rust")
fun `test disabled cfg_attr is not accounted 1`() = doTest("""
use test_proc_macros::attr_as_is;
#[cfg_attr(not(intellij_rust), attr_as_is)]
struct S;
""", None)
@MockAdditionalCfgOptions("intellij_rust")
fun `test disabled cfg_attr is not accounted 2`() = doTest("""
use test_proc_macros::attr_as_is;
#[cfg_attr(not(intellij_rust), allow())]
#[attr_as_is]
struct S;
""", Attr("attr_as_is", 0))
fun `test custom attribute is not a macro 1`() = doTest("""
#![register_attr(attr_as_is)]
use test_proc_macros::attr_as_is;
#[attr_as_is]
struct S;
""", None)
fun `test custom attribute is not a macro 2`() = doTest("""
#![register_attr(attr_as_is)]
use test_proc_macros::attr_as_is;
use test_proc_macros::attr_as_is as attr_as_is1;
#[attr_as_is]
#[attr_as_is1]
struct S;
""", Attr("attr_as_is1", 1))
fun `test custom tool is not a macro 1`() = doTest("""
#![register_tool(test_proc_macros)]
#[test_proc_macros::attr_as_is]
struct S;
""", None)
fun `test custom tool is not a macro 2`() = doTest("""
#![register_tool(attr)]
#[attr::foo::bar]
struct S;
""", None)
fun `test hardcoded identity macro`() = doTest("""
use test_proc_macros::attr_hardcoded_not_a_macro;
#[attr_hardcoded_not_a_macro]
struct S;
""", None)
fun `test hardcoded identity macro 2`() = doTest("""
use test_proc_macros::attr_hardcoded_not_a_macro;
#[attr_hardcoded_not_a_macro]
enum E {}
""", Attr("attr_hardcoded_not_a_macro", 0))
fun `test hardcoded identity macro 3`() = doTest("""
use test_proc_macros::attr_hardcoded_not_a_macro;
#[attr_hardcoded_not_a_macro]
mod m {}
""", Attr("attr_hardcoded_not_a_macro", 0))
@WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS)
fun `test not a macro if proc macro expansion is disabled`() {
setExperimentalFeatureEnabled(PROC_MACROS, false, testRootDisposable)
doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
mod foo {}
""", None)
}
@WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS)
fun `test not a macro if attr macro expansion is disabled 1`() {
setExperimentalFeatureEnabled(ATTR_PROC_MACROS, false, testRootDisposable)
doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
mod foo {}
""", None)
}
@WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, DERIVE_PROC_MACROS)
fun `test not a macro if attr macro expansion is disabled 2`() {
setExperimentalFeatureEnabled(ATTR_PROC_MACROS, false, testRootDisposable)
doTest("""
use test_proc_macros::attr_as_is;
#[attr_as_is]
#[derive(Foo)]
struct S;
""", Derive)
}
private fun doTest(@Language("Rust") code: String, expectedAttr: TestProcMacroAttribute) {
InlineFile(code)
val item = findItemWithAttrs()
check(item is RsAttrProcMacroOwner) { "${item.javaClass} must implement `RsAttrProcMacroOwner`" }
val actualAttr = (item as? RsAttrProcMacroOwner)?.procMacroAttribute?.toTestValue()
?: None
assertEquals(expectedAttr, actualAttr)
@Suppress("UNCHECKED_CAST")
val itemElementType = item.elementType as IStubElementType<*, PsiElement>
val stub = itemElementType.createStub(item, null)
if (stub is RsAttrProcMacroOwnerStub && actualAttr is Attr) {
assertEquals(item.stubbedText, stub.stubbedText)
assertEquals(item.startOffset, stub.startOffset)
assertEquals(item.endOfAttrsOffset, stub.endOfAttrsOffset)
}
}
private fun checkNotAProcMacroOwner(@Language("Rust") code: String) {
InlineFile(code)
val item = findItemWithAttrs()
check(item !is RsAttrProcMacroOwner) { "${item.javaClass} must NOT implement `RsAttrProcMacroOwner`" }
}
private fun findItemWithAttrs(): RsOuterAttributeOwner = (myFixture.file.descendantsOfType<RsOuterAttributeOwner>()
.toList()
.singleOrFilter { it.rawMetaItems.count() != 0 }
.singleOrNull()
?: error("The code snippet must contain only one item"))
private fun ProcMacroAttribute<RsMetaItem>.toTestValue() =
when (this) {
is ProcMacroAttribute.Attr -> Attr(attr.path!!.text, index)
is ProcMacroAttribute.Derive -> Derive
ProcMacroAttribute.None -> None
}
private sealed class TestProcMacroAttribute {
object None: TestProcMacroAttribute() {
override fun toString(): String = "None"
}
object Derive: TestProcMacroAttribute() {
override fun toString(): String = "Derive"
}
data class Attr(val attr: String, val index: Int): TestProcMacroAttribute()
}
}
| mit | e2408047e8c15ce41c47226fdf5426dd | 26.68709 | 119 | 0.562317 | 3.75126 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/inlineValue/RsInlineValueDialog.kt | 2 | 2285 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.inlineValue
import com.intellij.openapi.project.Project
import com.intellij.refactoring.RefactoringBundle
import org.rust.ide.refactoring.RsInlineDialog
import org.rust.stdext.capitalized
class RsInlineValueDialog(
private val context: InlineValueContext,
project: Project = context.element.project,
) : RsInlineDialog(context.element, context.reference, project) {
private val occurrencesNumber: Int = initOccurrencesNumber(context.element)
init {
init()
}
override fun doAction() {
invokeRefactoring(getProcessor())
}
private fun getProcessor(): RsInlineValueProcessor {
val mode = when {
isInlineThisOnly -> InlineValueMode.InlineThisOnly
isKeepTheDeclaration -> InlineValueMode.InlineAllAndKeepOriginal
else -> InlineValueMode.InlineAllAndRemoveOriginal
}
return RsInlineValueProcessor(project, context, mode)
}
override fun getBorderTitle(): String =
RefactoringBundle.message("inline.field.border.title")
override fun getNameLabelText(): String =
"${context.type.capitalized()} ${context.name} ${getOccurrencesText(occurrencesNumber)}"
override fun getInlineAllText(): String {
val text =
if (context.element.isWritable) {
"all.references.and.remove.the.local"
} else {
"all.invocations.in.project"
}
return RefactoringBundle.message(text)
}
override fun getInlineThisText(): String =
"Inline this only and keep the ${context.type}"
override fun getKeepTheDeclarationText(): String =
if (context.element.isWritable) {
"Inline all references and keep the ${context.type}"
} else {
super.getKeepTheDeclarationText()
}
override fun getHelpId(): String = "refactoring.inlineVariable"
}
val InlineValueContext.type: String
get() = when (this) {
is InlineValueContext.Variable -> "variable"
is InlineValueContext.Constant -> "constant"
}
val InlineValueContext.name: String
get() = this.element.name ?: ""
| mit | 987aeeaa6121a455efcb7110543c4ccd | 30.30137 | 96 | 0.675274 | 4.760417 | false | false | false | false |
google/dokka | core/src/main/kotlin/Formats/DacOutlineService.kt | 2 | 14702 | package org.jetbrains.dokka.Formats
import com.google.inject.Inject
import org.jetbrains.dokka.*
import java.net.URI
import com.google.inject.name.Named
import org.jetbrains.kotlin.cfg.pseudocode.AllTypes
interface DacOutlineFormatService {
fun computeOutlineURI(node: DocumentationNode): URI
fun format(to: Appendable, node: DocumentationNode)
}
class DacOutlineFormatter @Inject constructor(
uriProvider: JavaLayoutHtmlUriProvider,
languageService: LanguageService,
@Named("dacRoot") dacRoot: String,
@Named("generateClassIndex") generateClassIndex: Boolean,
@Named("generatePackageIndex") generatePackageIndex: Boolean
) : JavaLayoutHtmlFormatOutlineFactoryService {
val tocOutline = TocOutlineService(uriProvider, languageService, dacRoot, generateClassIndex, generatePackageIndex)
val outlines = listOf(tocOutline)
override fun generateOutlines(outputProvider: (URI) -> Appendable, nodes: Iterable<DocumentationNode>) {
for (node in nodes) {
for (outline in outlines) {
val uri = outline.computeOutlineURI(node)
val output = outputProvider(uri)
outline.format(output, node)
}
}
}
}
/**
* Outline service for generating a _toc.yaml file, responsible for pointing to the paths of each
* index.html file in the doc tree.
*/
class BookOutlineService(
val uriProvider: JavaLayoutHtmlUriProvider,
val languageService: LanguageService,
val dacRoot: String,
val generateClassIndex: Boolean,
val generatePackageIndex: Boolean
) : DacOutlineFormatService {
override fun computeOutlineURI(node: DocumentationNode): URI = uriProvider.outlineRootUri(node).resolve("_book.yaml")
override fun format(to: Appendable, node: DocumentationNode) {
appendOutline(to, listOf(node))
}
var outlineLevel = 0
/** Appends formatted outline to [StringBuilder](to) using specified [location] */
fun appendOutline(to: Appendable, nodes: Iterable<DocumentationNode>) {
if (outlineLevel == 0) to.appendln("reference:")
for (node in nodes) {
appendOutlineHeader(node, to)
val subPackages = node.members.filter {
it.kind == NodeKind.Package
}
if (subPackages.any()) {
val sortedMembers = subPackages.sortedBy { it.name.toLowerCase() }
appendOutlineLevel(to) {
appendOutline(to, sortedMembers)
}
}
}
}
fun appendOutlineHeader(node: DocumentationNode, to: Appendable) {
if (node is DocumentationModule) {
to.appendln("- title: Package Index")
to.appendln(" path: $dacRoot${uriProvider.outlineRootUri(node).resolve("packages.html")}")
to.appendln(" status_text: no-toggle")
} else {
to.appendln("- title: ${languageService.renderName(node)}")
to.appendln(" path: $dacRoot${uriProvider.mainUriOrWarn(node)}")
to.appendln(" status_text: no-toggle")
}
}
fun appendOutlineLevel(to: Appendable, body: () -> Unit) {
outlineLevel++
body()
outlineLevel--
}
}
/**
* Outline service for generating a _toc.yaml file, responsible for pointing to the paths of each
* index.html file in the doc tree.
*/
class TocOutlineService(
val uriProvider: JavaLayoutHtmlUriProvider,
val languageService: LanguageService,
val dacRoot: String,
val generateClassIndex: Boolean,
val generatePackageIndex: Boolean
) : DacOutlineFormatService {
override fun computeOutlineURI(node: DocumentationNode): URI = uriProvider.outlineRootUri(node).resolve("_toc.yaml")
override fun format(to: Appendable, node: DocumentationNode) {
appendOutline(to, listOf(node))
}
var outlineLevel = 0
/** Appends formatted outline to [StringBuilder](to) using specified [location] */
fun appendOutline(to: Appendable, nodes: Iterable<DocumentationNode>) {
if (outlineLevel == 0) to.appendln("toc:")
for (node in nodes) {
appendOutlineHeader(node, to)
val subPackages = node.members.filter {
it.kind == NodeKind.Package
}
if (subPackages.any()) {
val sortedMembers = subPackages.sortedBy { it.nameWithOuterClass() }
appendOutlineLevel {
appendOutline(to, sortedMembers)
}
}
}
}
fun appendOutlineHeader(node: DocumentationNode, to: Appendable) {
if (node is DocumentationModule) {
if (generateClassIndex) {
node.members.filter { it.kind == NodeKind.AllTypes }.firstOrNull()?.let {
to.appendln("- title: Class Index")
to.appendln(" path: $dacRoot${uriProvider.outlineRootUri(it).resolve("classes.html")}")
to.appendln()
}
}
if (generatePackageIndex) {
to.appendln("- title: Package Index")
to.appendln(" path: $dacRoot${uriProvider.outlineRootUri(node).resolve("packages.html")}")
to.appendln()
}
} else if (node.kind != NodeKind.AllTypes && !(node is DocumentationModule)) {
to.appendln("- title: ${languageService.renderName(node)}")
to.appendln(" path: $dacRoot${uriProvider.mainUriOrWarn(node)}")
to.appendln()
var addedSectionHeader = false
for (kind in NodeKind.classLike) {
val members = node.getMembersOfKinds(kind)
if (members.isNotEmpty()) {
if (!addedSectionHeader) {
to.appendln(" section:")
addedSectionHeader = true
}
to.appendln(" - title: ${kind.pluralizedName()}")
to.appendln()
to.appendln(" section:")
members.sortedBy { it.nameWithOuterClass().toLowerCase() }.forEach { member ->
to.appendln(" - title: ${languageService.renderNameWithOuterClass(member)}")
to.appendln(" path: $dacRoot${uriProvider.mainUriOrWarn(member)}".trimEnd('#'))
to.appendln()
}
}
}
to.appendln().appendln()
}
}
fun appendOutlineLevel(body: () -> Unit) {
outlineLevel++
body()
outlineLevel--
}
}
class DacNavOutlineService constructor(
val uriProvider: JavaLayoutHtmlUriProvider,
val languageService: LanguageService,
val dacRoot: String
) : DacOutlineFormatService {
override fun computeOutlineURI(node: DocumentationNode): URI =
uriProvider.outlineRootUri(node).resolve("navtree_data.js")
override fun format(to: Appendable, node: DocumentationNode) {
to.append("var NAVTREE_DATA = ").appendNavTree(node.members).append(";")
}
private fun Appendable.appendNavTree(nodes: Iterable<DocumentationNode>): Appendable {
append("[ ")
var first = true
for (node in nodes) {
if (!first) append(", ")
first = false
val interfaces = node.getMembersOfKinds(NodeKind.Interface)
val classes = node.getMembersOfKinds(NodeKind.Class)
val objects = node.getMembersOfKinds(NodeKind.Object)
val annotations = node.getMembersOfKinds(NodeKind.AnnotationClass)
val enums = node.getMembersOfKinds(NodeKind.Enum)
val exceptions = node.getMembersOfKinds(NodeKind.Exception)
append("[ \"${node.name}\", \"$dacRoot${uriProvider.tryGetMainUri(node)}\", [ ")
var needComma = false
if (interfaces.firstOrNull() != null) {
appendNavTreePagesOfKind("Interfaces", interfaces)
needComma = true
}
if (classes.firstOrNull() != null) {
if (needComma) append(", ")
appendNavTreePagesOfKind("Classes", classes)
needComma = true
}
if (objects.firstOrNull() != null) {
if (needComma) append(", ")
appendNavTreePagesOfKind("Objects", objects)
}
if (annotations.firstOrNull() != null) {
if (needComma) append(", ")
appendNavTreePagesOfKind("Annotations", annotations)
needComma = true
}
if (enums.firstOrNull() != null) {
if (needComma) append(", ")
appendNavTreePagesOfKind("Enums", enums)
needComma = true
}
if (exceptions.firstOrNull() != null) {
if (needComma) append(", ")
appendNavTreePagesOfKind("Exceptions", exceptions)
}
append(" ] ]")
}
append(" ]")
return this
}
private fun Appendable.appendNavTreePagesOfKind(kindTitle: String,
nodesOfKind: Iterable<DocumentationNode>): Appendable {
append("[ \"$kindTitle\", null, [ ")
var started = false
for (node in nodesOfKind) {
if (started) append(", ")
started = true
appendNavTreeChild(node)
}
append(" ], null, null ]")
return this
}
private fun Appendable.appendNavTreeChild(node: DocumentationNode): Appendable {
append("[ \"${node.nameWithOuterClass()}\", \"${dacRoot}${uriProvider.tryGetMainUri(node)}\"")
append(", null, null, null ]")
return this
}
}
class DacSearchOutlineService(
val uriProvider: JavaLayoutHtmlUriProvider,
val languageService: LanguageService,
val dacRoot: String
) : DacOutlineFormatService {
override fun computeOutlineURI(node: DocumentationNode): URI =
uriProvider.outlineRootUri(node).resolve("lists.js")
override fun format(to: Appendable, node: DocumentationNode) {
val pageNodes = node.getAllPageNodes()
var id = 0
to.append("var KTX_CORE_DATA = [\n")
var first = true
for (pageNode in pageNodes) {
if (pageNode.kind == NodeKind.Module) continue
if (!first) to.append(", \n")
first = false
to.append(" { " +
"id:$id, " +
"label:\"${pageNode.qualifiedName()}\", " +
"link:\"${dacRoot}${uriProvider.tryGetMainUri(pageNode)}\", " +
"type:\"${pageNode.getClassOrPackage()}\", " +
"deprecated:\"false\" }")
id++
}
to.append("\n];")
}
private fun DocumentationNode.getClassOrPackage(): String =
if (hasOwnPage())
"class"
else if (isPackage()) {
"package"
} else {
""
}
private fun DocumentationNode.getAllPageNodes(): Iterable<DocumentationNode> {
val allPageNodes = mutableListOf<DocumentationNode>()
recursiveSetAllPageNodes(allPageNodes)
return allPageNodes
}
private fun DocumentationNode.recursiveSetAllPageNodes(
allPageNodes: MutableList<DocumentationNode>) {
for (child in members) {
if (child.hasOwnPage() || child.isPackage()) {
allPageNodes.add(child)
child.qualifiedName()
child.recursiveSetAllPageNodes(allPageNodes)
}
}
}
}
/**
* Return all children of the node who are one of the selected `NodeKind`s. It recursively fetches
* all offspring, not just immediate children.
*/
fun DocumentationNode.getMembersOfKinds(vararg kinds: NodeKind): MutableList<DocumentationNode> {
val membersOfKind = mutableListOf<DocumentationNode>()
recursiveSetMembersOfKinds(kinds, membersOfKind)
return membersOfKind
}
private fun DocumentationNode.recursiveSetMembersOfKinds(kinds: Array<out NodeKind>,
membersOfKind: MutableList<DocumentationNode>) {
for (member in members) {
if (member.kind in kinds) {
membersOfKind.add(member)
}
member.recursiveSetMembersOfKinds(kinds, membersOfKind)
}
}
/**
* Returns whether or not this node owns a page. The criteria for whether a node owns a page is
* similar to the way javadoc is structured. Classes, Interfaces, Enums, AnnotationClasses,
* Exceptions, and Objects (Kotlin-specific) meet the criteria.
*/
fun DocumentationNode.hasOwnPage() =
kind == NodeKind.Class || kind == NodeKind.Interface || kind == NodeKind.Enum ||
kind == NodeKind.AnnotationClass || kind == NodeKind.Exception ||
kind == NodeKind.Object
/**
* In most cases, this returns the short name of the `Type`. When the Type is an inner Type, it
* prepends the name with the containing Type name(s).
*
* For example, if you have a class named OuterClass and an inner class named InnerClass, this would
* return OuterClass.InnerClass.
*
*/
fun DocumentationNode.nameWithOuterClass(): String {
val nameBuilder = StringBuilder(name)
var parent = owner
if (hasOwnPage()) {
while (parent != null && parent.hasOwnPage()) {
nameBuilder.insert(0, "${parent.name}.")
parent = parent.owner
}
}
return nameBuilder.toString()
}
/**
* Return whether the node is a package.
*/
fun DocumentationNode.isPackage(): Boolean {
return kind == NodeKind.Package
}
/**
* Return the 'page owner' of this node. `DocumentationNode.hasOwnPage()` defines the criteria for
* a page owner. If this node is not a page owner, then it iterates up through its ancestors to
* find the first page owner.
*/
fun DocumentationNode.pageOwner(): DocumentationNode {
if (hasOwnPage() || owner == null) {
return this
} else {
var parent: DocumentationNode = owner!!
while (!parent.hasOwnPage() && !parent.isPackage()) {
parent = parent.owner!!
}
return parent
}
}
fun NodeKind.pluralizedName() = when(this) {
NodeKind.Class -> "Classes"
NodeKind.Interface -> "Interfaces"
NodeKind.AnnotationClass -> "Annotations"
NodeKind.Enum -> "Enums"
NodeKind.Exception -> "Exceptions"
NodeKind.Object -> "Objects"
NodeKind.TypeAlias -> "TypeAliases"
else -> "${name}s"
} | apache-2.0 | aba2f40b1a61046b1981ceb870d3dc61 | 36.222785 | 121 | 0.596926 | 4.645182 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/calling-webservice/from-jvm/src/main/kotlin/org/tsdes/advanced/callingwebservice/fromjvm/OpenWeatherMap.kt | 1 | 1980 | package org.tsdes.advanced.callingwebservice.fromjvm
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import javax.ws.rs.client.ClientBuilder
import javax.ws.rs.core.UriBuilder
/**
* Another weather web service is:
* https://openweathermap.org
*
* Created by arcuri82 on 13-Jun-19.
*/
fun main(){
/*
We are going to use a third-party REST API from the network.
You need to be connected to internet to get this example working,
as we will need to connect to http://api.openweathermap.org
Furthermore, to use such API, we need to be registered as a user.
Every time we access the API, we need to send an authentication token,
representing who we are.
It is not uncommon for APIs to have "rate-limits" to the number of calls
you can do. If you want to do more calls, you need to pay.
It comes without saying that, if you want to build your own app that
does access http://api.openweathermap.org, you should register a new
user and use a different key, instead of the following.
*/
val API_KEY = "bde08c38dcc24dfbffc449466cea7e44"
//http://api.openweathermap.org/data/2.5/weather?appid=bde08c38dcc24dfbffc449466cea7e44&units=metric&q=Oslo,no
val uri = UriBuilder.fromUri("http://api.openweathermap.org/data/2.5/weather")
.port(80) // not necessary, as 80 is default anyway for http
.queryParam("appid", API_KEY)
.queryParam("units", "metric")
.queryParam("q", "Oslo,no")
.build()
val client = ClientBuilder.newClient()
val response = client.target(uri).request("application/json").get()
val result = response.readEntity(String::class.java)
println("Result as string : $result")
//just extract one element of interest
val json = JsonParser.parseString(result) as JsonObject
val temperature = json.get("main").asJsonObject.get("temp").asString
println("Temperature in Oslo: $temperature C'")
}
| lgpl-3.0 | d5579f658b183e86361c92c263ca7c46 | 35.666667 | 114 | 0.70202 | 3.837209 | false | false | false | false |
androidx/androidx | compose/ui/ui-graphics/src/skikoMain/kotlin/androidx/compose/ui/graphics/SkiaBackedRenderEffect.skiko.kt | 3 | 4912 | /*
* Copyright 2021 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.compose.ui.graphics
import androidx.compose.runtime.Immutable
import androidx.compose.ui.geometry.Offset
import org.jetbrains.skia.ImageFilter
/**
* Convert the [ImageFilter] instance into a Compose-compatible [RenderEffect]
*/
fun ImageFilter.asComposeRenderEffect(): RenderEffect =
SkiaBackedRenderEffect(this)
/**
* Intermediate rendering step used to render drawing commands with a corresponding
* visual effect. A [RenderEffect] can be configured on a [GraphicsLayerScope]
* and will be applied when drawn.
*/
@Immutable
actual sealed class RenderEffect actual constructor() {
private var internalImageFilter: ImageFilter? = null
fun asSkiaImageFilter(): ImageFilter =
internalImageFilter ?: createImageFilter().also { internalImageFilter = it }
protected abstract fun createImageFilter(): ImageFilter
/**
* Capability query to determine if the particular platform supports the [RenderEffect]. Not
* all platforms support all render effects
*/
actual open fun isSupported(): Boolean = true
}
@Immutable
internal class SkiaBackedRenderEffect(
val imageFilter: ImageFilter
) : RenderEffect() {
override fun createImageFilter(): ImageFilter = imageFilter
}
@Immutable
actual class BlurEffect actual constructor(
private val renderEffect: RenderEffect?,
private val radiusX: Float,
private val radiusY: Float,
private val edgeTreatment: TileMode
) : RenderEffect() {
override fun createImageFilter(): ImageFilter =
if (renderEffect == null) {
ImageFilter.makeBlur(
convertRadiusToSigma(radiusX),
convertRadiusToSigma(radiusY),
edgeTreatment.toSkiaTileMode()
)
} else {
ImageFilter.makeBlur(
convertRadiusToSigma(radiusX),
convertRadiusToSigma(radiusY),
edgeTreatment.toSkiaTileMode(),
renderEffect.asSkiaImageFilter(),
null
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is BlurEffect) return false
if (radiusX != other.radiusX) return false
if (radiusY != other.radiusY) return false
if (edgeTreatment != other.edgeTreatment) return false
if (renderEffect != other.renderEffect) return false
return true
}
override fun hashCode(): Int {
var result = renderEffect?.hashCode() ?: 0
result = 31 * result + radiusX.hashCode()
result = 31 * result + radiusY.hashCode()
result = 31 * result + edgeTreatment.hashCode()
return result
}
override fun toString(): String {
return "BlurEffect(renderEffect=$renderEffect, radiusX=$radiusX, radiusY=$radiusY, " +
"edgeTreatment=$edgeTreatment)"
}
companion object {
// Constant used to convert blur radius into a corresponding sigma value
// for the gaussian blur algorithm used within SkImageFilter.
// This constant approximates the scaling done in the software path's
// "high quality" mode, in SkBlurMask::Blur() (1 / sqrt(3)).
val BlurSigmaScale = 0.57735f
fun convertRadiusToSigma(radius: Float) =
if (radius > 0) {
BlurSigmaScale * radius + 0.5f
} else {
0.0f
}
}
}
@Immutable
actual class OffsetEffect actual constructor(
private val renderEffect: RenderEffect?,
private val offset: Offset
) : RenderEffect() {
override fun createImageFilter(): ImageFilter =
ImageFilter.makeOffset(offset.x, offset.y, renderEffect?.asSkiaImageFilter(), null)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is OffsetEffect) return false
if (renderEffect != other.renderEffect) return false
if (offset != other.offset) return false
return true
}
override fun hashCode(): Int {
var result = renderEffect?.hashCode() ?: 0
result = 31 * result + offset.hashCode()
return result
}
override fun toString(): String {
return "OffsetEffect(renderEffect=$renderEffect, offset=$offset)"
}
} | apache-2.0 | 41010aa0edc10b686a15d54d1f3a75aa | 31.111111 | 96 | 0.663477 | 4.552363 | false | false | false | false |
androidx/androidx | privacysandbox/tools/tools-apipackager/src/main/java/androidx/privacysandbox/tools/apipackager/PrivacySandboxApiPackager.kt | 3 | 3079 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.privacysandbox.tools.apipackager
import androidx.privacysandbox.tools.apipackager.AnnotationInspector.hasPrivacySandboxAnnotation
import java.nio.file.Path
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
import kotlin.io.path.notExists
import androidx.privacysandbox.tools.core.Metadata
import kotlin.io.path.extension
import kotlin.io.path.inputStream
class PrivacySandboxApiPackager {
/**
* Extracts API descriptors from SDKs annotated with Privacy Sandbox annotations.
*
* This function will output a file with SDK interface descriptors, which can later be used to
* generate the client-side sources for communicating with this SDK over IPC through the
* privacy sandbox.
*
* @param sdkClasspath path to the root directory that contains the SDK's compiled classes.
* Non-class files will be safely ignored.
* @param sdkInterfaceDescriptorsOutput output path for SDK Interface descriptors file.
*/
fun packageSdkDescriptors(
sdkClasspath: Path,
sdkInterfaceDescriptorsOutput: Path,
) {
require(sdkClasspath.exists() && sdkClasspath.isDirectory()) {
"$sdkClasspath is not a valid classpath."
}
require(sdkInterfaceDescriptorsOutput.notExists()) {
"$sdkInterfaceDescriptorsOutput already exists."
}
val outputFile = sdkInterfaceDescriptorsOutput.toFile().also {
it.parentFile.mkdirs()
it.createNewFile()
}
ZipOutputStream(outputFile.outputStream()).use { zipOutputStream ->
sdkClasspath.toFile().walk()
.map { it.toPath() }
.filter { shouldKeepFile(sdkClasspath, it) }
.forEach { file ->
val zipEntry = ZipEntry(sdkClasspath.relativize(file).toString())
zipOutputStream.putNextEntry(zipEntry)
file.inputStream().copyTo(zipOutputStream)
zipOutputStream.closeEntry()
}
}
}
private fun shouldKeepFile(sdkClasspath: Path, filePath: Path): Boolean {
if (sdkClasspath.relativize(filePath) == Metadata.filePath) {
return true
}
if (filePath.extension == "class" && hasPrivacySandboxAnnotation(filePath)) {
return true
}
return false
}
}
| apache-2.0 | 366c11bde3d54d085ce57f1dba24cd14 | 37.012346 | 98 | 0.679441 | 4.841195 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/LogDatabase.kt | 1 | 8163 | package org.thoughtcrime.securesms.database
import android.annotation.SuppressLint
import android.app.Application
import android.content.ContentValues
import android.database.Cursor
import net.zetetic.database.sqlcipher.SQLiteDatabase
import net.zetetic.database.sqlcipher.SQLiteOpenHelper
import org.signal.core.util.CursorUtil
import org.signal.core.util.SqlUtil
import org.signal.core.util.Stopwatch
import org.signal.core.util.delete
import org.signal.core.util.getTableRowCount
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.crypto.DatabaseSecret
import org.thoughtcrime.securesms.crypto.DatabaseSecretProvider
import org.thoughtcrime.securesms.database.model.LogEntry
import org.thoughtcrime.securesms.util.ByteUnit
import java.io.Closeable
import java.util.concurrent.TimeUnit
import kotlin.math.abs
/**
* Stores logs.
*
* Logs are very performance critical. Even though this database is written to on a low-priority background thread, we want to keep throughput high and ensure
* that we aren't creating excess garbage.
*
* This is it's own separate physical database, so it cannot do joins or queries with any other tables.
*/
class LogDatabase private constructor(
application: Application,
databaseSecret: DatabaseSecret
) :
SQLiteOpenHelper(
application,
DATABASE_NAME,
databaseSecret.asString(),
null,
DATABASE_VERSION,
0,
SqlCipherDeletingErrorHandler(DATABASE_NAME),
SqlCipherDatabaseHook()
),
SignalDatabaseOpenHelper {
companion object {
private val TAG = Log.tag(LogDatabase::class.java)
private val MAX_FILE_SIZE = ByteUnit.MEGABYTES.toBytes(20)
private val DEFAULT_LIFESPAN = TimeUnit.DAYS.toMillis(3)
private val LONGER_LIFESPAN = TimeUnit.DAYS.toMillis(21)
private const val DATABASE_VERSION = 2
private const val DATABASE_NAME = "signal-logs.db"
private const val TABLE_NAME = "log"
private const val ID = "_id"
private const val CREATED_AT = "created_at"
private const val KEEP_LONGER = "keep_longer"
private const val BODY = "body"
private const val SIZE = "size"
private val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY,
$CREATED_AT INTEGER,
$KEEP_LONGER INTEGER DEFAULT 0,
$BODY TEXT,
$SIZE INTEGER
)
""".trimIndent()
private val CREATE_INDEXES = arrayOf(
"CREATE INDEX keep_longer_index ON $TABLE_NAME ($KEEP_LONGER)",
"CREATE INDEX log_created_at_keep_longer_index ON $TABLE_NAME ($CREATED_AT, $KEEP_LONGER)"
)
@SuppressLint("StaticFieldLeak") // We hold an Application context, not a view context
@Volatile
private var instance: LogDatabase? = null
@JvmStatic
fun getInstance(context: Application): LogDatabase {
if (instance == null) {
synchronized(LogDatabase::class.java) {
if (instance == null) {
SqlCipherLibraryLoader.load()
instance = LogDatabase(context, DatabaseSecretProvider.getOrCreateDatabaseSecret(context))
instance!!.setWriteAheadLoggingEnabled(true)
}
}
}
return instance!!
}
}
override fun onCreate(db: SQLiteDatabase) {
Log.i(TAG, "onCreate()")
db.execSQL(CREATE_TABLE)
CREATE_INDEXES.forEach { db.execSQL(it) }
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
Log.i(TAG, "onUpgrade($oldVersion, $newVersion)")
if (oldVersion < 2) {
db.execSQL("DROP TABLE log")
db.execSQL("CREATE TABLE log (_id INTEGER PRIMARY KEY, created_at INTEGER, keep_longer INTEGER DEFAULT 0, body TEXT, size INTEGER)")
db.execSQL("CREATE INDEX keep_longer_index ON log (keep_longer)")
db.execSQL("CREATE INDEX log_created_at_keep_longer_index ON log (created_at, keep_longer)")
}
}
override fun onOpen(db: SQLiteDatabase) {
db.setForeignKeyConstraintsEnabled(true)
}
override fun getSqlCipherDatabase(): SQLiteDatabase {
return writableDatabase
}
fun insert(logs: List<LogEntry>, currentTime: Long) {
val db = writableDatabase
db.beginTransaction()
try {
logs.forEach { log ->
db.insert(TABLE_NAME, null, buildValues(log))
}
db.delete(
TABLE_NAME,
"($CREATED_AT < ? AND $KEEP_LONGER = ?) OR ($CREATED_AT < ? AND $KEEP_LONGER = ?)",
SqlUtil.buildArgs(currentTime - DEFAULT_LIFESPAN, 0, currentTime - LONGER_LIFESPAN, 1)
)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
}
fun getAllBeforeTime(time: Long): Reader {
return CursorReader(readableDatabase.query(TABLE_NAME, arrayOf(BODY), "$CREATED_AT < ?", SqlUtil.buildArgs(time), null, null, null))
}
fun getRangeBeforeTime(start: Int, length: Int, time: Long): List<String> {
val lines = mutableListOf<String>()
readableDatabase.query(TABLE_NAME, arrayOf(BODY), "$CREATED_AT < ?", SqlUtil.buildArgs(time), null, null, null, "$start,$length").use { cursor ->
while (cursor.moveToNext()) {
lines.add(CursorUtil.requireString(cursor, BODY))
}
}
return lines
}
fun trimToSize() {
val currentTime = System.currentTimeMillis()
val stopwatch = Stopwatch("trim")
val sizeOfSpecialLogs: Long = getSize("$KEEP_LONGER = ?", arrayOf("1"))
val remainingSize = MAX_FILE_SIZE - sizeOfSpecialLogs
stopwatch.split("keepers-size")
if (remainingSize <= 0) {
if (abs(remainingSize) > MAX_FILE_SIZE / 2) {
// Not only are KEEP_LONGER logs putting us over the storage limit, it's doing it by a lot! Delete half.
val logCount = readableDatabase.getTableRowCount(TABLE_NAME)
writableDatabase.execSQL("DELETE FROM $TABLE_NAME WHERE $ID < (SELECT MAX($ID) FROM (SELECT $ID FROM $TABLE_NAME LIMIT ${logCount / 2}))")
} else {
writableDatabase.delete(TABLE_NAME, "$KEEP_LONGER = ?", arrayOf("0"))
}
return
}
val sizeDiffThreshold = MAX_FILE_SIZE * 0.01
var lhs: Long = currentTime - DEFAULT_LIFESPAN
var rhs: Long = currentTime
var mid: Long = 0
var sizeOfChunk: Long
while (lhs < rhs - 2) {
mid = (lhs + rhs) / 2
sizeOfChunk = getSize("$CREATED_AT > ? AND $CREATED_AT < ? AND $KEEP_LONGER = ?", SqlUtil.buildArgs(mid, currentTime, 0))
if (sizeOfChunk > remainingSize) {
lhs = mid
} else if (sizeOfChunk < remainingSize) {
if (remainingSize - sizeOfChunk < sizeDiffThreshold) {
break
} else {
rhs = mid
}
} else {
break
}
}
stopwatch.split("binary-search")
writableDatabase.delete(TABLE_NAME, "$CREATED_AT < ? AND $KEEP_LONGER = ?", SqlUtil.buildArgs(mid, 0))
stopwatch.split("delete")
stopwatch.stop(TAG)
}
fun getLogCountBeforeTime(time: Long): Int {
readableDatabase.query(TABLE_NAME, arrayOf("COUNT(*)"), "$CREATED_AT < ?", SqlUtil.buildArgs(time), null, null, null).use { cursor ->
return if (cursor.moveToFirst()) {
cursor.getInt(0)
} else {
0
}
}
}
fun clearKeepLonger() {
writableDatabase.delete(TABLE_NAME)
.where("$KEEP_LONGER = ?", 1)
.run()
}
private fun buildValues(log: LogEntry): ContentValues {
return ContentValues().apply {
put(CREATED_AT, log.createdAt)
put(KEEP_LONGER, if (log.keepLonger) 1 else 0)
put(BODY, log.body)
put(SIZE, log.body.length)
}
}
private fun getSize(query: String?, args: Array<String>?): Long {
readableDatabase.query(TABLE_NAME, arrayOf("SUM($SIZE)"), query, args, null, null, null).use { cursor ->
return if (cursor.moveToFirst()) {
cursor.getLong(0)
} else {
0
}
}
}
interface Reader : Iterator<String>, Closeable
class CursorReader(private val cursor: Cursor) : Reader {
override fun hasNext(): Boolean {
return !cursor.isLast && cursor.count > 0
}
override fun next(): String {
cursor.moveToNext()
return CursorUtil.requireString(cursor, BODY)
}
override fun close() {
cursor.close()
}
}
}
| gpl-3.0 | 0de2cf877d3f62585260ad91afbe3751 | 30.038023 | 158 | 0.664217 | 3.976132 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/launch/KotlinLaunchShortcut.kt | 1 | 6080 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.launch
import java.util.ArrayList
import org.eclipse.core.resources.IContainer
import org.eclipse.core.resources.IFile
import org.eclipse.core.resources.IProject
import org.eclipse.core.resources.IResource
import org.eclipse.core.runtime.CoreException
import org.eclipse.core.runtime.IAdaptable
import org.eclipse.debug.core.DebugPlugin
import org.eclipse.debug.core.ILaunchConfiguration
import org.eclipse.debug.core.ILaunchConfigurationType
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy
import org.eclipse.debug.ui.DebugUITools
import org.eclipse.debug.ui.ILaunchShortcut
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants
import org.eclipse.jface.viewers.ISelection
import org.eclipse.jface.viewers.IStructuredSelection
import org.eclipse.ui.IEditorPart
import org.jetbrains.kotlin.core.builder.KotlinPsiManager
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.jetbrains.kotlin.core.utils.ProjectUtils
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.ui.editors.KotlinFileEditor
import org.eclipse.jdt.core.JavaCore
import org.jetbrains.kotlin.psi.KtDeclaration
class KotlinLaunchShortcut : ILaunchShortcut {
companion object {
fun createConfiguration(entryPoint: KtDeclaration, project: IProject): ILaunchConfiguration? {
val classFqName = getStartClassFqName(entryPoint)
if (classFqName == null) return null
val configWC = getLaunchConfigurationType().newInstance(null, "Config - " + entryPoint.getContainingKtFile().getName())
configWC.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, classFqName.asString())
configWC.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, project.getName())
return configWC.doSave()
}
fun getFileClassName(mainFile: IFile): FqName {
val ktFile = KotlinPsiManager.getParsedFile(mainFile)
return JvmFileClassUtil.getFileClassInfoNoResolve(ktFile).fileClassFqName
}
private fun getLaunchConfigurationType(): ILaunchConfigurationType {
return DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION)
}
}
override fun launch(selection: ISelection, mode: String) {
val mainFile = findFileToLaunch(selection) ?: return
val ktFile = KotlinPsiManager.getParsedFile(mainFile)
val entryPoint = getEntryPoint(ktFile)
if (entryPoint != null) {
launchWithMainClass(entryPoint, mainFile.getProject(), mode)
}
}
override fun launch(editor: IEditorPart, mode: String) {
if (editor !is KotlinFileEditor) return
val file = editor.eclipseFile
if (file == null) {
KotlinLogger.logError("Failed to retrieve IFile from editor " + editor, null)
return
}
val parsedFile = editor.parsedFile
if (parsedFile == null) return
val entryPoint = getEntryPoint(parsedFile)
if (entryPoint != null) {
launchWithMainClass(entryPoint, file.project, mode)
return
}
}
private fun launchWithMainClass(entryPoint: KtDeclaration, project: IProject, mode: String) {
val configuration = findLaunchConfiguration(getLaunchConfigurationType(), entryPoint, project) ?:
createConfiguration(entryPoint, project)
if (configuration != null) {
DebugUITools.launch(configuration, mode)
}
}
private fun findLaunchConfiguration(
configurationType: ILaunchConfigurationType,
entryPoint: KtDeclaration,
project: IProject): ILaunchConfiguration? {
val configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(configurationType)
val mainClassName = getStartClassFqName(entryPoint)?.asString()
if (mainClassName == null) return null
for (config in configs) {
if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, null as String?) == mainClassName &&
config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, null as String?) == project.name) {
return config
}
}
return null
}
private fun addFiles(files: ArrayList<IFile>, resource: IResource) {
when (resource.getType()) {
IResource.FILE -> {
val file = resource as IFile
if (resource.getFileExtension() == KotlinFileType.INSTANCE.getDefaultExtension()) {
files.add(file)
}
}
IResource.FOLDER, IResource.PROJECT -> {
val container = resource as IContainer
for (child in container.members()) {
addFiles(files, child)
}
}
}
}
} | apache-2.0 | 4420883c026e0a837c3c4d3cf69e81ed | 40.937931 | 144 | 0.670724 | 5.041459 | false | true | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lang/XQuerySpec.kt | 1 | 3270 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.lang
import com.intellij.navigation.ItemPresentation
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationType
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion
import uk.co.reecedunn.intellij.plugin.xpm.lang.impl.W3CSpecification
import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmIcons
import javax.swing.Icon
@Suppress("MemberVisibilityCanBePrivate")
object XQuerySpec : ItemPresentation, XpmSpecificationType {
// region ItemPresentation
override fun getPresentableText(): String = "XQuery: An XML Query Language"
override fun getLocationString(): String? = null
override fun getIcon(unused: Boolean): Icon = XpmIcons.W3.Product
// endregion
// region XpmSpecificationType
override val id: String = "xquery"
override val presentation: ItemPresentation
get() = this
// endregion
// region Versions
val WD_1_0_20030502: XpmSpecificationVersion = W3CSpecification(
this,
"1.0-20030502",
"1.0 (Working Draft 02 May 2003)",
"https://www.w3.org/TR/2003/WD-xquery-20030502/"
)
val REC_1_0_20070123: XpmSpecificationVersion = W3CSpecification(
this,
"1.0-20070123",
"1.0 (First Edition)",
"https://www.w3.org/TR/2007/REC-xquery-20070123/"
)
val REC_1_0_20101214: XpmSpecificationVersion = W3CSpecification(
this,
"1.0-20101214",
"1.0 (Second Edition)",
"https://www.w3.org/TR/2010/REC-xquery-20101214/"
)
val REC_3_0_20140408: XpmSpecificationVersion = W3CSpecification(
this,
"3.0-20140408",
"3.0",
"https://www.w3.org/TR/2014/REC-xquery-30-20140408/"
)
val CR_3_1_20151217: XpmSpecificationVersion = W3CSpecification(
this,
"3.1-20151217",
"3.1 (Candidate Recommendation 17 December 2015)",
"https://www.w3.org/TR/2015/CR-xquery-31-20151217/"
)
val REC_3_1_20170321: XpmSpecificationVersion = W3CSpecification(
this,
"3.1-20170321",
"3.1",
"https://www.w3.org/TR/2017/REC-xquery-31-20170321/"
)
val ED_4_0_20210113: XpmSpecificationVersion = W3CSpecification(
this,
"4.0-20210113",
"4.0 (Editor's Draft 13 January 2021)",
"https://qt4cg.org/branch/master/xquery-40/xquery-40.html"
)
val versions: List<XpmSpecificationVersion> = listOf(
WD_1_0_20030502,
REC_1_0_20070123,
REC_1_0_20101214,
REC_3_0_20140408,
CR_3_1_20151217,
REC_3_1_20170321,
ED_4_0_20210113
)
// endregion
}
| apache-2.0 | 4a575d50f6dcafda849801d3dc0d1c2c | 29.849057 | 79 | 0.666361 | 3.569869 | false | false | false | false |
HaasJona/komath | src/main/kotlin/de/komath/Fraction.kt | 1 | 38182 | /*
* Copyright (c) 2016 Jonathan Haas.
*
* 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.komath
import java.math.BigDecimal
import java.math.BigInteger
import java.math.MathContext
import java.math.RoundingMode
import java.util.regex.Pattern
/**
* Represents a mathematical fraction or ratio expressed by a numerator and a denominator with a value of
* [numerator]/[denominator]. A fraction is always expressed in a normalized form with the denominator always
* being positive (or zero) and reduced as much as possible. Examples:
*
* * of(2,4) = 1/2
* * of(2,-4) = -1/2
* * of(3,-8) = -3/8
*
* Similar to a double, a fraction can have special values representing infinity and NaN. This way, all the usual
* operations do not result in arithmetic exceptions. The special values are represented as follows:
*
* * 0/1 = Zero
* * 1/0 = Positive infinity
* * -1/0 = Negative infinity
* * 0/0 = NaN
*
* Again, all parameters are automatically reduced when constructing a fraction, and thus, these are the only possible
* "special" values. For example constructing a fraction with the value of 1234/0 will again result in 1/0 (positive infinity).
*
* Unlike doubles, there is no distinction between positive zero and negative zero, because the fraction class can
* represent arbitrarily small numbers and thus zero always represents exactly zero.
*
* [NaN] represents an invalid value and is for example returned when dividing zero by zero or multiplying infinity with zero.
* Unless otherwise noted, all operations of this class with a NaN value as argument also return NaN.
*
* This is a data based, immutable and threadsafe class.
*/
class Fraction internal constructor(val numerator: BigInteger, val denominator: BigInteger) : Number(), Comparable<Fraction> {
companion object {
/**
* Represents the value 0/0 (NaN)
*/
val NaN = Fraction(BigInteger.ZERO, BigInteger.ZERO)
/**
* Represents the value 0/1 (Zero)
*/
val ZERO = Fraction(BigInteger.ZERO, BigInteger.ONE)
/**
* Represents the value 1/1 (One)
*/
val ONE = Fraction(BigInteger.ONE, BigInteger.ONE)
/**
* Represents the value -1/1 (Negative One)
*/
val NEGATIVE_ONE = -ONE
/**
* Represents the value 1/0 (Positive Infinity)
*/
val POSITIVE_INFINITY = Fraction(BigInteger.ONE, BigInteger.ZERO)
/**
* Represents the value -1/0 (Negative Infinity)
*/
val NEGATIVE_INFINITY = -POSITIVE_INFINITY
/**
* Returns a Fraction with the specified [numerator] and [denominator]. The given values may be normalized and reduced.
*/
fun of(numerator: BigInteger, denominator: BigInteger = BigInteger.ONE): Fraction {
var gcd = numerator.gcd(denominator)
if (gcd == BigInteger.ZERO) {
return NaN
}
if (denominator < BigInteger.ZERO) gcd = -gcd
return Fraction(numerator / gcd, denominator / gcd)
}
/**
* Returns a Fraction with the specified [numerator] and [denominator]. The given values may be normalized and reduced.
*/
fun of(numerator: Long, denominator: Long): Fraction = of(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator))
/**
* Returns a Fraction with the specified [numerator] and [denominator]. The given values may be normalized and reduced.
*/
fun of(numerator: Int, denominator: Int): Fraction = of(numerator.toLong(), denominator.toLong())
/**
* Returns a Fraction with the specified integer value. The [denominator] will always be 1.
*/
fun of(value: BigInteger): Fraction = of(value, BigInteger.ONE)
/**
* Returns a Fraction with the specified integer value. The [denominator] will always be 1.
*/
fun of(value: Long): Fraction = of(BigInteger.valueOf(value), BigInteger.ONE)
/**
* Returns a Fraction with the specified integer value. The [denominator] will always be 1.
*/
fun of(value: Int): Fraction = of(value.toLong())
/**
* Returns a fraction that represents the exact value of the specified IEEE 754 double. Special values
* like NaN and Infinity are translated to the special fractions appropriately.
*
* Because of the binary exponent representation of a double value, the [denominator] of the created fraction
* will always be a power of 2 (or 0).
*
* For example `Fraction.ofExact(0.3) == 5404319552844595/18014398509481984`. If you need 3/10 instead, try [Fraction.of].
*/
fun ofExact(value: Double): Fraction {
if (value.isNaN()) return NaN
if (value.isInfinite()) {
return if (value > 0) POSITIVE_INFINITY else NEGATIVE_INFINITY
}
return ofExactNoSpecialValue(value)
}
/**
* Returns the simplest fraction, whose [double value][toDouble] is equal to the specified double (within double accuracy).
*
* Note that "the simplest" is computed on a best effort basis without requiring excessive computation. The exact algorithm may change in the future.
* The only guarantee is, that the Fraction converted back into a double will be equal to the specified double.
*
* For example `Fraction.of(0.3) == 3/10`
*/
fun of(value: Double): Fraction {
if (value.isNaN()) return NaN
if (value.isInfinite()) {
return if (value > 0) POSITIVE_INFINITY else NEGATIVE_INFINITY
}
val tmp = ofExactNoSpecialValue(value).continuedFraction()
return tmp.toFraction({ fraction -> value == fraction.toDouble() })
}
/**
* Bit fiddling to extract exact double value, special doubles like 0.0 or NaN must be handled separately.
*/
private fun ofExactNoSpecialValue(value: Double): Fraction {
val helper = FpHelper.ofDouble(value)
val exponent = helper.exp.intValueExact()
if (exponent >= 0)
return of(helper.significand.shiftLeft(exponent), BigInteger.ONE)
else
return of(helper.significand, BigInteger.ZERO.setBit(-exponent))
}
/**
* Returns a fraction that represents the exact value of the specified IEEE 754 single (float). Special values
* like NaN and Infinity are translated to the special fractions appropriately.
*
* Because of the binary exponent representation of a float value, the [denominator] of the created fraction
* will always be a power of 2 (or 0).
*
* For example `Fraction.ofExact(0.3f) == 5033165/16777216`. If you need 3/10 instead, try [Fraction.of].
*/
fun ofExact(value: Float): Fraction {
if (value.isNaN()) return NaN
if (value.isInfinite()) {
return if (value > 0) POSITIVE_INFINITY else NEGATIVE_INFINITY
}
return ofExactNoSpecialValue(value)
}
/**
* Returns the simplest fraction, whose [float value][toFloat] is equal to the specified float (within float accuracy).
*
* Note that "the simplest" is computed on a best effort basis without requiring excessive computation. The exact algorithm may change in the future.
* The only guarantee is, that the Fraction converted back into a float will be equal to the specified float.
*
* For example `Fraction.of(0.3f) == 3/10`
*/
fun of(value: Float): Fraction {
if (value.isNaN()) return NaN
if (value.isInfinite()) {
return if (value > 0) POSITIVE_INFINITY else NEGATIVE_INFINITY
}
val tmp = ofExactNoSpecialValue(value).continuedFraction()
return tmp.toFraction({ fraction -> value == fraction.toFloat() })
}
/**
* Bit fiddling to extract exact float value, special floats like 0.0 or NaN must be handled separately.
*/
private fun ofExactNoSpecialValue(value: Float): Fraction {
val helper = FpHelper.ofFloat(value)
val exponent = helper.exp.intValueExact()
if (exponent >= 0)
return of(helper.significand.shiftLeft(exponent), BigInteger.ONE)
else
return of(helper.significand, BigInteger.ZERO.setBit(-exponent))
}
/**
* Returns a fraction that represents the exact value of the specified BigDecimal.
*
* For example `Fraction.of(BigDecimal.valueOf(0.3)) == 3/10`.
*/
fun of(value: BigDecimal): Fraction {
if (value.scale() > 0)
return of(value.unscaledValue(), BigInteger.TEN.pow(value.scale()))
else
return of(value.toBigIntegerExact())
}
/**
* Returns a fraction that represents the exact value of `numerator/denominator`.
*/
fun of(numerator: BigDecimal, denominator: BigDecimal): Fraction = of(numerator) / of(denominator)
private val HEX_PATTERN_INLINE: Pattern = Pattern.compile("^\\s*(?:([+-]?\\p{Digit}+) +)?([+-]?(?:\\p{Digit}+(?:\\.\\p{Digit}*)?|\\.\\p{Digit})(?:[eE][+-]?\\p{Digit}+)?)(?:\\s*/\\s*([+-]?(?:\\p{Digit}+(?:\\.\\p{Digit}*)?|\\.\\p{Digit})(?:[eE][+-]?\\p{Digit}+)?))?\\s*$")
/**
* Parses a String and returns the fractional value of this String. The string can
* in particular have one of the following forms:
*
* - Decimal (example 3.65, anything that can be parsed by [BigDecimal])
* - Mixed String (example 5 3/4, as returned by [toMixedString])
* - Normal fraction (example 13/5, as returned by [toString])
* - Anything than can be parsed as a double (especially Infinity or NaN).
*
* Generally for any regular value, the String is expected to be
*
* - A integer value followed by whitespace (optional, default = 0) followed by
* - A decimal value representing the numerator followed by
* - A slash (optionally surrounded by whitespace) and a decimal value representing the denominator (optional, default = 1)
*
* The resulting fraction then has a value of
*
* integer + sign(integer) * numerator / denominator
*
* with sign(n) = -1 for n < 0, else 1
*
* Note that this means that "-4 3/5" will result in a fraction with the value of `-4 - 3/5` (-23/5)
* (as expected) and that it is usually not useful to repeat the sign at the numerator or denominator when
* creating a fraction using the mixed string representation. A [value] argument of "-4 -3/5" would actually
* result in a [Fraction] with a value of `-4 + 3/5` (-17/5).
*
* Note that this also means, that you can use decimals as [numerator] and [denominator].
* For example `Fraction.of("12.5/0.1")` would result in a [Fraction] with the value of 125/1.
*
*/
fun of(value: String): Fraction {
val matcher = HEX_PATTERN_INLINE.matcher(value)
if (matcher.matches()) {
val int = matcher.group(1)
val numerator = matcher.group(2)
val denominator = matcher.group(3)
var result = of(BigDecimal(numerator!!))
if (denominator != null) {
result /= of(BigDecimal(denominator))
}
if (int != null) {
if (int.startsWith('-')) {
result = -result
}
result += of(BigInteger(int))
}
return result
}
return of(value.toDouble())
}
const val PATTERN = "([+-]?\\p{Digit}+(?:\\.\\p{Digit}*)?|\\.\\p{Digit})(?:\\((\\p{Digit}+)\\))?(?:[eE]([+-]?\\p{Digit}+))?"
fun ofRepeatingString(value: String): Fraction {
val matcher = Pattern.compile(PATTERN).matcher(value)
if (matcher.matches()) {
val decimal: String = matcher.group(1)
val repeating: String? = matcher.group(2)
val exponent: String? = matcher.group(3)
val bigDecimal = BigDecimal(decimal)
val tmp: Fraction
if (repeating != null) {
val bigDecimalRepeating = BigDecimal(decimal + repeating).movePointRight(repeating.length)
val foo = bigDecimalRepeating.minus(bigDecimal)
tmp = of(foo) / of(BigDecimal.ONE.movePointRight(repeating.length) - BigDecimal.ONE)
} else {
tmp = of(bigDecimal)
}
if (exponent != null) {
return tmp * of(BigDecimal.ONE.movePointRight(Integer.parseInt(exponent)))
}
return tmp
}
throw IllegalArgumentException()
}
}
/**
* Returns the string representation of this fraction, which is equal to [numerator] + `/` + [denominator], for example `-13/5`.
*/
override fun toString(): String {
return "$numerator/$denominator"
}
/**
* Returns the mixed number representation of this fraction, which is formatted as `[-]a b/c`, for example
*
* * `1 3/5` for the fraction `8/5`
* * `-2 3/5` for the fraction `-13/5`
*
* If the integer part (`a`) or the [denominator] would be zero, this returns the same String as [toString]
*/
fun toMixedString(radix: Int = 10): String {
if (denominator == BigInteger.ZERO) return toString()
val divideAndRemainder = numerator.divideAndRemainder(denominator)
if (divideAndRemainder[0] == BigInteger.ZERO) return toString()
return "${divideAndRemainder[0].toString(radix)} ${divideAndRemainder[1].abs().toString(radix)}/${denominator.toString(radix)}"
}
/**
* Converts this fraction to the nearest double value.
*/
override fun toDouble(): Double {
if (this == NaN) return Double.NaN
if (this == POSITIVE_INFINITY) return Double.POSITIVE_INFINITY
if (this == NEGATIVE_INFINITY) return Double.NEGATIVE_INFINITY
val negExp = BigInteger.valueOf(denominator.bitLength().toLong()).shiftLeft(1) + BigInteger.valueOf(52)
val significand = numerator.shiftLeft(negExp.intValueExact()) / denominator
return FpHelper(significand, -negExp).toDouble()
}
/**
* Converts this fraction to the nearest float value.
*/
override fun toFloat(): Float {
if (this == NaN) return Float.NaN
if (this == POSITIVE_INFINITY) return Float.POSITIVE_INFINITY
if (this == NEGATIVE_INFINITY) return Float.NEGATIVE_INFINITY
val negExp = BigInteger.valueOf(denominator.bitLength().toLong()).shiftLeft(1) + BigInteger.valueOf(23)
val significand = numerator.shiftLeft(negExp.intValueExact()) / denominator
return FpHelper(significand, -negExp).toFloat()
}
/**
* Returns a (decimal) string representation of this fraction with the specified number of maximum decimal places and the specified radix (default: 10).
*
* Special values like Infinity or NaN are returned in the same way as [Double].toString()
*/
fun toString(n: Int, radix: Int = 10, roundingMode: RoundingMode = RoundingMode.DOWN): String {
if (radix < 2) throw IllegalArgumentException("radix")
if (denominator == BigInteger.ZERO) {
if (numerator > BigInteger.ZERO) {
return Double.POSITIVE_INFINITY.toString()
} else if (numerator < BigInteger.ZERO) {
return Double.NEGATIVE_INFINITY.toString()
} else {
return Double.NaN.toString()
}
}
val radixBigInt = BigInteger.valueOf(radix.toLong())
var divideAndRemainder = numerator.divideAndRemainder(denominator)
if (n == 0) {
return round(divideAndRemainder[0], divideAndRemainder[1], roundingMode).toString(radix)
}
val s = StringBuilder()
s.append(divideAndRemainder[0].toString(radix))
var remainder = divideAndRemainder[1].abs()
if (remainder == BigInteger.ZERO) return s.toString()
s.append('.')
for (i in 1..n) {
remainder *= radixBigInt
divideAndRemainder = remainder.divideAndRemainder(denominator)
remainder = divideAndRemainder[1]
if (i != n) {
s.append(divideAndRemainder[0].toString(radix))
} else {
s.append(round(divideAndRemainder[0], divideAndRemainder[1], roundingMode).toString(radix))
}
if (remainder == BigInteger.ZERO) break
}
return s.toString()
}
private fun round(divide: BigInteger, remainder: BigInteger, roundingMode: RoundingMode): BigInteger {
fun roundUp() = if (divide.signum() >= 0) divide + BigInteger.ONE else divide - BigInteger.ONE
val roundingModeInt = when (roundingMode) {
RoundingMode.CEILING -> if (numerator.signum() < 0) RoundingMode.DOWN else RoundingMode.UP
RoundingMode.FLOOR -> if (numerator.signum() < 0) RoundingMode.UP else RoundingMode.DOWN
RoundingMode.HALF_EVEN -> if (divide.toInt() % 2 == 0) RoundingMode.HALF_DOWN else RoundingMode.HALF_UP
else -> roundingMode
}
return when (roundingModeInt) {
RoundingMode.UP -> if (remainder != BigInteger.ZERO) roundUp() else divide
RoundingMode.DOWN -> divide
RoundingMode.HALF_UP -> if (remainder.abs().shiftLeft(1) >= denominator) roundUp() else divide
RoundingMode.HALF_DOWN -> if (remainder.abs().shiftLeft(1) > denominator) roundUp() else divide
else -> if (remainder == BigInteger.ZERO) divide else throw ArithmeticException("rounding necessary")
}
}
/**
* Returns a repeating String representation of this fraction in the specified radix (default: 10).
* The repeating part (if any) will be enclosed in parens, for example `of("7/12").toRepeatingString() == "0.58(3)"` or `of("22/7").toRepeatingString() == "3.(142857)"`.
*
* The integer part before the dot will never be included in the repeating portion of the String, for example `of(100,3).toRepeatingString(radix) == 33.(3)`.
*
* For large denominators, the resulting String can become very long and the computation can become very expensive. Because of that, a limit can be specified that limits the length
* of the fractional part to a specific count of digits. If this happens, there will be no parens in the resulting String, and it will instead end with "...". This limit can be disabled by
* using zero or a negative number for the limit.
*
* Special values like Infinity or NaN are returned in the same way as [Double].toString()
*/
fun toRepeatingString(radix: Int = 10, limit: Int = 255): String {
if (radix < 2) throw IllegalArgumentException("radix")
if (denominator == BigInteger.ZERO) {
if (numerator > BigInteger.ZERO) {
return Double.POSITIVE_INFINITY.toString()
} else if (numerator < BigInteger.ZERO) {
return Double.NEGATIVE_INFINITY.toString()
} else {
return Double.NaN.toString()
}
}
val radixBigInt = BigInteger.valueOf(radix.toLong())
val s = StringBuilder()
var divideAndRemainder = numerator.divideAndRemainder(denominator)
s.append(divideAndRemainder[0].toString(radix))
var remainder = divideAndRemainder[1].abs()
if (remainder == BigInteger.ZERO) return s.toString()
s.append('.')
val remainders = mutableMapOf<BigInteger, Int>()
while (true) {
val old = remainders.put(remainder, s.length)
if (old != null) {
s.insert(old, "(")
s.append(")")
return s.toString()
}
if (limit > 0 && remainders.size > limit) {
s.append("...")
return s.toString()
}
remainder *= radixBigInt
divideAndRemainder = remainder.divideAndRemainder(denominator)
remainder = divideAndRemainder[1]
s.append(divideAndRemainder[0].toString(radix))
if (remainder == BigInteger.ZERO) break
}
return s.toString()
}
/**
* Returns the BigInteger value (rounded towards zero) of this fraction. If the denominator is zero, returns zero.
*/
fun toBigInteger(): BigInteger = if (denominator == BigInteger.ZERO) BigInteger.ZERO else numerator / denominator
/**
* Returns the BigInteger value (rounded with the specified [roundingmode]) of this fraction. If the denominator is zero, returns zero.
*/
fun toBigInteger(roundingMode: RoundingMode): BigInteger {
val divideAndRemainder = numerator.divideAndRemainder(denominator)
return round(divideAndRemainder[0], divideAndRemainder[1], roundingMode)
}
/**
* Returns this as a BigDecimal
* @param scale scale of the {@code BigDecimal} quotient to be returned.
* @param roundingMode rounding mode to apply.
* @throws ArithmeticException if denominator is zero
*/
fun toBigDecimal(scale: Int, roundingMode: RoundingMode): BigDecimal = BigDecimal(numerator).divide(BigDecimal(denominator), scale, roundingMode)
/**
* Returns this as a BigDecimal
* @param mathContext the [MathContext] to use for rounding and accuracy
* @throws ArithmeticException if denominator is zero
*/
fun toBigDecimal(mathContext: MathContext): BigDecimal = BigDecimal(numerator).divide(BigDecimal(denominator), mathContext)
/**
* Returns `toBigInteger().toLong()`. If the denominator is zero, returns zero.
*/
override fun toLong() = toBigInteger().toLong()
/**
* Returns `toBigInteger().toInt()`. If the denominator is zero, returns zero.
*/
override fun toInt() = toBigInteger().toInt()
/**
* Returns `toBigInteger().toShort()`. If the denominator is zero, returns zero.
*/
override fun toShort() = toBigInteger().toShort()
/**
* Returns `toBigInteger().toChar()`. If the denominator is zero, returns zero.
*/
override fun toChar() = toBigInteger().toChar()
/**
* Returns `toBigInteger().toByte()`. If the denominator is zero, returns zero.
*/
override fun toByte() = toBigInteger().toByte()
fun toLongExact(roundingMode: RoundingMode = RoundingMode.DOWN) = toBigInteger(roundingMode).longValueExact()
fun toIntExact(roundingMode: RoundingMode = RoundingMode.DOWN) = toBigInteger(roundingMode).intValueExact()
fun toShortExact(roundingMode: RoundingMode = RoundingMode.DOWN) = toBigInteger(roundingMode).shortValueExact()
fun toByteExact(roundingMode: RoundingMode = RoundingMode.DOWN) = toBigInteger(roundingMode).byteValueExact()
operator fun plus(other: Fraction) = of(numerator * other.denominator + other.numerator * denominator, denominator * other.denominator)
operator fun minus(other: Fraction) = of(numerator * other.denominator - other.numerator * denominator, denominator * other.denominator)
operator fun times(other: Fraction) = of(numerator * other.numerator, denominator * other.denominator)
operator fun div(other: Fraction) = of(numerator * other.denominator, denominator * other.numerator)
operator fun rem(other: Fraction) = other * (this / other).frac()
operator fun unaryMinus(): Fraction = Fraction(-numerator, denominator)
operator fun unaryPlus(): Fraction = this
override infix operator fun compareTo(other: Fraction): Int {
return (numerator * other.denominator).compareTo(other.numerator * denominator)
}
/**
* Returns the multiplicative inverse of this fraction.
*
* * If this is [NaN], return [NaN].
* * If this is an infinity, returns [ZERO].
* * If this is [ZERO], returns [POSITIVE_INFINITY]
*
* @return the reciprocal fraction
*/
fun reciprocal(): Fraction {
if (numerator.signum() < 0) {
return Fraction(-denominator, -numerator)
}
return Fraction(denominator, numerator)
}
/**
* Returns the fractional part of this fraction, which is this fraction with any integer part removed (`this % 1`). For example:
*
* `frac(13/10) == frac(43/10) == 3/10`
*
* Negative fractions will return a negative fractional part, but otherwise work the same. For example:
*
* `frac(-13/10) == frac(-43/10) == -3/10`
*
* The returned fraction is always between (exclusive) -1/1 and 1/1. As an exception, if `this` is infinity or NaN, `this` is returned instead.
*/
fun frac(): Fraction {
if (denominator == BigInteger.ZERO) return this
return Fraction(numerator % denominator, denominator)
}
/**
* Returns the signum of the fraction:
*
* * 1 if the fraction is positive
* * -1 if the fraction is negative
* * 0 if the fraction is [ZERO] or [NaN]
*/
fun signum() = numerator.signum()
/**
* Converts this fraction into a continued fraction representation.
*
* @throws ArithmeticException if the denominator is zero (`this` is Infinity or NaN)
*/
fun continuedFraction(): ContinuedFraction {
if (denominator == BigInteger.ZERO) throw ArithmeticException(toString(0))
return ContinuedFraction.of(this)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Fraction) return false
if (numerator != other.numerator) return false
if (denominator != other.denominator) return false
return true
}
override fun hashCode() = numerator.hashCode() + denominator.hashCode() * 2047
operator fun component1() = numerator
operator fun component2() = denominator
/**
* Multiplies this fraction by 2 to the power of [shift] as if the number were shifted left in a binary representation and returns the resulting fraction.
*/
fun shiftLeft(shift: Int): Fraction {
if (denominator == BigInteger.ZERO) return this
var nu = numerator
var de = denominator
if (shift > 0) {
val lsb = de.lowestSetBit
if (shift > lsb) {
de = de.shiftRight(lsb)
nu = nu.shiftLeft(shift - lsb)
} else {
de = de.shiftRight(shift)
}
} else if (shift < 0) {
val lsb = nu.lowestSetBit
if (-shift > lsb) {
nu = nu.shiftRight(lsb)
de = de.shiftLeft(-shift - lsb)
} else {
nu = nu.shiftRight(-shift)
}
}
return Fraction(nu, de)
}
/**
* Divides this fraction by 2 to the power of [shift] as if the number were shifted right in a binary representation and returns the resulting fraction.
*/
fun shiftRight(shift: Int) = shiftLeft(-shift)
}
/**
* A representation of a simple continued fraction. This class currently expects a finite continued fraction, feeding it
* infinitely many BigIntegers may lead to some algorithms not terminating correctly for now.
*/
class ContinuedFraction private constructor(private val arg: Iterable<BigInteger>) : Comparable<ContinuedFraction>, Number(), Iterable<BigInteger> {
companion object {
/**
* Creates a continued fraction from a collection of BigIntegers [b0; b1, b2, ...]
*/
fun of(value: Collection<BigInteger>): ContinuedFraction {
return when {
value.isEmpty() -> throw IllegalArgumentException("Empty collection")
else -> ContinuedFraction(value.toList())
}
}
/**
* Converts an existing fraction into a continued fraction representation
*/
fun of(value: Fraction): ContinuedFraction = ContinuedFraction(Iterable { ContinuedFractionIterator(value) })
}
override fun iterator(): Iterator<BigInteger> {
return arg.iterator()
}
override fun toString(): String {
val builder = StringBuilder("[")
var n = 0
for (bigInteger in this) {
builder.append(bigInteger)
builder.append(if (n == 0) "; " else ", ")
n++
if (n > 10) {
builder.append("... ")
break
}
}
builder.setLength(builder.length - 2)
builder.append("]")
return builder.toString()
}
/**
* Converts this continued fraction back into a normal fraction representation.
*
* @param n How many convergents to calculate. This can be used to simplify a fraction. Defaults to
* Int.MAX_VALUE, which should return the original value (creating a continued fraction with more integers will likely lead to other problems)
*/
fun toFraction(n: Int = Int.MAX_VALUE): Fraction {
var olda = BigInteger.ZERO
var oldb = BigInteger.ONE
var cura = BigInteger.ONE
var curb = BigInteger.ZERO
var i = 0
for (bigInteger in this) {
val newa = cura * bigInteger + olda
val newb = curb * bigInteger + oldb
olda = cura
cura = newa
oldb = curb
curb = newb
if (++i == n) break
}
return Fraction.of(cura, curb)
}
/**
* Converts this continued fraction to a regular fraction and simplifies it as much as possible as long as the
* supplied condition is true. This method generates more and more exact first order approximations until the
* condition returns true. Generating second order approximations could in theory result in even simpler fractions,
* but this causes some performance difficulties that haven't been solved yet. In the future this method may be changed to
* (optionally) generate the best second order approximation.
*
* The condition is supposed to return true for `toFraction()` as parameter, however this is not enforced.
* If the condition never returns true for any approximation, this method returns the exact fractional value.
*/
fun toFraction(condition: (Fraction) -> Boolean): Fraction {
var olda = BigInteger.ZERO
var oldb = BigInteger.ONE
var cura = BigInteger.ONE
var curb = BigInteger.ZERO
for (bigInteger in this) {
val newa = cura * bigInteger + olda
val newb = curb * bigInteger + oldb
if (condition(Fraction.of(newa, newb))) {
return Fraction.of(newa, newb)
}
olda = cura
cura = newa
oldb = curb
curb = newb
}
return Fraction.of(cura, curb)
}
override fun compareTo(other: ContinuedFraction): Int {
return toFraction().compareTo(other.toFraction())
}
fun toBigInteger(): BigInteger = toFraction().toBigInteger()
fun toBigDecimal(scale: Int, roundingMode: RoundingMode): BigDecimal = toFraction().toBigDecimal(scale, roundingMode)
fun toBigDecimal(mathContext: MathContext): BigDecimal = toFraction().toBigDecimal(mathContext)
override fun toByte(): Byte {
return toFraction().toByte()
}
override fun toChar(): Char {
return toFraction().toChar()
}
override fun toDouble(): Double {
return toFraction().toDouble()
}
override fun toFloat(): Float {
return toFraction().toFloat()
}
override fun toInt(): Int {
return toFraction().toInt()
}
override fun toLong(): Long {
return toFraction().toLong()
}
override fun toShort(): Short {
return toFraction().toShort()
}
}
private class ContinuedFractionIterator(fraction: Fraction) : Iterator<BigInteger> {
var a: BigInteger
var b: BigInteger
init {
a = fraction.numerator
b = fraction.denominator
}
override fun hasNext(): Boolean {
return b != BigInteger.ZERO
}
override fun next(): BigInteger {
val h = a.divideAndRemainder(b)
a = b
b = h[1]
return h[0]
}
}
internal class FpHelper(val significand: BigInteger, val exp: BigInteger) {
companion object {
/**
* Bit fiddling to extract exact double value, special doubles like Infinity or NaN must be handled separately.
*/
fun ofDouble(value: Double): FpHelper {
val bits = java.lang.Double.doubleToLongBits(value)
val sign = bits < 0
var exp = (bits and 0x7ff0000000000000L ushr 52).toInt()
var significand = (bits and 0x000fffffffffffffL)
if (exp > 0) significand = significand or 0x0010000000000000L else exp = 1
if (sign) significand = -significand
return FpHelper(BigInteger.valueOf(significand), BigInteger.valueOf((exp - 1075).toLong()))
}
/**
* Bit fiddling to extract exact float value, special floats like Infinity or NaN must be handled separately.
*/
fun ofFloat(value: Float): FpHelper {
val bits = java.lang.Float.floatToIntBits(value)
val sign = bits < 0
var exp = (bits and 0x7f800000 ushr 23).toInt()
var significand = (bits and 0x007fffff)
if (exp > 0) significand = significand or 0x00800000 else exp = 1
if (sign) significand = -significand
return FpHelper(BigInteger.valueOf(significand.toLong()), BigInteger.valueOf((exp - 150).toLong()))
}
}
fun toDouble(): Double {
var mantissa = significand.abs()
val bitLength = mantissa.bitLength()
var e = exp
e += BigInteger.valueOf((bitLength - 53).toLong())
if (bitLength > 52)
mantissa = divide(mantissa, BigInteger.ZERO.setBit(bitLength - 53), RoundingMode.HALF_EVEN)
else
mantissa = mantissa.shiftRight(bitLength - 53)
e += BigInteger.valueOf(1075)
if (mantissa == BigInteger.ZERO) e = BigInteger.ZERO
if (e < BigInteger.ZERO) {
try {
mantissa = mantissa.shiftRight(1 - (e.intValueExact()))
} catch (e: ArithmeticException) {
mantissa = BigInteger.ZERO
}
e = BigInteger.ZERO
}
var intExp = try {
e.intValueExact()
} catch (e: ArithmeticException) {
2047
}
if (intExp > 2046) {
// Inf
intExp = 2047
mantissa = BigInteger.ZERO
}
var doubleBits: Long = (mantissa.longValueExact() and 0x000fffffffffffffL) or (intExp.toLong().shl(52))
if (significand.signum() < 0) {
doubleBits = doubleBits or 1L.shl(63)
}
return java.lang.Double.longBitsToDouble(doubleBits)
}
fun toFloat(): Float {
var mantissa = significand.abs()
val bitLength = mantissa.bitLength()
var e = exp
e += BigInteger.valueOf((bitLength - 24).toLong())
if (bitLength > 23)
mantissa = divide(mantissa, BigInteger.ZERO.setBit(bitLength - 24), RoundingMode.HALF_EVEN)
else
mantissa = mantissa.shiftRight(bitLength - 24)
e += BigInteger.valueOf(150)
if (mantissa == BigInteger.ZERO) e = BigInteger.ZERO
if (e < BigInteger.ZERO) {
try {
mantissa = mantissa.shiftRight(1 - (e.intValueExact()))
} catch (e: ArithmeticException) {
mantissa = BigInteger.ZERO
}
e = BigInteger.ZERO
}
var intExp = try {
e.intValueExact()
} catch (e: ArithmeticException) {
255
}
if (intExp > 254) {
// Inf
intExp = 255
mantissa = BigInteger.ZERO
}
var intBits: Int = (mantissa.intValueExact() and 0x007fffff) or (intExp.shl(23))
if (significand.signum() < 0) {
intBits = intBits or 1.shl(31)
}
return java.lang.Float.intBitsToFloat(intBits)
}
fun divide(p: BigInteger, q: BigInteger, mode: RoundingMode): BigInteger {
val pDec = BigDecimal(p)
val qDec = BigDecimal(q)
return pDec.divide(qDec, 0, mode).toBigIntegerExact()
}
}
| mit | 586639cc9225476740c168b649ee1518 | 40.322511 | 278 | 0.612592 | 4.506846 | false | false | false | false |
Zeyad-37/GenericUseCase | usecases/src/main/java/com/zeyad/usecases/network/ProgressResponseBody.kt | 2 | 1434 | package com.zeyad.usecases.network
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException
/**
* @author by ZIaDo on 7/11/17.
*/
internal class ProgressResponseBody(private val responseBody: ResponseBody, private val progressListener: ProgressListener) : ResponseBody() {
private lateinit var bufferedSource: BufferedSource
override fun contentType(): MediaType? {
return responseBody.contentType()
}
override fun contentLength(): Long {
return responseBody.contentLength()
}
override fun source(): BufferedSource {
if (!::bufferedSource.isInitialized) {
bufferedSource = Okio.buffer(source(responseBody.source()))
}
return bufferedSource
}
private fun source(source: Source): Source {
return object : ForwardingSource(source) {
var totalBytesRead = 0L
@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
val bytesRead = super.read(sink, byteCount)
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += if (bytesRead != -1L) bytesRead else 0
progressListener.update(totalBytesRead, responseBody.contentLength(),
bytesRead == -1L)
return bytesRead
}
}
}
}
| apache-2.0 | aa3f195f1bc9fa8f1aa5342e019a8b71 | 31.590909 | 142 | 0.637378 | 5.252747 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeList.kt | 1 | 5231 | package eu.kanade.tachiyomi.data.track.myanimelist
import android.content.Context
import android.graphics.Color
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import okhttp3.HttpUrl
import rx.Completable
import rx.Observable
import java.lang.Exception
class Myanimelist(private val context: Context, id: Int) : TrackService(id) {
companion object {
const val READING = 1
const val COMPLETED = 2
const val ON_HOLD = 3
const val DROPPED = 4
const val PLAN_TO_READ = 6
const val DEFAULT_STATUS = READING
const val DEFAULT_SCORE = 0
const val BASE_URL = "https://myanimelist.net"
const val USER_SESSION_COOKIE = "MALSESSIONID"
const val LOGGED_IN_COOKIE = "is_logged_in"
}
private val interceptor by lazy { MyAnimeListInterceptor(this) }
private val api by lazy { MyanimelistApi(client, interceptor) }
override val name: String
get() = "MyAnimeList"
override fun getLogo() = R.drawable.mal
override fun getLogoColor() = Color.rgb(46, 81, 162)
override fun getStatus(status: Int): String = with(context) {
when (status) {
READING -> getString(R.string.reading)
COMPLETED -> getString(R.string.completed)
ON_HOLD -> getString(R.string.on_hold)
DROPPED -> getString(R.string.dropped)
PLAN_TO_READ -> getString(R.string.plan_to_read)
else -> ""
}
}
override fun getStatusList(): List<Int> {
return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLAN_TO_READ)
}
override fun getScoreList(): List<String> {
return IntRange(0, 10).map(Int::toString)
}
override fun displayScore(track: Track): String {
return track.score.toInt().toString()
}
override fun add(track: Track): Observable<Track> {
return api.addLibManga(track)
}
override fun update(track: Track): Observable<Track> {
if (track.total_chapters != 0 && track.last_chapter_read == track.total_chapters) {
track.status = COMPLETED
}
return api.updateLibManga(track)
}
override fun bind(track: Track): Observable<Track> {
return api.findLibManga(track)
.flatMap { remoteTrack ->
if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
update(track)
} else {
// Set default fields if it's not found in the list
track.score = DEFAULT_SCORE.toFloat()
track.status = DEFAULT_STATUS
add(track)
}
}
}
override fun search(query: String): Observable<List<TrackSearch>> {
return api.search(query)
}
override fun refresh(track: Track): Observable<Track> {
return api.getLibManga(track)
.map { remoteTrack ->
track.copyPersonalFrom(remoteTrack)
track.total_chapters = remoteTrack.total_chapters
track
}
}
override fun login(username: String, password: String): Completable {
logout()
return Observable.fromCallable { api.login(username, password) }
.doOnNext { csrf -> saveCSRF(csrf) }
.doOnNext { saveCredentials(username, password) }
.doOnError { logout() }
.toCompletable()
}
// Attempt to login again if cookies have been cleared but credentials are still filled
fun ensureLoggedIn() {
if (isAuthorized) return
if (!isLogged) throw Exception("MAL Login Credentials not found")
val username = getUsername()
val password = getPassword()
logout()
try {
val csrf = api.login(username, password)
saveCSRF(csrf)
saveCredentials(username, password)
} catch (e: Exception) {
logout()
throw e
}
}
override fun logout() {
super.logout()
preferences.trackToken(this).delete()
networkService.cookieManager.remove(HttpUrl.parse(BASE_URL)!!)
}
val isAuthorized: Boolean
get() = super.isLogged &&
getCSRF().isNotEmpty() &&
checkCookies()
fun getCSRF(): String = preferences.trackToken(this).getOrDefault()
private fun saveCSRF(csrf: String) = preferences.trackToken(this).set(csrf)
private fun checkCookies(): Boolean {
var ckCount = 0
val url = HttpUrl.parse(BASE_URL)!!
for (ck in networkService.cookieManager.get(url)) {
if (ck.name() == USER_SESSION_COOKIE || ck.name() == LOGGED_IN_COOKIE)
ckCount++
}
return ckCount == 2
}
}
| apache-2.0 | 3659e69f727bd0794ad90d5a68dc9a7d | 30.69375 | 91 | 0.575225 | 4.658059 | false | false | false | false |
Maccimo/intellij-community | plugins/github/src/org/jetbrains/plugins/github/GHOpenInBrowserActionGroup.kt | 1 | 11265 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitFileRevision
import git4idea.GitRevisionNumber
import git4idea.GitUtil
import git4idea.history.GitHistoryUtils
import git4idea.repo.GitRepository
import org.apache.commons.httpclient.util.URIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.util.GHProjectRepositoriesManager
import org.jetbrains.plugins.github.util.GithubNotificationIdsHolder
import org.jetbrains.plugins.github.util.GithubNotifications
import org.jetbrains.plugins.github.util.GithubUtil
open class GHOpenInBrowserActionGroup
: ActionGroup(GithubBundle.messagePointer("open.on.github.action"),
GithubBundle.messagePointer("open.on.github.action.description"),
AllIcons.Vcs.Vendors.Github), DumbAware {
override fun update(e: AnActionEvent) {
val data = getData(e.dataContext)
e.presentation.isEnabledAndVisible = !data.isNullOrEmpty()
e.presentation.isPerformGroup = data?.size == 1
e.presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, e.presentation.isPerformGroup);
e.presentation.isPopupGroup = true
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
e ?: return emptyArray()
val data = getData(e.dataContext) ?: return emptyArray()
if (data.size <= 1) return emptyArray()
return data.map { GithubOpenInBrowserAction(it) }.toTypedArray()
}
override fun actionPerformed(e: AnActionEvent) {
getData(e.dataContext)?.let { GithubOpenInBrowserAction(it.first()) }?.actionPerformed(e)
}
override fun disableIfNoVisibleChildren(): Boolean = false
protected open fun getData(dataContext: DataContext): List<Data>? {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return null
return getDataFromPullRequest(project, dataContext)
?: getDataFromHistory(project, dataContext)
?: getDataFromLog(project, dataContext)
?: getDataFromVirtualFile(project, dataContext)
}
private fun getDataFromPullRequest(project: Project, dataContext: DataContext): List<Data>? {
val pullRequest = dataContext.getData(GHPRActionKeys.SELECTED_PULL_REQUEST)
?: dataContext.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)?.detailsData?.loadedDetails
?: return null
return listOf(Data.URL(project, pullRequest.url))
}
private fun getDataFromHistory(project: Project, dataContext: DataContext): List<Data>? {
val fileRevision = dataContext.getData(VcsDataKeys.VCS_FILE_REVISION) ?: return null
if (fileRevision !is GitFileRevision) return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(fileRevision.path)
if (repository == null) return null
val accessibleRepositories = project.service<GHProjectRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.ghRepositoryCoordinates, fileRevision.revisionNumber.asString()) }
}
private fun getDataFromLog(project: Project, dataContext: DataContext): List<Data>? {
val log = dataContext.getData(VcsLogDataKeys.VCS_LOG) ?: return null
val selectedCommits = log.selectedCommits
if (selectedCommits.size != 1) return null
val commit = ContainerUtil.getFirstItem(selectedCommits) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(commit.root)
if (repository == null) return null
val accessibleRepositories = project.service<GHProjectRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.ghRepositoryCoordinates, commit.hash.asString()) }
}
private fun getDataFromVirtualFile(project: Project, dataContext: DataContext): List<Data>? {
val virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile)
if (repository == null) return null
val accessibleRepositories = project.service<GHProjectRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
val changeListManager = ChangeListManager.getInstance(project)
if (changeListManager.isUnversioned(virtualFile)) return null
val change = changeListManager.getChange(virtualFile)
return if (change != null && change.type == Change.Type.NEW) null
else accessibleRepositories.map { Data.File(project, it.ghRepositoryCoordinates, repository.root, virtualFile) }
}
protected sealed class Data(val project: Project) {
@Nls
abstract fun getName(): String
class File(project: Project,
val repository: GHRepositoryCoordinates,
val gitRepoRoot: VirtualFile,
val virtualFile: VirtualFile) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class Revision(project: Project, val repository: GHRepositoryCoordinates, val revisionHash: String) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class URL(project: Project, @NlsSafe val htmlUrl: String) : Data(project) {
override fun getName() = htmlUrl
}
}
private companion object {
class GithubOpenInBrowserAction(val data: Data)
: DumbAwareAction({ data.getName() }) {
override fun actionPerformed(e: AnActionEvent) {
when (data) {
is Data.Revision -> openCommitInBrowser(data.repository, data.revisionHash)
is Data.File -> openFileInBrowser(data.project, data.gitRepoRoot, data.repository, data.virtualFile,
e.getData(CommonDataKeys.EDITOR))
is Data.URL -> BrowserUtil.browse(data.htmlUrl)
}
}
private fun openCommitInBrowser(path: GHRepositoryCoordinates, revisionHash: String) {
BrowserUtil.browse("${path.toUrl()}/commit/$revisionHash")
}
private fun openFileInBrowser(project: Project,
repositoryRoot: VirtualFile,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?) {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repositoryRoot)
if (relativePath == null) {
GithubNotifications.showError(project, GithubNotificationIdsHolder.OPEN_IN_BROWSER_FILE_IS_NOT_UNDER_REPO,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("open.on.github.file.is.not.under.repository"),
"Root: " + repositoryRoot.presentableUrl + ", file: " + virtualFile.presentableUrl)
return
}
val hash = getCurrentFileRevisionHash(project, virtualFile)
if (hash == null) {
GithubNotifications.showError(project,
GithubNotificationIdsHolder.OPEN_IN_BROWSER_CANNOT_GET_LAST_REVISION,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("cannot.get.last.revision"))
return
}
val githubUrl = GHPathUtil.makeUrlToOpen(editor, relativePath, hash, path)
BrowserUtil.browse(githubUrl)
}
private fun getCurrentFileRevisionHash(project: Project, file: VirtualFile): String? {
val ref = Ref<GitRevisionNumber>()
object : Task.Modal(project, GithubBundle.message("open.on.github.getting.last.revision"), true) {
override fun run(indicator: ProgressIndicator) {
ref.set(GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD") as GitRevisionNumber?)
}
override fun onThrowable(error: Throwable) {
GithubUtil.LOG.warn(error)
}
}.queue()
return if (ref.isNull) null else ref.get().rev
}
}
}
}
object GHPathUtil {
fun getFileURL(repository: GitRepository,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?): String? {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repository.root)
if (relativePath == null) {
return null
}
val hash = repository.currentRevision
if (hash == null) {
return null
}
return makeUrlToOpen(editor, relativePath, hash, path)
}
fun makeUrlToOpen(editor: Editor?, relativePath: String, branch: String, path: GHRepositoryCoordinates): String {
val builder = StringBuilder()
if (StringUtil.isEmptyOrSpaces(relativePath)) {
builder.append(path.toUrl()).append("/tree/").append(branch)
}
else {
builder.append(path.toUrl()).append("/blob/").append(branch).append('/').append(URIUtil.encodePath(relativePath))
}
if (editor != null && editor.document.lineCount >= 1) {
// lines are counted internally from 0, but from 1 on github
val selectionModel = editor.selectionModel
val begin = editor.document.getLineNumber(selectionModel.selectionStart) + 1
val selectionEnd = selectionModel.selectionEnd
var end = editor.document.getLineNumber(selectionEnd) + 1
if (editor.document.getLineStartOffset(end - 1) == selectionEnd) {
end -= 1
}
builder.append("#L").append(begin)
if (begin != end) {
builder.append("-L").append(end)
}
}
return builder.toString()
}
} | apache-2.0 | 4b4ae1ae3e98eaeb512847b03de2b30a | 41.194757 | 132 | 0.702885 | 4.929978 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/behavior/impl/DefaultCursorHandler.kt | 1 | 2263 | package org.hexworks.zircon.internal.behavior.impl
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.internal.behavior.InternalCursorHandler
import kotlin.math.min
class DefaultCursorHandler(initialCursorSpace: Size) : InternalCursorHandler {
override var isCursorVisible = false
override val isCursorAtTheEndOfTheLine: Boolean
get() = cursorPosition.x == cursorSpaceSize.width - 1
override val isCursorAtTheStartOfTheLine: Boolean
get() = cursorPosition.x == 0
override val isCursorAtTheFirstRow: Boolean
get() = cursorPosition.y == 0
override val isCursorAtTheLastRow: Boolean
get() = cursorPosition.y == cursorSpaceSize.height - 1
override var cursorSpaceSize = initialCursorSpace
set(value) {
field = value
this.cursorPosition = cursorPosition
}
override var cursorPosition = Position.defaultPosition()
set(value) {
require(value.hasNegativeComponent.not()) {
"Can't put the cursor at a negative position: $value"
}
field = cursorPosition
.withX(min(value.x, cursorSpaceSize.width - 1))
.withY(min(value.y, cursorSpaceSize.height - 1))
}
override fun moveCursorForward() {
this.cursorPosition = cursorPosition.let { (column) ->
if (cursorIsAtTheEndOfTheLine(column)) {
cursorPosition.withX(0).withRelativeY(1)
} else {
cursorPosition.withRelativeX(1)
}
}
}
override fun moveCursorBackward() {
this.cursorPosition = cursorPosition.let { (column) ->
if (cursorIsAtTheStartOfTheLine(column)) {
if (cursorPosition.y > 0) {
cursorPosition.withX(cursorSpaceSize.width - 1).withRelativeY(-1)
} else {
cursorPosition
}
} else {
cursorPosition.withRelativeX(-1)
}
}
}
private fun cursorIsAtTheEndOfTheLine(column: Int) = column + 1 == cursorSpaceSize.width
private fun cursorIsAtTheStartOfTheLine(column: Int) = column == 0
}
| apache-2.0 | 1104d9a21b8a96e250ffc0103e6d2e97 | 31.797101 | 92 | 0.623067 | 4.637295 | false | false | false | false |
75py/Aplin | app/src/main/java/com/nagopy/android/aplin/ui/main/compose/HorizontalAppSection.kt | 1 | 1642 | package com.nagopy.android.aplin.ui.main.compose
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.nagopy.android.aplin.domain.model.PackageModel
@Composable
fun HorizontalAppSection(
title: String,
packages: List<PackageModel>,
navigateToVerticalList: () -> Unit,
startDetailSettingsActivity: (String) -> Unit,
searchByWeb: (PackageModel) -> Unit,
) {
Column {
Row(
modifier = Modifier
.clickable {
navigateToVerticalList.invoke()
}
.padding(8.dp)
) {
Text(
text = title + " (${packages.size})",
fontWeight = FontWeight.Bold,
modifier = Modifier
.weight(1f)
)
Icon(
imageVector = Icons.Default.ArrowForward,
contentDescription = "",
)
}
Spacer(modifier = Modifier.height(8.dp))
HorizontalAppList(packages, startDetailSettingsActivity, searchByWeb)
}
}
| apache-2.0 | cf42200c3c0828ef4ba438647c3c5f94 | 32.510204 | 77 | 0.666261 | 4.651558 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/WithListSoftLinksEntityImpl.kt | 1 | 9456 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class WithListSoftLinksEntityImpl : WithListSoftLinksEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField
var _myName: String? = null
override val myName: String
get() = _myName!!
@JvmField
var _links: List<NameId>? = null
override val links: List<NameId>
get() = _links!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: WithListSoftLinksEntityData?) : ModifiableWorkspaceEntityBase<WithListSoftLinksEntity>(), WithListSoftLinksEntity.Builder {
constructor() : this(WithListSoftLinksEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity WithListSoftLinksEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isMyNameInitialized()) {
error("Field WithListSoftLinksEntity#myName should be initialized")
}
if (!getEntityData().isLinksInitialized()) {
error("Field WithListSoftLinksEntity#links should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as WithListSoftLinksEntity
this.entitySource = dataSource.entitySource
this.myName = dataSource.myName
this.links = dataSource.links.toMutableList()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var myName: String
get() = getEntityData().myName
set(value) {
checkModificationAllowed()
getEntityData().myName = value
changedProperty.add("myName")
}
private val linksUpdater: (value: List<NameId>) -> Unit = { value ->
changedProperty.add("links")
}
override var links: MutableList<NameId>
get() {
val collection_links = getEntityData().links
if (collection_links !is MutableWorkspaceList) return collection_links
collection_links.setModificationUpdateAction(linksUpdater)
return collection_links
}
set(value) {
checkModificationAllowed()
getEntityData().links = value
linksUpdater.invoke(value)
}
override fun getEntityData(): WithListSoftLinksEntityData = result ?: super.getEntityData() as WithListSoftLinksEntityData
override fun getEntityClass(): Class<WithListSoftLinksEntity> = WithListSoftLinksEntity::class.java
}
}
class WithListSoftLinksEntityData : WorkspaceEntityData.WithCalculablePersistentId<WithListSoftLinksEntity>(), SoftLinkable {
lateinit var myName: String
lateinit var links: MutableList<NameId>
fun isMyNameInitialized(): Boolean = ::myName.isInitialized
fun isLinksInitialized(): Boolean = ::links.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
for (item in links) {
result.add(item)
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
for (item in links) {
index.index(this, item)
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
for (item in links) {
val removedItem_item = mutablePreviousSet.remove(item)
if (!removedItem_item) {
index.index(this, item)
}
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val links_data = links.map {
val it_data = if (it == oldLink) {
changed = true
newLink as NameId
}
else {
null
}
if (it_data != null) {
it_data
}
else {
it
}
}
if (links_data != null) {
links = links_data as MutableList
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<WithListSoftLinksEntity> {
val modifiable = WithListSoftLinksEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): WithListSoftLinksEntity {
val entity = WithListSoftLinksEntityImpl()
entity._myName = myName
entity._links = links.toList()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun clone(): WithListSoftLinksEntityData {
val clonedEntity = super.clone()
clonedEntity as WithListSoftLinksEntityData
clonedEntity.links = clonedEntity.links.toMutableWorkspaceList()
return clonedEntity
}
override fun persistentId(): PersistentEntityId<*> {
return AnotherNameId(myName)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return WithListSoftLinksEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return WithListSoftLinksEntity(myName, links, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as WithListSoftLinksEntityData
if (this.entitySource != other.entitySource) return false
if (this.myName != other.myName) return false
if (this.links != other.links) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as WithListSoftLinksEntityData
if (this.myName != other.myName) return false
if (this.links != other.links) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + myName.hashCode()
result = 31 * result + links.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + myName.hashCode()
result = 31 * result + links.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(NameId::class.java)
this.links?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | 60cf83d0c7fe7b3a717ec948414bada6 | 30.945946 | 151 | 0.715525 | 5.207048 | false | false | false | false |
hsson/card-balance-app | app/src/main/java/se/creotec/chscardbalance2/model/OpenHour.kt | 1 | 3177 | // Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.model
import com.google.gson.annotations.SerializedName
import java.util.*
class OpenHour {
@SerializedName("day_of_week")
var dayOfWeek: Int = 2
set(value) {
if (value in 1..7) {
field = value
}
}
@SerializedName("start_hour")
var startHour: Int = 1
set(value) {
if (value in 0..2400) {
field = value
}
}
@SerializedName("end_hour")
var endHour: Int = 2400
set(value) {
if (value in 0..2400) {
field = value
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as OpenHour
if (dayOfWeek != other.dayOfWeek) return false
if (startHour != other.startHour) return false
if (endHour != other.endHour) return false
return true
}
override fun hashCode(): Int {
var result = dayOfWeek
result = 31 * result + startHour
result = 31 * result + endHour
return result
}
override fun toString(): String {
return "OpenHour(dayOfWeek=$dayOfWeek, startHour=$startHour, endHour=$endHour)"
}
companion object {
fun toUnixTimeStamp(time: Int): Long {
if (time !in 0..2400) {
return -1
}
val c = Calendar.getInstance()
c.time = Date()
val timeStr = time.toString()
if (timeStr.length <= 2) {
c.set(Calendar.HOUR_OF_DAY, 0)
c.set(Calendar.MINUTE, time)
return c.timeInMillis
} else if (timeStr.length == 3) {
c.set(Calendar.HOUR_OF_DAY, time/100)
c.set(Calendar.MINUTE, timeStr.substring(1).toInt())
return c.timeInMillis
} else {
c.set(Calendar.HOUR_OF_DAY, time/100)
c.set(Calendar.MINUTE, timeStr.substring(2).toInt())
return c.timeInMillis
}
}
fun isBefore(time: Int): Boolean {
if (time !in 0..2400) {
return false
}
val c = Calendar.getInstance()
c.time = Date()
val timeStr = time.toString()
if (timeStr.length <= 2) {
return c.get(Calendar.HOUR_OF_DAY) == 0 && c.get(Calendar.MINUTE) < time
}
val hour = time/100
if (timeStr.length == 3) {
val minute = timeStr.substring(1).toInt()
return c.get(Calendar.HOUR_OF_DAY) < hour || (c.get(Calendar.HOUR_OF_DAY) <= hour && c.get(Calendar.MINUTE) < minute)
} else {
val minute = timeStr.substring(2).toInt()
return c.get(Calendar.HOUR_OF_DAY) < hour || (c.get(Calendar.HOUR_OF_DAY) <= hour && c.get(Calendar.MINUTE) < minute)
}
}
}
} | mit | 38167a9fa00693dbd1a06ab7eaf7e97c | 30.147059 | 133 | 0.516373 | 4.195509 | false | false | false | false |
ingokegel/intellij-community | platform/analysis-impl/src/com/intellij/codeInsight/lookup/LookupUtil.kt | 12 | 4733 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.lookup
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.injected.editor.DocumentWindow
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.annotations.ApiStatus
import kotlin.math.max
import kotlin.math.min
@ApiStatus.Internal
object LookupUtil {
private val LOG = logger<LookupUtil>()
@JvmStatic
fun insertLookupInDocumentWindowIfNeeded(project: Project,
editor: Editor, caretOffset: Int,
prefix: Int,
lookupString: String): Int {
val document = getInjectedDocument(project, editor, caretOffset)
if (document == null) return insertLookupInDocument(caretOffset, editor.document, prefix, lookupString)
val file = PsiDocumentManager.getInstance(project).getPsiFile(document)
val offset = document.hostToInjected(caretOffset)
val lookupStart = min(offset, max(offset - prefix, 0))
var diff = -1
if (file != null) {
val ranges = InjectedLanguageManager.getInstance(project)
.intersectWithAllEditableFragments(file, TextRange.create(lookupStart, offset))
if (ranges.isNotEmpty()) {
diff = ranges[0].startOffset - lookupStart
if (ranges.size == 1 && diff == 0) diff = -1
}
}
return if (diff == -1) insertLookupInDocument(caretOffset, editor.document, prefix, lookupString)
else document.injectedToHost(
insertLookupInDocument(offset, document, prefix - diff, if (diff == 0) lookupString else lookupString.substring(diff))
)
}
@JvmStatic
fun getCaseCorrectedLookupString(item: LookupElement, prefixMatcher: PrefixMatcher, prefix: String): String {
val lookupString = item.lookupString
if (item.isCaseSensitive) {
return lookupString
}
val length = prefix.length
if (length == 0 || !prefixMatcher.prefixMatches(prefix)) return lookupString
var isAllLower = true
var isAllUpper = true
var sameCase = true
var i = 0
while (i < length && (isAllLower || isAllUpper || sameCase)) {
val c = prefix[i]
val isLower = c.isLowerCase()
val isUpper = c.isUpperCase()
// do not take this kind of symbols into account ('_', '@', etc.)
if (!isLower && !isUpper) {
i++
continue
}
isAllLower = isAllLower && isLower
isAllUpper = isAllUpper && isUpper
sameCase = sameCase && i < lookupString.length && isLower == lookupString[i].isLowerCase()
i++
}
if (sameCase) return lookupString
if (isAllLower) return StringUtil.toLowerCase(lookupString)
return if (isAllUpper) StringUtil.toUpperCase(lookupString) else lookupString
}
private fun getInjectedDocument(project: Project,
editor: Editor,
offset: Int): DocumentWindow? {
val hostFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
if (hostFile != null) { // inspired by com.intellij.codeInsight.editorActions.TypedHandler.injectedEditorIfCharTypedIsSignificant()
val injected = InjectedLanguageManager.getInstance(project)
.getCachedInjectedDocumentsInRange(hostFile, TextRange.create(offset, offset))
for (documentWindow in injected) {
if (documentWindow.isValid && documentWindow.containsRange(offset, offset)) {
return documentWindow
}
}
}
return null
}
private fun insertLookupInDocument(caretOffset: Int, document: Document, prefix: Int, lookupString: String): Int {
val lookupStart = min(caretOffset, max(caretOffset - prefix, 0))
val len = document.textLength
LOG.assertTrue(lookupStart in 0..len, "ls: $lookupStart caret: $caretOffset prefix:$prefix doc: $len")
LOG.assertTrue(caretOffset in 0..len, "co: $caretOffset doc: $len")
document.replaceString(lookupStart, caretOffset, lookupString)
return lookupStart + lookupString.length
}
@JvmStatic
fun performGuardedChange(editor: Editor?, action: Runnable) {
val lookup = editor?.let(LookupManager::getActiveLookup)
if (lookup == null) {
action.run()
}
else {
lookup.performGuardedChange(action)
}
}
} | apache-2.0 | e2bba2d20391d9d506fe50416bedad9f | 40.893805 | 140 | 0.692584 | 4.55973 | false | false | false | false |
ingokegel/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubChooseAccountDialog.kt | 7 | 3945 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.authentication.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.*
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.i18n.GithubBundle
import java.awt.Component
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.JTextArea
import javax.swing.ListSelectionModel
class GithubChooseAccountDialog @JvmOverloads constructor(project: Project?, parentComponent: Component?,
accounts: Collection<GithubAccount>,
@Nls(capitalization = Nls.Capitalization.Sentence) descriptionText: String?,
showHosts: Boolean, allowDefault: Boolean,
@Nls(capitalization = Nls.Capitalization.Title) title: String = GithubBundle.message(
"account.choose.title"),
@Nls(capitalization = Nls.Capitalization.Title) okText: String = GithubBundle.message(
"account.choose.button"))
: DialogWrapper(project, parentComponent, false, IdeModalityType.PROJECT) {
private val description: JTextArea? = descriptionText?.let {
JTextArea().apply {
minimumSize = Dimension(0, 0)
font = StartupUiUtil.getLabelFont()
text = it
lineWrap = true
wrapStyleWord = true
isEditable = false
isFocusable = false
isOpaque = false
border = null
margin = JBInsets.emptyInsets()
}
}
private val accountsList: JBList<GithubAccount> = JBList<GithubAccount>(accounts).apply {
selectionMode = ListSelectionModel.SINGLE_SELECTION
cellRenderer = object : ColoredListCellRenderer<GithubAccount>() {
override fun customizeCellRenderer(list: JList<out GithubAccount>,
value: GithubAccount,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
append(value.name)
if (showHosts) {
append(" ")
append(value.server.toString(), SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
border = JBUI.Borders.empty(0, UIUtil.DEFAULT_HGAP)
}
}
}
private val setDefaultCheckBox: JBCheckBox? = if (allowDefault) JBCheckBox(GithubBundle.message("account.choose.as.default")) else null
init {
this.title = title
setOKButtonText(okText)
init()
accountsList.selectedIndex = 0
}
override fun getDimensionServiceKey() = "Github.Dialog.Accounts.Choose"
override fun doValidate(): ValidationInfo? {
return if (accountsList.selectedValue == null) ValidationInfo(GithubBundle.message("account.choose.not.selected"), accountsList)
else null
}
val account: GithubAccount get() = accountsList.selectedValue
val setDefault: Boolean get() = setDefaultCheckBox?.isSelected ?: false
override fun createCenterPanel(): JComponent {
return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP)
.apply { description?.run(::addToTop) }
.addToCenter(JBScrollPane(accountsList).apply {
preferredSize = JBDimension(150, 20 * (accountsList.itemsCount + 1))
})
.apply { setDefaultCheckBox?.run(::addToBottom) }
}
override fun getPreferredFocusedComponent() = accountsList
} | apache-2.0 | 77e1cf1453cdef47bf259a16058a1981 | 40.978723 | 137 | 0.67858 | 5.07722 | false | false | false | false |
sys1yagi/longest-streak-android | app/src/main/java/com/sys1yagi/longeststreakandroid/notification/LocalNotificationHelper.kt | 1 | 1255 | package com.sys1yagi.longeststreakandroid.notification
import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.support.v4.app.NotificationCompat
import com.sys1yagi.longeststreakandroid.R
class LocalNotificationHelper(val context: Context) {
fun createNotification(title: String, ticker: String, message: String): NotificationCompat.Builder {
val notificationBuilder = NotificationCompat.Builder(context)
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
notificationBuilder.setContentTitle(title)
notificationBuilder.setAutoCancel(true)
notificationBuilder.setTicker(ticker)
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS)
notificationBuilder.setContentText(message)
return notificationBuilder
}
fun notify(notificationId: Int, notificationBuilder: NotificationCompat.Builder?) {
if (notificationBuilder == null) {
return
}
val notification = notificationBuilder.build()
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(notificationId, notification)
}
}
| mit | 1eb7b9d70fb9816340dcfd228159dcba | 39.483871 | 111 | 0.768127 | 5.730594 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/usecase/SaveQuestsForChallengeUseCase.kt | 1 | 3783 | package io.ipoli.android.challenge.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.quest.BaseQuest
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.RepeatingQuest
import io.ipoli.android.quest.data.persistence.QuestRepository
import io.ipoli.android.repeatingquest.persistence.RepeatingQuestRepository
import io.ipoli.android.repeatingquest.usecase.SaveRepeatingQuestUseCase
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 3/8/18.
*/
open class SaveQuestsForChallengeUseCase(
private val questRepository: QuestRepository,
private val repeatingQuestRepository: RepeatingQuestRepository,
private val saveRepeatingQuestUseCase: SaveRepeatingQuestUseCase
) : UseCase<SaveQuestsForChallengeUseCase.Params, List<BaseQuest>> {
override fun execute(parameters: SaveQuestsForChallengeUseCase.Params): List<BaseQuest> {
val result = mutableListOf<BaseQuest>()
val challengeId = parameters.challengeId
val (quests, repeatingQuests) = when (parameters) {
is Params.WithNewQuests -> {
parameters.quests
.partition {
it is Quest
}
}
is Params.WithExistingQuests -> {
val allQuests = parameters.allQuests
allQuests
.filter {
parameters.selectedQuestIds.contains(
it.id
)
}.partition {
it is Quest
}
}
}
quests
.map { (it as Quest).copy(challengeId = challengeId) }
.let { result.addAll(questRepository.save(it)) }
when (parameters) {
is Params.WithNewQuests -> {
repeatingQuests.forEach {
val rq = it as RepeatingQuest
result.add(
saveRepeatingQuestUseCase.execute(
SaveRepeatingQuestUseCase.Params(
name = rq.name,
subQuestNames = rq.subQuests.map { sq -> sq.name },
color = rq.color,
icon = rq.icon,
startTime = rq.startTime,
duration = rq.duration,
reminders = rq.reminders,
challengeId = challengeId,
repeatPattern = rq.repeatPattern
)
)
)
}
}
is Params.WithExistingQuests -> {
repeatingQuests
.map { (it as RepeatingQuest).copy(challengeId = challengeId) }
.let { result.addAll(repeatingQuestRepository.save(it)) }
val rqIds = repeatingQuests.map { it.id }
rqIds
.map { questRepository.findAllForRepeatingQuestAfterDate(it, true) }
.flatten()
.map { it.copy(challengeId = challengeId) }
.let { result.addAll(questRepository.save(it)) }
}
}
return result
}
sealed class Params(
open val challengeId: String
) {
data class WithNewQuests(
override val challengeId: String,
val quests: List<BaseQuest>
) : Params(challengeId)
data class WithExistingQuests(
override val challengeId: String,
val allQuests: List<BaseQuest>,
val selectedQuestIds: Set<String>
) : Params(challengeId)
}
} | gpl-3.0 | 9a1663c53c950ef39df8bed9b9fbe90c | 34.037037 | 93 | 0.527888 | 5.596154 | false | false | false | false |
Firenox89/Shinobooru | app/src/main/java/com/github/firenox89/shinobooru/ui/sync/SyncActivity.kt | 1 | 3114 | package com.github.firenox89.shinobooru.ui.sync
import android.os.Bundle
import android.view.MenuItem
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.github.firenox89.shinobooru.R
import com.github.firenox89.shinobooru.ui.base.BaseActivity
import kotlinx.android.synthetic.main.activity_sync.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.inject
import timber.log.Timber
class SyncActivity : BaseActivity() {
private val viewModel: SyncViewModel by inject()
override fun onCreate(savedInstanceState: Bundle?) {
//TODO check permissions
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sync)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
}
override fun onStart() {
super.onStart()
lifecycleScope.launch {
viewModel.loadCloudState().fold({ state ->
postsOnDeviceText.text = state.postsOnDevice.size.toString()
postsOnCloudText.text = state.postsOnCloud.size.toString()
postsToUpload.text = state.postsToUpload.size.toString()
postsToDownload.text = state.postsToDownload.size.toString()
syncButton.setOnClickListener {
//to avoid starting this twice
syncButton.isEnabled = false
val syncProgress = viewModel.sync(state.postsToUpload, state.postsToDownload)
lifecycleScope.launch {
for (progress in syncProgress) {
if (progress.error != null) {
toast("${progress.error.message}")
errorText.text = progress.error.message
}
syncProgressText.text = String.format(
getString(R.string.cloudSyncState),
progress.postUploaded,
progress.totalPostsToUpload,
progress.postDownloaded,
progress.totalPostsToDownload)
}
toast("Sync complete")
syncButton.isEnabled = true
}
}
syncButton.isEnabled = true
}, { exception ->
Timber.e(exception)
toast("${exception.message}")
})
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
private suspend fun toast(msg: String) = withContext(Dispatchers.Main) {
Toast.makeText(this@SyncActivity, msg, Toast.LENGTH_LONG).show()
}
} | mit | 11f91b0ac9bc5aa6a02e368c09f25002 | 38.43038 | 97 | 0.577392 | 5.492063 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/QuickPopupsLesson.kt | 3 | 2219 | // 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 training.learn.lesson.general.assistance
import com.intellij.codeInsight.documentation.QuickDocUtil
import com.intellij.codeInsight.hint.ImplementationViewComponent
import org.assertj.swing.timing.Timeout
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.ui.LearningUiUtil
import java.util.concurrent.TimeUnit
class QuickPopupsLesson(private val sample: LessonSample) :
KLesson("CodeAssistance.QuickPopups", LessonsBundle.message("quick.popups.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
task("QuickJavaDoc") {
text(LessonsBundle.message("quick.popups.show.documentation", action(it)))
triggerOnQuickDocumentationPopup()
restoreIfModifiedOrMoved(sample)
test { actions(it) }
}
task {
text(LessonsBundle.message("quick.popups.press.escape", action("EditorEscape")))
stateCheck { previous.ui?.isShowing != true }
restoreIfModifiedOrMoved()
test {
invokeActionViaShortcut("ESCAPE")
}
}
task("QuickImplementations") {
text(LessonsBundle.message("quick.popups.show.implementation", action(it)))
triggerUI().component { _: ImplementationViewComponent -> true }
restoreIfModifiedOrMoved()
test {
actions(it)
val delay = Timeout.timeout(3, TimeUnit.SECONDS)
LearningUiUtil.findShowingComponentWithTimeout(project, ImplementationViewComponent::class.java, delay)
Thread.sleep(500)
invokeActionViaShortcut("ESCAPE")
}
}
}
private fun TaskRuntimeContext.checkDocComponentClosed(): Boolean {
val activeDocComponent = QuickDocUtil.getActiveDocComponent(project)
return activeDocComponent == null || !activeDocComponent.isShowing
}
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("quick.popups.help.link"),
LessonUtil.getHelpLink("using-code-editor.html#quick_popups")),
)
} | apache-2.0 | 81edef550b86eb05f57ae1028c59ea2f | 36.627119 | 140 | 0.738621 | 4.887665 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/suite/performanceSuite.kt | 1 | 16526 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.perf.suite
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.*
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import com.intellij.usages.Usage
import com.intellij.util.ArrayUtilRt
import com.intellij.util.containers.toArray
import com.intellij.util.indexing.UnindexedFilesUpdater
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.perf.util.ExternalProject
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.disableAllInspections
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.enableAllInspections
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.enableInspections
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.enableSingleInspection
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.initDefaultProfile
import org.jetbrains.kotlin.idea.performance.tests.utils.*
import org.jetbrains.kotlin.idea.performance.tests.utils.project.*
import org.jetbrains.kotlin.idea.test.invalidateLibraryCache
import org.jetbrains.kotlin.idea.testFramework.Fixture
import org.jetbrains.kotlin.idea.testFramework.Fixture.Companion.cleanupCaches
import org.jetbrains.kotlin.idea.testFramework.ProjectBuilder
import org.jetbrains.kotlin.idea.testFramework.Stats
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import java.io.File
class PerformanceSuite {
companion object {
fun suite(
name: String,
stats: StatsScope,
block: (StatsScope) -> Unit
) {
TeamCity.suite(name) {
stats.stats.use {
block(stats)
}
}
}
private fun PsiFile.highlightFile(toIgnore: IntArray = ArrayUtilRt.EMPTY_INT_ARRAY): List<HighlightInfo> {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)!!
val editor = EditorFactory.getInstance().getEditors(document).first()
PsiDocumentManager.getInstance(project).commitAllDocuments()
return CodeInsightTestFixtureImpl.instantiateAndRun(this, editor, toIgnore, true)
}
fun rollbackChanges(vararg file: VirtualFile) {
val fileDocumentManager = FileDocumentManager.getInstance()
runInEdtAndWait {
fileDocumentManager.reloadFiles(*file)
}
ProjectManagerEx.getInstanceEx().openProjects.forEach { project ->
val psiDocumentManagerBase = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase
runInEdtAndWait {
psiDocumentManagerBase.clearUncommittedDocuments()
psiDocumentManagerBase.commitAllDocuments()
}
}
}
}
class StatsScope(val config: StatsScopeConfig, val stats: Stats, val rootDisposable: Disposable) {
fun app(f: ApplicationScope.() -> Unit) = ApplicationScope(rootDisposable, this).use(f)
fun <T> measure(name: String, f: MeasurementScope<T>.() -> Unit): List<T?> =
MeasurementScope<T>(name, stats, config).apply(f).run()
fun <T> measure(name: String, f: MeasurementScope<T>.() -> Unit, after: (() -> Unit)?): List<T?> =
MeasurementScope<T>(name, stats, config, after = after).apply(f).run()
fun typeAndMeasureAutoCompletion(name: String, fixture: Fixture, f: TypeAndAutoCompletionMeasurementScope.() -> Unit, after: (() -> Unit)?): List<String?> =
TypeAndAutoCompletionMeasurementScope(fixture, typeTestPrefix = "typeAndAutocomplete", name = name, stats = stats, config = config, after = after).apply(f).run()
fun typeAndMeasureUndo(name: String, fixture: Fixture, f: TypeAndUndoMeasurementScope.() -> Unit, after: (() -> Unit)?): List<String?> =
TypeAndUndoMeasurementScope(fixture, typeTestPrefix = "typeAndUndo", name = name, stats = stats, config = config, after = after).apply(f).run()
fun measureTypeAndHighlight(name: String, fixture: Fixture, f: TypeAndHighlightMeasurementScope.() -> Unit, after: (() -> Unit)?): List<HighlightInfo?> =
TypeAndHighlightMeasurementScope(fixture, typeTestPrefix = "", name = name, stats = stats, config = config, after = after).apply(f).run()
fun logStatValue(name: String, value: Any) {
logMessage { "buildStatisticValue key='${stats.name}: $name' value='$value'" }
TeamCity.statValue("${stats.name}: $name", value)
}
}
class ApplicationScope(val rootDisposable: Disposable, val stats: StatsScope) : AutoCloseable {
val application = initApp(rootDisposable)
val jdk: Sdk = initSdk(rootDisposable)
fun project(externalProject: ExternalProject, refresh: Boolean = false, block: ProjectScope.() -> Unit) =
ProjectScope(ProjectScopeConfig(externalProject, refresh), this).use(block)
fun project(block: ProjectWithDescriptorScope.() -> Unit) =
ProjectWithDescriptorScope(this).use(block)
fun project(name: String? = null, path: String, openWith: ProjectOpenAction = ProjectOpenAction.EXISTING_IDEA_PROJECT, block: ProjectScope.() -> Unit) =
ProjectScope(ProjectScopeConfig(path, openWith, name = name), this).use(block)
fun gradleProject(name: String? = null, path: String, refresh: Boolean = false, block: ProjectScope.() -> Unit) =
ProjectScope(ProjectScopeConfig(path, ProjectOpenAction.GRADLE_PROJECT, refresh, name = name), this).use(block)
fun warmUpProject() = project {
descriptor {
name("helloWorld")
module {
kotlinStandardLibrary()
kotlinFile("HelloMain") {
topFunction("main") {
param("args", "Array<String>")
body("""println("Hello World!")""")
}
}
}
}
fixture("src/HelloMain.kt").use { fixture ->
fixture.highlight()
.also {
fixture.checkNoErrors(it)
}
.firstOrNull { it.severity == HighlightSeverity.WARNING }
?: error("`[UNUSED_PARAMETER] Parameter 'args' is never used` has to be highlighted")
}
}
override fun close() {
application.setDataProvider(null)
}
}
abstract class AbstractProjectScope(val app: ApplicationScope) : AutoCloseable {
abstract val project: Project
private val openFiles = mutableListOf<VirtualFile>()
private var compilerTester: CompilerTester? = null
fun profile(profile: ProjectProfile): Unit = when (profile) {
EmptyProfile -> project.disableAllInspections()
DefaultProfile -> project.initDefaultProfile()
FullProfile -> project.enableAllInspections()
is CustomProfile -> project.enableInspections(*profile.inspectionNames.toArray(emptyArray()))
}
fun withCompiler() {
compilerTester = CompilerTester(project, ModuleManager.getInstance(project).modules.toList(), null)
}
fun rebuildProject() {
compilerTester?.rebuild() ?: error("compiler isn't ready for compilation")
}
fun Fixture.highlight() = highlight(psiFile)
fun Fixture.checkNoErrors(highlightInfos: List<HighlightInfo>?) {
val errorHighlightInfos = highlightInfos?.filter { it.severity == HighlightSeverity.ERROR }
check(errorHighlightInfos?.isNotEmpty() != true) {
"No ERRORs are expected in ${this.fileName}: $errorHighlightInfos"
}
}
fun highlight(editorFile: PsiFile?, toIgnore: IntArray = ArrayUtilRt.EMPTY_INT_ARRAY) =
editorFile?.highlightFile(toIgnore) ?: error("editor isn't ready for highlight")
fun findUsages(config: CursorConfig): Set<Usage> {
val offset = config.fixture.editor.caretModel.offset
val psiFile = config.fixture.psiFile
val psiElement = psiFile.findElementAt(offset) ?: error("psi element not found at ${psiFile.virtualFile} : $offset")
val ktDeclaration = PsiTreeUtil.getParentOfType(psiElement, KtDeclaration::class.java)
?: error("KtDeclaration not found at ${psiFile.virtualFile} : $offset")
return config.fixture.findUsages(ktDeclaration)
}
fun enableSingleInspection(inspectionName: String) =
this.project.enableSingleInspection(inspectionName)
fun enableAllInspections() =
this.project.enableAllInspections()
fun editor(path: String) =
openInEditor(project, path).psiFile.also { openFiles.add(it.virtualFile) }
fun fixture(path: String, updateScriptDependenciesIfNeeded: Boolean = true): Fixture {
return fixture(projectFileByName(project, path).virtualFile, path, updateScriptDependenciesIfNeeded)
}
fun fixture(file: VirtualFile, fileName: String? = null, updateScriptDependenciesIfNeeded: Boolean = true): Fixture {
val fixture = Fixture.openFixture(project, file, fileName)
openFiles.add(fixture.vFile)
if (file.name.endsWith(KotlinFileType.EXTENSION)) {
assert(fixture.psiFile is KtFile) {
"$file expected to be a Kotlin file"
}
}
if (updateScriptDependenciesIfNeeded) {
fixture.updateScriptDependenciesIfNeeded()
}
return fixture
}
fun <T> measure(vararg name: String, clearCaches: Boolean = true, f: MeasurementScope<T>.() -> Unit): List<T?> {
val after = wrapAfter(clearCaches)
return app.stats.measure(name.joinToString("-"), f, after)
}
private fun wrapAfter(clearCaches: Boolean): () -> Unit {
val after = if (clearCaches) {
fun() { project.cleanupCaches() }
} else {
fun() {}
}
return after
}
fun <T> measure(fixture: Fixture, f: MeasurementScope<T>.() -> Unit): List<T?> =
measure(fixture.fileName, f = f)
fun <T> measure(fixture: Fixture, vararg name: String, f: MeasurementScope<T>.() -> Unit): List<T?> =
measure(combineName(fixture, *name), f = f)
fun measureTypeAndHighlight(
fixture: Fixture,
vararg name: String,
f: TypeAndHighlightMeasurementScope.() -> Unit = {}
): List<HighlightInfo?> {
val after = wrapAfter(true)
return app.stats.measureTypeAndHighlight(combineName(fixture, *name), fixture, f, after)
}
fun measureHighlight(fixture: Fixture, vararg name: String): List<List<HighlightInfo>?> {
return measure<List<HighlightInfo>?>(combineNameWithSimpleFileName("highlighting", fixture, *name)) {
before = {
fixture.openInEditor()
}
test = {
fixture.highlight()
}
after = {
fixture.close()
project.cleanupCaches()
}
}.onEach { fixture.checkNoErrors(it) }
}
fun typeAndMeasureAutoCompletion(fixture: Fixture, vararg name: String, clearCaches: Boolean = true, f: TypeAndAutoCompletionMeasurementScope.() -> Unit): List<String?> {
val after = wrapAfter(clearCaches)
return app.stats.typeAndMeasureAutoCompletion(combineName(fixture, *name), fixture, f, after)
}
fun typeAndMeasureUndo(fixture: Fixture, vararg name: String, clearCaches: Boolean = true, f: TypeAndUndoMeasurementScope.() -> Unit = {}): List<String?> {
val after = wrapAfter(clearCaches)
return app.stats.typeAndMeasureUndo(combineName(fixture, *name), fixture, f, after)
}
fun combineName(fixture: Fixture, vararg name: String) =
listOf(name.joinToString("-"), fixture.fileName)
.filter { it.isNotEmpty() }
.joinToString(" ")
fun combineNameWithSimpleFileName(type: String, fixture: Fixture, vararg name: String): String =
listOf(type, name.joinToString("-"), fixture.simpleFilename())
.filter { it.isNotEmpty() }
.joinToString(" ")
override fun close(): Unit = RunAll(
{ compilerTester?.tearDown() },
{ project.let { prj -> app.application.closeProject(prj) } }
).run()
}
class ProjectWithDescriptorScope(app: ApplicationScope) : AbstractProjectScope(app) {
private var descriptor: ProjectBuilder? = null
override val project: Project by lazy {
val builder = descriptor ?: error("project is not configured")
val openProject = builder.openProjectOperation()
openProject.openProject().also {
openProject.postOpenProject(it)
}
}
fun descriptor(descriptor: ProjectBuilder.() -> Unit) {
this.descriptor = ProjectBuilder().apply(descriptor)
}
}
class ProjectScope(config: ProjectScopeConfig, app: ApplicationScope) : AbstractProjectScope(app) {
override val project: Project = initProject(config, app)
companion object {
fun initProject(config: ProjectScopeConfig, app: ApplicationScope): Project {
val projectPath = File(config.path).canonicalPath
UsefulTestCase.assertTrue("path ${config.path} does not exist, check README.md", File(projectPath).exists())
val openProject = OpenProject(
projectPath = projectPath,
projectName = config.projectName,
jdk = app.jdk,
projectOpenAction = config.openWith
)
val project = ProjectOpenAction.openProject(openProject)
openProject.projectOpenAction.postOpenProject(project, openProject)
// indexing
if (config.refresh) {
invalidateLibraryCache(project)
}
CodeInsightTestFixtureImpl.ensureIndexesUpToDate(project)
dispatchAllInvocationEvents()
with(DumbService.getInstance(project)) {
UnindexedFilesUpdater(project).queue()
completeJustSubmittedTasks()
}
dispatchAllInvocationEvents()
Fixture.enableAnnotatorsAndLoadDefinitions(project)
app.application.setDataProvider(TestDataProvider(project))
return project
}
}
}
}
sealed class ProjectProfile
object EmptyProfile : ProjectProfile()
object DefaultProfile : ProjectProfile()
object FullProfile : ProjectProfile()
data class CustomProfile(val inspectionNames: List<String>) : ProjectProfile()
fun UsefulTestCase.suite(
suiteName: String? = null,
config: StatsScopeConfig = StatsScopeConfig(),
block: PerformanceSuite.StatsScope.() -> Unit
) {
val stats = Stats(config.name ?: suiteName ?: name, outputConfig = config.outputConfig, profilerConfig = config.profilerConfig)
PerformanceSuite.suite(
suiteName ?: this.javaClass.name,
PerformanceSuite.StatsScope(config, stats, testRootDisposable),
block
)
}
| apache-2.0 | b9cc448b701bd571decdd3e7cb91104c | 44.029973 | 178 | 0.641716 | 5.000303 | false | true | false | false |
ktorio/ktor | ktor-shared/ktor-serialization/ktor-serialization-kotlinx/ktor-serialization-kotlinx-json/common/test/JsonSerializationTest.kt | 1 | 5562 | /*
* 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.serialization.kotlinx.test.json
import io.ktor.http.*
import io.ktor.serialization.*
import io.ktor.serialization.kotlinx.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.serialization.kotlinx.test.*
import io.ktor.test.dispatcher.*
import io.ktor.util.reflect.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.test.*
@OptIn(ExperimentalSerializationApi::class)
class JsonSerializationTest : AbstractSerializationTest<Json>() {
override val defaultContentType: ContentType = ContentType.Application.Json
override val defaultSerializationFormat: Json = DefaultJson
override fun assertEquals(expectedAsJson: String, actual: ByteArray, format: Json): Boolean {
return expectedAsJson == actual.decodeToString()
}
@Test
fun testJsonElements() = testSuspend {
val testSerializer = KotlinxSerializationConverter(defaultSerializationFormat)
testSerializer.testSerialize(
buildJsonObject {
put("a", "1")
put(
"b",
buildJsonObject {
put("c", 3)
}
)
put("x", JsonNull)
}
).let { result ->
assertEquals("""{"a":"1","b":{"c":3},"x":null}""", result.decodeToString())
}
testSerializer.testSerialize(
buildJsonObject {
put("a", "1")
put(
"b",
buildJsonArray {
add("c")
add(JsonPrimitive(2))
}
)
}
).let { result ->
assertEquals("""{"a":"1","b":["c",2]}""", result.decodeToString())
}
}
@Test
fun testContextual() = testSuspend {
val serializer = KotlinxSerializationConverter(
Json {
prettyPrint = true
encodeDefaults = true
serializersModule =
SerializersModule {
contextual(Either::class) { serializers: List<KSerializer<*>> ->
EitherSerializer(serializers[0], serializers[1])
}
}
}
)
val dogJson = """{"age": 8,"name":"Auri"}"""
assertEquals(
Either.Right(DogDTO(8, "Auri")),
serializer.deserialize(
Charsets.UTF_8,
typeInfo<Either<ErrorDTO, DogDTO>>(),
ByteReadChannel(dogJson.toByteArray())
)
)
val errorJson = """{"message": "Some error"}"""
assertEquals(
Either.Left(ErrorDTO("Some error")),
serializer.deserialize(
Charsets.UTF_8,
typeInfo<Either<ErrorDTO, DogDTO>>(),
ByteReadChannel(errorJson.toByteArray())
)
)
val emptyErrorJson = "{}"
assertEquals(
Either.Left(ErrorDTO("Some default error")),
serializer.deserialize(
Charsets.UTF_8,
typeInfo<Either<ErrorDTO, DogDTO>>(),
ByteReadChannel(emptyErrorJson.toByteArray())
)
)
}
@Test
fun testExtraFields() = testSuspend {
val testSerializer = KotlinxSerializationConverter(defaultSerializationFormat)
val dogExtraFieldJson = """{"age": 8,"name":"Auri","color":"Black"}"""
assertFailsWith<JsonConvertException> {
testSerializer.deserialize(
Charsets.UTF_8,
typeInfo<DogDTO>(),
ByteReadChannel(dogExtraFieldJson.toByteArray())
)
}
}
}
@Serializable
data class DogDTO(val age: Int, val name: String)
@Serializable
data class ErrorDTO(val message: String = "Some default error")
sealed class Either<out L, out R> {
data class Left<out L>(val left: L) : Either<L, Nothing>()
data class Right<out R>(val right: R) : Either<Nothing, R>()
}
class EitherSerializer<L, R>(
private val leftSerializer: KSerializer<L>,
private val rightSerializer: KSerializer<R>,
) : KSerializer<Either<L, R>> {
override val descriptor: SerialDescriptor =
buildClassSerialDescriptor("NetworkEitherSerializer") {
element("left", leftSerializer.descriptor)
element("right", rightSerializer.descriptor)
}
override fun deserialize(decoder: Decoder): Either<L, R> {
require(decoder is JsonDecoder) { "only works in JSON format" }
val element: JsonElement = decoder.decodeJsonElement()
return try {
Either.Right(decoder.json.decodeFromJsonElement(rightSerializer, element))
} catch (throwable: Throwable) {
Either.Left(decoder.json.decodeFromJsonElement(leftSerializer, element))
}
}
override fun serialize(encoder: Encoder, value: Either<L, R>) {
when (value) {
is Either.Left -> encoder.encodeSerializableValue(leftSerializer, value.left)
is Either.Right -> encoder.encodeSerializableValue(rightSerializer, value.right)
}
}
}
| apache-2.0 | ebaeb73f795cd2e98e0d215e60079ef2 | 32.709091 | 119 | 0.580726 | 4.926484 | false | true | false | false |
ktorio/ktor | ktor-io/posix/src/io/ktor/utils/io/core/StringsNative.kt | 1 | 1102 | package io.ktor.utils.io.core
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.internal.*
import kotlinx.cinterop.*
/**
* Create an instance of [String] from the specified [bytes] range starting at [offset] and bytes [length]
* interpreting characters in the specified [charset].
*/
@Suppress("FunctionName")
public actual fun String(bytes: ByteArray, offset: Int, length: Int, charset: Charset): String {
if (length == 0 && offset <= bytes.size) return ""
return bytes.usePinned { pinned ->
val ptr = pinned.addressOf(offset)
val view = ChunkBuffer(ptr, length, null)
view.resetForRead()
val packet = ByteReadPacket(view, ChunkBuffer.NoPoolManuallyManaged)
check(packet.remaining == length.toLong())
charset.newDecoder().decode(packet, Int.MAX_VALUE)
}
}
internal actual fun String.getCharsInternal(dst: CharArray, dstOffset: Int) {
val length = length
require(dstOffset + length <= dst.size)
var dstIndex = dstOffset
for (srcIndex in 0 until length) {
dst[dstIndex++] = this[srcIndex]
}
}
| apache-2.0 | 6338f5a44238247d16d0e61fefa10022 | 32.393939 | 106 | 0.685118 | 3.907801 | false | false | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/detector/ScDetector.kt | 1 | 1032 | package ch.abertschi.adfree.detector
import android.app.Notification
import org.jetbrains.anko.AnkoLogger
class ScDetector : AdDetectable, AnkoLogger {
private val keyword: String = "advertisement"
private val pack = "com.soundcloud.android"
override fun canHandle(payload: AdPayload): Boolean {
return payload?.statusbarNotification?.key?.toLowerCase()?.contains(pack) ?: false
}
override fun flagAsAdvertisement(payload: AdPayload): Boolean {
val extras = payload.statusbarNotification?.notification?.extras
val title: String? = extras?.getString(Notification.EXTRA_TITLE)?.trim()?.toLowerCase()
val subTitle: String? = extras?.getString(Notification.EXTRA_SUB_TEXT)
return title != null && title == keyword
&& subTitle == null
}
override fun getMeta(): AdDetectorMeta = AdDetectorMeta(
"Soundcloud", "experimental detector for soundcloud (english)",
true,
category = "Soundcloud",
debugOnly = false
)
} | apache-2.0 | 074de28fb14c736d178af08bc064b07d | 33.433333 | 95 | 0.686047 | 4.690909 | false | false | false | false |
carrotengineer/Warren | src/test/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl376HandlerTests.kt | 2 | 5408 | package engineer.carrot.warren.warren.handler.rpl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import engineer.carrot.warren.kale.irc.message.rfc1459.JoinMessage
import engineer.carrot.warren.kale.irc.message.rfc1459.rpl.Rpl376Message
import engineer.carrot.warren.warren.IMessageSink
import engineer.carrot.warren.warren.event.ConnectionLifecycleEvent
import engineer.carrot.warren.warren.event.IWarrenEventDispatcher
import engineer.carrot.warren.warren.extension.cap.CapLifecycle
import engineer.carrot.warren.warren.extension.cap.CapState
import engineer.carrot.warren.warren.state.*
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class Rpl376HandlerTests {
lateinit var handler: Rpl376Handler
lateinit var mockSink: IMessageSink
lateinit var connectionState: ConnectionState
lateinit var capState: CapState
lateinit var mockEventDispatcher: IWarrenEventDispatcher
@Before fun setUp() {
val lifecycleState = LifecycleState.CONNECTING
val capLifecycleState = CapLifecycle.NEGOTIATED
capState = CapState(lifecycle = capLifecycleState, negotiate = setOf(), server = mapOf(), accepted = setOf(), rejected = setOf())
connectionState = ConnectionState(server = "test.server", port = 6697, nickname = "test-nick", user = "test-nick", lifecycle = lifecycleState)
mockSink = mock()
mockEventDispatcher = mock()
handler = Rpl376Handler(mockEventDispatcher, mockSink, channelsToJoin = mapOf("#channel1" to null, "#channel2" to "testkey"), connectionState = connectionState, capState = capState)
}
@Test fun test_handle_JoinsChannelsAfterGettingMOTD_ConnectingState() {
connectionState.lifecycle = LifecycleState.CONNECTING
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
verify(mockSink).write(JoinMessage(channels = listOf("#channel1")))
verify(mockSink).write(JoinMessage(channels = listOf("#channel2"), keys = listOf("testkey")))
}
@Test fun test_handle_JoinsChannelsAfterGettingMOTD_RegisteringState() {
connectionState.lifecycle = LifecycleState.REGISTERING
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
verify(mockSink).write(JoinMessage(channels = listOf("#channel1")))
verify(mockSink).write(JoinMessage(channels = listOf("#channel2"), keys = listOf("testkey")))
}
@Test fun test_handle_ShouldIdentifyWithNickServ_NoCredentials_SetsAuthLifecycleToFailed() {
connectionState.nickServ = NickServState(shouldAuth = true, lifecycle = AuthLifecycle.AUTHING, credentials = null, channelJoinWaitSeconds = 0)
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
assertEquals(AuthLifecycle.AUTH_FAILED, connectionState.nickServ.lifecycle)
}
@Test fun test_handle_ShouldIdentifyWithNickServ_WithCredentials_SetsAuthLifecycleAuthed() {
val credentials = AuthCredentials(account = "", password = "")
connectionState.nickServ = NickServState(shouldAuth = true, lifecycle = AuthLifecycle.AUTHING, credentials = credentials, channelJoinWaitSeconds = 0)
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
assertEquals(AuthLifecycle.AUTHED, connectionState.nickServ.lifecycle)
}
@Test fun test_handle_ShouldIdentifyWithNickServ_WithCredentials_SendsNickservIdentify() {
val credentials = AuthCredentials(account = "account", password = "password")
connectionState.nickServ = NickServState(shouldAuth = true, lifecycle = AuthLifecycle.AUTHING, credentials = credentials, channelJoinWaitSeconds = 0)
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
verify(mockSink).writeRaw("NICKSERV identify account password")
}
@Test fun test_handle_ShouldNotIdentifyWithNickserv_SendsNoRawMessages() {
val handler = Rpl376Handler(mockEventDispatcher, mockSink, channelsToJoin = mapOf(), connectionState = connectionState, capState = capState)
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
verify(mockSink, never()).writeRaw(any())
}
@Test fun test_handle_UpdatesLifecycleStateToConnected() {
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
assertEquals(LifecycleState.CONNECTED, connectionState.lifecycle)
}
@Test fun test_handle_FiresConnectedEvent() {
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
verify(mockEventDispatcher).fire(ConnectionLifecycleEvent(lifecycle = LifecycleState.CONNECTED))
}
@Test fun test_handle_CapNegotiating_SetsToFailed() {
capState.lifecycle = CapLifecycle.NEGOTIATING
handler.handle(Rpl376Message(source = "test.source", target = "test-user", contents = "end of motd"), mapOf())
assertEquals(CapLifecycle.FAILED, capState.lifecycle)
}
} | isc | 5495666bf316cc39b045ac08d810b059 | 49.083333 | 189 | 0.736501 | 4.322942 | false | true | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/test/java/com/doctoror/particleswallpaper/userprefs/engine/EnginePreferenceValueMapperTest.kt | 1 | 2071 | package com.doctoror.particleswallpaper.userprefs.engine
import android.content.res.Resources
import com.doctoror.particleswallpaper.R
import org.junit.Assert.*
import org.junit.Test
import org.mockito.kotlin.mock
import java.util.*
private const val ENTRY_OPENGL = "OpenGL"
private const val ENTRY_CANVAS = "Canvas"
private const val VALUE_OPENGL = "opengl"
private const val VALUE_CANVAS = "canvas"
class EnginePreferenceValueMapperTest {
private val resources: Resources = mock {
on(it.getText(R.string.OpenGL)).thenReturn(ENTRY_OPENGL)
on(it.getText(R.string.Canvas)).thenReturn(ENTRY_CANVAS)
}
private val underTest = EnginePreferenceValueMapper(resources)
@Test
fun providesEntries() {
val entries = underTest.provideEntries()
assertTrue(Arrays.equals(entries, arrayOf<CharSequence>(ENTRY_OPENGL, ENTRY_CANVAS)))
}
@Test
fun providesEntryValues() {
val entries = underTest.provideEntryValues()
assertTrue(
Arrays.equals(
entries, arrayOf<CharSequence>(
VALUE_OPENGL,
VALUE_CANVAS
)
)
)
}
@Test
fun valueToEnabledStateIsTrueForNull() {
assertTrue(underTest.valueToOpenglEnabledState(null))
}
@Test
fun valueToEnabledStateIsTrueForOpenGL() {
assertTrue(underTest.valueToOpenglEnabledState(VALUE_OPENGL))
}
@Test
fun valueToEnabledStateIsFalseForCanvas() {
assertFalse(underTest.valueToOpenglEnabledState(VALUE_CANVAS))
}
@Test
fun valueToEnabledStateThrowsForUnexpectedValue() {
assertThrows(IllegalArgumentException::class.java) {
underTest.valueToOpenglEnabledState("Canvas")
}
}
@Test
fun valueForOpenEnabledStateIsOpenGl() {
assertEquals(VALUE_OPENGL, underTest.openglEnabledStateToValue(true))
}
@Test
fun valueForOpenDisabledStateIsCanvas() {
assertEquals(VALUE_CANVAS, underTest.openglEnabledStateToValue(false))
}
}
| apache-2.0 | 379cf8082e4eedc2be64458b842f1a24 | 26.25 | 93 | 0.682762 | 4.511983 | false | true | false | false |
adrianswiatek/numbers-teacher | NumbersTeacher/app/src/main/java/pl/aswiatek/numbersteacher/businesslogic/numbergenerator/algorithm/MostSignificantNumberGenerator.kt | 1 | 916 | package pl.aswiatek.numbersteacher.businesslogic.numbergenerator.algorithm
import pl.aswiatek.numbersteacher.businesslogic.Settings
import java.util.*
class MostSignificantNumberGenerator(
private val random: Random,
private val settings: Settings)
: NumberGeneratorAlgorithm {
override fun generate(previousNumber: Int): Int {
val properPreviousNumber = previousNumber / settings.questionRadix
var generatedNumber: Int
do {
generatedNumber = random.nextInt(settings.questionRadix)
} while (isInvalid(generatedNumber, properPreviousNumber))
return generatedNumber
.toString(settings.questionRadix)
.padEnd(settings.maxLength, '0')
.toInt(settings.questionRadix)
}
private fun isInvalid(generatedNumber: Int, previousNumber: Int) =
generatedNumber == previousNumber || generatedNumber == 0
} | mit | 5eebad0776362b253da6aec627813064 | 32.962963 | 74 | 0.717249 | 4.770833 | false | false | false | false |
cmzy/okhttp | mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt | 1 | 39797 | /*
* Copyright (C) 2011 Google Inc.
* Copyright (C) 2013 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 mockwebserver3
import java.io.Closeable
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ProtocolException
import java.net.Proxy
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.Collections
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.logging.Level
import java.util.logging.Logger
import javax.net.ServerSocketFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
import mockwebserver3.SocketPolicy.CONTINUE_ALWAYS
import mockwebserver3.SocketPolicy.DISCONNECT_AFTER_REQUEST
import mockwebserver3.SocketPolicy.DISCONNECT_AT_END
import mockwebserver3.SocketPolicy.DISCONNECT_AT_START
import mockwebserver3.SocketPolicy.DISCONNECT_DURING_REQUEST_BODY
import mockwebserver3.SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY
import mockwebserver3.SocketPolicy.DO_NOT_READ_REQUEST_BODY
import mockwebserver3.SocketPolicy.EXPECT_CONTINUE
import mockwebserver3.SocketPolicy.FAIL_HANDSHAKE
import mockwebserver3.SocketPolicy.NO_RESPONSE
import mockwebserver3.SocketPolicy.RESET_STREAM_AT_START
import mockwebserver3.SocketPolicy.SHUTDOWN_INPUT_AT_END
import mockwebserver3.SocketPolicy.SHUTDOWN_OUTPUT_AT_END
import mockwebserver3.SocketPolicy.SHUTDOWN_SERVER_AFTER_RESPONSE
import mockwebserver3.SocketPolicy.STALL_SOCKET_AT_START
import mockwebserver3.SocketPolicy.UPGRADE_TO_SSL_AT_END
import mockwebserver3.internal.duplex.DuplexResponseBody
import okhttp3.Headers
import okhttp3.Headers.Companion.headersOf
import okhttp3.HttpUrl
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.addHeaderLenient
import okhttp3.internal.closeQuietly
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.duplex.MwsDuplexAccess
import okhttp3.internal.http.HttpMethod
import okhttp3.internal.http2.ErrorCode
import okhttp3.internal.http2.Header
import okhttp3.internal.http2.Http2Connection
import okhttp3.internal.http2.Http2Stream
import okhttp3.internal.immutableListOf
import okhttp3.internal.platform.Platform
import okhttp3.internal.threadFactory
import okhttp3.internal.toImmutableList
import okhttp3.internal.ws.RealWebSocket
import okhttp3.internal.ws.WebSocketExtensions
import okhttp3.internal.ws.WebSocketProtocol
import okio.Buffer
import okio.BufferedSink
import okio.BufferedSource
import okio.ByteString.Companion.encodeUtf8
import okio.Sink
import okio.Timeout
import okio.buffer
import okio.sink
import okio.source
/**
* A scriptable web server. Callers supply canned responses and the server replays them upon request
* in sequence.
*/
class MockWebServer : Closeable {
private val taskRunnerBackend = TaskRunner.RealBackend(
threadFactory("MockWebServer TaskRunner", daemon = false))
private val taskRunner = TaskRunner(taskRunnerBackend)
private val requestQueue = LinkedBlockingQueue<RecordedRequest>()
private val openClientSockets =
Collections.newSetFromMap(ConcurrentHashMap<Socket, Boolean>())
private val openConnections =
Collections.newSetFromMap(ConcurrentHashMap<Http2Connection, Boolean>())
private val atomicRequestCount = AtomicInteger()
/**
* The number of HTTP requests received thus far by this server. This may exceed the number of
* HTTP connections when connection reuse is in practice.
*/
val requestCount: Int
get() = atomicRequestCount.get()
/** The number of bytes of the POST body to keep in memory to the given limit. */
var bodyLimit: Long = Long.MAX_VALUE
var serverSocketFactory: ServerSocketFactory? = null
@Synchronized get() {
if (field == null && started) {
field = ServerSocketFactory.getDefault() // Build the default value lazily.
}
return field
}
@Synchronized set(value) {
check(!started) { "serverSocketFactory must not be set after start()" }
field = value
}
private var serverSocket: ServerSocket? = null
private var sslSocketFactory: SSLSocketFactory? = null
private var tunnelProxy: Boolean = false
private var clientAuth = CLIENT_AUTH_NONE
/**
* The dispatcher used to respond to HTTP requests. The default dispatcher is a [QueueDispatcher],
* which serves a fixed sequence of responses from a [queue][enqueue].
*
* Other dispatchers can be configured. They can vary the response based on timing or the content
* of the request.
*/
var dispatcher: Dispatcher = QueueDispatcher()
private var portField: Int = -1
val port: Int
get() {
before()
return portField
}
val hostName: String
get() {
before()
return inetSocketAddress!!.address.canonicalHostName
}
private var inetSocketAddress: InetSocketAddress? = null
/**
* True if ALPN is used on incoming HTTPS connections to negotiate a protocol like HTTP/1.1 or
* HTTP/2. This is true by default; set to false to disable negotiation and restrict connections
* to HTTP/1.1.
*/
var protocolNegotiationEnabled: Boolean = true
/**
* The protocols supported by ALPN on incoming HTTPS connections in order of preference. The list
* must contain [Protocol.HTTP_1_1]. It must not contain null.
*
* This list is ignored when [negotiation is disabled][protocolNegotiationEnabled].
*/
@get:JvmName("protocols") var protocols: List<Protocol> =
immutableListOf(Protocol.HTTP_2, Protocol.HTTP_1_1)
set(value) {
val protocolList = value.toImmutableList()
require(Protocol.H2_PRIOR_KNOWLEDGE !in protocolList || protocolList.size == 1) {
"protocols containing h2_prior_knowledge cannot use other protocols: $protocolList"
}
require(Protocol.HTTP_1_1 in protocolList || Protocol.H2_PRIOR_KNOWLEDGE in protocolList) {
"protocols doesn't contain http/1.1: $protocolList"
}
require(null !in protocolList as List<Protocol?>) { "protocols must not contain null" }
field = protocolList
}
var started: Boolean = false
private var shutdown: Boolean = false
@Synchronized private fun before() {
if (started) return // Don't call start() in case we're already shut down.
try {
start()
} catch (e: IOException) {
throw RuntimeException(e)
}
}
@JvmName("-deprecated_port")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "port"),
level = DeprecationLevel.ERROR)
fun getPort(): Int = port
fun toProxyAddress(): Proxy {
before()
val address = InetSocketAddress(inetSocketAddress!!.address.canonicalHostName, port)
return Proxy(Proxy.Type.HTTP, address)
}
@JvmName("-deprecated_serverSocketFactory")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(
expression = "run { this.serverSocketFactory = serverSocketFactory }"
),
level = DeprecationLevel.ERROR)
fun setServerSocketFactory(serverSocketFactory: ServerSocketFactory) = run {
this.serverSocketFactory = serverSocketFactory
}
/**
* Returns a URL for connecting to this server.
*
* @param path the request path, such as "/".
*/
fun url(path: String): HttpUrl {
return HttpUrl.Builder()
.scheme(if (sslSocketFactory != null) "https" else "http")
.host(hostName)
.port(port)
.build()
.resolve(path)!!
}
@JvmName("-deprecated_bodyLimit")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(
expression = "run { this.bodyLimit = bodyLimit }"
),
level = DeprecationLevel.ERROR)
fun setBodyLimit(bodyLimit: Long) = run { this.bodyLimit = bodyLimit }
@JvmName("-deprecated_protocolNegotiationEnabled")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(
expression = "run { this.protocolNegotiationEnabled = protocolNegotiationEnabled }"
),
level = DeprecationLevel.ERROR)
fun setProtocolNegotiationEnabled(protocolNegotiationEnabled: Boolean) = run {
this.protocolNegotiationEnabled = protocolNegotiationEnabled
}
@JvmName("-deprecated_protocols")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "run { this.protocols = protocols }"),
level = DeprecationLevel.ERROR)
fun setProtocols(protocols: List<Protocol>) = run { this.protocols = protocols }
@JvmName("-deprecated_protocols")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "protocols"),
level = DeprecationLevel.ERROR)
fun protocols(): List<Protocol> = protocols
/**
* Serve requests with HTTPS rather than otherwise.
*
* @param tunnelProxy true to expect the HTTP CONNECT method before negotiating TLS.
*/
fun useHttps(sslSocketFactory: SSLSocketFactory, tunnelProxy: Boolean) {
this.sslSocketFactory = sslSocketFactory
this.tunnelProxy = tunnelProxy
}
/**
* Configure the server to not perform SSL authentication of the client. This leaves
* authentication to another layer such as in an HTTP cookie or header. This is the default and
* most common configuration.
*/
fun noClientAuth() {
this.clientAuth = CLIENT_AUTH_NONE
}
/**
* Configure the server to [want client auth][SSLSocket.setWantClientAuth]. If the
* client presents a certificate that is [trusted][TrustManager] the handshake will
* proceed normally. The connection will also proceed normally if the client presents no
* certificate at all! But if the client presents an untrusted certificate the handshake
* will fail and no connection will be established.
*/
fun requestClientAuth() {
this.clientAuth = CLIENT_AUTH_REQUESTED
}
/**
* Configure the server to [need client auth][SSLSocket.setNeedClientAuth]. If the
* client presents a certificate that is [trusted][TrustManager] the handshake will
* proceed normally. If the client presents an untrusted certificate or no certificate at all the
* handshake will fail and no connection will be established.
*/
fun requireClientAuth() {
this.clientAuth = CLIENT_AUTH_REQUIRED
}
/**
* Awaits the next HTTP request, removes it, and returns it. Callers should use this to verify the
* request was sent as intended. This method will block until the request is available, possibly
* forever.
*
* @return the head of the request queue
*/
@Throws(InterruptedException::class)
fun takeRequest(): RecordedRequest = requestQueue.take()
/**
* Awaits the next HTTP request (waiting up to the specified wait time if necessary), removes it,
* and returns it. Callers should use this to verify the request was sent as intended within the
* given time.
*
* @param timeout how long to wait before giving up, in units of [unit]
* @param unit a [TimeUnit] determining how to interpret the [timeout] parameter
* @return the head of the request queue
*/
@Throws(InterruptedException::class)
fun takeRequest(timeout: Long, unit: TimeUnit): RecordedRequest? =
requestQueue.poll(timeout, unit)
@JvmName("-deprecated_requestCount")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "requestCount"),
level = DeprecationLevel.ERROR)
fun getRequestCount(): Int = requestCount
/**
* Scripts [response] to be returned to a request made in sequence. The first request is
* served by the first enqueued response; the second request by the second enqueued response; and
* so on.
*
* @throws ClassCastException if the default dispatcher has been
* replaced with [setDispatcher][dispatcher].
*/
fun enqueue(response: MockResponse) =
(dispatcher as QueueDispatcher).enqueueResponse(response.clone())
/**
* Starts the server on the loopback interface for the given port.
*
* @param port the port to listen to, or 0 for any available port. Automated tests should always
* use port 0 to avoid flakiness when a specific port is unavailable.
*/
@Throws(IOException::class)
@JvmOverloads fun start(port: Int = 0) = start(InetAddress.getByName("localhost"), port)
/**
* Starts the server on the given address and port.
*
* @param inetAddress the address to create the server socket on
* @param port the port to listen to, or 0 for any available port. Automated tests should always
* use port 0 to avoid flakiness when a specific port is unavailable.
*/
@Throws(IOException::class)
fun start(inetAddress: InetAddress, port: Int) = start(InetSocketAddress(inetAddress, port))
/**
* Starts the server and binds to the given socket address.
*
* @param inetSocketAddress the socket address to bind the server on
*/
@Synchronized @Throws(IOException::class)
private fun start(inetSocketAddress: InetSocketAddress) {
check(!shutdown) { "shutdown() already called" }
if (started) return
started = true
this.inetSocketAddress = inetSocketAddress
serverSocket = serverSocketFactory!!.createServerSocket()
// Reuse if the user specified a port
serverSocket!!.reuseAddress = inetSocketAddress.port != 0
serverSocket!!.bind(inetSocketAddress, 50)
portField = serverSocket!!.localPort
taskRunner.newQueue().execute("MockWebServer $portField", cancelable = false) {
try {
logger.fine("$this starting to accept connections")
acceptConnections()
} catch (e: Throwable) {
logger.log(Level.WARNING, "$this failed unexpectedly", e)
}
// Release all sockets and all threads, even if any close fails.
serverSocket?.closeQuietly()
val openClientSocket = openClientSockets.iterator()
while (openClientSocket.hasNext()) {
openClientSocket.next().closeQuietly()
openClientSocket.remove()
}
val httpConnection = openConnections.iterator()
while (httpConnection.hasNext()) {
httpConnection.next().closeQuietly()
httpConnection.remove()
}
dispatcher.shutdown()
}
}
@Throws(Exception::class)
private fun acceptConnections() {
while (true) {
val socket: Socket
try {
socket = serverSocket!!.accept()
} catch (e: SocketException) {
logger.fine("${this@MockWebServer} done accepting connections: ${e.message}")
return
}
val socketPolicy = dispatcher.peek().socketPolicy
if (socketPolicy === DISCONNECT_AT_START) {
dispatchBookkeepingRequest(0, socket)
socket.close()
} else {
openClientSockets.add(socket)
serveConnection(socket)
}
}
}
@Synchronized
@Throws(IOException::class)
fun shutdown() {
if (shutdown) return
shutdown = true
if (!started) return // Nothing to shut down.
val serverSocket = this.serverSocket ?: return // If this is null, start() must have failed.
// Cause acceptConnections() to break out.
serverSocket.close()
// Await shutdown.
for (queue in taskRunner.activeQueues()) {
if (!queue.idleLatch().await(5, TimeUnit.SECONDS)) {
throw IOException("Gave up waiting for queue to shut down")
}
}
taskRunnerBackend.shutdown()
}
private fun serveConnection(raw: Socket) {
taskRunner.newQueue().execute("MockWebServer ${raw.remoteSocketAddress}", cancelable = false) {
try {
SocketHandler(raw).handle()
} catch (e: IOException) {
logger.fine("$this connection from ${raw.inetAddress} failed: $e")
} catch (e: Exception) {
logger.log(Level.SEVERE, "$this connection from ${raw.inetAddress} crashed", e)
}
}
}
internal inner class SocketHandler(private val raw: Socket) {
private var sequenceNumber = 0
@Throws(Exception::class)
fun handle() {
val socketPolicy = dispatcher.peek().socketPolicy
var protocol = Protocol.HTTP_1_1
val socket: Socket
when {
sslSocketFactory != null -> {
if (tunnelProxy) {
createTunnel()
}
if (socketPolicy === FAIL_HANDSHAKE) {
dispatchBookkeepingRequest(sequenceNumber, raw)
processHandshakeFailure(raw)
return
}
socket = sslSocketFactory!!.createSocket(raw, raw.inetAddress.hostAddress,
raw.port, true)
val sslSocket = socket as SSLSocket
sslSocket.useClientMode = false
if (clientAuth == CLIENT_AUTH_REQUIRED) {
sslSocket.needClientAuth = true
} else if (clientAuth == CLIENT_AUTH_REQUESTED) {
sslSocket.wantClientAuth = true
}
openClientSockets.add(socket)
if (protocolNegotiationEnabled) {
Platform.get().configureTlsExtensions(sslSocket, null, protocols)
}
sslSocket.startHandshake()
if (protocolNegotiationEnabled) {
val protocolString = Platform.get().getSelectedProtocol(sslSocket)
protocol =
if (protocolString != null) Protocol.get(protocolString) else Protocol.HTTP_1_1
Platform.get().afterHandshake(sslSocket)
}
openClientSockets.remove(raw)
}
Protocol.H2_PRIOR_KNOWLEDGE in protocols -> {
socket = raw
protocol = Protocol.H2_PRIOR_KNOWLEDGE
}
else -> socket = raw
}
if (socketPolicy === STALL_SOCKET_AT_START) {
dispatchBookkeepingRequest(sequenceNumber, socket)
return // Ignore the socket until the server is shut down!
}
if (protocol === Protocol.HTTP_2 || protocol === Protocol.H2_PRIOR_KNOWLEDGE) {
val http2SocketHandler = Http2SocketHandler(socket, protocol)
val connection = Http2Connection.Builder(false, taskRunner)
.socket(socket)
.listener(http2SocketHandler)
.build()
connection.start(taskRunner = taskRunner)
openConnections.add(connection)
openClientSockets.remove(socket)
return
} else if (protocol !== Protocol.HTTP_1_1) {
throw AssertionError()
}
val source = socket.source().buffer()
val sink = socket.sink().buffer()
while (processOneRequest(socket, source, sink)) {
}
if (sequenceNumber == 0) {
logger.warning(
"${this@MockWebServer} connection from ${raw.inetAddress} didn't make a request")
}
socket.close()
openClientSockets.remove(socket)
}
/**
* Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response is
* dispatched.
*/
@Throws(IOException::class, InterruptedException::class)
private fun createTunnel() {
val source = raw.source().buffer()
val sink = raw.sink().buffer()
while (true) {
val socketPolicy = dispatcher.peek().socketPolicy
check(processOneRequest(raw, source, sink)) { "Tunnel without any CONNECT!" }
if (socketPolicy === UPGRADE_TO_SSL_AT_END) return
}
}
/**
* Reads a request and writes its response. Returns true if further calls should be attempted
* on the socket.
*/
@Throws(IOException::class, InterruptedException::class)
private fun processOneRequest(
socket: Socket,
source: BufferedSource,
sink: BufferedSink
): Boolean {
if (source.exhausted()) {
return false // No more requests on this socket.
}
val request = readRequest(socket, source, sink, sequenceNumber)
atomicRequestCount.incrementAndGet()
requestQueue.add(request)
if (request.failure != null) {
return false // Nothing to respond to.
}
val response = dispatcher.dispatch(request)
if (response.socketPolicy === DISCONNECT_AFTER_REQUEST) {
socket.close()
return false
}
if (response.socketPolicy === NO_RESPONSE) {
// This read should block until the socket is closed. (Because nobody is writing.)
if (source.exhausted()) return false
throw ProtocolException("unexpected data")
}
var reuseSocket = true
val requestWantsWebSockets = "Upgrade".equals(request.getHeader("Connection"),
ignoreCase = true) && "websocket".equals(request.getHeader("Upgrade"),
ignoreCase = true)
val responseWantsWebSockets = response.webSocketListener != null
if (requestWantsWebSockets && responseWantsWebSockets) {
handleWebSocketUpgrade(socket, source, sink, request, response)
reuseSocket = false
} else {
writeHttpResponse(socket, sink, response)
}
if (logger.isLoggable(Level.FINE)) {
logger.fine(
"${this@MockWebServer} received request: $request and responded: $response")
}
// See warnings associated with these socket policies in SocketPolicy.
when (response.socketPolicy) {
DISCONNECT_AT_END, DO_NOT_READ_REQUEST_BODY -> {
socket.close()
return false
}
SHUTDOWN_INPUT_AT_END -> socket.shutdownInput()
SHUTDOWN_OUTPUT_AT_END -> socket.shutdownOutput()
SHUTDOWN_SERVER_AFTER_RESPONSE -> shutdown()
else -> {
}
}
sequenceNumber++
return reuseSocket
}
}
@Throws(Exception::class)
private fun processHandshakeFailure(raw: Socket) {
val context = SSLContext.getInstance("TLS")
context.init(null, arrayOf<TrustManager>(UNTRUSTED_TRUST_MANAGER), SecureRandom())
val sslSocketFactory = context.socketFactory
val socket = sslSocketFactory.createSocket(
raw, raw.inetAddress.hostAddress, raw.port, true) as SSLSocket
try {
socket.startHandshake() // we're testing a handshake failure
throw AssertionError()
} catch (expected: IOException) {
}
socket.close()
}
@Throws(InterruptedException::class)
private fun dispatchBookkeepingRequest(sequenceNumber: Int, socket: Socket) {
val request = RecordedRequest(
"", headersOf(), emptyList(), 0L, Buffer(), sequenceNumber, socket)
atomicRequestCount.incrementAndGet()
requestQueue.add(request)
dispatcher.dispatch(request)
}
/** @param sequenceNumber the index of this request on this connection.*/
@Throws(IOException::class)
private fun readRequest(
socket: Socket,
source: BufferedSource,
sink: BufferedSink,
sequenceNumber: Int
): RecordedRequest {
var request = ""
val headers = Headers.Builder()
var contentLength = -1L
var chunked = false
var expectContinue = false
val requestBody = TruncatingBuffer(bodyLimit)
val chunkSizes = mutableListOf<Int>()
var failure: IOException? = null
try {
request = source.readUtf8LineStrict()
if (request.isEmpty()) {
throw ProtocolException("no request because the stream is exhausted")
}
while (true) {
val header = source.readUtf8LineStrict()
if (header.isEmpty()) {
break
}
addHeaderLenient(headers, header)
val lowercaseHeader = header.lowercase(Locale.US)
if (contentLength == -1L && lowercaseHeader.startsWith("content-length:")) {
contentLength = header.substring(15).trim().toLong()
}
if (lowercaseHeader.startsWith("transfer-encoding:") && lowercaseHeader.substring(
18).trim() == "chunked") {
chunked = true
}
if (lowercaseHeader.startsWith("expect:") && lowercaseHeader.substring(
7).trim().equals("100-continue", ignoreCase = true)) {
expectContinue = true
}
}
val socketPolicy = dispatcher.peek().socketPolicy
if (expectContinue && socketPolicy === EXPECT_CONTINUE || socketPolicy === CONTINUE_ALWAYS) {
sink.writeUtf8("HTTP/1.1 100 Continue\r\n")
sink.writeUtf8("Content-Length: 0\r\n")
sink.writeUtf8("\r\n")
sink.flush()
}
var hasBody = false
val policy = dispatcher.peek()
if (policy.socketPolicy == DO_NOT_READ_REQUEST_BODY) {
// Ignore the body completely.
} else if (contentLength != -1L) {
hasBody = contentLength > 0L
throttledTransfer(policy, socket, source, requestBody.buffer(), contentLength, true)
} else if (chunked) {
hasBody = true
while (true) {
val chunkSize = source.readUtf8LineStrict().trim().toInt(16)
if (chunkSize == 0) {
readEmptyLine(source)
break
}
chunkSizes.add(chunkSize)
throttledTransfer(policy, socket, source,
requestBody.buffer(), chunkSize.toLong(), true)
readEmptyLine(source)
}
}
val method = request.substringBefore(' ')
require(!hasBody || HttpMethod.permitsRequestBody(method)) {
"Request must not have a body: $request"
}
} catch (e: IOException) {
failure = e
}
return RecordedRequest(request, headers.build(), chunkSizes, requestBody.receivedByteCount,
requestBody.buffer, sequenceNumber, socket, failure)
}
@Throws(IOException::class)
private fun handleWebSocketUpgrade(
socket: Socket,
source: BufferedSource,
sink: BufferedSink,
request: RecordedRequest,
response: MockResponse
) {
val key = request.getHeader("Sec-WebSocket-Key")
response.setHeader("Sec-WebSocket-Accept", WebSocketProtocol.acceptHeader(key!!))
writeHttpResponse(socket, sink, response)
// Adapt the request and response into our Request and Response domain model.
val scheme = if (request.tlsVersion != null) "https" else "http"
val authority = request.getHeader("Host") // Has host and port.
val fancyRequest = Request.Builder()
.url("$scheme://$authority/")
.headers(request.headers)
.build()
val statusParts = response.status.split(' ', limit = 3)
val fancyResponse = Response.Builder()
.code(statusParts[1].toInt())
.message(statusParts[2])
.headers(response.headers)
.request(fancyRequest)
.protocol(Protocol.HTTP_1_1)
.build()
val connectionClose = CountDownLatch(1)
val streams = object : RealWebSocket.Streams(false, source, sink) {
override fun close() = connectionClose.countDown()
}
val webSocket = RealWebSocket(
taskRunner = taskRunner,
originalRequest = fancyRequest,
listener = response.webSocketListener!!,
random = SecureRandom(),
pingIntervalMillis = 0,
extensions = WebSocketExtensions.parse(response.headers),
minimumDeflateSize = 0L // Compress all messages if compression is enabled.
)
response.webSocketListener!!.onOpen(webSocket, fancyResponse)
val name = "MockWebServer WebSocket ${request.path!!}"
webSocket.initReaderAndWriter(name, streams)
try {
webSocket.loopReader()
// Even if messages are no longer being read we need to wait for the connection close signal.
connectionClose.await()
} catch (e: IOException) {
webSocket.failWebSocket(e, null)
} finally {
source.closeQuietly()
}
}
@Throws(IOException::class)
private fun writeHttpResponse(socket: Socket, sink: BufferedSink, response: MockResponse) {
sleepIfDelayed(response.getHeadersDelay(TimeUnit.MILLISECONDS))
sink.writeUtf8(response.status)
sink.writeUtf8("\r\n")
writeHeaders(sink, response.headers)
val body = response.getBody() ?: return
sleepIfDelayed(response.getBodyDelay(TimeUnit.MILLISECONDS))
throttledTransfer(response, socket, body, sink, body.size, false)
if ("chunked".equals(response.headers["Transfer-Encoding"], ignoreCase = true)) {
writeHeaders(sink, response.trailers)
}
}
@Throws(IOException::class)
private fun writeHeaders(sink: BufferedSink, headers: Headers) {
for ((name, value) in headers) {
sink.writeUtf8(name)
sink.writeUtf8(": ")
sink.writeUtf8(value)
sink.writeUtf8("\r\n")
}
sink.writeUtf8("\r\n")
sink.flush()
}
private fun sleepIfDelayed(delayMs: Long) {
if (delayMs != 0L) {
Thread.sleep(delayMs)
}
}
/**
* Transfer bytes from [source] to [sink] until either [byteCount] bytes have
* been transferred or [source] is exhausted. The transfer is throttled according to [policy].
*/
@Throws(IOException::class)
private fun throttledTransfer(
policy: MockResponse,
socket: Socket,
source: BufferedSource,
sink: BufferedSink,
byteCount: Long,
isRequest: Boolean
) {
var byteCountNum = byteCount
if (byteCountNum == 0L) return
val buffer = Buffer()
val bytesPerPeriod = policy.throttleBytesPerPeriod
val periodDelayMs = policy.getThrottlePeriod(TimeUnit.MILLISECONDS)
val halfByteCount = byteCountNum / 2
val disconnectHalfway = if (isRequest) {
policy.socketPolicy === DISCONNECT_DURING_REQUEST_BODY
} else {
policy.socketPolicy === DISCONNECT_DURING_RESPONSE_BODY
}
while (!socket.isClosed) {
var b = 0L
while (b < bytesPerPeriod) {
// Ensure we do not read past the allotted bytes in this period.
var toRead = minOf(byteCountNum, bytesPerPeriod - b)
// Ensure we do not read past halfway if the policy will kill the connection.
if (disconnectHalfway) {
toRead = minOf(toRead, byteCountNum - halfByteCount)
}
val read = source.read(buffer, toRead)
if (read == -1L) return
sink.write(buffer, read)
sink.flush()
b += read
byteCountNum -= read
if (disconnectHalfway && byteCountNum == halfByteCount) {
socket.close()
return
}
if (byteCountNum == 0L) return
}
sleepIfDelayed(periodDelayMs)
}
}
@Throws(IOException::class)
private fun readEmptyLine(source: BufferedSource) {
val line = source.readUtf8LineStrict()
check(line.isEmpty()) { "Expected empty but was: $line" }
}
override fun toString(): String = "MockWebServer[$portField]"
@Throws(IOException::class)
override fun close() = shutdown()
/** A buffer wrapper that drops data after [bodyLimit] bytes. */
private class TruncatingBuffer(
private var remainingByteCount: Long
) : Sink {
val buffer = Buffer()
var receivedByteCount = 0L
@Throws(IOException::class)
override fun write(source: Buffer, byteCount: Long) {
val toRead = minOf(remainingByteCount, byteCount)
if (toRead > 0L) {
source.read(buffer, toRead)
}
val toSkip = byteCount - toRead
if (toSkip > 0L) {
source.skip(toSkip)
}
remainingByteCount -= toRead
receivedByteCount += byteCount
}
@Throws(IOException::class)
override fun flush() {
}
override fun timeout(): Timeout = Timeout.NONE
@Throws(IOException::class)
override fun close() {
}
}
/** Processes HTTP requests layered over HTTP/2. */
private inner class Http2SocketHandler constructor(
private val socket: Socket,
private val protocol: Protocol
) : Http2Connection.Listener() {
private val sequenceNumber = AtomicInteger()
@Throws(IOException::class)
override fun onStream(stream: Http2Stream) {
val peekedResponse = dispatcher.peek()
if (peekedResponse.socketPolicy === RESET_STREAM_AT_START) {
dispatchBookkeepingRequest(sequenceNumber.getAndIncrement(), socket)
stream.close(ErrorCode.fromHttp2(peekedResponse.http2ErrorCode)!!, null)
return
}
val request = readRequest(stream)
atomicRequestCount.incrementAndGet()
requestQueue.add(request)
if (request.failure != null) {
return // Nothing to respond to.
}
val response: MockResponse = dispatcher.dispatch(request)
val socketPolicy = response.socketPolicy
if (socketPolicy === DISCONNECT_AFTER_REQUEST) {
socket.close()
return
}
writeResponse(stream, request, response)
if (logger.isLoggable(Level.FINE)) {
logger.fine(
"${this@MockWebServer} received request: $request " +
"and responded: $response protocol is $protocol")
}
when (socketPolicy) {
DISCONNECT_AT_END -> {
stream.connection.shutdown(ErrorCode.NO_ERROR)
}
DO_NOT_READ_REQUEST_BODY -> {
stream.close(ErrorCode.fromHttp2(response.http2ErrorCode)!!, null)
}
else -> {
}
}
}
@Throws(IOException::class)
private fun readRequest(stream: Http2Stream): RecordedRequest {
val streamHeaders = stream.takeHeaders()
val httpHeaders = Headers.Builder()
var method = "<:method omitted>"
var path = "<:path omitted>"
var readBody = true
for ((name, value) in streamHeaders) {
if (name == Header.TARGET_METHOD_UTF8) {
method = value
} else if (name == Header.TARGET_PATH_UTF8) {
path = value
} else if (protocol === Protocol.HTTP_2 || protocol === Protocol.H2_PRIOR_KNOWLEDGE) {
httpHeaders.add(name, value)
} else {
throw IllegalStateException()
}
if (name == "expect" && value.equals("100-continue", ignoreCase = true)) {
// Don't read the body unless we've invited the client to send it.
readBody = false
}
}
val headers = httpHeaders.build()
val peek = dispatcher.peek()
if (!readBody && peek.socketPolicy === EXPECT_CONTINUE) {
val continueHeaders =
listOf(Header(Header.RESPONSE_STATUS, "100 Continue".encodeUtf8()))
stream.writeHeaders(continueHeaders, outFinished = false, flushHeaders = true)
stream.connection.flush()
readBody = true
}
val body = Buffer()
val requestLine = "$method $path HTTP/1.1"
var exception: IOException? = null
if (readBody && !peek.isDuplex && peek.socketPolicy !== DO_NOT_READ_REQUEST_BODY) {
try {
val contentLengthString = headers["content-length"]
val byteCount = contentLengthString?.toLong() ?: Long.MAX_VALUE
throttledTransfer(peek, socket, stream.getSource().buffer(),
body, byteCount, true)
} catch (e: IOException) {
exception = e
}
}
return RecordedRequest(requestLine, headers, emptyList(), body.size, body,
sequenceNumber.getAndIncrement(), socket, exception)
}
@Throws(IOException::class)
private fun writeResponse(
stream: Http2Stream,
request: RecordedRequest,
response: MockResponse
) {
val settings = response.settings
stream.connection.setSettings(settings)
if (response.socketPolicy === NO_RESPONSE) {
return
}
val http2Headers = mutableListOf<Header>()
val statusParts = response.status.split(' ', limit = 3)
val headersDelayMs = response.getHeadersDelay(TimeUnit.MILLISECONDS)
val bodyDelayMs = response.getBodyDelay(TimeUnit.MILLISECONDS)
if (statusParts.size < 2) {
throw AssertionError("Unexpected status: ${response.status}")
}
http2Headers.add(Header(Header.RESPONSE_STATUS, statusParts[1]))
val headers = response.headers
for ((name, value) in headers) {
http2Headers.add(Header(name, value))
}
val trailers = response.trailers
sleepIfDelayed(headersDelayMs)
val body = response.getBody()
val outFinished = (body == null &&
response.pushPromises.isEmpty() &&
!response.isDuplex)
val flushHeaders = body == null || bodyDelayMs != 0L
require(!outFinished || trailers.size == 0) {
"unsupported: no body and non-empty trailers $trailers"
}
stream.writeHeaders(http2Headers, outFinished, flushHeaders)
if (trailers.size > 0) {
stream.enqueueTrailers(trailers)
}
pushPromises(stream, request, response.pushPromises)
if (body != null) {
stream.getSink().buffer().use { sink ->
sleepIfDelayed(bodyDelayMs)
throttledTransfer(response, socket, body, sink, body.size, false)
}
} else if (response.isDuplex) {
val duplexResponseBody = response.duplexResponseBody!!
duplexResponseBody.onRequest(request, stream)
} else if (!outFinished) {
stream.close(ErrorCode.NO_ERROR, null)
}
}
@Throws(IOException::class)
private fun pushPromises(
stream: Http2Stream,
request: RecordedRequest,
promises: List<PushPromise>
) {
for (pushPromise in promises) {
val pushedHeaders = mutableListOf<Header>()
pushedHeaders.add(Header(Header.TARGET_AUTHORITY, url(pushPromise.path).host))
pushedHeaders.add(Header(Header.TARGET_METHOD, pushPromise.method))
pushedHeaders.add(Header(Header.TARGET_PATH, pushPromise.path))
val pushPromiseHeaders = pushPromise.headers
for ((name, value) in pushPromiseHeaders) {
pushedHeaders.add(Header(name, value))
}
val requestLine = "${pushPromise.method} ${pushPromise.path} HTTP/1.1"
val chunkSizes = emptyList<Int>() // No chunked encoding for HTTP/2.
requestQueue.add(RecordedRequest(requestLine, pushPromise.headers, chunkSizes, 0,
Buffer(), sequenceNumber.getAndIncrement(), socket))
val hasBody = pushPromise.response.getBody() != null
val pushedStream = stream.connection.pushStream(stream.id, pushedHeaders, hasBody)
writeResponse(pushedStream, request, pushPromise.response)
}
}
}
companion object {
init {
MwsDuplexAccess.instance = object : MwsDuplexAccess() {
override fun setBody(
mockResponse: MockResponse,
duplexResponseBody: DuplexResponseBody
) {
mockResponse.setBody(duplexResponseBody)
}
}
}
private const val CLIENT_AUTH_NONE = 0
private const val CLIENT_AUTH_REQUESTED = 1
private const val CLIENT_AUTH_REQUIRED = 2
private val UNTRUSTED_TRUST_MANAGER = object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(
chain: Array<X509Certificate>,
authType: String
) = throw CertificateException()
override fun checkServerTrusted(
chain: Array<X509Certificate>,
authType: String
) = throw AssertionError()
override fun getAcceptedIssuers(): Array<X509Certificate> = throw AssertionError()
}
private val logger = Logger.getLogger(MockWebServer::class.java.name)
}
}
| apache-2.0 | 63be8998e895ef4ea0d7b2f7291e8bfb | 33.426471 | 100 | 0.672915 | 4.545112 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/asset/PlatformAssets.kt | 1 | 2641 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.asset
@Suppress("unused")
object PlatformAssets : Assets() {
val MINECRAFT_ICON = loadIcon("/assets/icons/platform/Minecraft.png")
val MINECRAFT_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val BUKKIT_ICON = loadIcon("/assets/icons/platform/Bukkit.png")
val BUKKIT_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val SPIGOT_ICON = loadIcon("/assets/icons/platform/Spigot.png")
val SPIGOT_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val PAPER_ICON = loadIcon("/assets/icons/platform/Paper.png")
val PAPER_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val FORGE_ICON = loadIcon("/assets/icons/platform/Forge.png")
val FORGE_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val SPONGE_ICON = loadIcon("/assets/icons/platform/Sponge.png")
val SPONGE_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val SPONGE_ICON_DARK = loadIcon("/assets/icons/platform/Sponge_dark.png")
val SPONGE_ICON_2X_DARK = loadIcon("/assets/icons/platform/Sponge@2x_dark.png")
val SPONGE_FORGE_ICON = loadIcon("/assets/icons/platform/SpongeForge.png")
val SPONGE_FORGE_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val SPONGE_FORGE_ICON_DARK = loadIcon("/assets/icons/platform/SpongeForge_dark.png")
val SPONGE_FORGE_ICON_2X_DARK = loadIcon("/assets/icons/platform/SpongeForge@2x_dark.png")
val BUNGEECORD_ICON = loadIcon("/assets/icons/platform/BungeeCord.png")
val BUNGEECORD_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val WATERFALL_ICON = loadIcon("/assets/icons/platform/Waterfall.png")
val WATERFALL_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val LITELOADER_ICON = loadIcon("/assets/icons/platform/LiteLoader.png")
val LITELOADER_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val MIXIN_ICON = loadIcon("/assets/icons/platform/Mixins.png")
val MIXIN_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val MIXIN_ICON_DARK = loadIcon("/assets/icons/platform/Mixins_dark.png")
val MIXIN_ICON_2X_DARK = loadIcon("/assets/icons/platform/Mixins@2x_dark.png")
val MCP_ICON = loadIcon("/assets/icons/platform/MCP.png")
val MCP_ICON_2X = loadIcon("/assets/icons/platform/[email protected]")
val MCP_ICON_DARK = loadIcon("/assets/icons/platform/MCP_dark.png")
val MCP_ICON_2X_DARK = loadIcon("/assets/icons/platform/MCP@2x_dark.png")
}
| mit | 4d24569d6b1be9dccdb52ecffd02e0e8 | 47.018182 | 94 | 0.72056 | 3.162874 | false | false | false | false |
JetBrains/spek | integration-test/src/commonTest/kotlin/org/spekframework/spek2/TestSupport.kt | 1 | 6808 | package org.spekframework.spek2
import org.spekframework.spek2.dsl.Root
import org.spekframework.spek2.runtime.SpekRuntime
import org.spekframework.spek2.runtime.discovery.DiscoveryContext
import org.spekframework.spek2.runtime.discovery.DiscoveryContextBuilder
import org.spekframework.spek2.runtime.execution.DiscoveryRequest
import org.spekframework.spek2.runtime.execution.ExecutionListener
import org.spekframework.spek2.runtime.execution.ExecutionRequest
import org.spekframework.spek2.runtime.execution.ExecutionResult
import org.spekframework.spek2.runtime.scope.GroupScopeImpl
import org.spekframework.spek2.runtime.scope.Path
import org.spekframework.spek2.runtime.scope.PathBuilder
import org.spekframework.spek2.runtime.scope.TestScopeImpl
import kotlin.test.assertEquals
sealed class ExecutionEvent {
data class Test(val description: String, val success: Boolean): ExecutionEvent()
data class TestIgnored(val description: String, val reason: String?): ExecutionEvent()
class GroupStart(val description: String): ExecutionEvent()
class GroupEnd(val description: String, val success: Boolean): ExecutionEvent()
data class GroupIgnored(val description: String, val reason: String?): ExecutionEvent()
}
class ExecutionTreeBuilder {
private val events = mutableListOf<ExecutionEvent>()
fun groupStart(description: String) {
events.add(ExecutionEvent.GroupStart(description))
}
fun groupEnd(description: String, success: Boolean = true) {
events.add(ExecutionEvent.GroupEnd(description, success))
}
fun groupIgnored(description: String, reason: String?) {
events.add(ExecutionEvent.GroupIgnored(description, reason))
}
fun test(description: String, success: Boolean = true) {
events.add(ExecutionEvent.Test(description, success))
}
fun testIgnored(description: String, reason: String?) {
events.add(ExecutionEvent.TestIgnored(description, reason))
}
fun group(description: String, success: Boolean = true, block: ExecutionTreeBuilder.() -> Unit) {
groupStart(description)
this.block()
groupEnd(description, success)
}
fun build() = events.toList()
}
class ExecutionRecorder: ExecutionListener {
private var started = false
private var finished = false
private lateinit var treeBuilder: ExecutionTreeBuilder
override fun executionStart() {
started = true
treeBuilder = ExecutionTreeBuilder()
}
override fun executionFinish() {
finished = false
}
override fun testExecutionStart(test: TestScopeImpl) {
// nada
}
override fun testExecutionFinish(test: TestScopeImpl, result: ExecutionResult) {
treeBuilder.test(test.path.name, result is ExecutionResult.Success)
}
override fun testIgnored(test: TestScopeImpl, reason: String?) {
treeBuilder.testIgnored(test.path.name, reason)
}
override fun groupExecutionStart(group: GroupScopeImpl) {
treeBuilder.groupStart(group.path.name)
}
override fun groupExecutionFinish(group: GroupScopeImpl, result: ExecutionResult) {
treeBuilder.groupEnd(group.path.name, result is ExecutionResult.Success)
}
override fun groupIgnored(group: GroupScopeImpl, reason: String?) {
treeBuilder.groupIgnored(group.path.name, reason)
}
fun events(): List<ExecutionEvent> {
return treeBuilder.build()
}
fun successfulTestCount() = events().count { it is ExecutionEvent.Test && it.success }
fun failedTestCount() = events().count { it is ExecutionEvent.Test && !it.success }
fun hasNoSuccessfulTests() = successfulTestCount() == 0
fun hasNoFailedTests() = failedTestCount() == 0
fun successfulGroupCount() = events().count { it is ExecutionEvent.GroupEnd && it.success }
fun failedGroupCount() = events().count { it is ExecutionEvent.GroupEnd && !it.success }
}
class SpekTestHelper {
fun discoveryContext(block: DiscoveryContextBuilder.() -> Unit): DiscoveryContext {
val builder = DiscoveryContextBuilder()
builder.block()
return builder.build()
}
fun executeTests(context: DiscoveryContext, vararg paths: Path): ExecutionRecorder {
val runtime = SpekRuntime()
val recorder = ExecutionRecorder()
val discoveryResult = runtime.discover(DiscoveryRequest(context, listOf(*paths)))
runtime.execute(ExecutionRequest(discoveryResult.roots, recorder))
return recorder
}
fun <T: Spek> executeTest(test: T): ExecutionRecorder {
val path = PathBuilder.from(test::class)
.build()
return executeTests(discoveryContext {
addTest(test::class) { test }
}, path)
}
fun assertExecutionEquals(actual: List<ExecutionEvent>, block: ExecutionTreeBuilder.() -> Unit) {
val builder = ExecutionTreeBuilder()
builder.block()
val expected = builder.build()
assertEquals(executionToString(expected), executionToString(actual))
}
/**
* Prints out something like the following
*
* foo bar {
* should do this -> PASSED
* should fail -> FAILED
* should be ignored -> IGNORED
* }
* ignored -> IGNORED
*/
private fun executionToString(events: List<ExecutionEvent>): String {
var nest = 0
val builder = StringBuilder()
val indent = {
builder.append(" ".repeat(nest))
}
events.forEach { event ->
when (event) {
is ExecutionEvent.GroupStart -> {
indent()
builder.append("${event.description} {\n")
nest += 1
}
is ExecutionEvent.GroupEnd -> {
nest -= 1
indent()
builder.append("}\n")
}
is ExecutionEvent.GroupIgnored -> {
indent()
builder.append("${event.description} -> IGNORED(${event.reason})\n")
}
is ExecutionEvent.Test -> {
indent()
val result = if (event.success) {
"PASSED"
} else {
"FAILED"
}
builder.append("${event.description} -> $result\n")
}
is ExecutionEvent.TestIgnored -> {
indent()
builder.append("${event.description} -> IGNORED(${event.reason})\n")
}
}
}
return builder.toString()
}
}
abstract class AbstractSpekTest(block: Root.(SpekTestHelper) -> Unit): Spek({
block(SpekTestHelper())
})
| bsd-3-clause | c2a7c2f5936f042b4208986c2d5ea3fa | 33.04 | 101 | 0.643361 | 4.770848 | false | true | false | false |
android/project-replicator | code/codegen/src/main/kotlin/com/android/gradle/replicator/parsing/ArgsParser.kt | 1 | 5164 | package com.android.gradle.replicator.parsing
import java.io.File
import java.io.FileReader
import java.util.*
/**
* Class for parsing command line and property file arguments
*/
class ArgsParser {
companion object {
const val UNLIMITED_ARGC = -1
}
class Option(val argc: Int) {
val argv = mutableListOf<String>()
var isPresent: Boolean = false
val first
get() = argv[0]
val orNull
get() = if (isPresent) this else null
}
private val longNameOpts = mutableMapOf<String, Option>()
private val shortNameOpts = mutableMapOf<String, Option>()
private val argsFileOpts = mutableMapOf<String, Option>()
/**
* Creates an [Option], stores it and returns it
*
* @param longName: the long name for the option (ex: option for --option)
* @param shortName: the short name for the option (ex: o for -o)
* @param propertyName: the property file name for the option (ex: option for option=...)
* @return: the created option
*/
fun option(longName: String = "", shortName: String = "", propertyName: String = "", argc: Int = 0): Option {
val option = Option(argc)
if (longName.isNotEmpty()) {
if (longNameOpts.containsKey("--$longName")) {
throw IllegalArgumentException("arg $longName already exists")
}
longNameOpts["--$longName"] = option
}
if (shortName.isNotEmpty()) {
if (shortNameOpts.containsKey("-$shortName")) {
throw IllegalArgumentException("arg $shortName already exists")
}
shortNameOpts["-$shortName"] = option
}
if (propertyName.isNotEmpty()) {
if (argsFileOpts.containsKey(propertyName)) {
throw IllegalArgumentException("arg $propertyName already exists")
}
argsFileOpts[propertyName] = option
}
if (shortName.isEmpty() && longName.isEmpty() && propertyName.isEmpty()) {
throw IllegalArgumentException("option must have a short name, a long name or an args file name")
}
return option
}
/**
* Parses the command-line args and populates the previously created options
*
* @param args: the command-line args
*/
fun parseArgs(args: Array<String>) {
var lastOption: Option? = null
args.forEach { arg ->
if (arg.startsWith("--")) {
// Sanity check
if (!longNameOpts.containsKey(arg)) {
throw java.lang.IllegalArgumentException("invalid argument $arg")
}
if (longNameOpts[arg]!!.isPresent) {
throw java.lang.IllegalArgumentException("option used twice $arg")
}
lastOption = longNameOpts[arg]!!
lastOption!!.isPresent = true
} else if (arg.startsWith("-") && arg.toIntOrNull() == null) {
// Sanity check
if (!shortNameOpts.containsKey(arg)) {
throw java.lang.IllegalArgumentException("invalid argument $arg")
}
if (shortNameOpts[arg]!!.isPresent) {
throw java.lang.IllegalArgumentException("option used twice $arg")
}
lastOption = shortNameOpts[arg]!!
lastOption!!.isPresent = true
} else {
lastOption!!.argv.add(arg)
}
}
// Post-parse sanity check
(shortNameOpts + longNameOpts).forEach { opt ->
if (opt.value.isPresent && opt.value.argv.size != UNLIMITED_ARGC && opt.value.argv.size != opt.value.argc) {
throw java.lang.IllegalArgumentException("wrong # of args for ${opt.key}. Expected ${opt.value.argc} but got ${opt.value.argv.size}")
}
}
}
/**
* Parses a property file and populates the previously created options
*
* @param propertyFile: the property file
*/
fun parsePropertyFile(propertyFile: File) {
val arguments = FileReader(propertyFile).use {
Properties().also { properties -> properties.load(it) }
}
arguments.forEach { arg ->
// Ignore invalid args
if (argsFileOpts.containsKey(arg.key)) {
val currentOption = argsFileOpts[arg.key]!!
// Override command line options
if (currentOption.isPresent) {
currentOption.argv.clear()
}
arg.value?.toString()?.split(",")?.let {
currentOption.argv.addAll(it)
}
currentOption.isPresent = true
}
}
// Post-parse sanity check
argsFileOpts.forEach { opt ->
if (opt.value.isPresent && opt.value.argc != UNLIMITED_ARGC && opt.value.argv.size != opt.value.argc) {
throw java.lang.IllegalArgumentException("wrong # of args for ${opt.key}. Expected ${opt.value.argc} but got ${opt.value.argv.size}")
}
}
}
} | apache-2.0 | 63fbce571d6c6e6a4b1594a52a092efa | 36.977941 | 149 | 0.560999 | 4.803721 | false | false | false | false |
fwcd/kotlin-language-server | shared/src/main/kotlin/org/javacs/kt/classpath/WithStdlibResolver.kt | 1 | 3091 | package org.javacs.kt.classpath
import java.nio.file.Path
/** A classpath resolver that ensures another resolver contains the stdlib */
internal class WithStdlibResolver(private val wrapped: ClassPathResolver) : ClassPathResolver {
override val resolverType: String get() = "Stdlib + ${wrapped.resolverType}"
override val classpath: Set<ClassPathEntry> get() = wrapWithStdlibEntries(wrapped.classpath)
override val classpathOrEmpty: Set<ClassPathEntry> get() = wrapWithStdlibEntries(wrapped.classpathOrEmpty)
override val buildScriptClasspath: Set<Path> get() = wrapWithStdlib(wrapped.buildScriptClasspath)
override val buildScriptClasspathOrEmpty: Set<Path> get() = wrapWithStdlib(wrapped.buildScriptClasspathOrEmpty)
override val classpathWithSources: Set<ClassPathEntry> = wrapWithStdlibEntries(wrapped.classpathWithSources)
}
private fun wrapWithStdlibEntries(paths: Set<ClassPathEntry>): Set<ClassPathEntry> {
return wrapWithStdlib(paths.map { it.compiledJar }.toSet()).map { ClassPathEntry(it, paths.find { it1 -> it1.compiledJar == it }?.sourceJar) }.toSet()
}
private fun wrapWithStdlib(paths: Set<Path>): Set<Path> {
// Ensure that there is exactly one kotlin-stdlib present, and/or exactly one of kotlin-stdlib-common, -jdk8, etc.
val isStdlib: ((Path) -> Boolean) = {
val pathString = it.toString()
pathString.contains("kotlin-stdlib") && !pathString.contains("kotlin-stdlib-common")
}
val linkedStdLibs = paths.filter(isStdlib)
.mapNotNull { StdLibItem.from(it) }
.groupBy { it.key }
.map { candidates ->
// For each "kotlin-stdlib-blah", use the newest. This may not be correct behavior if the project has lots of
// conflicting dependencies, but in general should get enough of the stdlib loaded that we can display errors
candidates.value.sortedWith(
compareByDescending<StdLibItem> { it.major } then
compareByDescending { it.minor } then
compareByDescending { it.patch }
).first().path
}
val stdlibs = linkedStdLibs.ifEmpty {
findKotlinStdlib()?.let { listOf(it) } ?: listOf()
}
return paths.filterNot(isStdlib).union(stdlibs)
}
private data class StdLibItem(
val key : String,
val major : Int,
val minor: Int,
val patch : Int,
val path: Path
) {
companion object {
// Matches names like: "kotlin-stdlib-jdk7-1.2.51.jar"
val parser = Regex("""(kotlin-stdlib(-[^-]+)?)-(\d+)\.(\d+)\.(\d+)\.jar""")
fun from(path: Path) : StdLibItem? {
return parser.matchEntire(path.fileName.toString())?.let { match ->
StdLibItem(
key = match.groups[1]?.value ?: match.groups[0]?.value!!,
major = match.groups[3]?.value?.toInt() ?: 0,
minor = match.groups[4]?.value?.toInt() ?: 0,
patch = match.groups[5]?.value?.toInt() ?: 0,
path = path
)
}
}
}
}
| mit | 4f90b1b09d7ab96a5fc94a668819c35e | 43.157143 | 154 | 0.64154 | 4.293056 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/formatting/SolFormattingBlock.kt | 1 | 4354 | package me.serce.solidity.ide.formatting
import com.intellij.formatting.*
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.TokenType
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.formatter.FormatterUtil
import com.intellij.psi.tree.IElementType
import me.serce.solidity.lang.core.SolidityTokenTypes.*
import java.util.*
import kotlin.collections.ArrayList
class SolFormattingBlock(
private val astNode: ASTNode,
private val alignment: Alignment?,
private val indent: Indent,
private val wrap: Wrap?,
private val codeStyleSettings: CodeStyleSettings,
private val spacingBuilder: SpacingBuilder
) : ASTBlock {
private val nodeSubBlocks: List<Block> by lazy { buildSubBlocks() }
private val isNodeIncomplete: Boolean by lazy { FormatterUtil.isIncomplete(node) }
override fun getSubBlocks(): List<Block> = nodeSubBlocks
private fun buildSubBlocks(): List<Block> {
val blocks = ArrayList<Block>()
var child = astNode.firstChildNode
while (child != null) {
val childType = child.elementType
if (child.textRange.length == 0) {
child = child.treeNext
continue
}
if (childType === TokenType.WHITE_SPACE) {
child = child.treeNext
continue
}
val e = buildSubBlock(child)
blocks.add(e)
child = child.treeNext
}
return Collections.unmodifiableList(blocks)
}
private fun buildSubBlock(child: ASTNode): Block {
val indent = calcIndent(child)
return SolFormattingBlock(child, alignment, indent, null, codeStyleSettings, spacingBuilder)
}
private fun calcIndent(child: ASTNode): Indent {
val childType = child.elementType
val type = astNode.elementType
val parent = astNode.treeParent
val parentType = parent?.elementType
val result = when {
child is PsiComment && type in listOf(
CONTRACT_DEFINITION,
BLOCK,
ENUM_DEFINITION,
FUNCTION_DEFINITION,
CONSTRUCTOR_DEFINITION,
STRUCT_DEFINITION
) -> Indent.getNormalIndent()
childType.isContractPart() -> Indent.getNormalIndent()
// fields inside structs
type == STRUCT_DEFINITION && childType == VARIABLE_DECLARATION -> Indent.getNormalIndent()
// inside a block, list of parameters, etc..
parentType in listOf(BLOCK, ENUM_DEFINITION, YUL_BLOCK, PARAMETER_LIST, INDEXED_PARAMETER_LIST) -> Indent.getNormalIndent()
// all expressions inside parens should have indentation when lines are split
parentType in listOf(IF_STATEMENT, WHILE_STATEMENT, DO_WHILE_STATEMENT, FOR_STATEMENT) && childType != BLOCK -> {
Indent.getNormalIndent()
}
// all function calls
parentType in listOf(FUNCTION_CALL_ARGUMENTS) -> Indent.getNormalIndent()
else -> Indent.getNoneIndent()
}
return result
}
private fun newChildIndent(childIndex: Int): Indent? = when {
node.elementType in listOf(BLOCK, YUL_BLOCK, CONTRACT_DEFINITION, STRUCT_DEFINITION, ENUM_DEFINITION) -> {
val lbraceIndex = subBlocks.indexOfFirst { it is ASTBlock && it.node?.elementType == LBRACE }
if (lbraceIndex != -1 && lbraceIndex < childIndex) {
Indent.getNormalIndent()
} else {
Indent.getNoneIndent()
}
}
else -> Indent.getNoneIndent()
}
override fun getNode(): ASTNode = astNode
override fun getTextRange(): TextRange = astNode.textRange
override fun getWrap(): Wrap? = wrap
override fun getIndent(): Indent? = indent
override fun getAlignment(): Alignment? = alignment
override fun getSpacing(child1: Block?, child2: Block): Spacing? {
return spacingBuilder.getSpacing(this, child1, child2)
}
override fun getChildAttributes(newChildIndex: Int): ChildAttributes =
ChildAttributes(newChildIndent(newChildIndex), null)
override fun isIncomplete(): Boolean = isNodeIncomplete
override fun isLeaf(): Boolean = astNode.firstChildNode == null
// TODO nicer way to do the same
private fun IElementType.isContractPart() = this in listOf(
STATE_VARIABLE_DECLARATION,
USING_FOR_DECLARATION,
STRUCT_DEFINITION,
MODIFIER_DEFINITION,
FUNCTION_DEFINITION,
CONSTRUCTOR_DEFINITION,
EVENT_DEFINITION,
ERROR_DEFINITION,
ENUM_DEFINITION
)
}
| mit | e512dbf22dbc83cc2adb4c60a8ed2958 | 32.751938 | 129 | 0.710152 | 4.497934 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/secondStep/modulesEditor/ModulesEditorTree.kt | 6 | 5773 | // 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.tools.projectWizard.wizard.ui.secondStep.modulesEditor
import com.intellij.icons.AllIcons
import com.intellij.ui.ColoredTreeCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBLabel
import com.intellij.ui.treeStructure.Tree
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Sourceset
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.path
import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.borderPanel
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.icon
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.awt.Component
import java.awt.Graphics2D
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JTree
import javax.swing.tree.*
class ModulesEditorTree(
private val onSelected: (DisplayableSettingItem?) -> Unit,
context: Context,
isTreeEditable: Boolean,
private val addModule: (JComponent) -> Unit
) : Tree(DefaultMutableTreeNode(PROJECT_USER_OBJECT)) {
val model: DefaultTreeModel get() = super.getModel() as DefaultTreeModel
@Suppress("ClassName")
object PROJECT_USER_OBJECT
fun reload() {
val openPaths = (0 until rowCount).mapNotNull { row ->
getPathForRow(row).takeIf { isExpanded(it) }
}
model.reload()
openPaths.forEach(::expandPath)
}
fun selectModule(moduleToSelect: Module) {
for (value in (model.root as DefaultMutableTreeNode).depthFirstEnumeration().iterator()) {
val node = value as? DefaultMutableTreeNode ?: continue
val module = node.userObject as? Module ?: continue
if (module.path == moduleToSelect.path) {
selectionPath = TreePath(node.path)
break
}
}
}
val selectedSettingItem
get() = selectedNode?.userObject?.safeAs<DisplayableSettingItem>()
val selectedNode
get() = getSelectedNodes(DefaultMutableTreeNode::class.java) {
it.userObject is DisplayableSettingItem
}.singleOrNull()
init {
getSelectionModel().selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
setShowsRootHandles(true)
addTreeSelectionListener {
onSelected(selectedSettingItem)
}
emptyText.clear()
emptyText.appendText(KotlinNewProjectWizardUIBundle.message("editor.modules.no.modules"))
emptyText.appendSecondaryText(
KotlinNewProjectWizardUIBundle.message("editor.modules.add.module"),
SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES
) {
addModule(this)
}
setCellRenderer(CellRenderer(context, renderErrors = isTreeEditable))
}
}
private class CellRenderer(private val context: Context, renderErrors: Boolean) : TreeCellRenderer {
override fun getTreeCellRendererComponent(
tree: JTree?,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean
): Component {
setError(null)
val renderedCell = coloredCellRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus)
return borderPanel {
addToCenter(renderedCell)
addToRight(iconLabel)
}
}
private val iconLabel = JBLabel("")
private fun setError(error: ValidationResult.ValidationError?) {
val message = error?.messages?.firstOrNull()
if (message == null) {
iconLabel.icon = null
} else {
iconLabel.icon = AllIcons.General.Error
}
}
private val coloredCellRenderer = object : ColoredTreeCellRenderer() {
override fun customizeCellRenderer(
tree: JTree,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean
) {
if (value?.safeAs<DefaultMutableTreeNode>()?.userObject == ModulesEditorTree.PROJECT_USER_OBJECT) {
icon = AllIcons.Nodes.Project
append(KotlinNewProjectWizardUIBundle.message("editor.modules.project"))
return
}
val setting = (value as? DefaultMutableTreeNode)?.userObject as? DisplayableSettingItem ?: return
icon = when (setting) {
is Module -> setting.icon
is Sourceset -> AllIcons.Nodes.Module
else -> null
}
append(setting.text)
setting.greyText?.let { greyText ->
append(" ")
append(greyText, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
if (renderErrors) {
if (setting is Module) context.read {
val validationResult = setting.validator.validate(this, setting)
val error = validationResult.safeAs<ValidationResult.ValidationError>()
?.takeIf { it.target === setting }
setError(error)
} else {
setError(null)
}
}
}
}
} | apache-2.0 | 528913765d42885eaa2e164fe8942323 | 36.738562 | 158 | 0.655812 | 5.126998 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/abccomputer/activity/LoginActivity.kt | 1 | 5166 | package com.tungnui.abccomputer.activity
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.tungnui.abccomputer.R
import com.tungnui.abccomputer.SettingsMy
import com.tungnui.abccomputer.api.CustomerServices
import com.tungnui.abccomputer.api.ServiceGenerator
import com.tungnui.abccomputer.data.constant.AppConstants
import com.tungnui.abccomputer.models.Customer
import com.tungnui.abccomputer.model.LineItem
import com.tungnui.abccomputer.listener.LoginListener
import com.tungnui.abccomputer.utils.ActivityUtils
import com.tungnui.abccomputer.utils.AnalyticsUtils
import com.tungnui.abccomputer.utils.AppUtility
import com.tungnui.abccomputer.utils.DialogUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_login.*
import java.util.ArrayList
class LoginActivity : BaseLoginActivity() {
// initialize variables
private var mContext: Context? = null
private var mActivity: Activity? = null
private var shouldOrder = false
private var lineItems: ArrayList<LineItem>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initVar()
initView()
initFbLogin()
initGoogleLogin()
setGoogleButtonText(getString(R.string.google_cap))
initListener()
}
private fun initVar() {
// variables instance
mContext = applicationContext
mActivity = this@LoginActivity
lineItems = ArrayList()
val intent = intent
if (intent.hasExtra(AppConstants.KEY_LINE_ITEM_LIST)) {
lineItems = intent.getParcelableArrayListExtra(AppConstants.KEY_LINE_ITEM_LIST)
}
if (intent.hasExtra(AppConstants.KEY_LOGIN_ORDER)) {
shouldOrder = intent.getBooleanExtra(AppConstants.KEY_LOGIN_ORDER, false)
}
// analytics event trigger
AnalyticsUtils.getAnalyticsUtils(mContext).trackEvent("Login Activity")
}
private fun initView() {
setContentView(R.layout.activity_login)
AppUtility.noInternetWarning(tvSkipLogin, mContext)
}
private fun initListener() {
btnGoRegister.setOnClickListener{
ActivityUtils.instance.invokeActivity(this@LoginActivity,RegisterActivity::class.java, false)
}
tvSkipLogin?.setOnClickListener {
ActivityUtils.instance.invokeActivity(this@LoginActivity, MainActivity::class.java, true)
// analytics event trigger
AnalyticsUtils.getAnalyticsUtils(mContext).trackEvent("Skipped login process")
}
btnLoginEmail.setOnClickListener { invokeEmailLogin() }
setLoginListener(object : LoginListener {
override fun onRegisterResponse(customer: Customer) {
}
override fun onLoginResponse(id: Int) {
handleLogin(id)
}
override fun onLoginResponse(customer: Customer) {
handleLogin(customer)
}
})
}
private fun handleLogin(customer:Customer){
var progressDialog = DialogUtils.showProgressDialog(this@LoginActivity, getString(R.string.msg_loading), false)
val customerService = ServiceGenerator.createService(CustomerServices::class.java)
customerService.getByEmail(customer.email!!)
.subscribeOn((Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ items ->
val customer = items[0];
SettingsMy.setActiveUser(customer)
whatNext()
},
{ error ->
ActivityUtils.instance.invokeRegisterActivity(this@LoginActivity,customer.firstName!!, customer.email!!, shouldOrder)
})
}
private fun handleLogin(id:Int){
val customerService = ServiceGenerator.createService(CustomerServices::class.java)
val progressDialog = DialogUtils.showProgressDialog(this, getString(R.string.msg_loading), false)
customerService.single(id)
.subscribeOn((Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ item ->
SettingsMy.setActiveUser(item)
whatNext()
DialogUtils.dismissProgressDialog(progressDialog)
},
{ error ->
Toast.makeText(applicationContext, "Không thể đăng nhập", Toast.LENGTH_SHORT).show()
Log.e("ERROR", error.message)
DialogUtils.dismissProgressDialog(progressDialog)
})
}
private fun whatNext() {
if (shouldOrder) {
ActivityUtils.instance.invokeOrderShipping(this@LoginActivity)
} else {
ActivityUtils.instance.invokeActivity(this@LoginActivity, MainActivity::class.java, true)
}
}
}
| mit | 1888e8bb2639fc05417c6b57384e3894 | 36.115108 | 145 | 0.65691 | 5.118056 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/targets/models/WA6Ring.kt | 1 | 2879 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.targets.models
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.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.CERULEAN_BLUE
import de.dreier.mytargets.shared.utils.Color.DARK_GRAY
import de.dreier.mytargets.shared.utils.Color.FLAMINGO_RED
import de.dreier.mytargets.shared.utils.Color.LEMON_YELLOW
class WA6Ring : TargetModelBase(
id = ID,
nameRes = R.string.wa_6_ring,
zones = listOf(
CircularZone(0.084f, LEMON_YELLOW, DARK_GRAY, 3),
CircularZone(0.166f, LEMON_YELLOW, DARK_GRAY, 3),
CircularZone(0.334f, LEMON_YELLOW, DARK_GRAY, 3),
CircularZone(0.5f, FLAMINGO_RED, DARK_GRAY, 3),
CircularZone(0.666f, FLAMINGO_RED, DARK_GRAY, 3),
CircularZone(0.834f, CERULEAN_BLUE, DARK_GRAY, 3),
CircularZone(1.0f, CERULEAN_BLUE, DARK_GRAY, 3)
),
scoringStyles = listOf(
ScoringStyle(R.string.recurve_style_x_5, true, 10, 10, 9, 8, 7, 6, 5),
ScoringStyle(R.string.recurve_style_10_5, false, 10, 10, 9, 8, 7, 6, 5),
ScoringStyle(R.string.compound_style, false, 10, 9, 9, 8, 7, 6, 5),
ScoringStyle(false, 11, 10, 9, 8, 7, 6, 5),
ScoringStyle(true, 5, 5, 5, 4, 4, 3, 3),
ScoringStyle(false, 9, 9, 9, 7, 7, 5, 5)
),
diameters = listOf(
Dimension(40f, CENTIMETER),
Dimension(60f, CENTIMETER),
Dimension(80f, CENTIMETER),
Dimension(92f, CENTIMETER),
Dimension(122f, CENTIMETER)
)
) {
init {
realSizeFactor = 0.6f
decorator = CenterMarkDecorator(DARK_GRAY, 8.333f, 4, false)
}
override fun shouldDrawZone(zone: Int, scoringStyle: Int): Boolean {
// Do not draw second ring if we have a compound face
return !(scoringStyle == 1 && zone == 0) && !(scoringStyle == 2 && zone == 1)
}
companion object {
const val ID = 1L
}
}
| gpl-2.0 | 5ec2c58e226195938410980b16b48a62 | 40.724638 | 88 | 0.639805 | 3.545567 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/lwjgl/llvm/src/templates/kotlin/llvm/LTOTypes.kt | 4 | 1605 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package llvm
import org.lwjgl.generator.*
val LTO_BINDING = simpleBinding(Module.LLVM, libraryName = "LTO", libraryExpression = "Configuration.LLVM_LTO_LIBRARY_NAME, \"LTO\"")
val lto_code_gen_t = "lto_code_gen_t".handle
val lto_module_t = "lto_module_t".handle
val thinlto_code_gen_t = "thinlto_code_gen_t".handle
val lto_bool_t = PrimitiveType("lto_bool_t", PrimitiveMapping.BOOLEAN)
val off_t = IntegerType("off_t", PrimitiveMapping.LONG, unsigned = true)
val lto_codegen_diagnostic_severity_t = "lto_codegen_diagnostic_severity_t".enumType
val lto_codegen_model = "lto_codegen_model".enumType
val lto_debug_model = "lto_debug_model".enumType
val lto_symbol_attributes = "lto_symbol_attributes".enumType
val lto_diagnostic_handler_t = Module.LLVM.callback {
void(
"LTODiagnosticHandler",
"Diagnostic handler type.",
lto_codegen_diagnostic_severity_t("severity", "the severity"),
charUTF8.const.p("diag", "the actual diagnostic. The diagnostic is not prefixed by any of severity keyword, e.g., 'error: '."),
opaque_p("ctxt", "used to pass the context set with the diagnostic handler")
) {
documentation = "Instances of this interface may be passed to the #codegen_set_diagnostic_handler() method."
}
}
val LTOObjectBuffer = struct(Module.LLVM, "LTOObjectBuffer", mutable = false) {
documentation = "Type to wrap a single object returned by {@code ThinLTO}."
char.const.p("Buffer", "")
AutoSize("Buffer")..size_t("Size", "")
}
| bsd-3-clause | 5e78061c415ab02265fc6f0ee8a23de2 | 38.146341 | 135 | 0.705919 | 3.393235 | false | false | false | false |
google/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinBuildScriptManipulator.kt | 3 | 28536 | // 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.gradleJava.configuration
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalLibraryDescriptor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.buildArgumentString
import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.replaceLanguageFeature
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.configuration.*
import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.*
import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.utils.addToStdlib.cast
class KotlinBuildScriptManipulator(
override val scriptFile: KtFile,
override val preferNewSyntax: Boolean
) : GradleBuildScriptManipulator<KtFile> {
override fun isApplicable(file: PsiFile): Boolean = file is KtFile
private val gradleVersion = GradleVersionProvider.fetchGradleVersion(scriptFile)
override fun isConfiguredWithOldSyntax(kotlinPluginName: String) = runReadAction {
scriptFile.containsApplyKotlinPlugin(kotlinPluginName) && scriptFile.containsCompileStdLib()
}
override fun isConfigured(kotlinPluginExpression: String): Boolean = runReadAction {
scriptFile.containsKotlinPluginInPluginsGroup(kotlinPluginExpression) && scriptFile.containsCompileStdLib()
}
override fun configureProjectBuildScript(kotlinPluginName: String, version: IdeKotlinVersion): Boolean {
if (useNewSyntax(kotlinPluginName, gradleVersion)) return false
val originalText = scriptFile.text
scriptFile.getBuildScriptBlock()?.apply {
addDeclarationIfMissing("var $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true).also {
addExpressionAfterIfMissing("$GSK_KOTLIN_VERSION_PROPERTY_NAME = \"$version\"", it)
}
getRepositoriesBlock()?.apply {
addRepositoryIfMissing(version)
addMavenCentralIfMissing()
}
getDependenciesBlock()?.addPluginToClassPathIfMissing()
}
return originalText != scriptFile.text
}
override fun configureModuleBuildScript(
kotlinPluginName: String,
kotlinPluginExpression: String,
stdlibArtifactName: String,
version: IdeKotlinVersion,
jvmTarget: String?
): Boolean {
val originalText = scriptFile.text
val useNewSyntax = useNewSyntax(kotlinPluginName, gradleVersion)
scriptFile.apply {
if (useNewSyntax) {
createPluginInPluginsGroupIfMissing(kotlinPluginExpression, version)
getDependenciesBlock()?.addNoVersionCompileStdlibIfMissing(stdlibArtifactName)
getRepositoriesBlock()?.apply {
val repository = getRepositoryForVersion(version)
if (repository != null) {
scriptFile.module?.getBuildScriptSettingsPsiFile()?.let {
with(GradleBuildScriptSupport.getManipulator(it)) {
addPluginRepository(repository)
addMavenCentralPluginRepository()
addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY)
}
}
}
}
} else {
script?.blockExpression?.addDeclarationIfMissing("val $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true)
getApplyBlock()?.createPluginIfMissing(kotlinPluginName)
getDependenciesBlock()?.addCompileStdlibIfMissing(stdlibArtifactName)
}
getRepositoriesBlock()?.apply {
addRepositoryIfMissing(version)
addMavenCentralIfMissing()
}
jvmTarget?.let {
changeKotlinTaskParameter("jvmTarget", it, forTests = false)
changeKotlinTaskParameter("jvmTarget", it, forTests = true)
}
}
return originalText != scriptFile.text
}
override fun changeLanguageFeatureConfiguration(
feature: LanguageFeature,
state: LanguageFeature.State,
forTests: Boolean
): PsiElement? =
scriptFile.changeLanguageFeatureConfiguration(feature, state, forTests)
override fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? =
scriptFile.changeKotlinTaskParameter("languageVersion", version, forTests)
override fun changeApiVersion(version: String, forTests: Boolean): PsiElement? =
scriptFile.changeKotlinTaskParameter("apiVersion", version, forTests)
override fun addKotlinLibraryToModuleBuildScript(
targetModule: Module?,
scope: DependencyScope,
libraryDescriptor: ExternalLibraryDescriptor
) {
val dependencyText = getCompileDependencySnippet(
libraryDescriptor.libraryGroupId,
libraryDescriptor.libraryArtifactId,
libraryDescriptor.maxVersion,
scope.toGradleCompileScope(scriptFile.module?.buildSystemType == BuildSystemType.AndroidGradle)
)
if (targetModule != null && usesNewMultiplatform()) {
val findOrCreateTargetSourceSet = scriptFile
.getKotlinBlock()
?.getSourceSetsBlock()
?.findOrCreateTargetSourceSet(targetModule.name.takeLastWhile { it != '.' })
val dependenciesBlock = findOrCreateTargetSourceSet?.getDependenciesBlock()
dependenciesBlock?.addExpressionIfMissing(dependencyText)
} else {
scriptFile.getDependenciesBlock()?.addExpressionIfMissing(dependencyText)
}
}
private fun KtBlockExpression.findOrCreateTargetSourceSet(moduleName: String) =
findTargetSourceSet(moduleName) ?: createTargetSourceSet(moduleName)
private fun KtBlockExpression.findTargetSourceSet(moduleName: String): KtBlockExpression? = statements.find {
it.isTargetSourceSetDeclaration(moduleName)
}?.getOrCreateBlock()
private fun KtExpression.getOrCreateBlock(): KtBlockExpression? = when (this) {
is KtCallExpression -> getBlock() ?: addBlock()
is KtReferenceExpression -> replace(KtPsiFactory(project).createExpression("$text {\n}")).cast<KtCallExpression>().getBlock()
is KtProperty -> delegateExpressionOrInitializer?.getOrCreateBlock()
else -> error("Impossible create block for $this")
}
private fun KtCallExpression.addBlock(): KtBlockExpression? = parent.addAfter(
KtPsiFactory(project).createEmptyBody(), this
) as? KtBlockExpression
private fun KtBlockExpression.createTargetSourceSet(moduleName: String) = addExpressionIfMissing("getByName(\"$moduleName\") {\n}")
.cast<KtCallExpression>()
.getBlock()
override fun getKotlinStdlibVersion(): String? = scriptFile.getKotlinStdlibVersion()
private fun KtBlockExpression.addCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? =
findStdLibDependency()
?: addExpressionIfMissing(
getCompileDependencySnippet(
KOTLIN_GROUP_ID,
stdlibArtifactName,
version = "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME"
)
) as? KtCallExpression
private fun addPluginRepositoryExpression(expression: String) {
scriptFile.getPluginManagementBlock()?.findOrCreateBlock("repositories")?.addExpressionIfMissing(expression)
}
override fun addMavenCentralPluginRepository() {
addPluginRepositoryExpression("mavenCentral()")
}
override fun addPluginRepository(repository: RepositoryDescription) {
addPluginRepositoryExpression(repository.toKotlinRepositorySnippet())
}
override fun addResolutionStrategy(pluginId: String) {
scriptFile
.getPluginManagementBlock()
?.findOrCreateBlock("resolutionStrategy")
?.findOrCreateBlock("eachPlugin")
?.addExpressionIfMissing(
"""
if (requested.id.id == "$pluginId") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}")
}
""".trimIndent()
)
}
private fun KtBlockExpression.addNoVersionCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? =
findStdLibDependency() ?: addExpressionIfMissing(
"implementation(${getKotlinModuleDependencySnippet(
stdlibArtifactName,
null
)})"
) as? KtCallExpression
private fun KtFile.containsCompileStdLib(): Boolean =
findScriptInitializer("dependencies")?.getBlock()?.findStdLibDependency() != null
private fun KtFile.containsApplyKotlinPlugin(pluginName: String): Boolean =
findScriptInitializer("apply")?.getBlock()?.findPlugin(pluginName) != null
private fun KtFile.containsKotlinPluginInPluginsGroup(pluginName: String): Boolean =
findScriptInitializer("plugins")?.getBlock()?.findPluginInPluginsGroup(pluginName) != null
private fun KtBlockExpression.findPlugin(pluginName: String): KtCallExpression? {
return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find {
it.calleeExpression?.text == "plugin" && it.valueArguments.firstOrNull()?.text == "\"$pluginName\""
}
}
private fun KtBlockExpression.findClassPathDependencyVersion(pluginName: String): String? {
return PsiTreeUtil.getChildrenOfAnyType(this, KtCallExpression::class.java).mapNotNull {
if (it?.calleeExpression?.text == "classpath") {
val dependencyName = it.valueArguments.firstOrNull()?.text?.removeSurrounding("\"")
if (dependencyName?.startsWith(pluginName) == true) dependencyName.substringAfter("$pluginName:") else null
} else null
}.singleOrNull()
}
private fun getPluginInfoFromBuildScript(
operatorName: String?,
pluginVersion: KtExpression?,
receiverCalleeExpression: KtCallExpression?
): Pair<String, String>? {
val receiverCalleeExpressionText = receiverCalleeExpression?.calleeExpression?.text?.trim()
val receivedPluginName = when {
receiverCalleeExpressionText == "id" ->
receiverCalleeExpression.valueArguments.firstOrNull()?.text?.trim()?.removeSurrounding("\"")
operatorName == "version" -> receiverCalleeExpressionText
else -> null
}
val pluginVersionText = pluginVersion?.text?.trim()?.removeSurrounding("\"") ?: return null
return receivedPluginName?.to(pluginVersionText)
}
private fun KtBlockExpression.findPluginVersionInPluginGroup(pluginName: String): String? {
val versionsToPluginNames =
PsiTreeUtil.getChildrenOfAnyType(this, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java).mapNotNull {
when (it) {
is KtBinaryExpression -> getPluginInfoFromBuildScript(
it.operationReference.text,
it.right,
it.left as? KtCallExpression
)
is KtDotQualifiedExpression ->
(it.selectorExpression as? KtCallExpression)?.run {
getPluginInfoFromBuildScript(
calleeExpression?.text,
valueArguments.firstOrNull()?.getArgumentExpression(),
it.receiverExpression as? KtCallExpression
)
}
else -> null
}
}.toMap()
return versionsToPluginNames.getOrDefault(pluginName, null)
}
private fun KtBlockExpression.findPluginInPluginsGroup(pluginName: String): KtCallExpression? {
return PsiTreeUtil.getChildrenOfAnyType(
this,
KtCallExpression::class.java,
KtBinaryExpression::class.java,
KtDotQualifiedExpression::class.java
).mapNotNull {
when (it) {
is KtCallExpression -> it
is KtBinaryExpression -> {
if (it.operationReference.text == "version") it.left as? KtCallExpression else null
}
is KtDotQualifiedExpression -> {
if ((it.selectorExpression as? KtCallExpression)?.calleeExpression?.text == "version") {
it.receiverExpression as? KtCallExpression
} else null
}
else -> null
}
}.find {
"${it.calleeExpression?.text?.trim() ?: ""}(${it.valueArguments.firstOrNull()?.text ?: ""})" == pluginName
}
}
private fun KtFile.findScriptInitializer(startsWith: String): KtScriptInitializer? =
PsiTreeUtil.findChildrenOfType(this, KtScriptInitializer::class.java).find { it.text.startsWith(startsWith) }
private fun KtBlockExpression.findBlock(name: String): KtBlockExpression? {
return getChildrenOfType<KtCallExpression>().find {
it.calleeExpression?.text == name &&
it.valueArguments.singleOrNull()?.getArgumentExpression() is KtLambdaExpression
}?.getBlock()
}
private fun KtScriptInitializer.getBlock(): KtBlockExpression? =
PsiTreeUtil.findChildOfType(this, KtCallExpression::class.java)?.getBlock()
private fun KtCallExpression.getBlock(): KtBlockExpression? =
(valueArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression)?.bodyExpression
?: lambdaArguments.lastOrNull()?.getLambdaExpression()?.bodyExpression
private fun KtFile.getKotlinStdlibVersion(): String? {
return findScriptInitializer("dependencies")?.getBlock()?.let {
when (val expression = it.findStdLibDependency()?.valueArguments?.firstOrNull()?.getArgumentExpression()) {
is KtCallExpression -> expression.valueArguments.getOrNull(1)?.text?.trim('\"')
is KtStringTemplateExpression -> expression.text?.trim('\"')?.substringAfterLast(":")?.removePrefix("$")
else -> null
}
}
}
private fun KtBlockExpression.findStdLibDependency(): KtCallExpression? {
return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find {
val calleeText = it.calleeExpression?.text
calleeText in SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
&& (it.valueArguments.firstOrNull()?.getArgumentExpression()?.isKotlinStdLib() ?: false)
}
}
private fun KtExpression.isKotlinStdLib(): Boolean = when (this) {
is KtCallExpression -> {
val calleeText = calleeExpression?.text
(calleeText == "kotlinModule" || calleeText == "kotlin") &&
valueArguments.firstOrNull()?.getArgumentExpression()?.text?.startsWith("\"stdlib") ?: false
}
is KtStringTemplateExpression -> text.startsWith("\"$STDLIB_ARTIFACT_PREFIX")
else -> false
}
private fun KtFile.getPluginManagementBlock(): KtBlockExpression? = findOrCreateScriptInitializer("pluginManagement", true)
private fun KtFile.getKotlinBlock(): KtBlockExpression? = findOrCreateScriptInitializer("kotlin")
private fun KtBlockExpression.getSourceSetsBlock(): KtBlockExpression? = findOrCreateBlock("sourceSets")
private fun KtFile.getRepositoriesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("repositories")
private fun KtFile.getDependenciesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("dependencies")
private fun KtFile.getPluginsBlock(): KtBlockExpression? = findOrCreateScriptInitializer("plugins", true)
private fun KtFile.createPluginInPluginsGroupIfMissing(pluginName: String, version: IdeKotlinVersion): KtCallExpression? =
getPluginsBlock()?.let {
it.findPluginInPluginsGroup(pluginName)
?: it.addExpressionIfMissing("$pluginName version \"${version.artifactVersion}\"") as? KtCallExpression
}
private fun KtFile.createApplyBlock(): KtBlockExpression? {
val apply = psiFactory.createScriptInitializer("apply {\n}")
val plugins = findScriptInitializer("plugins")
val addedElement = plugins?.addSibling(apply) ?: addToScriptBlock(apply)
addedElement?.addNewLinesIfNeeded()
return (addedElement as? KtScriptInitializer)?.getBlock()
}
private fun KtFile.getApplyBlock(): KtBlockExpression? = findScriptInitializer("apply")?.getBlock() ?: createApplyBlock()
private fun KtBlockExpression.createPluginIfMissing(pluginName: String): KtCallExpression? =
findPlugin(pluginName) ?: addExpressionIfMissing("plugin(\"$pluginName\")") as? KtCallExpression
private fun KtFile.changeCoroutineConfiguration(coroutineOption: String): PsiElement? {
val snippet = "experimental.coroutines = Coroutines.${coroutineOption.toUpperCase()}"
val kotlinBlock = getKotlinBlock() ?: return null
addImportIfMissing("org.jetbrains.kotlin.gradle.dsl.Coroutines")
val statement = kotlinBlock.statements.find { it.text.startsWith("experimental.coroutines") }
return if (statement != null) {
statement.replace(psiFactory.createExpression(snippet))
} else {
kotlinBlock.add(psiFactory.createExpression(snippet)).apply { addNewLinesIfNeeded() }
}
}
private fun KtFile.changeLanguageFeatureConfiguration(
feature: LanguageFeature,
state: LanguageFeature.State,
forTests: Boolean
): PsiElement? {
if (usesNewMultiplatform()) {
state.assertApplicableInMultiplatform()
return getKotlinBlock()
?.findOrCreateBlock("sourceSets")
?.findOrCreateBlock("all")
?.addExpressionIfMissing("languageSettings.enableLanguageFeature(\"${feature.name}\")")
}
val pluginsBlock = findScriptInitializer("plugins")?.getBlock()
val rawKotlinVersion = pluginsBlock?.findPluginVersionInPluginGroup("kotlin")
?: pluginsBlock?.findPluginVersionInPluginGroup("org.jetbrains.kotlin.jvm")
?: findScriptInitializer("buildscript")?.getBlock()?.findBlock("dependencies")?.findClassPathDependencyVersion("org.jetbrains.kotlin:kotlin-gradle-plugin")
val kotlinVersion = rawKotlinVersion?.let(IdeKotlinVersion::opt)
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val parameterName = "freeCompilerArgs"
return addOrReplaceKotlinTaskParameter(
parameterName,
"listOf(\"$featureArgumentString\")",
forTests
) {
val newText = text.replaceLanguageFeature(
feature,
state,
kotlinVersion,
prefix = "$parameterName = listOf(",
postfix = ")"
)
replace(psiFactory.createExpression(newText))
}
}
private fun KtFile.addOrReplaceKotlinTaskParameter(
parameterName: String,
defaultValue: String,
forTests: Boolean,
replaceIt: KtExpression.() -> PsiElement
): PsiElement? {
val taskName = if (forTests) "compileTestKotlin" else "compileKotlin"
val optionsBlock = findScriptInitializer("$taskName.kotlinOptions")?.getBlock()
return if (optionsBlock != null) {
val assignment = optionsBlock.statements.find {
(it as? KtBinaryExpression)?.left?.text == parameterName
}
assignment?.replaceIt() ?: optionsBlock.addExpressionIfMissing("$parameterName = $defaultValue")
} else {
addImportIfMissing("org.jetbrains.kotlin.gradle.tasks.KotlinCompile")
script?.blockExpression?.addDeclarationIfMissing("val $taskName: KotlinCompile by tasks")
addTopLevelBlock("$taskName.kotlinOptions")?.addExpressionIfMissing("$parameterName = $defaultValue")
}
}
private fun KtFile.changeKotlinTaskParameter(parameterName: String, parameterValue: String, forTests: Boolean): PsiElement? {
return addOrReplaceKotlinTaskParameter(parameterName, "\"$parameterValue\"", forTests) {
replace(psiFactory.createExpression("$parameterName = \"$parameterValue\""))
}
}
private fun KtBlockExpression.getRepositorySnippet(version: IdeKotlinVersion): String? {
val repository = getRepositoryForVersion(version)
return when {
repository != null -> repository.toKotlinRepositorySnippet()
!isRepositoryConfigured(text) -> MAVEN_CENTRAL
else -> null
}
}
private fun KtFile.getBuildScriptBlock(): KtBlockExpression? = findOrCreateScriptInitializer("buildscript", true)
private fun KtFile.findOrCreateScriptInitializer(name: String, first: Boolean = false): KtBlockExpression? =
findScriptInitializer(name)?.getBlock() ?: addTopLevelBlock(name, first)
private fun KtBlockExpression.getRepositoriesBlock(): KtBlockExpression? = findOrCreateBlock("repositories")
private fun KtBlockExpression.getDependenciesBlock(): KtBlockExpression? = findOrCreateBlock("dependencies")
private fun KtBlockExpression.addRepositoryIfMissing(version: IdeKotlinVersion): KtCallExpression? {
val snippet = getRepositorySnippet(version) ?: return null
return addExpressionIfMissing(snippet) as? KtCallExpression
}
private fun KtBlockExpression.addMavenCentralIfMissing(): KtCallExpression? =
if (!isRepositoryConfigured(text)) addExpressionIfMissing(MAVEN_CENTRAL) as? KtCallExpression else null
private fun KtBlockExpression.findOrCreateBlock(name: String, first: Boolean = false) = findBlock(name) ?: addBlock(name, first)
private fun KtBlockExpression.addPluginToClassPathIfMissing(): KtCallExpression? =
addExpressionIfMissing(getKotlinGradlePluginClassPathSnippet()) as? KtCallExpression
private fun KtBlockExpression.addBlock(name: String, first: Boolean = false): KtBlockExpression? {
return psiFactory.createExpression("$name {\n}")
.let { if (first) addAfter(it, null) else add(it) }
?.apply { addNewLinesIfNeeded() }
?.cast<KtCallExpression>()
?.getBlock()
}
private fun KtFile.addTopLevelBlock(name: String, first: Boolean = false): KtBlockExpression? {
val scriptInitializer = psiFactory.createScriptInitializer("$name {\n}")
val addedElement = addToScriptBlock(scriptInitializer, first) as? KtScriptInitializer
addedElement?.addNewLinesIfNeeded()
return addedElement?.getBlock()
}
private fun PsiElement.addSibling(element: PsiElement): PsiElement = parent.addAfter(element, this)
private fun PsiElement.addNewLineBefore(lineBreaks: Int = 1) {
parent.addBefore(psiFactory.createNewLine(lineBreaks), this)
}
private fun PsiElement.addNewLineAfter(lineBreaks: Int = 1) {
parent.addAfter(psiFactory.createNewLine(lineBreaks), this)
}
private fun PsiElement.addNewLinesIfNeeded(lineBreaks: Int = 1) {
if (prevSibling != null && prevSibling.text.isNotBlank()) {
addNewLineBefore(lineBreaks)
}
if (nextSibling != null && nextSibling.text.isNotBlank()) {
addNewLineAfter(lineBreaks)
}
}
private fun KtFile.addToScriptBlock(element: PsiElement, first: Boolean = false): PsiElement? =
if (first) script?.blockExpression?.addAfter(element, null) else script?.blockExpression?.add(element)
private fun KtFile.addImportIfMissing(path: String): KtImportDirective =
importDirectives.find { it.importPath?.pathStr == path } ?: importList?.add(
psiFactory.createImportDirective(
ImportPath.fromString(
path
)
)
) as KtImportDirective
private fun KtBlockExpression.addExpressionAfterIfMissing(text: String, after: PsiElement): KtExpression = addStatementIfMissing(text) {
addAfter(psiFactory.createExpression(it), after)
}
private fun KtBlockExpression.addExpressionIfMissing(text: String, first: Boolean = false): KtExpression = addStatementIfMissing(text) {
psiFactory.createExpression(it).let { created ->
if (first) addAfter(created, null) else add(created)
}
}
private fun KtBlockExpression.addDeclarationIfMissing(text: String, first: Boolean = false): KtDeclaration =
addStatementIfMissing(text) {
psiFactory.createDeclaration<KtDeclaration>(it).let { created ->
if (first) addAfter(created, null) else add(created)
}
}
private inline fun <reified T : PsiElement> KtBlockExpression.addStatementIfMissing(
text: String,
crossinline factory: (String) -> PsiElement
): T {
statements.find { StringUtil.equalsIgnoreWhitespaces(it.text, text) }?.let {
return it as T
}
return factory(text).apply { addNewLinesIfNeeded() } as T
}
private fun KtPsiFactory.createScriptInitializer(text: String): KtScriptInitializer =
createFile("dummy.kts", text).script?.blockExpression?.firstChild as KtScriptInitializer
private val PsiElement.psiFactory: KtPsiFactory
get() = KtPsiFactory(this)
private fun getCompileDependencySnippet(
groupId: String,
artifactId: String,
version: String?,
compileScope: String = "implementation"
): String {
if (groupId != KOTLIN_GROUP_ID) {
return "$compileScope(\"$groupId:$artifactId:$version\")"
}
val kotlinPluginName =
if (scriptFile.module?.buildSystemType == BuildSystemType.AndroidGradle) {
"kotlin-android"
} else {
KotlinGradleModuleConfigurator.KOTLIN
}
if (useNewSyntax(kotlinPluginName, gradleVersion)) {
return "$compileScope(${getKotlinModuleDependencySnippet(artifactId)})"
}
val libraryVersion = if (version == GSK_KOTLIN_VERSION_PROPERTY_NAME) "\$$version" else version
return "$compileScope(${getKotlinModuleDependencySnippet(artifactId, libraryVersion)})"
}
companion object {
private const val STDLIB_ARTIFACT_PREFIX = "org.jetbrains.kotlin:kotlin-stdlib"
const val GSK_KOTLIN_VERSION_PROPERTY_NAME = "kotlin_version"
fun getKotlinGradlePluginClassPathSnippet(): String =
"classpath(${getKotlinModuleDependencySnippet("gradle-plugin", "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME")})"
fun getKotlinModuleDependencySnippet(artifactId: String, version: String? = null): String {
val moduleName = artifactId.removePrefix("kotlin-")
return when (version) {
null -> "kotlin(\"$moduleName\")"
"\$$GSK_KOTLIN_VERSION_PROPERTY_NAME" -> "kotlinModule(\"$moduleName\", $GSK_KOTLIN_VERSION_PROPERTY_NAME)"
else -> "kotlinModule(\"$moduleName\", ${"\"$version\""})"
}
}
}
}
private fun KtExpression.isTargetSourceSetDeclaration(moduleName: String): Boolean = with(text) {
when (this@isTargetSourceSetDeclaration) {
is KtProperty -> startsWith("val $moduleName by") || initializer?.isTargetSourceSetDeclaration(moduleName) == true
is KtCallExpression -> startsWith("getByName(\"$moduleName\")")
else -> false
}
}
| apache-2.0 | e26a0c102a6accf849bcf1441b0bb78f | 45.780328 | 167 | 0.670802 | 5.839165 | false | false | false | false |
eugenkiss/kotlinfx | kotlinfx-core/src/main/kotlin/kotlinfx/builders/Geometry.kt | 2 | 514 | package kotlinfx.builders
// Allows a more flexible way to express insets. Both ways of the Java version are possible, but also
// the specification of a selection of sides like `Insets(top=10.0,left=20.0)`.
public fun Insets(
all: Double = 0.0,
top: Double = 0.0,
right: Double = 0.0,
bottom: Double = 0.0,
left: Double = 0.0
): javafx.geometry.Insets = if (all != 0.0) javafx.geometry.Insets(all)
else javafx.geometry.Insets(top, right, bottom, left)
| mit | 008dc2357f76a46cac6e6a8b3a967c04 | 38.538462 | 101 | 0.638132 | 3.569444 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.