repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
pie-flavor/Kludge
src/main/kotlin/flavor/pie/kludge/advancements.kt
1
3394
package flavor.pie.kludge import org.spongepowered.api.advancement.Advancement import org.spongepowered.api.advancement.TreeLayout import org.spongepowered.api.advancement.TreeLayoutElement import org.spongepowered.api.advancement.criteria.AdvancementCriterion import org.spongepowered.api.advancement.criteria.ScoreCriterionProgress import org.spongepowered.api.text.Text import java.time.Instant /** * @see Advancement.toToastText */ val Advancement.toastText: List<Text> get() = toToastText() /** * @see TreeLayout.getElement */ operator fun TreeLayout.get(advancement: Advancement): TreeLayoutElement? = getElement(advancement).unwrap() /** * @see AdvancementCriterion.and */ infix fun AdvancementCriterion.and(criterion: AdvancementCriterion): AdvancementCriterion = and(criterion) /** * @see AdvancementCriterion.and */ infix fun AdvancementCriterion.and(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = and(criteria) /** * @see AdvancementCriterion.or */ infix fun AdvancementCriterion.or(criterion: AdvancementCriterion): AdvancementCriterion = or(criterion) /** * @see AdvancementCriterion.or */ infix fun AdvancementCriterion.or(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = or(criteria) /** * @see ScoreCriterionProgress.add */ operator fun ScoreCriterionProgress.plusAssign(score: Int) { add(score) } /** * @see ScoreCriterionProgress.add */ operator fun ScoreCriterionProgress.plus(score: Int): Instant? = add(score).unwrap() /** * @see ScoreCriterionProgress.remove */ operator fun ScoreCriterionProgress.minusAssign(score: Int) { remove(score) } /** * @see ScoreCriterionProgress.remove */ operator fun ScoreCriterionProgress.minus(score: Int): Instant? = remove(score).unwrap() /** * Multiplies the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.timesAssign(score: Int) { set(this.score * score) } /** * Multiplies the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.times(score: Int): Instant? = set(this.score * score).unwrap() /** * Divides the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.divAssign(score: Int) { set(this.score / score) } /** * Divides the score by [score]. * @see ScoreCriterionProgress.set */ operator fun ScoreCriterionProgress.div(score: Int): Instant? = set(this.score / score).unwrap() /** * Adds 1 to the score. * @see ScoreCriterionProgress.add */ operator fun ScoreCriterionProgress.inc(): ScoreCriterionProgress = apply { add(1) } /** * Subtracts 1 from the score. * @see ScoreCriterionProgress.remove */ operator fun ScoreCriterionProgress.dec(): ScoreCriterionProgress = apply { remove(1) } /** * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.unaryPlus(): Int = +score /** * Gets the score multiplied by -1. * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.unaryMinus(): Int = -score /** * Compares the score to [i]. * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.compareTo(i: Int): Int = score.compareTo(i) /** * Compares the scores of both progresses. * @see ScoreCriterionProgress.getScore */ operator fun ScoreCriterionProgress.compareTo(progress: ScoreCriterionProgress): Int = score.compareTo(progress.score)
mit
ddb7debdd07768e67cb944f97fda42e6
27.762712
118
0.763111
4.002358
false
false
false
false
NLPIE/BioMedICUS
biomedicus-core/src/main/kotlin/edu/umn/biomedicus/sentences/SentenceEndingStats.kt
1
2220
/* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.sentences import edu.umn.nlpengine.Document import edu.umn.nlpengine.DocumentsProcessor import edu.umn.nlpengine.labelIndex class SentenceEndingStats : DocumentsProcessor { val periodRegex = Regex("[.]\\s*$") val exRegex = Regex("[!]\\s*$") val questRegex = Regex("[?]\\s*$") val semiRegex = Regex("[;]\\s*$") val colonRegex = Regex("[:]\\s*$") val quoteRegex = Regex("[.!?;:][\"”]\\s*\$") var periods = 0 var exclams = 0 var questions = 0 var semicolon = 0 var colon = 0 var quote = 0 var none = 0 override fun process(document: Document) { val sentences = document.labelIndex<Sentence>() for (sentence in sentences) { if (sentence.sentenceClass == Sentence.unknown) continue val text = sentence.coveredText(document.text) when { periodRegex.containsMatchIn(text) -> periods++ exRegex.containsMatchIn(text) -> exclams++ questRegex.containsMatchIn(text) -> questions++ semiRegex.containsMatchIn(text) -> semicolon++ colonRegex.containsMatchIn(text) -> colon++ quoteRegex.containsMatchIn(text) -> quote++ else -> none++ } } } override fun done() { println("periods: $periods") println("exclams: $exclams") println("questions: $questions") println("semicolon: $semicolon") println("colon: $colon") println("quote: $quote") println("none: $none") } }
apache-2.0
4064a914366bfeb8f6c1743760282d25
32.104478
75
0.622182
4.306796
false
false
false
false
waicool20/SKrypton
src/main/kotlin/com/waicool20/skrypton/jni/objects/SKryptonApp.kt
1
6637
/* * The MIT License (MIT) * * Copyright (c) SKrypton by waicool20 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.waicool20.skrypton.jni.objects import com.waicool20.skrypton.jni.CPointer import com.waicool20.skrypton.jni.NativeInterface import com.waicool20.skrypton.util.OS import com.waicool20.skrypton.util.SystemUtils import com.waicool20.skrypton.util.div import com.waicool20.skrypton.util.loggerFor import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.streams.toList import kotlin.system.exitProcess import javafx.application.Platform /** * A singleton app instance for this library and is the main entry point for any program that wants * to use any of the SKrypton APIs. This object is in charge of initializing the native components * and managing it. */ object SKryptonApp : NativeInterface() { /** * Holds a [Path] pointing to the directory used by SKrypton, this directory contains all the * native libraries and resources that SKrypton will use. */ val APP_DIRECTORY: Path = Paths.get(System.getProperty("user.home")) / ".skrypton" private val logger = loggerFor<SKryptonApp>() /** * Native pointer, initialized in [initialize]. */ override lateinit var handle: CPointer // Get the load order from the nativeLibraries-<OS> file in resources private val nativeDependencies = run { val resourceFile = when { OS.isLinux() -> "nativeLibraries-linux.txt" OS.isWindows() -> "nativeLibraries-windows.txt" OS.isMac() -> TODO("I don't have a mac to test this stuff yet") else -> error("Unsupported system") } SKryptonApp::class.java .getResourceAsStream("/com/waicool20/skrypton/resources/$resourceFile") ?.bufferedReader()?.lines()?.toList()?.filterNot { it.isNullOrEmpty() } ?: error("Could not read '$resourceFile' from classpath.") } init { if (Files.notExists(APP_DIRECTORY)) error("Could not find SKrypton Native components folder, did you install it?") val libs = Files.walk(APP_DIRECTORY / "lib") .filter { Files.isRegularFile(it) && "${it.fileName}".dropWhile { it != '.' }.contains(OS.libraryExtention) } .sorted { path1, path2 -> nativeDependencies.indexOfFirst { "${path1.fileName}".contains(it) } - nativeDependencies.indexOfFirst { "${path2.fileName}".contains(it) } }.toList() libs.plusElement(APP_DIRECTORY / System.mapLibraryName("SKryptonNative")).forEach { logger.debug { "Loading library at $it" } SystemUtils.loadLibrary(it, true) } } /** * Initializes the native components. * * @param args Arguments to pass to the native components, recommended to just pass the array * received from the main function. Default is an empty array. * @param remoteDebugPort The remote debug port is initialized if given a valid value from 0 to 65535 * and that the port is not previously occupied. Default is -1 (Not initialized). * @param action Action to be executed with the SKryptonApp instance as its receiver. * @return [SKryptonApp] instance (Can be used to chain [exec] function). */ fun initialize(args: Array<String> = emptyArray(), remoteDebugPort: Int = -1, action: SKryptonApp.() -> Unit = {} ): SKryptonApp { if (remoteDebugPort in 0..65535) { putEnv("QTWEBENGINE_REMOTE_DEBUGGING", remoteDebugPort.toString()) } handle = CPointer(initialize_N(args)) this.action() return this } /** * Blocking function which starts the execution of the SKryptonApp. * * @param exit Whether or not to exit when SKryptonApp instance is done. Defaults to false * @return If [exit] is false, this function will return the exit code of the native side. */ fun exec(exit: Boolean = false): Int { val exitCode = exec_N() if (exit) exitProcess(exitCode) return exitCode } /** * Executes the given action on the thread where SKryptonApp exists. This is similar to the * [Platform.runLater] method. * * @param action Action to be executed. */ fun runOnMainThread(action: () -> Unit) = runOnMainThread_N(Runnable { action() }) //<editor-fold desc="Environment functions"> /** * Puts an variable into the native environment, it is lost when the SKryptonApp is done executing. * * @param key The name of the environment variable. * @param value The value of the environment variable. */ fun putEnv(key: String, value: String) = putEnv_N(key, value) /** * Gets the value of the native environment variable. * * @param key The name of the environment variable. * @return The value of the environment variable. */ fun getEnv(key: String) = getEnv_N(key) //</editor-fold> /** * Closes the SKryptonApp instance explicitly. */ override fun close() { dispose_N() } //<editor-fold desc="Native functions"> private external fun putEnv_N(key: String, value: String) private external fun getEnv_N(key: String): String private external fun runOnMainThread_N(action: Runnable) private external fun initialize_N(args: Array<String>): Long private external fun exec_N(): Int private external fun dispose_N() //</editor-fold> }
mit
5923a072f9dca5a6ca0c43d8cc42d800
38.742515
125
0.670484
4.481431
false
false
false
false
konrad-jamrozik/droidmate
dev/droidmate/buildSrc/src/main/kotlin/org/droidmate/buildsrc/build.kt
1
6575
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2016 Konrad Jamrozik // // 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/>. // // email: [email protected] // web: www.droidmate.org // "unused" warning is suppressed because vals in this project are being used in the 'droidmate' project gradle build scripts // as well as in the 'droidmate' project itself. The "unused" warning doesn't properly recognize some of the usages. @file:Suppress("unused") package org.droidmate.buildsrc import com.konradjamrozik.OS import com.konradjamrozik.asEnvDir import com.konradjamrozik.resolveDir import com.konradjamrozik.resolveRegularFile import org.zeroturnaround.exec.ProcessExecutor import java.io.ByteArrayOutputStream import java.io.File import java.nio.file.Paths import java.util.* import java.util.concurrent.TimeUnit private val exeExt = if (OS.isWindows) ".exe" else "" //region Values directly based on system environment variables val java_home = "JAVA_HOME".asEnvDir private val android_sdk_dir = "ANDROID_HOME".asEnvDir //endregion val jarsigner_relative_path = "bin/jarsigner$exeExt" val jarsigner = java_home.resolveRegularFile(jarsigner_relative_path) //region Android SDK components private val build_tools_version = "25.0.1" private val android_platform_version_api19 = "19" private val android_platform_version_api23 = "23" val aapt_command_relative = "build-tools/$build_tools_version/aapt$exeExt" val adb_command_relative = "platform-tools/adb$exeExt" val aapt_command = android_sdk_dir.resolveRegularFile(aapt_command_relative) val adb_command = android_sdk_dir.resolveRegularFile(adb_command_relative) private val android_platform_dir_api19 = android_sdk_dir.resolveDir("platforms/android-$android_platform_version_api19") private val android_platform_dir_api23 = android_sdk_dir.resolveDir("platforms/android-$android_platform_version_api23") val uiautomator_jar_api19 = android_platform_dir_api19.resolveRegularFile("uiautomator.jar") val uiautomator_jar_api23 = android_platform_dir_api23.resolveRegularFile("uiautomator.jar") val android_jar_api19 = android_platform_dir_api19.resolveRegularFile("android.jar") val android_jar_api23 = android_platform_dir_api23.resolveRegularFile("android.jar") val android_extras_m2repo = android_sdk_dir.resolveDir("extras/android/m2repository") //endregion val monitor_generator_res_name_monitor_template = "monitorTemplate.txt" private val monitor_generator_output_dir = "temp" fun generated_monitor(apiLevel: Int) : String { return "$monitor_generator_output_dir/generated_Monitor_api$apiLevel.java" } val monitor_generator_output_relative_path_api19 = generated_monitor(19) val monitor_generator_output_relative_path_api23 = generated_monitor(23) val apk_inliner_param_input_default = Paths.get("input-apks") val apk_inliner_param_output_dir_default = Paths.get("output-apks") val apk_inliner_param_input = "-input" val apk_inliner_param_output_dir = "-outputDir" val AVD_dir_for_temp_files = "/data/local/tmp/" val uia2_daemon_project_name = "uiautomator2-daemon" val uia2_daemon_relative_project_dir = File("projects", uia2_daemon_project_name) val monitored_apk_fixture_api19_name = "MonitoredApkFixture_api19-debug.apk" val monitored_apk_fixture_api23_name = "MonitoredApkFixture_api23-debug.apk" val monitored_inlined_apk_fixture_api19_name = "${monitored_apk_fixture_api19_name.removeSuffix(".apk")}-inlined.apk" val monitored_inlined_apk_fixture_api23_name = "${monitored_apk_fixture_api23_name.removeSuffix(".apk")}-inlined.apk" val monitor_api19_apk_name = "monitor_api19.apk" val monitor_api23_apk_name = "monitor_api23.apk" val monitor_on_avd_apk_name = "monitor.apk" /** * Denotes name of directory containing apk fixtures for testing. The handle to this path is expected to be obtained * in following ways: * * From a build.gradle script: * * new File(sourceSets.test.resources.srcDirs[0], <this_var_reference>) * * From compiled source code: * * new Resource("<this_var_reference>").extractTo(fs.getPath(BuildConstants.dir_name_temp_extracted_resources)) */ val apk_fixtures = "fixtures/apks" val test_temp_dir_name = "temp_dir_for_tests" val monitored_apis_txt = "monitored_apis.txt" /** * Directory for resources extracted from jars in the classpath. * * Some resources have to be extracted to a directory. For example, an .apk file that is inside a .jar needs to be pushed * to a device. */ val dir_name_temp_extracted_resources = "temp_extracted_resources" // !!! DUPLICATION WARNING !!! with org.droidmate.MonitorConstants.monitor_time_formatter_locale val locale = Locale.US fun executeCommand(commandName: String, commandContent: String): Int { val cmd = if (OS.isWindows) "cmd /c " else "" val commandString = cmd + commandContent println("=========================") println("Executing command named: $commandName") println("Command string:") println(commandString) val err = ByteArrayOutputStream() val out = ByteArrayOutputStream() val process = ProcessExecutor() .readOutput(true) .redirectOutput(out) .redirectError(err) .timeout(120, TimeUnit.SECONDS) print("executing...") val result = process.commandSplit(commandString).execute() println(" DONE") println("return code: ${result.exitValue}") val stderrContent = err.toString(Charsets.UTF_8.toString()) val stdoutContent = out.toString(Charsets.UTF_8.toString()) if (stderrContent != "") { println("----------------- stderr:") println(stderrContent) println("----------------- /stderr") } else println("stderr is empty") if (stdoutContent != "") { if (result.exitValue == 0) println("stdout is ${stdoutContent.length} chars long") else { println("----------------- stdout:") println(stdoutContent) println("----------------- /stderr") } } else println("stdout is empty") println("=========================") return result.exitValue }
gpl-3.0
8648f4b899b6fc0457104074c3e01b3c
39.097561
125
0.741901
3.644678
false
false
false
false
MaibornWolff/codecharta
analysis/import/MetricGardenerImporter/src/test/resources/MetricGardenerRawFile.kt
1
1199
package de.maibornwolff.codecharta.importer.metricgardenerimporter.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import de.maibornwolff.codecharta.model.Path @JsonIgnoreProperties("types") class MetricGardenerRawFile( @JsonProperty("name") var name: String?, @JsonProperty("type") var type: String?, @JsonProperty("metrics") var metrics: Map<String, Any> ) { fun getPathWithoutFileName(): Path { if (!name.isNullOrBlank()) { return Path(name!!.split("\\").dropLast(1)) } return Path(emptyList()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MetricGardenerRawFile if (name != other.name) return false if (type != other.type) return false if (metrics != other.metrics) return false return true } override fun hashCode(): Int { var result = name?.hashCode() ?: 0 result = 31 * result + (type?.hashCode() ?: 0) result = 31 * result + metrics.hashCode() return result } }
bsd-3-clause
6aec248e359a5044aeaf8145b4ff3da4
28.975
72
0.646372
4.541667
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/utils/OCRCommand.kt
1
2291
package net.perfectdreams.loritta.morenitta.commands.vanilla.utils import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.jsonArray import com.github.salomonbrys.kotson.jsonObject import com.github.salomonbrys.kotson.string import com.google.gson.JsonParser import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.gson import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import net.dv8tion.jda.api.EmbedBuilder import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import java.io.ByteArrayOutputStream import java.util.* import javax.imageio.ImageIO import net.perfectdreams.loritta.morenitta.LorittaBot class OCRCommand(loritta: LorittaBot) : AbstractCommand(loritta, "ocr", listOf("ler", "read"), net.perfectdreams.loritta.common.commands.CommandCategory.UTILS) { override fun getDescriptionKey() = LocaleKeyData("commands.command.ocr.description") override suspend fun run(context: CommandContext,locale: BaseLocale) { val contextImage = context.getImageAt(0, createTextAsImageIfNotFound = false) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } ByteArrayOutputStream().use { ImageIO.write(contextImage, "png", it) val json = jsonObject( "requests" to jsonArray( jsonObject( "features" to jsonArray( jsonObject( "maxResults" to 1, "type" to "TEXT_DETECTION" ) ), "image" to jsonObject( "content" to Base64.getEncoder().encodeToString(it.toByteArray()) ) ) ) ) val responses = loritta.googleVisionOCRClient.ocr(it.toByteArray()) val builder = EmbedBuilder() builder.setTitle("\uD83D\uDCDD\uD83D\uDD0D OCR") try { builder.setDescription("```${responses.responses.first().textAnnotations!!.first().description}```") } catch (e: Exception) { builder.setDescription("**${locale["commands.command.ocr.couldntFind"]}**") } context.sendMessage(context.getAsMention(true), builder.build()) } } }
agpl-3.0
e3b031573d760cc3b3c87e76907e080e
36.57377
161
0.744653
3.984348
false
false
false
false
r-artworks/game-seed
core/src/com/rartworks/engine/collisions/CollisionInfo.kt
1
876
package com.rartworks.engine.collisions /** * Contains a [shape] and info container for collision filtering. */ class CollisionInfo(val shape: CollisionShape, private val id: Int, vararg private val collidesWith: Int) { val categoryBits: Short get() = this.id.toShort() val maskBits: Short init { val others = this.collidesWith.toList() this.maskBits = others.fold(0) { prev, elem -> prev.or(elem) }.toShort() } /** * Sets the [maskBits] to the body. */ fun enable() { this.setMaskBits(this.maskBits) } /** * Clear the body's maskBits to disable collisions. */ fun disable() { this.setMaskBits(0) } /** * Sets the [maskBits] to the body. */ private fun setMaskBits(maskBits: Short) { this.shape.body.fixtureList.forEach { val filterData = it.filterData filterData.maskBits = maskBits it.filterData = filterData } } }
mit
19581a9e62af3f925465a2fe5a44b6c4
19.857143
107
0.679224
3.095406
false
false
false
false
seventhmoon/GeoIp-android
app/src/main/java/com/androidfung/geoip/MainActivity.kt
1
1902
package com.androidfung.geoip import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.databinding.DataBindingUtil import com.androidfung.geoip.ServicesManager.geoIpService import com.androidfung.geoip.databinding.ActivityMainBinding import com.androidfung.geoip.model.GeoIpResponseModel import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val ipApiService = geoIpService ipApiService.getGeoIp().enqueue(object : Callback<GeoIpResponseModel> { override fun onResponse(call: Call<GeoIpResponseModel>, response: Response<GeoIpResponseModel>) { binding.response = response.body() Log.d(TAG, response.toString()) response.body()?.let { Log.d(TAG, it.toString()) // Log.d(TAG, it.body().toString()) if (it.isError) { showError(it.reason) Log.e(TAG, it.reason.toString()) } } } override fun onFailure(call: Call<GeoIpResponseModel>, t: Throwable) { showError(t.toString()) Log.e(TAG, t.toString()) } }) } private fun showError(message: String?) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } companion object { private val TAG = MainActivity::class.java.simpleName } }
mit
d407d3775d87dd89945064094c339746
35.596154
109
0.646688
4.719603
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/date/timestampTest.kt
2
3916
package com.sksamuel.kotest.matchers.date import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.date.shouldBeAfter import io.kotest.matchers.date.shouldBeBefore import io.kotest.matchers.date.shouldBeBetween import io.kotest.matchers.date.shouldNotBeAfter import io.kotest.matchers.date.shouldNotBeBefore import io.kotest.matchers.date.shouldNotBeBetween import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import java.sql.Timestamp import java.time.Instant class TimeStampTest : FreeSpec() { init { "two timestamp of same instance should be same" { val nowInstance = Instant.now() Timestamp.from(nowInstance) shouldBe Timestamp.from(nowInstance) } "two timestamp of different instance should be not be same" { val nowInstance = Instant.now() val anotherInstance = nowInstance.plusMillis(1000L) Timestamp.from(nowInstance) shouldNotBe Timestamp.from(anotherInstance) } "timestamp of current instance should be after the timestamp of past instance" { val nowInstance = Instant.now() val instanceBeforeFiveSecond = nowInstance.minusMillis(5000L) Timestamp.from(nowInstance) shouldBeAfter Timestamp.from(instanceBeforeFiveSecond) } "timestamp of current instance should not be after the timestamp of future instance" { val nowInstance = Instant.now() val instanceAfterFiveSecond = nowInstance.plusMillis(5000L) Timestamp.from(nowInstance) shouldNotBeAfter Timestamp.from(instanceAfterFiveSecond) } "timestamp of current instance should not be after the another timestamp of same instance" { val nowInstance = Instant.now() Timestamp.from(nowInstance) shouldNotBeAfter Timestamp.from(nowInstance) } "timestamp of current instance should be before the timestamp of future instance" { val nowInstance = Instant.now() val instanceAfterFiveSecond = nowInstance.plusMillis(5000L) Timestamp.from(nowInstance) shouldBeBefore Timestamp.from(instanceAfterFiveSecond) } "timestamp of current instance should not be before the timestamp of past instance" { val nowInstance = Instant.now() val instanceBeforeFiveSecond = nowInstance.minusMillis(5000L) Timestamp.from(nowInstance) shouldNotBeBefore Timestamp.from(instanceBeforeFiveSecond) } "timestamp of current instance should not be before the another timestamp of same instance" { val nowInstance = Instant.now() Timestamp.from(nowInstance) shouldNotBeBefore Timestamp.from(nowInstance) } "current timestamp should be between timestamp of past and future" { val nowInstant = Instant.now() val currentTimestamp = Timestamp.from(nowInstant) val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000)) val futureTimestamp = Timestamp.from(nowInstant.plusMillis(5000)) currentTimestamp.shouldBeBetween(pastTimestamp, futureTimestamp) } "past timestamp should not be between timestamp of current instant and future" { val nowInstant = Instant.now() val currentTimestamp = Timestamp.from(nowInstant) val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000)) val futureTimestamp = Timestamp.from(nowInstant.plusMillis(5000)) pastTimestamp.shouldNotBeBetween(currentTimestamp, futureTimestamp) } "future timestamp should not be between timestamp of current instant and future" { val nowInstant = Instant.now() val currentTimestamp = Timestamp.from(nowInstant) val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000)) val futureTimestamp = Timestamp.from(nowInstant.plusMillis(5000)) futureTimestamp.shouldNotBeBetween(pastTimestamp, currentTimestamp) } } }
apache-2.0
63574e36de918fafbc6740529b0c3807
44.534884
99
0.72906
4.82266
false
true
false
false
kotlintest/kotlintest
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/doubles.kt
1
1539
package io.kotest.property.arbitrary import io.kotest.property.Shrinker import kotlin.math.abs import kotlin.math.round /** * Returns an [Arb] where each value is a randomly chosen Double. */ fun Arb.Companion.double(): Arb<Double> { val edgecases = listOf( 0.0, 1.0, -1.0, 1e300, Double.MIN_VALUE, Double.MAX_VALUE, Double.NEGATIVE_INFINITY, Double.NaN, Double.POSITIVE_INFINITY ) return arb(DoubleShrinker, edgecases) { it.random.nextDouble() } } /** * Returns an [Arb] which is the same as [double] but does not include +INFINITY, -INFINITY or NaN. * * This will only generate numbers ranging from [from] (inclusive) to [to] (inclusive) */ fun Arb.Companion.numericDoubles( from: Double = Double.MIN_VALUE, to: Double = Double.MAX_VALUE ): Arb<Double> { val edgecases = listOf(0.0, 1.0, -1.0, 1e300, Double.MIN_VALUE, Double.MAX_VALUE).filter { it in (from..to) } return arb(DoubleShrinker, edgecases) { it.random.nextDouble(from, to) } } fun Arb.Companion.positiveDoubles(): Arb<Double> = double().filter { it > 0.0 } fun Arb.Companion.negativeDoubles(): Arb<Double> = double().filter { it < 0.0 } object DoubleShrinker : Shrinker<Double> { override fun shrink(value: Double): List<Double> { return if (value == 0.0) emptyList() else { val a = listOf(0.0, 1.0, -1.0, abs(value), value / 3, value / 2) val b = (1..5).map { value - it }.reversed().filter { it > 0 } (a + b + round(value)).distinct() } } }
apache-2.0
077a7be2fd8035c0affe138232305090
30.408163
112
0.642625
3.288462
false
false
false
false
mcxiaoke/kotlin-koi
core/src/main/kotlin/com/mcxiaoke/koi/ext/String.kt
1
5839
package com.mcxiaoke.koi.ext import com.mcxiaoke.koi.Const import com.mcxiaoke.koi.Encoding import java.io.File import java.io.UnsupportedEncodingException import java.math.BigInteger import java.net.URLDecoder import java.util.* /** * User: mcxiaoke * Date: 16/1/22 * Time: 13:35 */ fun String.quote(): String { return "'$this'" } fun CharSequence.isBlank(): Boolean { val len: Int = this.length if (len == 0) { return true } forEach { c -> if (!Character.isWhitespace(c)) { return false } } return true } fun String.toHexBytes(): ByteArray { val len = this.length val data = ByteArray(len / 2) var i = 0 while (i < len) { data[i / 2] = ((Character.digit(this[i], 16) shl 4) + Character.digit(this[i + 1], 16)).toByte() i += 2 } return data } fun String.withoutQuery(): String { return this.split("\\?".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] } fun String?.isNameSafe(): Boolean { // Note, we check whether it matches what's known to be safe, // rather than what's known to be unsafe. Non-ASCII, control // characters, etc. are all unsafe by default. if (this == null) { return false } return Const.SAFE_FILENAME_PATTERN.matcher(this).matches() } fun String.toSafeFileName(): String { val size = this.length val builder = StringBuilder(size * 2) forEachIndexed { i, c -> var valid = c in 'a'..'z' valid = valid || c in 'A'..'Z' valid = valid || c in '0'..'9' valid = valid || c == '_' || c == '-' || c == '.' if (valid) { builder.append(c) } else { // Encode the character using hex notation builder.append('x') builder.append(Integer.toHexString(i)) } } return builder.toString() } fun String.toQueries(): Map<String, String> { val map: Map<String, String> = mapOf() if (this.isEmpty()) { return map } try { val queries = HashMap<String, String>() for (param in this.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) { val pair = param.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val key = URLDecoder.decode(pair[0], Encoding.UTF_8) if (pair.size > 1) { val value = URLDecoder.decode(pair[1], Encoding.UTF_8) queries.put(key, value) } } return queries } catch (ex: UnsupportedEncodingException) { throw RuntimeException(ex) } } @JvmOverloads fun String.toStringList(delimiters: String = "?", trimTokens: Boolean = true, ignoreEmptyTokens: Boolean = true): List<String> { val st = StringTokenizer(this, delimiters) val tokens = ArrayList<String>() while (st.hasMoreTokens()) { var token = st.nextToken() if (trimTokens) { token = token.trim { it <= ' ' } } if (!ignoreEmptyTokens || token.isNotEmpty()) { tokens.add(token) } } return tokens } @JvmOverloads fun String.toStringArray(delimiters: String = "?", trimTokens: Boolean = true, ignoreEmptyTokens: Boolean = true): Array<String> { return toStringList(delimiters, trimTokens, ignoreEmptyTokens).toTypedArray() } fun String.trimLeadingCharacter(leadingCharacter: Char): String { if (this.isEmpty()) { return this } val sb = StringBuilder(this) while (sb.isNotEmpty() && sb[0] == leadingCharacter) { sb.deleteCharAt(0) } return sb.toString() } fun String.trimTrailingCharacter(trailingCharacter: Char): String { if (this.isEmpty()) { return this } val sb = StringBuilder(this) while (sb.isNotEmpty() && sb[sb.length - 1] == trailingCharacter) { sb.deleteCharAt(sb.length - 1) } return sb.toString() } fun String.trimAllWhitespace(): String { if (this.isEmpty()) { return this } val sb = StringBuilder(this) var index = 0 while (sb.length > index) { if (Character.isWhitespace(sb[index])) { sb.deleteCharAt(index) } else { index++ } } return sb.toString() } fun CharSequence.containsWhitespace(): Boolean { if (this.isEmpty()) { return false } forEach { c -> if (Character.isWhitespace(c)) { return true } } return false } fun String.fileNameWithoutExtension(): String { if (isEmpty()) { return this } var filePath = this val extenPosi = filePath.lastIndexOf(Const.FILE_EXTENSION_SEPARATOR) val filePosi = filePath.lastIndexOf(File.separator) if (filePosi == -1) { return if (extenPosi == -1) filePath else filePath.substring(0, extenPosi) } if (extenPosi == -1) { return filePath.substring(filePosi + 1) } return if (filePosi < extenPosi) filePath.substring(filePosi + 1, extenPosi) else filePath.substring(filePosi + 1) } fun String.fileName(): String { if (isEmpty()) { return this } var filePath = this val filePosi = filePath.lastIndexOf(File.separator) return if (filePosi == -1) filePath else filePath.substring(filePosi + 1) } fun String.fileExtension(): String { if (isEmpty()) { return this } var filePath = this val extenPosi = filePath.lastIndexOf(Const.FILE_EXTENSION_SEPARATOR) val filePosi = filePath.lastIndexOf(File.separator) if (extenPosi == -1) { return "" } return if (filePosi >= extenPosi) "" else filePath.substring(extenPosi + 1) }
apache-2.0
31cac6c249473fb55a75addd044b9dc2
26.032407
96
0.58075
3.939946
false
false
false
false
FurhatRobotics/example-skills
JokeBot/src/main/kotlin/furhatos/app/jokebot/flow/main/jokeSequence.kt
1
3481
package furhatos.app.jokebot.flow.main import furhatos.app.jokebot.flow.Parent import furhatos.app.jokebot.jokes.* import furhatos.app.jokebot.nlu.BadJoke import furhatos.app.jokebot.nlu.GoodJoke import furhatos.app.jokebot.util.calculateJokeScore import furhatos.flow.kotlin.* import furhatos.nlu.common.No import furhatos.nlu.common.Yes import furhatos.skills.emotions.UserGestures /** * This state gets jokes, tells jokes, and records the user's response to it. * * Once the joke has been told, prompts the user if they want to hear another joke. */ val JokeSequence: State = state(Parent) { onEntry { //Get joke from the JokeHandler val joke = JokeHandler.getJoke() //Build an utterance with the joke. val utterance = utterance { +getJokeComment(joke.score) //Get comment on joke, using the score +delay(200) //Short delay +joke.intro //Deliver the intro of the joke +delay(1500) //Always let the intro sink in +joke.punchline //Deliver the punchline of the joke. } furhat.say(utterance) /** * Calls a state which we know returns a joke score. */ JokeHandler.changeJokeScore(call(JokeScore) as Double) //Prompt the user if they want to hear another joke. furhat.ask(continuePrompt.random()) } onResponse<Yes> { furhat.say("Sweet!") reentry() } onResponse<No> { furhat.say("Alright, thanks for letting me practice!") if (users.count > 1) { furhat.attend(users.other) furhat.ask("How about you? do you want some jokes?") } else { goto(Idle) } } onResponse { furhat.ask("Yes or no?") } onNoResponse { furhat.ask("I didn't hear you.") } } /** * This state records the users reaction to a joke, and terminates with calculated joke value. * Joke value is based on if the user smiled and/or the user said it was a good/bad joke. */ val JokeScore: State = state(Parent) { var saidBadJoke = false var saidGoodJoke = false var timeSmiledAtJoke = 0L var timestampStartedLaughing = 0L val jokeTimeout = 4000 // We wait for a reaction for 4 seconds onEntry { furhat.listen() } onResponse<GoodJoke>(instant = true) { saidGoodJoke = true } onResponse<BadJoke>(instant = true) { saidBadJoke = true } onResponse(instant = true) { //Do nothing } onNoResponse(instant = true) { //Do nothing } onUserGesture(UserGestures.Smile, cond = { it.isCurrentUser }, instant = true) { timestampStartedLaughing = System.currentTimeMillis() //Timestamp the moment the user started smiling. propagate() } onUserGestureEnd(UserGestures.Smile, cond = { it.isCurrentUser }, instant = true) { timeSmiledAtJoke += System.currentTimeMillis() - timestampStartedLaughing //Calculating the amount of millis spent laughing timestampStartedLaughing = 0L propagate() } onTime(delay = jokeTimeout) { if (timestampStartedLaughing != 0L) { timeSmiledAtJoke += System.currentTimeMillis() - timestampStartedLaughing } furhat.say(getResponseOnUser(timeSmiledAtJoke != 0L, saidBadJoke, saidGoodJoke)) terminate(calculateJokeScore(timeSmiledAtJoke, jokeTimeout, saidBadJoke, saidGoodJoke)) } }
mit
4a7f4de12f3e87ffdc3f46bf2cccc1c0
28.008333
131
0.647228
3.889385
false
false
false
false
maskaravivek/apps-android-commons
app/src/main/java/fr/free/nrw/commons/customselector/ui/selector/CustomSelectorActivity.kt
3
7150
package fr.free.nrw.commons.customselector.ui.selector import android.app.Activity import android.app.Dialog import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.view.View import android.view.Window import android.widget.Button import android.widget.ImageButton import android.widget.TextView import androidx.lifecycle.ViewModelProvider import fr.free.nrw.commons.R import fr.free.nrw.commons.customselector.listeners.FolderClickListener import fr.free.nrw.commons.customselector.listeners.ImageSelectListener import fr.free.nrw.commons.customselector.model.Image import fr.free.nrw.commons.media.ZoomableActivity import fr.free.nrw.commons.theme.BaseActivity import java.io.File import javax.inject.Inject /** * Custom Selector Activity. */ class CustomSelectorActivity: BaseActivity(), FolderClickListener, ImageSelectListener { /** * View model. */ private lateinit var viewModel: CustomSelectorViewModel /** * isImageFragmentOpen is true when the image fragment is in view. */ private var isImageFragmentOpen = false /** * Current ImageFragment attributes. */ private var bucketId: Long = 0L private lateinit var bucketName: String /** * Pref for saving selector state. */ private lateinit var prefs: SharedPreferences /** * View Model Factory. */ @Inject lateinit var customSelectorViewModelFactory: CustomSelectorViewModelFactory /** * onCreate Activity, sets theme, initialises the view model, setup view. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_custom_selector) prefs = applicationContext.getSharedPreferences("CustomSelector", MODE_PRIVATE) viewModel = ViewModelProvider(this, customSelectorViewModelFactory).get( CustomSelectorViewModel::class.java ) setupViews() if(prefs.getBoolean("customSelectorFirstLaunch", true)) { // show welcome dialog on first launch showWelcomeDialog() prefs.edit().putBoolean("customSelectorFirstLaunch", false).apply() } // Open folder if saved in prefs. if(prefs.contains(FOLDER_ID)){ val lastOpenFolderId: Long = prefs.getLong(FOLDER_ID, 0L) val lastOpenFolderName: String? = prefs.getString(FOLDER_NAME, null) val lastItemId: Long = prefs.getLong(ITEM_ID, 0) lastOpenFolderName?.let { onFolderClick(lastOpenFolderId, it, lastItemId) } } } /** * Show Custom Selector Welcome Dialog. */ private fun showWelcomeDialog() { val dialog = Dialog(this) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setContentView(R.layout.custom_selector_info_dialog) (dialog.findViewById(R.id.btn_ok) as Button).setOnClickListener { dialog.dismiss() } dialog.show() } /** * Set up view, default folder view. */ private fun setupViews() { supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, FolderFragment.newInstance()) .commit() fetchData() setUpToolbar() } /** * Start data fetch in view model. */ private fun fetchData() { viewModel.fetchImages() } /** * Change the title of the toolbar. */ private fun changeTitle(title: String) { val titleText = findViewById<TextView>(R.id.title) if(titleText != null) { titleText.text = title } } /** * Set up the toolbar, back listener, done listener. */ private fun setUpToolbar() { val back : ImageButton = findViewById(R.id.back) back.setOnClickListener { onBackPressed() } val done : ImageButton = findViewById(R.id.done) done.setOnClickListener { onDone() } } /** * override on folder click, change the toolbar title on folder click. */ override fun onFolderClick(folderId: Long, folderName: String, lastItemId: Long) { supportFragmentManager.beginTransaction() .add(R.id.fragment_container, ImageFragment.newInstance(folderId, lastItemId)) .addToBackStack(null) .commit() changeTitle(folderName) bucketId = folderId bucketName = folderName isImageFragmentOpen = true } /** * override Selected Images Change, update view model selected images. */ override fun onSelectedImagesChanged(selectedImages: ArrayList<Image>) { viewModel.selectedImages.value = selectedImages val done : ImageButton = findViewById(R.id.done) done.visibility = if (selectedImages.isEmpty()) View.INVISIBLE else View.VISIBLE } /** * onLongPress * @param imageUri : uri of image */ override fun onLongPress(imageUri: Uri) { val intent = Intent(this, ZoomableActivity::class.java).setData(imageUri); startActivity(intent) } /** * OnDone clicked. * Get the selected images. Remove any non existent file, forward the data to finish selector. */ fun onDone() { val selectedImages = viewModel.selectedImages.value if(selectedImages.isNullOrEmpty()) { finishPickImages(arrayListOf()) return } var i = 0 while (i < selectedImages.size) { val path = selectedImages[i].path val file = File(path) if (!file.exists()) { selectedImages.removeAt(i) i-- } i++ } finishPickImages(selectedImages) } /** * finishPickImages, Load the data to the intent and set result. * Finish the activity. */ private fun finishPickImages(images: ArrayList<Image>) { val data = Intent() data.putParcelableArrayListExtra("Images", images) setResult(Activity.RESULT_OK, data) finish() } /** * Back pressed. * Change toolbar title. */ override fun onBackPressed() { super.onBackPressed() val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container) if(fragment != null && fragment is FolderFragment){ isImageFragmentOpen = false changeTitle(getString(R.string.custom_selector_title)) } } /** * On activity destroy * If image fragment is open, overwrite its attributes otherwise discard the values. */ override fun onDestroy() { if(isImageFragmentOpen){ prefs.edit().putLong(FOLDER_ID, bucketId).putString(FOLDER_NAME, bucketName).apply() } else { prefs.edit().remove(FOLDER_ID).remove(FOLDER_NAME).apply() } super.onDestroy() } companion object { const val FOLDER_ID : String = "FolderId" const val FOLDER_NAME : String = "FolderName" const val ITEM_ID : String = "ItemId" } }
apache-2.0
d4e1e257d737df3f7334dc6a7815316d
29.429787
98
0.643776
4.722589
false
false
false
false
DUCodeWars/TournamentFramework
src/main/java/org/DUCodeWars/framework/server/net/packets/notifications/packets/IdPacket.kt
2
1293
package org.DUCodeWars.framework.server.net.packets.notifications.packets import com.google.gson.JsonObject import org.DUCodeWars.framework.server.net.packets.JsonSerialiser import org.DUCodeWars.framework.server.net.packets.notifications.NotificationPacketSer import org.DUCodeWars.framework.server.net.packets.notifications.NotificationRequest private val action = "id" class IdPS : NotificationPacketSer<IdRequest>(action) { override val reqSer = IdReqSer() } class IdRequest(val id: Int) : NotificationRequest(action) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as IdRequest if (id != other.id) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + id return result } } class IdReqSer() : JsonSerialiser<IdRequest>() { override fun ser(packet: IdRequest): JsonObject { val json = JsonObject() json.addProperty("id", packet.id) return json } override fun deserialise(json: JsonObject): IdRequest { val id = json["id"].asInt return IdRequest(id) } }
mit
7f3f535f1ba5620af551b8e413569286
27.755556
86
0.683681
4.211726
false
false
false
false
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/utils/DefaultOption.kt
1
631
package net.pterodactylus.sone.utils /** * Basic implementation of an [Option]. * * @param <T> The type of the option */ class DefaultOption<T> @JvmOverloads constructor( private val defaultValue: T, private val validator: ((T) -> Boolean)? = null ) : Option<T> { @Volatile private var value: T? = null override fun get() = value ?: defaultValue override fun getReal(): T? = value override fun validate(value: T?): Boolean = value == null || validator?.invoke(value) ?: true override fun set(value: T?) { require(validate(value)) { "New Value ($value) could not be validated." } this.value = value } }
gpl-3.0
40700f2d104a2fb57a47e626878b30bf
21.535714
75
0.66878
3.448087
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/gui/AutoGui.kt
2
5218
package com.cout970.magneticraft.systems.gui import com.cout970.magneticraft.IVector2 import com.cout970.magneticraft.misc.gui.SlotType import com.cout970.magneticraft.misc.gui.TypedSlot import com.cout970.magneticraft.misc.guiTexture import com.cout970.magneticraft.misc.vector.vec2Of import com.cout970.magneticraft.systems.gui.render.DrawableBox import net.minecraft.client.Minecraft import net.minecraft.client.gui.ScaledResolution import net.minecraft.inventory.Slot class AutoGui(override val container: AutoContainer) : GuiBase(container) { lateinit var background: List<DrawableBox> lateinit var slots: List<DrawableBox> var oldGuiScale = 0 override fun initGui() { val config = container.builder.config this.xSize = config.background.xi this.ySize = config.background.yi super.initGui() this.slots = createSlots(container.inventorySlots) this.background = if (config.top) { createRectWithBorders(pos, size) } else { createRectWithBorders(pos + vec2Of(0, 76), size - vec2Of(0, 76)) } } override fun setWorldAndResolution(mc: Minecraft, width: Int, height: Int) { val size = container.builder.config.background oldGuiScale = mc.gameSettings.guiScale if (width < size.xi || height < size.yi) { mc.gameSettings.guiScale = 3 val sr = ScaledResolution(mc) super.setWorldAndResolution(mc, sr.scaledWidth, sr.scaledHeight) return } super.setWorldAndResolution(mc, width, height) } override fun onGuiClosed() { super.onGuiClosed() mc.gameSettings.guiScale = oldGuiScale } override fun initComponents() { container.builder.build(this, container) } override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) { bindTexture(guiTexture("misc")) background.forEach { it.draw() } super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY) bindTexture(guiTexture("misc")) slots.forEach { it.draw() } } fun createRectWithBorders(pPos: IVector2, pSize: IVector2): List<DrawableBox> { val leftUp = DrawableBox( screenPos = pPos, screenSize = vec2Of(4), texturePos = vec2Of(0), textureSize = vec2Of(4) ) val leftDown = DrawableBox( screenPos = pPos + vec2Of(0, pSize.yi - 4), screenSize = vec2Of(4), texturePos = vec2Of(0, 5), textureSize = vec2Of(4) ) val rightUp = DrawableBox( screenPos = pPos + vec2Of(pSize.xi - 4, 0), screenSize = vec2Of(4), texturePos = vec2Of(5, 0), textureSize = vec2Of(4) ) val rightDown = DrawableBox( screenPos = pPos + vec2Of(pSize.xi - 4, pSize.yi - 4), screenSize = vec2Of(4), texturePos = vec2Of(5, 5), textureSize = vec2Of(4) ) val left = DrawableBox( screenPos = pPos + vec2Of(0, 4), screenSize = vec2Of(4, pSize.y - 8), texturePos = vec2Of(0, 10), textureSize = vec2Of(4, 1) ) val right = DrawableBox( screenPos = pPos + vec2Of(pSize.xi - 4, 4), screenSize = vec2Of(4, pSize.yi - 8), texturePos = vec2Of(5, 10), textureSize = vec2Of(4, 1) ) val up = DrawableBox( screenPos = pPos + vec2Of(4, 0), screenSize = vec2Of(pSize.xi - 8, 4), texturePos = vec2Of(10, 0), textureSize = vec2Of(1, 4) ) val down = DrawableBox( screenPos = pPos + vec2Of(4, pSize.yi - 4), screenSize = vec2Of(pSize.xi - 8, 4), texturePos = vec2Of(10, 5), textureSize = vec2Of(1, 4) ) val center = DrawableBox( screenPos = pPos + vec2Of(4, 4), screenSize = vec2Of(pSize.xi - 8, pSize.yi - 8), texturePos = vec2Of(5, 3), textureSize = vec2Of(1, 1) ) return listOf( leftUp, leftDown, rightUp, rightDown, left, right, up, down, center ) } fun createSlots(slots: List<Slot>): List<DrawableBox> { val boxes = mutableListOf<DrawableBox>() slots.forEach { slot -> val x = guiLeft + slot.xPos - 1 val y = guiTop + slot.yPos - 1 val type = (slot as? TypedSlot)?.type ?: SlotType.NORMAL val icon = when (type) { SlotType.INPUT -> vec2Of(55, 81) SlotType.OUTPUT -> vec2Of(36, 81) SlotType.FILTER -> vec2Of(74, 81) SlotType.NORMAL -> vec2Of(36, 100) SlotType.BUTTON -> vec2Of(74, 100) SlotType.FLOPPY -> vec2Of(144, 69) SlotType.BATTERY -> vec2Of(144, 87) } boxes += DrawableBox( screenPos = vec2Of(x, y), screenSize = vec2Of(18), texturePos = icon ) } return boxes } }
gpl-2.0
bc009b4048a0a0092422c92d47dc8b1a
31.416149
97
0.568225
3.831131
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/telemetry/startuptelemetry/StartupPathProvider.kt
1
4203
/* 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.telemetry.startuptelemetry import android.app.Activity import android.content.Intent import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting.Companion.NONE import androidx.annotation.VisibleForTesting.Companion.PRIVATE import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner /** * This should be a member variable of [Activity] because its data is tied to the lifecycle of an * Activity. Call [attachOnActivityOnCreate] & [onIntentReceived] for this class to work correctly. */ class StartupPathProvider { enum class StartupPath { MAIN, VIEW, /** * The start up path if we received an Intent but we're unable to categorize it into other buckets. */ UNKNOWN, /** * The start up path has not been set. This state includes: * - this API is accessed before it is set * - if no intent is received before the activity is STARTED (e.g. app switcher) */ NOT_SET, } /** * Returns the [StartupPath] for the currently started activity. This value will be set * after an [Intent] is received that causes this activity to move into the STARTED state. */ var startupPathForActivity = StartupPath.NOT_SET private set private var wasResumedSinceStartedState = false fun attachOnActivityOnCreate(lifecycle: Lifecycle, intent: Intent?) { lifecycle.addObserver(StartupPathLifecycleObserver()) onIntentReceived(intent) } // N.B.: this method duplicates the actual logic for determining what page to open. // Unfortunately, it's difficult to re-use that logic because it occurs in many places throughout // the code so we do the simple thing for now and duplicate it. It's noticeably different from // what you might expect: e.g. ACTION_MAIN can open a URL and if ACTION_VIEW provides an invalid // URL, it'll perform a MAIN action. However, it's fairly representative of what users *intended* // to do when opening the app and shouldn't change much because it's based on Android system-wide // conventions, so it's probably fine for our purposes. private fun getStartupPathFromIntent(intent: Intent): StartupPath = when (intent.action) { Intent.ACTION_MAIN -> StartupPath.MAIN Intent.ACTION_VIEW -> StartupPath.VIEW else -> StartupPath.UNKNOWN } /** * Expected to be called when a new [Intent] is received by the [Activity]: i.e. * [Activity.onCreate] and [Activity.onNewIntent]. */ fun onIntentReceived(intent: Intent?) { // We want to set a path only if the intent causes the Activity to move into the STARTED state. // This means we want to discard any intents that are received when the app is foregrounded. // However, we can't use the Lifecycle.currentState to determine this because: // - the app is briefly paused (state becomes STARTED) before receiving the Intent in // the foreground so we can't say <= STARTED // - onIntentReceived can be called from the CREATED or STARTED state so we can't say == CREATED // So we're forced to track this state ourselves. if (!wasResumedSinceStartedState && intent != null) { startupPathForActivity = getStartupPathFromIntent(intent) } } @VisibleForTesting(otherwise = NONE) fun getTestCallbacks() = StartupPathLifecycleObserver() @VisibleForTesting(otherwise = PRIVATE) inner class StartupPathLifecycleObserver : DefaultLifecycleObserver { override fun onResume(owner: LifecycleOwner) { wasResumedSinceStartedState = true } override fun onStop(owner: LifecycleOwner) { // Clear existing state. startupPathForActivity = StartupPath.NOT_SET wasResumedSinceStartedState = false } } }
mpl-2.0
09d49802595224f7a2320de3ac81872a
41.887755
107
0.698073
4.706607
false
true
false
false
stephanenicolas/toothpick
toothpick-runtime/src/test/kotlin/toothpick/inject/lazy/KInjectionOfLazyProviderTest.kt
1
2926
/* * Copyright 2019 Stephane Nicolas * Copyright 2019 Daniel Molinero Reguera * * 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 toothpick.inject.lazy import org.hamcrest.CoreMatchers.isA import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.CoreMatchers.sameInstance import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import toothpick.Lazy import toothpick.ScopeImpl import toothpick.Toothpick import toothpick.config.Module import toothpick.data.KBar import toothpick.data.KFooWithLazy import toothpick.data.KFooWithNamedLazy /* * Test injection of {@code Lazy}s. */ class KInjectionOfLazyProviderTest { @Test @Throws(Exception::class) fun testSimpleInjection() { // GIVEN val scope = ScopeImpl("") val fooWithLazy = KFooWithLazy() // WHEN Toothpick.inject(fooWithLazy, scope) // THEN assertThat(fooWithLazy.bar, notNullValue()) assertThat(fooWithLazy.bar, isA(Lazy::class.java)) val bar1 = fooWithLazy.bar.get() assertThat(bar1, isA(KBar::class.java)) val bar2 = fooWithLazy.bar.get() assertThat(bar2, isA(KBar::class.java)) assertThat(bar2, sameInstance(bar1)) } @Test @Throws(Exception::class) fun testNamedInjection() { // GIVEN val scope = ScopeImpl("") scope.installModules(object : Module() { init { bind(KBar::class.java).withName("foo").to(KBar::class.java) } }) val fooWithLazy = KFooWithNamedLazy() // WHEN Toothpick.inject(fooWithLazy, scope) // THEN assertThat(fooWithLazy.bar, notNullValue()) assertThat(fooWithLazy.bar, isA(Lazy::class.java)) val bar1 = fooWithLazy.bar.get() assertThat(bar1, isA(KBar::class.java)) val bar2 = fooWithLazy.bar.get() assertThat(bar2, isA(KBar::class.java)) assertThat(bar2, sameInstance(bar1)) } @Test(expected = IllegalStateException::class) @Throws(Exception::class) fun testLazyAfterClosingScope() { // GIVEN val scopeName = "" val fooWithLazy = KFooWithLazy() // WHEN Toothpick.inject(fooWithLazy, Toothpick.openScope(scopeName)) Toothpick.closeScope(scopeName) System.gc() // THEN fooWithLazy.bar.get() // should crash } }
apache-2.0
4fe964ac695eb7708b0a8a29dd445c27
29.164948
75
0.665414
4.041436
false
true
false
false
wireapp/wire-android
common-test/src/main/kotlin/com/waz/zclient/framework/data/users/UsersTestDataProvider.kt
1
2145
package com.waz.zclient.framework.data.users import com.waz.zclient.framework.data.TestDataProvider import java.util.UUID data class UsersTestData( val id: String, val domain: String, val teamId: String, val name: String, val email: String, val phone: String, val trackingId: String, val picture: String, val accentId: Int, val sKey: String, val connection: String, val connectionTimestamp: Long, val connectionMessage: String, val conversation: String, val conversationDomain: String, val relation: String, val timestamp: Long, val verified: String, val deleted: Boolean, val availability: Int, val handle: String, val providerId: String, val integrationId: String, val expiresAt: Long, val managedBy: String, val selfPermission: Int, val copyPermission: Int, val createdBy: String ) object UsersTestDataProvider : TestDataProvider<UsersTestData>() { override fun provideDummyTestData(): UsersTestData = UsersTestData( id = UUID.randomUUID().toString(), domain = "staging.zinfra.io", teamId = UUID.randomUUID().toString(), name = "name", email = "[email protected]", phone = "0123456789", trackingId = UUID.randomUUID().toString(), picture = UUID.randomUUID().toString(), accentId = 0, sKey = "key", connection = "0", connectionTimestamp = 0, connectionMessage = "connectionMessage", conversation = UUID.randomUUID().toString(), conversationDomain = "staging.zinfra.io", relation = "0", timestamp = System.currentTimeMillis(), verified = "", deleted = false, availability = 0, handle = "handle", providerId = UUID.randomUUID().toString(), integrationId = UUID.randomUUID().toString(), expiresAt = 0, managedBy = "", selfPermission = 0, copyPermission = 0, createdBy = "" ) }
gpl-3.0
93440d1fd9c142723b0d6e08330ff499
30.086957
66
0.591608
4.756098
false
true
false
false
wuan/bo-android2
app/src/main/java/org/blitzortung/android/v2/StateFragment.kt
1
2421
/* Blitzortung.org lightning monitor android app Copyright (C) 2012 - 2015 Andreas Würl 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 org.blitzortung.android.v2 import android.app.Fragment import android.os.Bundle import org.blitzortung.android.data.result.Result import org.slf4j.LoggerFactory import rx.schedulers.Schedulers import rx.subjects.BehaviorSubject class StateFragment : Fragment() { interface OnCreateListener { fun onStateCreated(stateFragment: StateFragment) } var resultSubject: BehaviorSubject<Result?>? = null private set private var onCreateListener: OnCreateListener? = null override fun onCreate(savedInstanceState: Bundle?) { LOGGER.info("StateFragment.onCreate()") super.onCreate(savedInstanceState) retainInstance = true resultSubject = BehaviorSubject.create<Result>() resultSubject!!.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.newThread()) } override fun onPause() { LOGGER.info("StateFragment.onPause()") super.onPause() onCreateListener = null } override fun onResume() { LOGGER.info("StateFragment.onResume()") super.onResume() if (onCreateListener != null) { LOGGER.info("StateFragment.onResume() call onCreateListener") onCreateListener!!.onStateCreated(this) } } override fun onDestroy() { LOGGER.debug("StateFragment.onDestroy()") super.onDestroy() resultSubject = null } fun setOnCreateListener(onCreateListener: OnCreateListener) { this.onCreateListener = onCreateListener } companion object { val TAG = StateFragment::class.java.getSimpleName() private val LOGGER = LoggerFactory.getLogger(StateFragment::class.java) } }
gpl-3.0
df65cb88ca6a38da4a77c136f8e9e637
27.139535
93
0.712397
4.689922
false
false
false
false
npryce/result4k
src/main/kotlin/com/natpryce/nullables.kt
1
1057
package com.natpryce /* * Translate between the Result and Nullable/Optional/Maybe monads */ /** * Convert a nullable value to a Result, using the result of [failureDescription] as the failure reason * if the value is null. */ inline fun <T, E> T?.asResultOr(failureDescription: () -> E) = if (this != null) Success(this) else Failure(failureDescription()) /** * Convert a Success of a nullable value to a Success of a non-null value or a Failure, * using the result of [failureDescription] as the failure reason, if the value is null. */ inline fun <T: Any, E> Result<T?,E>.filterNotNull(failureDescription: () -> E) = flatMap { it.asResultOr(failureDescription) } /** * Returns the success value, or null if the Result is a failure. */ fun <T, E> Result<T, E>.valueOrNull() = when (this) { is Success<T> -> value is Failure<E> -> null } /** * Returns the failure reason, or null if the Result is a success. */ fun <T, E> Result<T, E>.failureOrNull() = when (this) { is Success<T> -> null is Failure<E> -> reason }
apache-2.0
93568f5b0a49ea97a04d30ec9ddac1f9
29.2
103
0.672658
3.454248
false
false
false
false
xfournet/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestCase.kt
1
35414
/* * 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 com.intellij.testGuiFramework.impl import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.openapi.util.io.FileUtil import com.intellij.testGuiFramework.cellReader.ExtendedJComboboxCellReader import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader import com.intellij.testGuiFramework.fixtures.* import com.intellij.testGuiFramework.fixtures.extended.ExtendedButtonFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedTableFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedTreeFixture import com.intellij.testGuiFramework.fixtures.extended.RowFixture import com.intellij.testGuiFramework.fixtures.newProjectWizard.NewProjectWizardFixture import com.intellij.testGuiFramework.framework.GuiTestLocalRunner import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.framework.GuiTestUtil.waitUntilFound import com.intellij.testGuiFramework.framework.IdeTestApplication.getTestScreenshotDirPath import com.intellij.testGuiFramework.impl.GuiTestUtilKt.findBoundedComponentByText import com.intellij.testGuiFramework.impl.GuiTestUtilKt.getComponentText import com.intellij.testGuiFramework.impl.GuiTestUtilKt.isTextComponent import com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher import com.intellij.testGuiFramework.launcher.system.SystemInfo import com.intellij.testGuiFramework.launcher.system.SystemInfo.isMac import com.intellij.testGuiFramework.util.Clipboard import com.intellij.testGuiFramework.util.Key import com.intellij.testGuiFramework.util.Shortcut import com.intellij.ui.CheckboxTree import com.intellij.ui.HyperlinkLabel import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.treeStructure.treetable.TreeTable import com.intellij.util.ui.AsyncProcessIcon import org.fest.swing.exception.ActionFailedException import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.fixture.* import org.fest.swing.image.ScreenshotTaker import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause import org.fest.swing.timing.Timeout import org.fest.swing.timing.Timeout.timeout import org.junit.Rule import org.junit.runner.RunWith import java.awt.Component import java.awt.Container import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit import javax.swing.* import javax.swing.text.JTextComponent /** * The main base class that should be extended for writing GUI tests. * * GuiTestCase contains methods of TestCase class like setUp() and tearDown() but also has a set of methods allows to use Kotlin DSL for * writing GUI tests (starts from comment KOTLIN DSL FOR GUI TESTING). The main concept of this DSL is using contexts of the current * component. Kotlin language gives us an opportunity to omit fixture instances to perform their methods, therefore code looks simpler and * more clear. Just use contexts functions to find appropriate fixtures and to operate with them: * * {@code <code> * welcomeFrame { // <- context of WelcomeFrameFixture * createNewProject() * dialog("New Project Wizard") { * // context of DialogFixture of dialog with title "New Project Wizard" * } * } * </code>} * * All fixtures (or DSL methods for theese fixtures) has a timeout to find component on screen and equals to #defaultTimeout. To check existence * of specific component by its fixture use exists lambda function with receiver. * * The more descriptive documentation about entire framework could be found in the root of testGuiFramework (HowToUseFramework.md) * */ @RunWith(GuiTestLocalRunner::class) open class GuiTestCase { @Rule @JvmField val guiTestRule = GuiTestRule() /** * default timeout to find target component for fixture. Using seconds as time unit. */ var defaultTimeout = 120L val settingsTitle: String = if (isMac()) "Preferences" else "Settings" val defaultSettingsTitle: String = if (isMac()) "Default Preferences" else "Default Settings" val slash: String = File.separator fun robot() = guiTestRule.robot() //********************KOTLIN DSL FOR GUI TESTING************************* //*********CONTEXT LAMBDA FUNCTIONS WITH RECEIVERS*********************** /** * Context function: finds welcome frame and creates WelcomeFrameFixture instance as receiver object. Code block after it call methods on * the receiver object (WelcomeFrameFixture instance). */ open fun welcomeFrame(func: WelcomeFrameFixture.() -> Unit) { func(guiTestRule.findWelcomeFrame()) } /** * Context function: finds IDE frame and creates IdeFrameFixture instance as receiver object. Code block after it call methods on the * receiver object (IdeFrameFixture instance). */ fun ideFrame(func: IdeFrameFixture.() -> Unit) { func(guiTestRule.findIdeFrame()) } /** * Context function: finds dialog with specified title and creates JDialogFixture instance as receiver object. Code block after it call * methods on the receiver object (JDialogFixture instance). * * @title title of searching dialog window. If dialog should be only one title could be omitted or set to null. * @needToKeepDialog is true if no need to wait when dialog is closed * @timeout time in seconds to find dialog in GUI hierarchy. */ fun dialog(title: String? = null, ignoreCaseTitle: Boolean = false, timeout: Long = defaultTimeout, needToKeepDialog: Boolean = false, func: JDialogFixture.() -> Unit) { val dialog = dialog(title, ignoreCaseTitle, timeout) func(dialog) if (!needToKeepDialog) dialog.waitTillGone() } /** * Waits for a native file chooser, types the path in a textfield and closes it by clicking OK button. Or runs AppleScript if the file chooser * is a Mac native. */ fun chooseFileInFileChooser(path: String, timeout: Long = defaultTimeout) { val macNativeFileChooser = SystemInfo.isMac() && (System.getProperty("ide.mac.file.chooser.native", "true").toLowerCase() == "false") if (macNativeFileChooser) { MacFileChooserDialogFixture(robot()).selectByPath(path) } else { val fileChooserDialog: JDialog try { fileChooserDialog = GuiTestUtilKt.withPauseWhenNull(timeout.toInt()) { robot().finder() .findAll(GuiTestUtilKt.typeMatcher(JDialog::class.java) { true }) .firstOrNull { GuiTestUtilKt.findAllWithBFS(it, JPanel::class.java).any { it.javaClass.name.contains(FileChooserDialogImpl::class.java.simpleName) } } } } catch (timeoutError: WaitTimedOutError) { throw ComponentLookupException("Unable to find file chooser dialog in ${timeout.toInt()} seconds") } val dialogFixture = JDialogFixture(robot(), fileChooserDialog) with(dialogFixture) { asyncProcessIcon().waitUntilStop(20) textfield("") invokeAction("\$SelectAll") typeText(path) button("OK").clickWhenEnabled() waitTillGone() } } } /** * Context function: imports a simple project to skip steps of creation, creates IdeFrameFixture instance as receiver object when project * is loaded. Code block after it call methods on the receiver object (IdeFrameFixture instance). */ fun simpleProject(func: IdeFrameFixture.() -> Unit) { func(guiTestRule.importSimpleProject()) } /** * Context function: finds dialog "New Project Wizard" and creates NewProjectWizardFixture instance as receiver object. Code block after * it call methods on the receiver object (NewProjectWizardFixture instance). */ fun projectWizard(func: NewProjectWizardFixture.() -> Unit) { func(guiTestRule.findNewProjectWizard()) } /** * Context function for IdeFrame: activates project view in IDE and creates ProjectViewFixture instance as receiver object. Code block after * it call methods on the receiver object (ProjectViewFixture instance). */ fun IdeFrameFixture.projectView(func: ProjectViewFixture.() -> Unit) { func(this.projectView) } /** * Context function for IdeFrame: activates toolwindow view in IDE and creates CustomToolWindowFixture instance as receiver object. Code * block after it call methods on the receiver object (CustomToolWindowFixture instance). * * @id - a toolwindow id. */ fun IdeFrameFixture.toolwindow(id: String, func: CustomToolWindowFixture.() -> Unit) { func(CustomToolWindowFixture(id, this)) } //*********FIXTURES METHODS WITHOUT ROBOT and TARGET; KOTLIN ONLY /** * Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture. * * @timeout in seconds to find JList component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.jList(containingItem: String? = null, timeout: Long = defaultTimeout): JListFixture = if (target() is Container) { val extCellReader = ExtendedJListCellReader() val myJList = waitUntilFound(target() as Container, JList::class.java, timeout) { jList -> if (containingItem == null) true //if were searching for any jList() else { val elements = (0 until jList.model.size).map { it -> extCellReader.valueAt(jList, it) } elements.any { it.toString() == containingItem } && jList.isShowing } } val jListFixture = JListFixture(guiTestRule.robot(), myJList) jListFixture.replaceCellReader(extCellReader) jListFixture } else throw unableToFindComponent("JList") /** * Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture. * * @timeout in seconds to find JButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.button(name: String, timeout: Long = defaultTimeout): ExtendedButtonFixture = if (target() is Container) { val jButton = waitUntilFound(target() as Container, JButton::class.java, timeout) { it.isShowing && it.isVisible && it.text == name } ExtendedButtonFixture(guiTestRule.robot(), jButton) } else throw unableToFindComponent("""JButton named by $name""") fun <S, C : Component> ComponentFixture<S, C>.componentWithBrowseButton(boundedLabelText: String, timeout: Long = defaultTimeout): ComponentWithBrowseButtonFixture { if (target() is Container) { val boundedLabel = waitUntilFound(target() as Container, JLabel::class.java, timeout) { it.text == boundedLabelText && it.isShowing } val component = boundedLabel.labelFor if (component is ComponentWithBrowseButton<*>) { return ComponentWithBrowseButtonFixture(component, guiTestRule.robot()) } } throw unableToFindComponent("ComponentWithBrowseButton with labelFor=$boundedLabelText") } fun <S, C : Component> ComponentFixture<S, C>.treeTable(timeout: Long = defaultTimeout): TreeTableFixture { if (target() is Container) { val table = waitUntilFound(guiTestRule.robot(), target() as Container, typeMatcher(TreeTable::class.java) { true }, timeout.toFestTimeout() ) return TreeTableFixture(guiTestRule.robot(), table) } else throw UnsupportedOperationException( "Sorry, unable to find inspections tree with ${target()} as a Container") } fun <S, C : Component> ComponentFixture<S, C>.spinner(boundedLabelText: String, timeout: Long = defaultTimeout): JSpinnerFixture { if (target() is Container) { val boundedLabel = waitUntilFound(target() as Container, JLabel::class.java, timeout) { it.text == boundedLabelText } val component = boundedLabel.labelFor if (component is JSpinner) return JSpinnerFixture(guiTestRule.robot(), component) } throw unableToFindComponent("""JSpinner with $boundedLabelText bounded label""") } /** * Finds a JComboBox component in hierarchy of context component by text of label and returns ComboBoxFixture. * * @timeout in seconds to find JComboBox component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.combobox(labelText: String, timeout: Long = defaultTimeout): ComboBoxFixture = if (target() is Container) { try { waitUntilFound(target() as Container, Component::class.java, timeout) { it.isShowing && it.isTextComponent() && it.getComponentText() == labelText } } catch (e: WaitTimedOutError) { throw ComponentLookupException("Unable to find label for a combobox with text \"$labelText\" in $timeout seconds") } val comboBox = findBoundedComponentByText(guiTestRule.robot(), target() as Container, labelText, JComboBox::class.java) val comboboxFixture = ComboBoxFixture(guiTestRule.robot(), comboBox) comboboxFixture.replaceCellReader(ExtendedJComboboxCellReader()) comboboxFixture } else throw unableToFindComponent("""JComboBox near label by "$labelText"""") /** * Finds a JCheckBox component in hierarchy of context component by text of label and returns CheckBoxFixture. * * @timeout in seconds to find JCheckBox component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.checkbox(labelText: String, timeout: Long = defaultTimeout): CheckBoxFixture = if (target() is Container) { val jCheckBox = waitUntilFound(target() as Container, JCheckBox::class.java, timeout) { it.isShowing && it.isVisible && it.text == labelText } CheckBoxFixture(guiTestRule.robot(), jCheckBox) } else throw unableToFindComponent("""JCheckBox label by "$labelText""") /** * Finds a ActionLink component in hierarchy of context component by name and returns ActionLinkFixture. * * @timeout in seconds to find ActionLink component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.actionLink(name: String, timeout: Long = defaultTimeout): ActionLinkFixture = if (target() is Container) { ActionLinkFixture.findActionLinkByName(name, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } else throw unableToFindComponent("""ActionLink by name "$name"""") /** * Finds a ActionButton component in hierarchy of context component by action name and returns ActionButtonFixture. * * @actionName text or action id of an action button (@see com.intellij.openapi.actionSystem.ActionManager#getId()) * @timeout in seconds to find ActionButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.actionButton(actionName: String, timeout: Long = defaultTimeout): ActionButtonFixture = if (target() is Container) { try { ActionButtonFixture.findByText(actionName, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } catch (componentLookupException: ComponentLookupException) { ActionButtonFixture.findByActionId(actionName, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } } else throw unableToFindComponent("""ActionButton by action name "$actionName"""") /** * Finds a ActionButton component in hierarchy of context component by action class name and returns ActionButtonFixture. * * @actionClassName qualified name of class for action * @timeout in seconds to find ActionButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.actionButtonByClass(actionClassName: String, timeout: Long = defaultTimeout): ActionButtonFixture = if (target() is Container) { ActionButtonFixture.findByActionClassName(actionClassName, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } else throw unableToFindComponent("""ActionButton by action class name "$actionClassName"""") /** * Finds a JRadioButton component in hierarchy of context component by label text and returns JRadioButtonFixture. * * @timeout in seconds to find JRadioButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.radioButton(textLabel: String, timeout: Long = defaultTimeout): RadioButtonFixture = if (target() is Container) GuiTestUtil.findRadioButton(guiTestRule.robot(), target() as Container, textLabel, timeout.toFestTimeout()) else throw unableToFindComponent("""RadioButton by label "$textLabel"""") /** * Finds a JTextComponent component (JTextField) in hierarchy of context component by text of label and returns JTextComponentFixture. * * @textLabel could be a null if label is absent * @timeout in seconds to find JTextComponent component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.textfield(textLabel: String?, timeout: Long = defaultTimeout): JTextComponentFixture { val target = target() if (target is Container) { return textfield(textLabel, target, timeout) } else throw unableToFindComponent("""JTextComponent (JTextField) by label "$textLabel"""") } fun textfield(textLabel: String?, container: Container, timeout: Long): JTextComponentFixture { if (textLabel.isNullOrEmpty()) { val jTextField = waitUntilFound(container, JTextField::class.java, timeout) { jTextField -> jTextField.isShowing } return JTextComponentFixture(guiTestRule.robot(), jTextField) } //wait until label has appeared waitUntilFound(container, Component::class.java, timeout) { it.isShowing && it.isVisible && it.isTextComponent() && it.getComponentText() == textLabel } val jTextComponent = findBoundedComponentByText(guiTestRule.robot(), container, textLabel!!, JTextComponent::class.java) return JTextComponentFixture(guiTestRule.robot(), jTextComponent) } /** * Finds a JTree component in hierarchy of context component by a path and returns ExtendedTreeFixture. * * @pathStrings comma separated array of Strings, representing path items: jTree("myProject", "src", "Main.java") * @timeout in seconds to find JTree component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.jTree(vararg pathStrings: String, timeout: Long = defaultTimeout): ExtendedTreeFixture = if (target() is Container) jTreePath(target() as Container, timeout, *pathStrings) else throw unableToFindComponent("""JTree "${if (pathStrings.isNotEmpty()) "by path $pathStrings" else ""}"""") /** * Finds a CheckboxTree component in hierarchy of context component by a path and returns CheckboxTreeFixture. * * @pathStrings comma separated array of Strings, representing path items: checkboxTree("JBoss", "JBoss Drools") * @timeout in seconds to find JTree component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.checkboxTree(vararg pathStrings: String, timeout: Long = defaultTimeout): CheckboxTreeFixture = if (target() is Container) { val extendedTreeFixture = jTreePath(target() as Container, timeout, *pathStrings) if (extendedTreeFixture.tree !is CheckboxTree) throw ComponentLookupException("Found JTree but not a CheckboxTree") CheckboxTreeFixture(guiTestRule.robot(), extendedTreeFixture.tree) } else throw unableToFindComponent("""CheckboxTree "${if (pathStrings.isNotEmpty()) "by path $pathStrings" else ""}"""") /** * Finds a JTable component in hierarchy of context component by a cellText and returns JTableFixture. * * @timeout in seconds to find JTable component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.table(cellText: String, timeout: Long = defaultTimeout): JTableFixture = if (target() is Container) { val jTable = waitUntilFound(target() as Container, JTable::class.java, timeout) { val jTableFixture = JTableFixture(guiTestRule.robot(), it) jTableFixture.replaceCellReader(ExtendedJTableCellReader()) try { jTableFixture.cell(cellText) true } catch (e: ActionFailedException) { false } } JTableFixture(guiTestRule.robot(), jTable) } else throw unableToFindComponent("""JTable with cell text "$cellText"""") /** * Finds popup on screen with item (itemName) and clicks on it item * * @timeout timeout in seconds to find JTextComponent component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.popupClick(itemName: String, timeout: Long = defaultTimeout) = if (target() is Container) { JBListPopupFixture.clickPopupMenuItem(itemName, false, target() as Container, guiTestRule.robot(), timeout.toFestTimeout()) } else throw unableToFindComponent("Popup") /** * Finds a LinkLabel component in hierarchy of context component by a link name and returns fixture for it. * * @timeout in seconds to find LinkLabel component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.linkLabel(linkName: String, timeout: Long = defaultTimeout) = if (target() is Container) { val myLinkLabel = waitUntilFound( guiTestRule.robot(), target() as Container, typeMatcher(LinkLabel::class.java) { it.isShowing && (it.text == linkName) }, timeout.toFestTimeout()) ComponentFixture(ComponentFixture::class.java, guiTestRule.robot(), myLinkLabel) } else throw unableToFindComponent("LinkLabel") fun <S, C : Component> ComponentFixture<S, C>.hyperlinkLabel(labelText: String, timeout: Long = defaultTimeout): HyperlinkLabelFixture = if (target() is Container) { val hyperlinkLabel = waitUntilFound(guiTestRule.robot(), target() as Container, typeMatcher(HyperlinkLabel::class.java) { it.isShowing && (it.text == labelText) }, timeout.toFestTimeout()) HyperlinkLabelFixture(guiTestRule.robot(), hyperlinkLabel) } else throw unableToFindComponent("""HyperlinkLabel by label text: "$labelText"""") /** * Finds a table of plugins component in hierarchy of context component by a link name and returns fixture for it. * * @timeout in seconds to find table of plugins component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.pluginTable(timeout: Long = defaultTimeout) = if (target() is Container) PluginTableFixture.find(guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) else throw unableToFindComponent("PluginTable") /** * Finds a Message component in hierarchy of context component by a title MessageFixture. * * @timeout in seconds to find component for Message * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Long = defaultTimeout) = if (target() is Container) MessagesFixture.findByTitle(guiTestRule.robot(), target() as Container, title, timeout.toFestTimeout()) else throw unableToFindComponent("Message") /** * Finds a Message component in hierarchy of context component by a title MessageFixture. * * @timeout in seconds to find component for Message * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Long = defaultTimeout, func: MessagesFixture.() -> Unit) { if (target() is Container) func(MessagesFixture.findByTitle(guiTestRule.robot(), target() as Container, title, timeout.toFestTimeout())) else throw unableToFindComponent("Message") } /** * Finds a JBLabel component in hierarchy of context component by a label name and returns fixture for it. * * @timeout in seconds to find JBLabel component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.label(labelName: String, timeout: Long = defaultTimeout): JLabelFixture = if (target() is Container) { val jbLabel = waitUntilFound( guiTestRule.robot(), target() as Container, typeMatcher(JBLabel::class.java) { it.isShowing && (it.text == labelName || labelName in it.text) }, timeout.toFestTimeout()) JLabelFixture(guiTestRule.robot(), jbLabel) } else throw unableToFindComponent("JBLabel") private fun <S, C : Component> ComponentFixture<S, C>.unableToFindComponent(component: String): ComponentLookupException = ComponentLookupException("""Sorry, unable to find $component component with ${target()} as a Container""") /** * Find an AsyncProcessIcon component in a current context (gets by receiver) and returns a fixture for it. * * @timeout timeout in seconds to find AsyncProcessIcon */ fun <S, C : Component> ComponentFixture<S, C>.asyncProcessIcon(timeout: Long = defaultTimeout): AsyncProcessIconFixture { val asyncProcessIcon = waitUntilFound( guiTestRule.robot(), target() as Container, typeMatcher(AsyncProcessIcon::class.java) { it.isShowing && it.isVisible }, timeout.toFestTimeout()) return AsyncProcessIconFixture(guiTestRule.robot(), asyncProcessIcon) } //*********FIXTURES METHODS FOR IDEFRAME WITHOUT ROBOT and TARGET /** * Context function for IdeFrame: get current editor and create EditorFixture instance as a receiver object. Code block after * it call methods on the receiver object (EditorFixture instance). */ fun IdeFrameFixture.editor(func: FileEditorFixture.() -> Unit) { func(this.editor) } /** * Context function for IdeFrame: get the tab with specific opened file and create EditorFixture instance as a receiver object. Code block after * it call methods on the receiver object (EditorFixture instance). */ fun IdeFrameFixture.editor(tabName: String, func: FileEditorFixture.() -> Unit) { val editorFixture = this.editor.selectTab(tabName) func(editorFixture) } /** * Context function for IdeFrame: creates a MainToolbarFixture instance as receiver object. Code block after * it call methods on the receiver object (MainToolbarFixture instance). */ fun IdeFrameFixture.toolbar(func: MainToolbarFixture.() -> Unit) { func(this.toolbar) } /** * Context function for IdeFrame: creates a NavigationBarFixture instance as receiver object. Code block after * it call methods on the receiver object (NavigationBarFixture instance). */ fun IdeFrameFixture.navigationBar(func: NavigationBarFixture.() -> Unit) { func(this.navigationBar) } fun IdeFrameFixture.configurationList(func: RunConfigurationListFixture.() -> Unit) { func(this.runConfigurationList) } /** * Extension function for IDE to iterate through the menu. * * @path items like: popup("New", "File") */ fun IdeFrameFixture.popup(vararg path: String) = this.invokeMenuPath(*path) fun CustomToolWindowFixture.ContentFixture.editor(func: EditorFixture.() -> Unit) { func(this.editor()) } //*********COMMON FUNCTIONS WITHOUT CONTEXT /** * Type text by symbol with a constant delay. Generate system key events, so entered text will aply to a focused component. */ fun typeText(text: String) = GuiTestUtil.typeText(text, guiTestRule.robot(), 10) /** * @param keyStroke should follow {@link KeyStrokeAdapter#getKeyStroke(String)} instructions and be generated by {@link KeyStrokeAdapter#toString(KeyStroke)} preferably * * examples: shortcut("meta comma"), shortcut("ctrl alt s"), shortcut("alt f11") * modifiers order: shift | ctrl | control | meta | alt | altGr | altGraph */ fun shortcut(keyStroke: String) = GuiTestUtil.invokeActionViaShortcut(guiTestRule.robot(), keyStroke) fun shortcut(shortcut: Shortcut) = shortcut(shortcut.getKeystroke()) fun shortcut(key: Key) = shortcut(key.name) /** * copies a given string to a system clipboard */ fun copyToClipboard(string: String) = Clipboard.copyToClipboard(string) /** * Invoke action by actionId through its keystroke */ fun invokeAction(actionId: String) = GuiTestUtil.invokeAction(guiTestRule.robot(), actionId) /** * Take a screenshot for a specific component. Screenshot remain scaling and represent it in name of file. */ fun screenshot(component: Component, screenshotName: String) { val extension = "${getScaleSuffix()}.png" val pathWithTestFolder = getTestScreenshotDirPath().path + slash + this.guiTestRule.getTestName() val fileWithTestFolder = File(pathWithTestFolder) FileUtil.ensureExists(fileWithTestFolder) var screenshotFilePath = File(fileWithTestFolder, screenshotName + extension) if (screenshotFilePath.isFile) { val format = SimpleDateFormat("MM-dd-yyyy.HH.mm.ss") val now = format.format(GregorianCalendar().time) screenshotFilePath = File(fileWithTestFolder, screenshotName + "." + now + extension) } ScreenshotTaker().saveComponentAsPng(component, screenshotFilePath.path) println(message = "Screenshot for a component \"$component\" taken and stored at ${screenshotFilePath.path}") } /** * Finds JDialog with a specific title (if title is null showing dialog should be only one) and returns created JDialogFixture */ fun dialog(title: String? = null, ignoreCaseTitle: Boolean, timeoutInSeconds: Long): JDialogFixture { if (title == null) { val jDialog = waitUntilFound(null, JDialog::class.java, timeoutInSeconds) { true } return JDialogFixture(guiTestRule.robot(), jDialog) } else { try { val dialog = GuiTestUtilKt.withPauseWhenNull(timeoutInSeconds.toInt()) { val allMatchedDialogs = guiTestRule.robot().finder().findAll(typeMatcher(JDialog::class.java) { if (ignoreCaseTitle) it.title.toLowerCase() == title.toLowerCase() else it.title == title }).filter { it.isShowing && it.isEnabled && it.isVisible } if (allMatchedDialogs.size > 1) throw Exception( "Found more than one (${allMatchedDialogs.size}) dialogs matched title \"$title\"") allMatchedDialogs.firstOrNull() } return JDialogFixture(guiTestRule.robot(), dialog) } catch (timeoutError: WaitTimedOutError) { throw ComponentLookupException("Timeout error for finding JDialog by title \"$title\" for $timeoutInSeconds seconds") } } } private fun Long.toFestTimeout(): Timeout = if (this == 0L) timeout(50, TimeUnit.MILLISECONDS) else timeout(this, TimeUnit.SECONDS) private fun jTreePath(container: Container, timeout: Long, vararg pathStrings: String): ExtendedTreeFixture { val myTree: JTree? val pathList = pathStrings.toList() myTree = if (pathList.isEmpty()) { waitUntilFound(guiTestRule.robot(), container, typeMatcher(JTree::class.java) { true }, timeout.toFestTimeout()) } else { waitUntilFound(guiTestRule.robot(), container, typeMatcher(JTree::class.java) { ExtendedTreeFixture(guiTestRule.robot(), it).hasPath(pathList) }, timeout.toFestTimeout()) } return ExtendedTreeFixture(guiTestRule.robot(), myTree) } fun exists(fixture: () -> AbstractComponentFixture<*, *, *>): Boolean { val tmp = defaultTimeout defaultTimeout = 0 try { fixture.invoke() defaultTimeout = tmp } catch (ex: Exception) { when (ex) { is ComponentLookupException, is WaitTimedOutError -> { defaultTimeout = tmp; return false } else -> throw ex } } return true } //*********SOME EXTENSION FUNCTIONS FOR FIXTURES fun JListFixture.doubleClickItem(itemName: String) { this.item(itemName).doubleClick() } //necessary only for Windows private fun getScaleSuffix(): String? { val scaleEnabled: Boolean = (GuiTestUtil.getSystemPropertyOrEnvironmentVariable("sun.java2d.uiScale.enabled")?.toLowerCase().equals( "true")) if (!scaleEnabled) return "" val uiScaleVal = GuiTestUtil.getSystemPropertyOrEnvironmentVariable("sun.java2d.uiScale") ?: return "" return "@${uiScaleVal}x" } fun <ComponentType : Component> waitUntilFound(container: Container?, componentClass: Class<ComponentType>, timeout: Long, matcher: (ComponentType) -> Boolean): ComponentType { return GuiTestUtil.waitUntilFound(guiTestRule.robot(), container, typeMatcher(componentClass) { matcher(it) }, timeout.toFestTimeout()) } fun pause(condition: String = "Unspecified condition", timeoutSeconds: Long = 120, testFunction: () -> Boolean) { Pause.pause(object : Condition(condition) { override fun test() = testFunction() }, Timeout.timeout(timeoutSeconds, TimeUnit.SECONDS)) } fun tableRowValues(table: JTableFixture, rowIndex: Int): List<String> { val fixture = ExtendedTableFixture(guiTestRule.robot(), table.target()) return RowFixture(rowIndex, fixture).values() } fun tableRowCount(table: JTableFixture): Int { val fixture = ExtendedTableFixture(guiTestRule.robot(), table.target()) return fixture.rowCount() } }
apache-2.0
9f98e03f7d18fbcc7410fa93df92a820
45.172099
170
0.715734
4.803852
false
true
false
false
Agusyc/DayCounter
app/src/main/java/com/agusyc/daycounter/Counter.kt
1
1017
package com.agusyc.daycounter import android.content.Context import android.content.SharedPreferences // This class represents a Counter internal class Counter (context: Context, val id: Int, val isWidget: Boolean) { // We declare all the needed variables val label: String val date: Long val color: Int val colorIndex: Int val notification: Boolean init { // We get the right prefs file, according to the isWidget variable, and we parse all the needed data val prefs: SharedPreferences = if (isWidget) context.getSharedPreferences("DaysPrefs", Context.MODE_PRIVATE) else context.getSharedPreferences("ListDaysPrefs", Context.MODE_PRIVATE) label = prefs.getString(id.toString() + "label", "") date = prefs.getLong(id.toString() + "date", 0) color = prefs.getInt(id.toString() + "color", 0) colorIndex = prefs.getInt(id.toString() + "color_index", 0) notification = prefs.getBoolean(id.toString() + "notification", false) } }
mit
f18774494dc9d4d5f8db4a543019c663
38.115385
189
0.695182
4.202479
false
false
false
false
googlecodelabs/android-testing
app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksActivity.kt
1
2842
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.tasks import android.app.Activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.example.android.architecture.blueprints.todoapp.R import com.google.android.material.navigation.NavigationView /** * Main activity for the todoapp. Holds the Navigation Host Fragment and the Drawer, Toolbar, etc. */ class TasksActivity : AppCompatActivity() { private lateinit var drawerLayout: DrawerLayout private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.tasks_act) setupNavigationDrawer() setSupportActionBar(findViewById(R.id.toolbar)) val navController: NavController = findNavController(R.id.nav_host_fragment) appBarConfiguration = AppBarConfiguration.Builder(R.id.tasks_fragment_dest, R.id.statistics_fragment_dest) .setOpenableLayout(drawerLayout) .build() setupActionBarWithNavController(navController, appBarConfiguration) findViewById<NavigationView>(R.id.nav_view) .setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { return findNavController(R.id.nav_host_fragment).navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } private fun setupNavigationDrawer() { drawerLayout = (findViewById<DrawerLayout>(R.id.drawer_layout)) .apply { setStatusBarBackground(R.color.colorPrimaryDark) } } } // Keys for navigation const val ADD_EDIT_RESULT_OK = Activity.RESULT_FIRST_USER + 1 const val DELETE_RESULT_OK = Activity.RESULT_FIRST_USER + 2 const val EDIT_RESULT_OK = Activity.RESULT_FIRST_USER + 3
apache-2.0
53d385bfb0ed544aa0c6726d36095d57
39.028169
98
0.749824
4.841567
false
true
false
false
notion/Plumb
compiler/src/test/kotlin/rxjoin/internal/codegen/writer/JoinerWriterTest.kt
2
4544
package rxjoin.internal.codegen.writer import com.google.common.truth.Truth.assertAbout import com.google.testing.compile.JavaFileObjects import com.google.testing.compile.JavaSourceSubjectFactory import org.junit.Test import rxjoin.internal.codegen.RxJoinProcessor class JoinerWriterTest { private val singleClassSource = JavaFileObjects.forSourceLines("rxjoin.example.JoinedClassA", "package rxjoin.example;", "import rx.Observable;", "import rx.subjects.BehaviorSubject;", "import rxjoin.annotation.*;", "@Joined(JoinedClassA.JoinedViewModelA.class)", "public class JoinedClassA {", " JoinedViewModelA viewModel = new JoinedViewModelA();", " @Out(\"integer\")", " public Observable<Integer> integerObservable;", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " public class JoinedViewModelA {", " @In(\"integer\")", " public BehaviorSubject<Integer> integerSubject = BehaviorSubject.create();", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " @Out(\"string\")", " public Observable<String> stringObservable;", " }", "}") private val invalidSourceWithInAsObserver = JavaFileObjects.forSourceLines("rxjoin.example.JoinedClassA", "package rxjoin.example;", "import rx.Observable;", "import rx.Observer;", "import rx.subjects.BehaviorSubject;", "import rxjoin.annotation.*;", "@Joined(JoinedClassA.JoinedViewModelA.class)", "public class JoinedClassA {", " JoinedViewModelA viewModel = new JoinedViewModelA();", " @Out(\"integer\")", " public Observable<Integer> integerObservable;", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " public class JoinedViewModelA {", " @In(\"integer\")", " public Observer<Integer> integerObserver = BehaviorSubject.create();", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " @Out(\"string\")", " public Observable<String> stringObservable;", " }", "}") private val joinedClassAJoiner = JavaFileObjects.forSourceLines("rxjoin.JoinedClassA_Joiner", "package rxjoin;", "", "import java.lang.Override;", "import rx.subscriptions.CompositeSubscription;", "import rxjoin.example.JoinedClassA;", "", "public class JoinedClassA_Joiner implements Joiner<JoinedClassA, JoinedClassA.JoinedViewModelA> {", " private CompositeSubscription subscriptions;", "", " @Override", " public void join(JoinedClassA joined, JoinedClassA.JoinedViewModelA joinedTo) {", " if (subscriptions != null && !subscriptions.isUnsubscribed()) {", " subscriptions.unsubscribe();", " }", " subscriptions = new CompositeSubscription();", " subscriptions.add(Utils.replicate(joined.integerObservable, joinedTo.integerSubject));", " subscriptions.add(Utils.replicate(joinedTo.stringObservable, joinedTo.stringSubject));", " subscriptions.add(Utils.replicate(joinedTo.stringObservable, joined.stringSubject));", " }", "", " @Override", " public void demolish() {", " subscriptions.unsubscribe();", " }", "}" ) @Test fun test_compile_simpleCase() { assertAbout(JavaSourceSubjectFactory.javaSource()) .that(singleClassSource) .processedWith(RxJoinProcessor()) .compilesWithoutError() .and() .generatesSources(joinedClassAJoiner) } @Test fun test_invalidViewmodelThrowsError() { assertAbout(JavaSourceSubjectFactory.javaSource()) .that(invalidSourceWithInAsObserver) .processedWith(RxJoinProcessor()) .failsToCompile() .withErrorContaining("@In-annotated element integerObserver must extend Subject<*, *>.") } }
apache-2.0
e9c9fbeedbc91b6679b7c5795406af8d
37.508475
112
0.589129
5.054505
false
true
false
false
google/ksp
test-utils/testData/api/javaModifiers.kt
1
10036
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // TEST PROCESSOR: JavaModifierProcessor // EXPECTED: // C: ABSTRACT PUBLIC : ABSTRACT PUBLIC // C.staticStr: PRIVATE : PRIVATE // C.s1: FINAL JAVA_TRANSIENT : FINAL JAVA_TRANSIENT // C.i1: JAVA_STATIC JAVA_VOLATILE PROTECTED : JAVA_STATIC JAVA_VOLATILE PROTECTED // C.NestedC: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // NestedC.<init>: FINAL PUBLIC : FINAL PUBLIC // C.InnerC: PUBLIC : PUBLIC // InnerC.<init>: FINAL PUBLIC : FINAL PUBLIC // C.intFun: JAVA_DEFAULT JAVA_SYNCHRONIZED : JAVA_DEFAULT JAVA_SYNCHRONIZED // C.foo: ABSTRACT JAVA_STRICT : ABSTRACT JAVA_STRICT // C.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterJavaClass: PUBLIC : PUBLIC // OuterJavaClass.staticPublicField: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // OuterJavaClass.staticPackageProtectedField: JAVA_STATIC : JAVA_STATIC // OuterJavaClass.staticProtectedField: JAVA_STATIC PROTECTED : JAVA_STATIC PROTECTED // OuterJavaClass.staticPrivateField: JAVA_STATIC PRIVATE : JAVA_STATIC PRIVATE // OuterJavaClass.InnerJavaClass: PUBLIC : PUBLIC // InnerJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterJavaClass.NestedJavaClass: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // NestedJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterJavaClass.staticPublicMethod: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // OuterJavaClass.staticPackageProtectedMethod: JAVA_STATIC : JAVA_STATIC // OuterJavaClass.staticProtectedMethod: JAVA_STATIC PROTECTED : JAVA_STATIC PROTECTED // OuterJavaClass.staticPrivateMethod: JAVA_STATIC PRIVATE : JAVA_STATIC PRIVATE // OuterJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass: OPEN : PUBLIC // OuterKotlinClass.InnerKotlinClass: INNER : FINAL PUBLIC // InnerKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass.NestedKotlinClass: OPEN : PUBLIC // NestedKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass.Companion: : FINAL JAVA_STATIC PUBLIC // Companion.companionMethod: : FINAL PUBLIC // Companion.companionField: CONST : FINAL PUBLIC // Companion.privateCompanionMethod: PRIVATE : FINAL PRIVATE // Companion.privateCompanionField: PRIVATE : FINAL PRIVATE // Companion.jvmStaticCompanionMethod: : FINAL JAVA_STATIC PUBLIC // Companion.jvmStaticCompanionField: : FINAL JAVA_STATIC PUBLIC // Companion.customJvmStaticCompanionMethod: : FINAL PUBLIC // Companion.customJvmStaticCompanionField: : FINAL PUBLIC // Companion.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass.transientProperty: : FINAL JAVA_TRANSIENT PUBLIC // OuterKotlinClass.volatileProperty: : FINAL JAVA_VOLATILE PUBLIC // OuterKotlinClass.strictfpFun: : FINAL JAVA_STRICT PUBLIC // OuterKotlinClass.synchronizedFun: : FINAL JAVA_SYNCHRONIZED PUBLIC // OuterKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterJavaClass: OPEN PUBLIC : PUBLIC // DependencyOuterJavaClass.DependencyNestedJavaClass: OPEN PUBLIC : PUBLIC // DependencyNestedJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterJavaClass.DependencyInnerJavaClass: INNER OPEN PUBLIC : PUBLIC // DependencyInnerJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterJavaClass.synchronizedFun: JAVA_SYNCHRONIZED OPEN : JAVA_SYNCHRONIZED // DependencyOuterJavaClass.strictfpFun: JAVA_STRICT OPEN : JAVA_STRICT // DependencyOuterJavaClass.transientField: FINAL JAVA_TRANSIENT : FINAL JAVA_TRANSIENT // DependencyOuterJavaClass.volatileField: FINAL JAVA_VOLATILE : FINAL JAVA_VOLATILE // DependencyOuterJavaClass.staticPublicMethod: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // DependencyOuterJavaClass.staticPackageProtectedMethod: JAVA_STATIC : JAVA_STATIC // DependencyOuterJavaClass.staticProtectedMethod: JAVA_STATIC PROTECTED : JAVA_STATIC PROTECTED // DependencyOuterJavaClass.staticPrivateMethod: JAVA_STATIC PRIVATE : JAVA_STATIC PRIVATE // DependencyOuterJavaClass.staticPublicField: FINAL JAVA_STATIC PUBLIC : FINAL JAVA_STATIC PUBLIC // DependencyOuterJavaClass.staticPackageProtectedField: FINAL JAVA_STATIC : FINAL JAVA_STATIC // DependencyOuterJavaClass.staticProtectedField: FINAL JAVA_STATIC PROTECTED : FINAL JAVA_STATIC PROTECTED // DependencyOuterJavaClass.staticPrivateField: FINAL JAVA_STATIC PRIVATE : FINAL JAVA_STATIC PRIVATE // DependencyOuterJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterKotlinClass: OPEN PUBLIC : PUBLIC // DependencyOuterKotlinClass.transientProperty: FINAL PUBLIC : FINAL JAVA_TRANSIENT PUBLIC // DependencyOuterKotlinClass.volatileProperty: FINAL PUBLIC : FINAL JAVA_VOLATILE PUBLIC // DependencyOuterKotlinClass.strictfpFun: FINAL PUBLIC : FINAL JAVA_STRICT PUBLIC // DependencyOuterKotlinClass.synchronizedFun: FINAL PUBLIC : FINAL JAVA_SYNCHRONIZED PUBLIC // DependencyOuterKotlinClass.Companion: FINAL PUBLIC : FINAL PUBLIC // Companion.companionField: FINAL PUBLIC : FINAL PUBLIC // Companion.customJvmStaticCompanionField: FINAL PUBLIC : FINAL PUBLIC // Companion.jvmStaticCompanionField: FINAL PUBLIC : FINAL PUBLIC // Companion.privateCompanionField: FINAL PUBLIC : FINAL PUBLIC // Companion.companionMethod: FINAL PUBLIC : FINAL PUBLIC // Companion.customJvmStaticCompanionMethod: FINAL PUBLIC : FINAL PUBLIC // Companion.jvmStaticCompanionMethod: FINAL PUBLIC : FINAL PUBLIC // Companion.privateCompanionMethod: FINAL PRIVATE : FINAL PRIVATE // Companion.<init>: FINAL PRIVATE : FINAL PRIVATE // DependencyOuterKotlinClass.DependencyInnerKotlinClass: FINAL INNER PUBLIC : FINAL PUBLIC // DependencyInnerKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterKotlinClass.DependencyNestedKotlinClass: OPEN PUBLIC : PUBLIC // DependencyNestedKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // END // MODULE: module1 // FILE: DependencyOuterJavaClass.java public class DependencyOuterJavaClass { public class DependencyInnerJavaClass {} public static class DependencyNestedJavaClass {} public static void staticPublicMethod() {} public static String staticPublicField; static void staticPackageProtectedMethod() {} static String staticPackageProtectedField; protected static void staticProtectedMethod() {} protected static String staticProtectedField; private static void staticPrivateMethod() {} private static String staticPrivateField; transient String transientField = ""; volatile String volatileField = ""; synchronized String synchronizedFun() { return ""; } strictfp String strictfpFun() { return ""; } } // FILE: DependencyOuterKotlinClass.kt typealias DependencyCustomJvmStatic=JvmStatic open class DependencyOuterKotlinClass { inner class DependencyInnerKotlinClass open class DependencyNestedKotlinClass companion object { fun companionMethod() {} val companionField:String = "" private fun privateCompanionMethod() {} val privateCompanionField:String = "" @JvmStatic fun jvmStaticCompanionMethod() {} @JvmStatic val jvmStaticCompanionField:String = "" @DependencyCustomJvmStatic fun customJvmStaticCompanionMethod() {} @DependencyCustomJvmStatic val customJvmStaticCompanionField:String = "" } @Transient val transientProperty: String = "" @Volatile var volatileProperty: String = "" @Strictfp fun strictfpFun(): String = "" @Synchronized fun synchronizedFun(): String = "" } // MODULE: main(module1) // FILE: a.kt annotation class Test @Test class Foo : C() { } @Test class Bar : OuterJavaClass() @Test class Baz : OuterKotlinClass() @Test class JavaDependency : DependencyOuterJavaClass() @Test class KotlinDependency : DependencyOuterKotlinClass() // FILE: C.java public abstract class C { private String staticStr = "str" final transient String s1; protected static volatile int i1; default synchronized int intFun() { return 1; } abstract strictfp void foo() {} public static class NestedC { } public class InnerC { } } // FILE: OuterJavaClass.java public class OuterJavaClass { public class InnerJavaClass {} public static class NestedJavaClass {} public static void staticPublicMethod() {} public static String staticPublicField; static void staticPackageProtectedMethod() {} static String staticPackageProtectedField; protected static void staticProtectedMethod() {} protected static String staticProtectedField; private static void staticPrivateMethod() {} private static String staticPrivateField; } // FILE: OuterKotlinClass.kt typealias CustomJvmStatic=JvmStatic open class OuterKotlinClass { inner class InnerKotlinClass open class NestedKotlinClass companion object { fun companionMethod() {} const val companionField:String = "" private fun privateCompanionMethod() {} private val privateCompanionField:String = "" @JvmStatic fun jvmStaticCompanionMethod() {} @JvmStatic val jvmStaticCompanionField:String = "" @CustomJvmStatic fun customJvmStaticCompanionMethod() {} @CustomJvmStatic val customJvmStaticCompanionField:String = "" } @Transient val transientProperty: String = "" @Volatile var volatileProperty: String = "" @Strictfp fun strictfpFun(): String = "" @Synchronized fun synchronizedFun(): String = "" }
apache-2.0
c92745fe8abbb1106366d702e503096d
40.131148
107
0.765444
4.754145
false
false
false
false
jrasmuson/Shaphat
src/test/kotlin/DynamoIntegrationSpec.kt
1
2673
import DynamoUtils.createNewTable import DynamoUtils.tableName import com.amazonaws.client.builder.AwsClientBuilder import com.amazonaws.services.dynamodbv2.AmazonDynamoDB import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded import models.AlreadyFinishedRequest import models.ModerationResult import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import kotlin.test.assertEquals // Spek can't give jvm arguments to test so have to use junit //Also Spek is having problems stopping the database so the test keeps running //object DynamoIntegrationSpec : Spek({ // var amazonDynamoDB:AmazonDynamoDB? = DynamoDBEmbedded.create().amazonDynamoDB() // createNewTable(amazonDynamoDB) // val dynamoClient = DynamoClient(DynamoDBMapper(amazonDynamoDB), tableName) // given("a dynamo connection") { // // val endpoint = AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "") //// val amazonDynamoDB = AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(endpoint).build() // // //// on("creating a table") { //// it("returns success") { //// val createNewTable = createNewTable(amazonDynamoDB) //// assertEquals(tableName, createNewTable.tableName) //// } //// } // // on("loading an empty list") { // it("doesn't have any failed batches") { // val batchWrite = dynamoClient.batchWrite(emptyList<ModerationResult>()) // assertEquals(0, batchWrite.size) // } // } // // on("loading one item") { // val result = ModerationResult("test.com", "http://test.com/image1") // it("load successfully") { // val batchWrite = dynamoClient.batchWrite(listOf(result)) // assertEquals(0, batchWrite.size) // } // } // on("get back the request") { // val request = AlreadyFinishedRequest("test.com", "http://test.com/insertedImage.jpg") // dynamoClient.batchWrite(listOf(request)) // it("get the one result") { // val batchWrite = dynamoClient.batchGet(listOf(request)) // assertEquals(1, batchWrite?.size) // } // } // // } // afterGroup{ // println("before shut") // amazonDynamoDB?.shutdown() // amazonDynamoDB=null // println("after shut") // } //})
apache-2.0
46e5e9af7d437b7564b4c0124ed8c77a
40.78125
115
0.65058
4.137771
false
true
false
false
JimSeker/ui
Navigation/MenuDemo_kt/app/src/main/java/edu/cs4730/menudemo_kt/MainActivity.kt
1
2247
package edu.cs4730.menudemo_kt import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.PopupMenu class MainActivity : AppCompatActivity() { lateinit var popup: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) popup = findViewById<View>(R.id.label2) as TextView popup.setOnClickListener { v -> showPopupMenu(v) //this is to the code below, not an API call. } } private fun showPopupMenu(v: View) { val popupM = PopupMenu( this, v ) //note "this" is the activity context, if you are using this in a fragment. using getActivity() popupM.inflate(R.menu.popup) popupM.setOnMenuItemClickListener { item -> Toast.makeText(applicationContext, item.toString(), Toast.LENGTH_LONG).show() true } popupM.show() } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, 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.menuandfragdemo) { startActivity(Intent(this@MainActivity, FragMenuActivity::class.java)) return true } else if (id == R.id.actbaritemsdemo) { startActivity(Intent(this@MainActivity, ActionMenuActivity::class.java)) return true } else if (id == R.id.viewpagerbuttondemo) { startActivity(Intent(this@MainActivity, ViewPagerButtonMenuActivity::class.java)) return true } return super.onOptionsItemSelected(item) } }
apache-2.0
e50b00adb6a8b265bd173e353e2eb5a6
35.241935
106
0.664441
4.567073
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadController.kt
3
3892
package eu.kanade.tachiyomi.ui.recently_read import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.manga.MangaController import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.recently_read_controller.* /** * Fragment that shows recently read manga. * Uses R.layout.fragment_recently_read. * UI related actions should be called from here. */ class RecentlyReadController : NucleusController<RecentlyReadPresenter>(), FlexibleAdapter.OnUpdateListener, RecentlyReadAdapter.OnRemoveClickListener, RecentlyReadAdapter.OnResumeClickListener, RecentlyReadAdapter.OnCoverClickListener, RemoveHistoryDialog.Listener { /** * Adapter containing the recent manga. */ var adapter: RecentlyReadAdapter? = null private set override fun getTitle(): String? { return resources?.getString(R.string.label_recent_manga) } override fun createPresenter(): RecentlyReadPresenter { return RecentlyReadPresenter() } override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { return inflater.inflate(R.layout.recently_read_controller, container, false) } /** * Called when view is created * * @param view created view */ override fun onViewCreated(view: View) { super.onViewCreated(view) // Initialize adapter recycler.layoutManager = LinearLayoutManager(view.context) adapter = RecentlyReadAdapter(this@RecentlyReadController) recycler.setHasFixedSize(true) recycler.adapter = adapter } override fun onDestroyView(view: View) { adapter = null super.onDestroyView(view) } /** * Populate adapter with chapters * * @param mangaHistory list of manga history */ fun onNextManga(mangaHistory: List<RecentlyReadItem>) { adapter?.updateDataSet(mangaHistory) } override fun onUpdateEmptyView(size: Int) { if (size > 0) { empty_view.hide() } else { empty_view.show(R.drawable.ic_glasses_black_128dp, R.string.information_no_recent_manga) } } override fun onResumeClick(position: Int) { val activity = activity ?: return val (manga, chapter, _) = adapter?.getItem(position)?.mch ?: return val nextChapter = presenter.getNextChapter(chapter, manga) if (nextChapter != null) { val intent = ReaderActivity.newIntent(activity, manga, nextChapter) startActivity(intent) } else { activity.toast(R.string.no_next_chapter) } } override fun onRemoveClick(position: Int) { val (manga, _, history) = adapter?.getItem(position)?.mch ?: return RemoveHistoryDialog(this, manga, history).showDialog(router) } override fun onCoverClick(position: Int) { val manga = adapter?.getItem(position)?.mch?.manga ?: return router.pushController(MangaController(manga).withFadeTransaction()) } override fun removeHistory(manga: Manga, history: History, all: Boolean) { if (all) { // Reset last read of chapter to 0L presenter.removeAllFromHistory(manga.id!!) } else { // Remove all chapters belonging to manga from library presenter.removeFromHistory(history) } } }
apache-2.0
6441e3276df83e5492950e2327930927
31.991525
100
0.686793
4.515081
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/KotlinExtensions.kt
1
1401
package org.http4k import java.net.URLEncoder import java.nio.ByteBuffer import java.util.Base64 fun ByteBuffer.length() = limit() - position() fun ByteBuffer.asString(): String = String(array(), position(), length()) fun ByteBuffer.base64Encode() : String = Base64.getEncoder().encodeToString(array()) fun String.asByteBuffer(): ByteBuffer = ByteBuffer.wrap(toByteArray()) fun String.quoted() = "\"${replace("\"", "\\\"")}\"" fun String.unquoted(): String = replaceFirst("^\"".toRegex(), "").replaceFirst("\"$".toRegex(), "").replace("\\\"", "\"") fun StringBuilder.appendIfNotBlank(valueToCheck: String, vararg toAppend: String): StringBuilder = appendIf({ valueToCheck.isNotBlank() }, *toAppend) fun StringBuilder.appendIfNotEmpty(valueToCheck: List<Any>, vararg toAppend: String): StringBuilder = appendIf({ valueToCheck.isNotEmpty() }, *toAppend) fun StringBuilder.appendIfPresent(valueToCheck: Any?, vararg toAppend: String): StringBuilder = appendIf({ valueToCheck != null }, *toAppend) fun StringBuilder.appendIf(condition: () -> Boolean, vararg toAppend: String): StringBuilder = apply { if (condition()) toAppend.forEach { append(it) } } fun String.base64Decoded(): String = String(Base64.getDecoder().decode(this)) fun String.base64Encode() = String(Base64.getEncoder().encode(toByteArray())) fun String.urlEncoded(): String = URLEncoder.encode(this, "utf-8")
apache-2.0
ec5e6d4e522c2bd7695cc76df80d6d5f
37.916667
121
0.723055
4.025862
false
false
false
false
Retronic/life-in-space
core/src/main/kotlin/com/retronicgames/lis/mission/resources/ResourceManager.kt
1
1580
/** * Copyright (C) 2015 Oleg Dolya * Copyright (C) 2015 Eduardo Garcia * * This file is part of Life in Space, by Retronic Games * * Life in Space 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. * * Life in Space 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 Life in Space. If not, see <http://www.gnu.org/licenses/>. */ package com.retronicgames.lis.mission.resources import com.badlogic.gdx.utils.ObjectMap import com.badlogic.gdx.utils.OrderedMap import com.retronicgames.gdx.set import com.retronicgames.lis.mission.Mission import com.retronicgames.utils.value.MutableValue class ResourceManager(mission: Mission):Iterable<ObjectMap.Entry<ResourceType, MutableValue<Int>>> { private val resources = OrderedMap<ResourceType, MutableValue<Int>>(ResourceType.values().size) init { ResourceType.values().forEach { resourceType -> resources[resourceType] = MutableValue(0) } mission.initialResources().forEach { entry -> resources[entry.key].value = entry.value } } override fun iterator() = resources.iterator() fun getResourceQuantity(type: ResourceType) = resources.get(type).value }
gpl-3.0
8953ccb35c30a09a804965f820123b70
34.909091
100
0.758228
3.9599
false
false
false
false
bertilxi/Chilly_Willy_Delivery
mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/model/Deal.kt
1
1494
package dam.isi.frsf.utn.edu.ar.delivery.model import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class Deal( @SerializedName("title") @Expose var title: String = "", @SerializedName("description") @Expose var description: String = "", @SerializedName("isLastDeal") @Expose var isLastDeal: Boolean = false ) : Parcelable { fun withTitle(title: String): Deal { this.title = title return this } fun withDescription(description: String): Deal { this.description = description return this } fun withIsLastDeal(isLastDeal: Boolean): Deal { this.isLastDeal = isLastDeal return this } companion object { @JvmField val CREATOR: Parcelable.Creator<Deal> = object : Parcelable.Creator<Deal> { override fun createFromParcel(source: Parcel): Deal = Deal(source) override fun newArray(size: Int): Array<Deal?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readString(), source.readString(), 1 == source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(title) dest.writeString(description) dest.writeInt((if (isLastDeal) 1 else 0)) } }
mit
33a9b7bf98b13a3b040e99506ff3dc30
26.685185
93
0.625167
4.355685
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/async/TaskManager.kt
1
6993
/**************************************************************************************** * Copyright (c) 2021 Arthur Milchior <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.async import android.content.res.Resources import androidx.annotation.VisibleForTesting /** * The TaskManager has two related purposes. * * A concrete TaskManager's mission is to take a TaskDelegate, potentially a CollectionListener, and execute them. * Currently, the default TaskManager is SingleTaskManager, which executes the tasks in order in which they are generated. It essentially consists in using basic AsyncTask properties with CollectionTask. * It should eventually be replaced by non deprecated system. * * The only other TaskManager currently is ForegroundTaskManager, which runs everything foreground and is used for unit testings. * * The class itself contains a static element which is the currently used TaskManager. Tasks can be executed on the current TaskManager with the static method launchTaskManager. */ abstract class TaskManager { protected abstract fun removeTaskConcrete(task: CollectionTask<*, *>): Boolean abstract fun <Progress, Result> launchCollectionTaskConcrete(task: TaskDelegateBase<Progress, Result>): Cancellable protected abstract fun setLatestInstanceConcrete(task: CollectionTask<*, *>) abstract fun <Progress, Result> launchCollectionTaskConcrete( task: TaskDelegateBase<Progress, Result>, listener: TaskListener<in Progress, in Result?>? ): Cancellable abstract fun waitToFinishConcrete() abstract fun waitToFinishConcrete(timeoutSeconds: Int?): Boolean abstract fun cancelCurrentlyExecutingTaskConcrete() abstract fun cancelAllTasksConcrete(taskType: Class<*>) abstract fun waitForAllToFinishConcrete(timeoutSeconds: Int): Boolean /** * Helper class for allowing inner function to publish progress of an AsyncTask. */ @Suppress("SENSELESS_COMPARISON") class ProgressCallback<Progress>(task: ProgressSender<Progress>, val resources: Resources) { private var mTask: ProgressSender<Progress>? = null fun publishProgress(value: Progress) { mTask?.doProgress(value) } init { if (resources != null) { mTask = task } else { mTask = null } } } companion object { private var sTaskManager: TaskManager = SingleTaskManager() /** * @param tm The new task manager * @return The previous one. It may still have tasks running */ @VisibleForTesting fun setTaskManager(tm: TaskManager): TaskManager { val previous = sTaskManager sTaskManager = tm return previous } fun removeTask(task: CollectionTask<*, *>): Boolean { return sTaskManager.removeTaskConcrete(task) } /** * Starts a new [CollectionTask], with no listener * * * Tasks will be executed serially, in the order in which they are started. * * * This method must be called on the main thread. * * @param task the task to execute * @return the newly created task */ fun setLatestInstance(task: CollectionTask<*, *>) { sTaskManager.setLatestInstanceConcrete(task) } fun <Progress, Result> launchCollectionTask(task: TaskDelegateBase<Progress, Result>): Cancellable { return sTaskManager.launchCollectionTaskConcrete(task) } /** * Starts a new [CollectionTask], with a listener provided for callbacks during execution * * * Tasks will be executed serially, in the order in which they are started. * * * This method must be called on the main thread. * * @param task the task to execute * @param listener to the status and result of the task, may be null * @return the newly created task */ fun <Progress, Result> launchCollectionTask( task: TaskDelegateBase<Progress, Result>, listener: TaskListener<in Progress, in Result?>? ): Cancellable { return sTaskManager.launchCollectionTaskConcrete(task, listener) } /** * Block the current thread until the currently running CollectionTask instance (if any) has finished. */ fun waitToFinish() { sTaskManager.waitToFinishConcrete() } /** * Block the current thread until the currently running CollectionTask instance (if any) has finished. * @param timeoutSeconds timeout in seconds (or null to wait indefinitely) * @return whether or not the previous task was successful or not, OR if an exception occurred (for example: timeout) */ fun waitToFinish(timeoutSeconds: Int?): Boolean { return sTaskManager.waitToFinishConcrete(timeoutSeconds) } /** Cancel the current task only if it's of type taskType */ fun cancelCurrentlyExecutingTask() { sTaskManager.cancelCurrentlyExecutingTaskConcrete() } /** Cancel all tasks of type taskType */ fun cancelAllTasks(taskType: Class<*>) { sTaskManager.cancelAllTasksConcrete(taskType) } /** * Block the current thread until all CollectionTasks have finished. * @param timeoutSeconds timeout in seconds * @return whether all tasks exited successfully */ fun waitForAllToFinish(timeoutSeconds: Int): Boolean { return sTaskManager.waitForAllToFinishConcrete(timeoutSeconds) } } }
gpl-3.0
3b2a597af12d420da3f39574830befa4
42.7
203
0.60369
5.5936
false
false
false
false
cemrich/zapp
app/src/main/java/de/christinecoenen/code/zapp/app/settings/helper/ShortcutPreference.kt
1
2486
package de.christinecoenen.code.zapp.app.settings.helper import android.annotation.TargetApi import android.content.Context import android.text.TextUtils import android.util.AttributeSet import android.widget.Toast import androidx.preference.MultiSelectListPreference import androidx.preference.Preference import de.christinecoenen.code.zapp.R import de.christinecoenen.code.zapp.models.channels.IChannelList import de.christinecoenen.code.zapp.models.channels.json.JsonChannelList import de.christinecoenen.code.zapp.utils.system.ShortcutHelper.areShortcutsSupported import de.christinecoenen.code.zapp.utils.system.ShortcutHelper.getChannelIdsOfShortcuts import de.christinecoenen.code.zapp.utils.system.ShortcutHelper.updateShortcutsToChannels import java.util.* class ShortcutPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : MultiSelectListPreference(context, attrs), Preference.OnPreferenceChangeListener { private lateinit var channelList: IChannelList init { if (areShortcutsSupported()) { loadChannelList() setSummaryToSelectedChannels() isEnabled = true } } override fun onPreferenceChange(preference: Preference, selectedValues: Any): Boolean { @Suppress("UNCHECKED_CAST") val selectedIds = selectedValues as Set<String> val success = saveShortcuts(selectedIds) if (!success) { // shortcuts could not be saved Toast.makeText(context, R.string.pref_shortcuts_too_many, Toast.LENGTH_LONG).show() } loadValuesFromShortcuts() setSummaryToSelectedChannels() return success } private fun loadChannelList() { channelList = JsonChannelList(context) val entries = channelList.map { it.name } val values = channelList.map { it.id } setEntries(entries.toTypedArray()) // human readable entryValues = values.toTypedArray() // ids loadValuesFromShortcuts() } private fun loadValuesFromShortcuts() { val shortcutIds = getChannelIdsOfShortcuts(context) values = HashSet(shortcutIds) } @TargetApi(25) private fun saveShortcuts(channelIds: Set<String>): Boolean { val channels = channelIds.map { channelList[it]!! } return updateShortcutsToChannels(context, channels) } private fun setSummaryToSelectedChannels() { if (values.size == 0) { setSummary(R.string.pref_shortcuts_summary_limit) return } val selectedChannelNames = channelList .filter { values.contains(it.id) } .map { it.name } summary = TextUtils.join(", ", selectedChannelNames) } }
mit
41edaa81a22f2e9648572e3fec90b8ad
28.595238
89
0.782784
3.921136
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/model/scan/ScanStateModel.kt
2
1689
package org.wordpress.android.fluxc.model.scan import org.wordpress.android.fluxc.model.scan.threat.ThreatModel import java.util.Date data class ScanStateModel( val state: State, val reason: Reason, val threats: List<ThreatModel>? = null, val credentials: List<Credentials>? = null, val hasCloud: Boolean = false, val mostRecentStatus: ScanProgressStatus? = null, val currentStatus: ScanProgressStatus? = null, val hasValidCredentials: Boolean = false ) { enum class State(val value: String) { IDLE("idle"), SCANNING("scanning"), PROVISIONING("provisioning"), UNAVAILABLE("unavailable"), UNKNOWN("unknown"); companion object { fun fromValue(value: String): State? { return values().firstOrNull { it.value == value } } } } data class Credentials( val type: String, val role: String, val host: String?, val port: Int?, val user: String?, val path: String?, val stillValid: Boolean ) data class ScanProgressStatus( val startDate: Date?, val duration: Int = 0, val progress: Int = 0, val error: Boolean = false, val isInitial: Boolean = false ) enum class Reason(val value: String?) { MULTISITE_NOT_SUPPORTED("multisite_not_supported"), VP_ACTIVE_ON_SITE("vp_active_on_site"), NO_REASON(null), UNKNOWN("unknown"); companion object { fun fromValue(value: String?): Reason { return values().firstOrNull { it.value == value } ?: UNKNOWN } } } }
gpl-2.0
2348f625d18b77d578a3ddf99fa091bf
27.15
76
0.589698
4.480106
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/text/LanternTextRenderer.kt
1
10250
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.text import net.kyori.adventure.text.BuildableComponent import net.kyori.adventure.text.NBTComponentBuilder import net.kyori.adventure.text.event.HoverEvent import net.kyori.adventure.text.format.Style import net.kyori.adventure.text.renderer.AbstractComponentRenderer import org.lanternpowered.api.text.BlockDataText import org.lanternpowered.api.text.DataText import org.lanternpowered.api.text.EntityDataText import org.lanternpowered.api.text.KeybindText import org.lanternpowered.api.text.LiteralText import org.lanternpowered.api.text.ScoreText import org.lanternpowered.api.text.SelectorText import org.lanternpowered.api.text.StorageDataText import org.lanternpowered.api.text.Text import org.lanternpowered.api.text.TextBuilder import org.lanternpowered.api.text.TranslatableText import org.lanternpowered.api.text.textOf import java.text.MessageFormat abstract class LanternTextRenderer<C> : AbstractComponentRenderer<C>() { companion object { private val Merges = Style.Merge.of( Style.Merge.COLOR, Style.Merge.DECORATIONS, Style.Merge.INSERTION, Style.Merge.FONT) } protected fun <T : BuildableComponent<T, B>, B : TextBuilder<T, B>> B.applyChildren(text: Text, context: C): B = apply { for (child in text.children()) this.append(render(child, context)) } protected fun <T : BuildableComponent<T, B>, B : TextBuilder<T, B>> B.applyStyle(text: Text, context: C): B = apply { this.mergeStyle(text, Merges) this.clickEvent(text.clickEvent()) this.insertion(text.insertion()) this.hoverEvent(renderHoverEventIfNeeded(text.hoverEvent(), context) ?: text.hoverEvent()) } protected fun <T : BuildableComponent<T, B>, B : TextBuilder<T, B>> B.applyStyleAndChildren(text: Text, context: C): B = this.applyChildren(text, context).applyStyle(text, context) private fun <T : DataText<T, B>, B : NBTComponentBuilder<T, B>> B.applyNbt(text: DataText<*, *>): B = apply { this.nbtPath(text.nbtPath()) this.interpret(text.interpret()) } final override fun renderText(text: LiteralText, context: C): Text = this.renderLiteralIfNeeded(text, context) ?: text final override fun renderStorageNbt(text: StorageDataText, context: C): Text = this.renderStorageNbtIfNeeded(text, context) ?: text final override fun renderEntityNbt(text: EntityDataText, context: C): Text = this.renderEntityNbtIfNeeded(text, context) ?: text final override fun renderBlockNbt(text: BlockDataText, context: C): Text = this.renderBlockNbtIfNeeded(text, context) ?: text final override fun renderScore(text: ScoreText, context: C): Text = this.renderScoreIfNeeded(text, context) ?: text final override fun renderKeybind(text: KeybindText, context: C): Text = this.renderKeybindIfNeeded(text, context) ?: text final override fun renderSelector(text: SelectorText, context: C): Text = this.renderSelectorIfNeeded(text, context) ?: text final override fun renderTranslatable(text: TranslatableText, context: C): Text = this.renderTranslatableIfNeeded(text, context) ?: text protected open fun renderLiteralIfNeeded(text: LiteralText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.text().content(text.content()) } } protected open fun renderStorageNbtIfNeeded(text: StorageDataText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.storageNBT() .storage(text.storage()) .applyNbt(text) } } protected open fun renderEntityNbtIfNeeded(text: EntityDataText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.entityNBT() .selector(text.selector()) .applyNbt(text) } } protected open fun renderBlockNbtIfNeeded(text: BlockDataText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.blockNBT() .pos(text.pos()) .applyNbt(text) } } protected open fun renderScoreIfNeeded(text: ScoreText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.score() .objective(text.objective()) .value(text.value()) .name(text.name()) } } protected open fun renderKeybindIfNeeded(text: KeybindText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.keybind().keybind(text.keybind()) } } protected open fun renderSelectorIfNeeded(text: SelectorText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.selector().pattern(text.pattern()) } } protected open fun renderTranslatableIfNeeded(text: TranslatableText, context: C): Text? { val format = this.translate(text.key(), context) val args = text.args() if (format == null) { val renderedArgs = this.renderListIfNeeded(text.args(), context) return this.renderIfNeeded(text, context, force = renderedArgs != null) { Text.translatable().key(text.key()) .args(renderedArgs ?: args) } } val builder = Text.text() if (args.isEmpty()) return builder.content(format.format(null, StringBuffer(), null).toString()) .applyStyleAndChildren(text, context) .build() val nulls = arrayOfNulls<Any>(args.size) val sb = format.format(nulls, StringBuffer(), null) val itr = format.formatToCharacterIterator(nulls) while (itr.index < itr.endIndex) { val end = itr.runLimit val index = itr.getAttribute(MessageFormat.Field.ARGUMENT) as Int? if (index != null) { builder.append(this.render(args[index], context)) } else { builder.append(textOf(sb.substring(itr.index, end))) } itr.index = end } return builder.applyStyleAndChildren(text, context).build() } private fun <T : Text, B : TextBuilder<T, B>> renderIfNeeded( text: Text, context: C, force: Boolean = false, builderSupplier: () -> B ): T? { val children = this.renderListIfNeeded(text.children(), context) val hoverEvent = this.renderHoverEventIfNeeded(text.hoverEvent(), context) if (children == null && hoverEvent == null && !force) return null val builder = builderSupplier() builder.append(children ?: text.children()) builder.mergeStyle(text, Style.Merge.colorAndDecorations()) builder.hoverEvent(hoverEvent ?: text.hoverEvent()) builder.clickEvent(text.clickEvent()) builder.insertion(text.insertion()) return builder.build() } protected fun renderHoverEventIfNeeded(hoverEvent: HoverEvent<*>?, context: C): HoverEvent<*>? { if (hoverEvent == null) return null return when (val value = hoverEvent.value()) { is Text -> { val text = this.renderIfNeeded(value, context) ?: return null HoverEvent.showText(text) } is HoverEvent.ShowEntity -> { val name = value.name() ?: return null val text = this.renderIfNeeded(name, context) ?: return null HoverEvent.showEntity(HoverEvent.ShowEntity.of(value.type(), value.id(), text)) } is HoverEvent.ShowItem -> null // TODO else -> hoverEvent.withRenderedValue(this, context) } } /** * Renders the given [Text] for the [context]. This function will return `null` * in case nothing changed to the contents when rendering. */ fun renderIfNeeded(text: Text, context: C): Text? { return when (text) { is LiteralText -> this.renderLiteralIfNeeded(text, context) is TranslatableText -> this.renderTranslatableIfNeeded(text, context) is KeybindText -> this.renderKeybindIfNeeded(text, context) is ScoreText -> this.renderScoreIfNeeded(text, context) is SelectorText -> this.renderSelectorIfNeeded(text, context) is DataText<*, *> -> when (text) { is BlockDataText -> this.renderBlockNbtIfNeeded(text, context) is EntityDataText -> this.renderEntityNbtIfNeeded(text, context) is StorageDataText -> this.renderStorageNbtIfNeeded(text, context) else -> text } else -> text } } /** * Renders the given list of [Text], if it's needed. */ fun renderListIfNeeded(list: List<Text>, context: C): List<Text>? { if (list.isEmpty()) return null var resultList: MutableList<Text>? = null for (index in list.indices) { val text = list[index] val result = this.renderIfNeeded(text, context) if (result != null) { if (resultList == null) { resultList = ArrayList(list.size) resultList.addAll(list.subList(0, index)) } resultList.add(result) } else { resultList?.add(text) } } return resultList } /** * Gets a message format from a key and context. * * @param context a context * @param key a translation key * @return a message format or `null` to skip translation */ protected abstract fun translate(key: String, context: C): MessageFormat? }
mit
c0248d296c1c5b8ca3139d5c15e00bc1
38.883268
124
0.624488
4.40103
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/DataHolderBase.kt
1
4454
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import com.google.common.collect.ImmutableSet import org.lanternpowered.api.util.optional.emptyOptional import org.lanternpowered.api.util.uncheckedCast import org.spongepowered.api.data.DataHolder import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.Value import java.util.Optional import kotlin.reflect.KProperty interface DataHolderBase : DataHolder, ValueContainerBase { /** * Gets a element delegate for the given [Key]. */ @JvmDefault operator fun <V : Value<E>, E : Any, H : DataHolder> Key<V>.provideDelegate(thisRef: H, property: KProperty<*>): DataHolderProperty<H, E> = KeyElementProperty(this) /** * Gets a element delegate for the given [Key]. */ @JvmDefault operator fun <V : Value<E>, E : Any, H : DataHolder> Optional<out Key<V>>.provideDelegate(thisRef: H, property: KProperty<*>): DataHolderProperty<H, E> = get().provideDelegate(thisRef, property) /** * Gets a value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> value(key: Key<V>): DataHolderProperty<H, V> = KeyValueProperty(key) /** * Gets a value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> value(key: Optional<out Key<V>>): DataHolderProperty<H, V> = value(key.get()) /** * Gets a optional element delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optional(key: Key<V>): DataHolderProperty<H, E?> = OptionalKeyElementProperty(key) /** * Gets a optional element delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optional(key: Optional<out Key<V>>): DataHolderProperty<H, E?> = optional(key.get()) /** * Gets a optional value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optionalValue(key: Key<V>): DataHolderProperty<H, V?> = OptionalKeyValueProperty(key) /** * Gets a optional value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optionalValue(key: Optional<out Key<V>>): DataHolderProperty<H, V?> = optionalValue(key.get()) @JvmDefault override fun supports(key: Key<*>) = supportsKey(key.uncheckedCast<Key<Value<Any>>>()) /** * Gets whether the [Key] is supported by this [LocalDataHolder]. */ @JvmDefault private fun <V : Value<E>, E : Any> supportsKey(key: Key<V>): Boolean { val globalRegistration = GlobalKeyRegistry[key] if (globalRegistration != null) return globalRegistration.anyDataProvider().isSupported(this) return false } @JvmDefault override fun <E : Any, V : Value<E>> getValue(key: Key<V>): Optional<V> { val globalRegistration = GlobalKeyRegistry[key] if (globalRegistration != null) return globalRegistration.dataProvider<V, E>().getValue(this) return emptyOptional() } @JvmDefault override fun <E : Any> get(key: Key<out Value<E>>): Optional<E> { val globalRegistration = GlobalKeyRegistry[key] if (globalRegistration != null) return globalRegistration.dataProvider<Value<E>, E>().get(this) return emptyOptional() } @JvmDefault override fun getKeys(): Set<Key<*>> { val keys = ImmutableSet.builder<Key<*>>() GlobalKeyRegistry.registrations.stream() .filter { registration -> registration.anyDataProvider().isSupported(this) } .forEach { registration -> keys.add(registration.key) } return keys.build() } @JvmDefault override fun getValues(): Set<Value.Immutable<*>> { val values = ImmutableSet.builder<Value.Immutable<*>>() for (registration in GlobalKeyRegistry.registrations) { registration.anyDataProvider().getValue(this).ifPresent { value -> values.add(value.asImmutable()) } } return values.build() } }
mit
604add584c2130e8a51773fbad089afa
34.632
142
0.648181
4.063869
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientBlockPlacementDecoder.kt
1
1543
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.codec.play import org.lanternpowered.server.network.buffer.ByteBuffer import org.lanternpowered.server.network.packet.PacketDecoder import org.lanternpowered.server.network.packet.CodecContext import org.lanternpowered.server.network.vanilla.packet.codec.play.CodecUtils.decodeDirection import org.lanternpowered.server.network.vanilla.packet.type.play.ClientBlockPlacementPacket import org.spongepowered.api.data.type.HandTypes import org.spongepowered.math.vector.Vector3d object ClientBlockPlacementDecoder : PacketDecoder<ClientBlockPlacementPacket> { override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientBlockPlacementPacket { val hand = if (buf.readVarInt() == 0) HandTypes.MAIN_HAND.get() else HandTypes.OFF_HAND.get() val position = buf.readBlockPosition() val face = decodeDirection(buf.readVarInt()) val ox = buf.readFloat().toDouble() val oy = buf.readFloat().toDouble() val oz = buf.readFloat().toDouble() val offset = Vector3d(ox, oy, oz) val insideBlock = buf.readBoolean() return ClientBlockPlacementPacket(position, offset, face, hand, insideBlock) } }
mit
a3af3df65a61efd3719582844d74f6e2
44.382353
101
0.751782
4.007792
false
false
false
false
mediathekview/MediathekView
src/main/kotlin/org/jdesktop/swingx/VerticalLayout.kt
1
2441
package org.jdesktop.swingx import java.awt.Component import java.awt.Container import java.awt.Dimension import java.awt.LayoutManager import java.io.Serializable import kotlin.math.max abstract class AbstractLayoutManager : LayoutManager, Serializable { override fun addLayoutComponent(name: String, comp: Component) { //do nothing } override fun removeLayoutComponent(comp: Component) { // do nothing } override fun minimumLayoutSize(parent: Container): Dimension { return preferredLayoutSize(parent) } companion object { private const val serialVersionUID = 1446292747820044161L } } /** * SwingX VerticalLayout implementation recreated in Kotlin. * Unfortunately SwingX is not maintained anymore :( */ class VerticalLayout @JvmOverloads constructor(var gap: Int = 0) : AbstractLayoutManager() { internal class Separator(private var next: Int, private val separator: Int) { fun get(): Int { val result = next next = separator return result } } override fun preferredLayoutSize(parent: Container): Dimension { val pref = Dimension(0, 0) val sep = Separator(0, gap) var i = 0 val c = parent.componentCount while (i < c) { val m = parent.getComponent(i) if (m.isVisible) { val componentPreferredSize = parent.getComponent(i).preferredSize pref.height += componentPreferredSize.height + sep.get() pref.width = max(pref.width, componentPreferredSize.width) } i++ } val insets = parent.insets pref.width += insets.left + insets.right pref.height += insets.top + insets.bottom return pref } override fun layoutContainer(parent: Container) { val insets = parent.insets val size = parent.size val width = size.width - insets.left - insets.right var height = insets.top var i = 0 val c = parent.componentCount while (i < c) { val m = parent.getComponent(i) if (m.isVisible) { m.setBounds(insets.left, height, width, m.preferredSize.height) height += m.size.height + gap } i++ } } companion object { private const val serialVersionUID = 5342270033773736441L } }
gpl-3.0
fd781298c5d4fa07765a12366db18939
28.780488
81
0.615731
4.658397
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/labels/Labels.kt
1
4228
package nl.hannahsten.texifyidea.util.labels import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.index.LatexParameterLabeledCommandsIndex import nl.hannahsten.texifyidea.index.LatexParameterLabeledEnvironmentsIndex import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.reference.InputFileReference import nl.hannahsten.texifyidea.util.files.commandsInFile import nl.hannahsten.texifyidea.util.files.commandsInFileSet import nl.hannahsten.texifyidea.util.files.psiFile /** * Finds all the defined labels in the fileset of the file. * * @return A set containing all labels that are defined in the fileset of the given file. */ fun PsiFile.findLatexAndBibtexLabelStringsInFileSet(): Set<String> = (findLatexLabelStringsInFileSetAsSequence() + findBibtexLabelsInFileSetAsSequence()).toSet() /** * Finds all the defined latex labels in the fileset of the file. * May contain duplicates. * * @return A set containing all labels that are defined in the fileset of the given file. */ fun PsiFile.findLatexLabelStringsInFileSetAsSequence(): Sequence<String> { val allCommands = this.commandsInFileSet() return findLatexLabelingElementsInFileSet().map { it.extractLabelName(referencingFileSetCommands = allCommands) } } /** * All labels in this file. */ fun PsiFile.findLatexLabelingElementsInFile(): Sequence<PsiElement> = sequenceOf( findLabelingCommandsInFile(), LatexParameterLabeledEnvironmentsIndex.getItems(this).asSequence(), LatexParameterLabeledCommandsIndex.getItems(this).asSequence() ).flatten() /** * All labels in the fileset. * May contain duplicates. */ fun PsiFile.findLatexLabelingElementsInFileSet(): Sequence<PsiElement> = sequenceOf( findLabelingCommandsInFileSet(), LatexParameterLabeledEnvironmentsIndex.getItemsInFileSet(this).asSequence(), LatexParameterLabeledCommandsIndex.getItemsInFileSet(this).asSequence() ).flatten() /** * Make a sequence of all commands in the file set that specify a label. This does not include commands which define a label via an * optional parameter. */ fun PsiFile.findLabelingCommandsInFileSet(): Sequence<LatexCommands> { // If using the xr package to include label definitions in external files, include those external files when searching for labeling commands in the fileset val externalCommands = this.findXrPackageExternalDocuments().flatMap { it.commandsInFileSet() } return (this.commandsInFileSet() + externalCommands).asSequence().findLatexCommandsLabels(this.project) } /** * Find external files which contain label definitions, as used by the xr package, which are called with \externaldocument anywhere in the fileset. */ fun PsiFile.findXrPackageExternalDocuments(): List<PsiFile> { return this.commandsInFileSet() .filter { it.name == LatexGenericRegularCommand.EXTERNALDOCUMENT.commandWithSlash } .flatMap { it.references.filterIsInstance<InputFileReference>() } .mapNotNull { it.findAnywhereInProject(it.key)?.psiFile(project) } } /** * @see [findLabelingCommandsInFileSet] but then only for commands in this file. */ fun PsiFile.findLabelingCommandsInFile(): Sequence<LatexCommands> { return this.commandsInFile().asSequence().findLatexCommandsLabels(this.project) } /* * Filtering sequence or collection */ /** * Finds all the labeling commands within the collection of PsiElements. * * @return A collection of all label commands. */ fun Collection<PsiElement>.findLatexCommandsLabels(project: Project): Collection<LatexCommands> { val commandNames = project.getLabelDefinitionCommands() return filterIsInstance<LatexCommands>().filter { commandNames.contains(it.name) } } /** * Finds all the labeling commands within the sequence of PsiElements. * * @return A sequence of all label commands. */ fun Sequence<PsiElement>.findLatexCommandsLabels(project: Project): Sequence<LatexCommands> { val commandNames = project.getLabelDefinitionCommands() return filterIsInstance<LatexCommands>().filter { commandNames.contains(it.name) } }
mit
3a7ef625c42ec4c2f1328e2b6b546a39
40.45098
159
0.788553
4.427225
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/Collections.kt
1
4675
package nl.hannahsten.texifyidea.util import java.util.* import java.util.stream.Collectors import java.util.stream.Stream /** * Puts all the elements of an array into a mutable map. * * The format is `key0, value0, key1, value1, ...`. This means that there must always be an even amount of elements. * * @return A map mapping `keyN` to `valueN` (see description above). When there are no elements, an empty map will be * returned * @throws IllegalArgumentException When there is an odd amount of elements in the array. */ @Throws(IllegalArgumentException::class) fun <T> mutableMapOfArray(args: Array<out T>): MutableMap<T, T> { if (args.isEmpty()) { return HashMap() } if (args.size % 2 != 0) { throw IllegalArgumentException("Must have an even number of elements, got ${args.size} instead.") } val map: MutableMap<T, T> = HashMap() for (i in 0 until args.size - 1 step 2) { map[args[i]] = args[i + 1] } return map } /** * Puts some elements into a mutable map. * * The format is `key0, value0, key1, value1, ...`. This means that there must always be an even amount of elements. * * @return A map mapping `keyN` to `valueN` (see description above). When there are no elements, an empty map will be * returned * @throws IllegalArgumentException When there is an odd amount of elements in the array. */ fun <T> mutableMapOfVarargs(vararg args: T): MutableMap<T, T> = mutableMapOfArray(args) /** * Puts some into a mutable map. * * The format is `key0, value0, key1, value1, ...`. This means that there must always be an even amount of elements. * * @return A map mapping `keyN` to `valueN` (see description above). When there are no elements, an empty map will be * returned * @throws IllegalArgumentException When there is an odd amount of elements in the array. */ fun <T> mapOfVarargs(vararg args: T): Map<T, T> = mutableMapOfArray(args) /** * Gets a random element from the list using the given random object. */ fun <T> List<T>.randomElement(random: Random): T = this[random.nextInt(this.size)] /** * Looks up keys in the map that has the given `value`. * * @return All keys with the given value. */ fun <K, V> Map<K, V>.findKeys(value: V): Set<K> { return entries.asSequence() .filter { (_, v) -> v == value } .map { it.key } .toSet() } /** * Finds at least `amount` elements matching the given predicate. * * @param amount * How many items the collection must contain at least in order to return true. Must be nonnegative. * @return `true` when `amount` or more elements in the collection match the given predicate. */ inline fun <T> Collection<T>.findAtLeast(amount: Int, predicate: (T) -> Boolean): Boolean { require(amount >= 0) { "Amount must be positive." } // Edge cases. when (amount) { 0 -> none(predicate) 1 -> any(predicate) } // More than 1 item, iterate. var matches = 0 for (element in this) { if (predicate(element)) { matches += 1 if (matches >= amount) { return true } } } return false } /** * Checks if all given predicates can be matched at least once. * * @return `true` if all predicates match for at least 1 element in the collection, `false` otherwise. */ inline fun <T> Collection<T>.anyMatchAll(predicate: (T) -> Boolean, vararg predicates: (T) -> Boolean): Boolean { val matches = BooleanArray(predicates.size + 1) var matchCount = 0 for (element in this) { for (i in predicates.indices) { if (!matches[i] && predicates[i](element)) { matches[i] = true matchCount += 1 } } if (!matches.last() && predicate(element)) { matches[matches.size - 1] = true matchCount += 1 } } return matchCount == matches.size } /** * Checks if the map contains the given value as either a key or value. */ fun <T> Map<T, T>.containsKeyOrValue(value: T) = containsKey(value) || containsValue(value) /** * Collects stream to [List]. */ fun <T> Stream<T>.list(): List<T> = this.mutableList() /** * Collects stream to [MutableList]. */ fun <T> Stream<T>.mutableList(): MutableList<T> = this.collect(Collectors.toList()) /** * Collects stream to [Set]. */ fun <T> Stream<T>.set(): Set<T> = this.mutableSet() /** * Collects stream to [MutableSet] */ fun <T> Stream<T>.mutableSet(): MutableSet<T> = this.collect(Collectors.toSet()) /** * Converts the collection to a vector. */ fun <T> Collection<T>.toVector() = Vector(this)
mit
9b54307f123579916987af0755f1a5fa
29.167742
117
0.633369
3.672427
false
false
false
false
B515/Schedule
app/src/main/kotlin/xyz/b515/schedule/ui/view/TodayCoursesFragment.kt
1
1742
package xyz.b515.schedule.ui.view import android.app.Fragment import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.support.v7.widget.DefaultItemAnimator import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_today.view.* import xyz.b515.schedule.Constant import xyz.b515.schedule.R import xyz.b515.schedule.db.CourseManager import xyz.b515.schedule.ui.adapter.CourseAdapter import java.util.* /** * Created by Yun on 2017.4.24. */ class TodayCoursesFragment : Fragment() { lateinit var adapter: CourseAdapter private val manager: CourseManager by lazy { CourseManager(context) } private val preferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_today, container, false) adapter = CourseAdapter(arrayListOf()) view.recycler.adapter = adapter view.recycler.itemAnimator = DefaultItemAnimator() val today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) val currentWeek = preferences.getInt(Constant.CURRENT_WEEK, -1) + 1 adapter.items.clear() manager.getAllCourse() .flatMap { it.spacetimes!! } .filter { it.weekday == today } .filter { currentWeek in it.startWeek..it.endWeek } .sortedBy { it.startTime } .forEach { adapter.items.add(it.course) } adapter.notifyDataSetChanged() return view } }
apache-2.0
0109c9d8b668af60650498f90fe10f71
35.291667
116
0.71814
4.410127
false
false
false
false
FHannes/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt
11
7261
package org.jetbrains.builtInWebServer import com.google.common.base.Function import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import com.intellij.ProjectTopics import com.intellij.openapi.application.Application import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.SmartList import com.intellij.util.containers.computeIfAny import com.intellij.util.io.exists import java.nio.file.Paths import java.util.concurrent.TimeUnit private val cacheSize: Long = 4096 * 4 /** * Implement [WebServerRootsProvider] to add your provider */ class WebServerPathToFileManager(application: Application, private val project: Project) { val pathToInfoCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()!! // time to expire should be greater than pathToFileCache private val virtualFileToPathInfo = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>() internal val pathToExistShortTermCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()!! /** * https://youtrack.jetbrains.com/issue/WEB-25900 * * Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search * (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir) */ internal val parentToSuitableRoot = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, List<SuitableRoot>>( CacheLoader.from(Function { path -> val suitableRoots = SmartList<SuitableRoot>() var moduleQualifier: String? = null val modules = runReadAction { ModuleManager.getInstance(project).modules } for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } for (root in rootProvider.getRoots(module.rootManager)) { if (root.findChild(path!!) != null) { if (moduleQualifier == null) { moduleQualifier = getModuleNameQualifier(project, module) } suitableRoots.add(SuitableRoot(root, moduleQualifier)) } } } } suitableRoots }))!! init { application.messageBus.connect(project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { for (event in events) { if (event is VFileContentChangeEvent) { val file = event.file for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) { if (rootsProvider.isClearCacheOnFileContentChanged(file)) { clearCache() break } } } else { clearCache() break } } } }) project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { clearCache() } }) } companion object { @JvmStatic fun getInstance(project: Project) = ServiceManager.getService(project, WebServerPathToFileManager::class.java)!! } private fun clearCache() { pathToInfoCache.invalidateAll() virtualFileToPathInfo.invalidateAll() pathToExistShortTermCache.invalidateAll() parentToSuitableRoot.invalidateAll() } @JvmOverloads fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? { return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile() } @JvmOverloads fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? { var pathInfo = pathToInfoCache.getIfPresent(path) if (pathInfo == null || !pathInfo.isValid) { if (pathToExistShortTermCache.getIfPresent(path) == false) { return null } pathInfo = doFindByRelativePath(path, pathQuery) if (cacheResult) { if (pathInfo != null && pathInfo.isValid) { pathToInfoCache.put(path, pathInfo) } else { pathToExistShortTermCache.put(path, false) } } } return pathInfo } fun getPath(file: VirtualFile) = getPathInfo(file)?.path fun getPathInfo(child: VirtualFile): PathInfo? { var result = virtualFileToPathInfo.getIfPresent(child) if (result == null) { result = WebServerRootsProvider.EP_NAME.extensions.computeIfAny { it.getPathInfo(child, project) } if (result != null) { virtualFileToPathInfo.put(child, result) } } return result } internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? { val result = WebServerRootsProvider.EP_NAME.extensions.computeIfAny { it.resolve(path, project, pathQuery) } ?: return null result.file?.let { virtualFileToPathInfo.put(it, result) } return result } fun getResolver(path: String) = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER } interface FileResolver { fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo? } private val RELATIVE_PATH_RESOLVER = object : FileResolver { override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? { // WEB-17691 built-in server doesn't serve files it doesn't have in the project tree // temp:// reports isInLocalFileSystem == true, but it is not true if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") { return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) } } val file = Paths.get(root.path, path) return if (file.exists()) { PathInfo(file, null, root, moduleName, isLibrary) } else { null } } } private val EMPTY_PATH_RESOLVER = object : FileResolver { override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? { val file = findIndexFile(root) ?: return null return PathInfo(null, file, root, moduleName, isLibrary) } } internal val defaultPathQuery = PathQuery()
apache-2.0
990ebc814ae254b809ddc366b21867cd
38.467391
161
0.707754
4.748855
false
false
false
false
NextFaze/dev-fun
dokka/src/main/java/wiki/Components.kt
1
17838
package wiki import com.nextfaze.devfun.DeveloperAnnotation import com.nextfaze.devfun.category.DeveloperCategory import com.nextfaze.devfun.compiler.DevFunProcessor import com.nextfaze.devfun.core.DevFun import com.nextfaze.devfun.core.call import com.nextfaze.devfun.core.devFun import com.nextfaze.devfun.function.DeveloperFunction import com.nextfaze.devfun.function.DeveloperProperty import com.nextfaze.devfun.function.FunctionItem import com.nextfaze.devfun.httpd.DevHttpD import com.nextfaze.devfun.httpd.devDefaultPort import com.nextfaze.devfun.httpd.frontend.HttpFrontEnd import com.nextfaze.devfun.inject.CompositeInstanceProvider import com.nextfaze.devfun.inject.InstanceProvider import com.nextfaze.devfun.inject.dagger2.InjectFromDagger2 import com.nextfaze.devfun.inject.dagger2.tryGetInstanceFromComponent import com.nextfaze.devfun.inject.dagger2.useAutomaticDagger2Injector import com.nextfaze.devfun.invoke.view.ColorPicker import com.nextfaze.devfun.menu.DevMenu import com.nextfaze.devfun.menu.MenuController import com.nextfaze.devfun.menu.controllers.CogOverlay import com.nextfaze.devfun.menu.controllers.KeySequence import com.nextfaze.devfun.reference.Dagger2Component import com.nextfaze.devfun.reference.Dagger2Scope import com.nextfaze.devfun.reference.DeveloperLogger import com.nextfaze.devfun.reference.DeveloperReference import com.nextfaze.devfun.stetho.DevStetho import com.nextfaze.devfun.utils.glide.GlideUtils import com.nextfaze.devfun.utils.leakcanary.LeakCanaryUtils import java.util.ServiceLoader /** DevFun is designed to be modular, in terms of both its dependencies (limiting impact to main source tree) and its plugin-like architecture. ![Component Dependencies](https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/uml/components.png) * <!-- START doctoc generated TOC please keep comment here to allow auto update --> * <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> * * * - [Main Modules](#main-modules) * - [Annotations](#annotations) * - [Compiler](#compiler) * - [Gradle Plugin](#gradle-plugin) * - [Core Modules](#core-modules) * - [DevFun](#devfun) * - [Menu](#menu) * - [Inject Modules](#inject-modules) * - [Dagger 2](#dagger-2) * - [Supported Versions](#supported-versions) * - [Limitations](#limitations) * - [Instance and Component Resolution](#instance-and-component-resolution) * - [Reflection Based](#reflection-based) * - [Annotation Based](#annotation-based) * - [Custom Instance Provider](#custom-instance-provider) * - [Util Modules](#util-modules) * - [Glide](#glide) * - [Leak Canary](#leak-canary) * - [Invoke Modules](#invoke-modules) * - [Color Picker View](#color-picker-view) * - [Experimental Modules](#experimental-modules) * - [HttpD](#httpd) * - [Custom Port](#custom-port) * - [Http Front-end](#http-front-end) * - [Stetho](#stetho) * * <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Main Modules Minimum required libraries - annotations and annotation processor. `IMG_START<img src="https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/gif/enable-sign-in.gif" alt="DevFun demonstration" width="35%" align="right"/>IMG_END` ### Annotations Provides DevFun annotations and various interface definitions: - [DeveloperFunction] - [DeveloperCategory] - [DeveloperReference] - [DeveloperAnnotation] - [DeveloperLogger] - [DeveloperProperty] - [Dagger2Component] This library contains primarily interface definitions and inline functions, and will have a negligible impact on your method count and dex sizes. Apply to your main `compile` configuration: * ```kotlin * implementation("com.nextfaze.devfun:devfun-annotations:2.1.0") * ``` ### Compiler Annotation processor [DevFunProcessor] that handles [DeveloperFunction], [DeveloperCategory], [DeveloperReference], and [DeveloperAnnotation] annotations. This should be applied to your non-main kapt configuration 'kaptDebug' to avoid running/using it on release builds. * ```kotlin * kaptDebug("com.nextfaze.devfun:devfun-compiler:2.1.0") * ``` Configuration options can be applied using Android DSL: * ```kotlin * android { * defaultConfig { * javaCompileOptions { * annotationProcessorOptions { * argument("devfun.argument", "value") * } * } * } * } * ``` Full list available at [com.nextfaze.devfun.compiler]. ### Gradle Plugin Used to configure/provide the compiler with the project/build configurations. In your `build.gradle` add the DevFun Gradle plugin to your build script. If you can use the Gradle `plugins` block (which you should be able to do - this locates and downloads it for you): * ```kotlin * plugins { * id("com.nextfaze.devfun") version "2.1.0" * } * ``` __Or__ the legacy method using `apply`; Add the plugin to your classpath (found in the `jcenter()` repository): * ```kotlin * buildscript { * dependencies { * classpath("com.nextfaze.devfun:devfun-gradle-plugin:2.1.0") * } * } * ``` And in your `build.gradle`: * ```kotlin * apply { * plugin("com.nextfaze.devfun") * } * ``` ## Core Modules Modules that extend the accessibility of DevFun (e.g. add menu/http server). _Also see [Experimental Modules](#experimental-modules) below._ ### DevFun Core of [DevFun]. Loads modules and definitions. Apply to your non-main configuration: * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun:2.1.0") * ``` Modules are loaded by [DevFun] using Java's [ServiceLoader]. [DevFun] loads, transforms, and sorts the generated function definitions, again via the [ServiceLoader] mechanism. To inject function invocations, [InstanceProvider]s are used, which will attempt to locate (or create) object instances. A composite instance provider [CompositeInstanceProvider] at [DevFun.instanceProviders] is used via convenience function (extension) [FunctionItem.call] that uses the currently loaded [devFun] instance. If using Dagger 2.x, you can use the `devfun-inject-dagger2` module for a simple reflection based provider or related helper functions. A heavily reflective version will be used automatically, but if it fails (e.g. it expects a `Component` in your application class), a manual implementation can be provided. See the demo app [DemoInstanceProvider](https://github.com/NextFaze/dev-fun/tree/master/demo/src/debug/java/com/nextfaze/devfun/demo/devfun/DevFun.kt#L52) for a sample implementation. `IMG_START<img src="https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/gif/registration-flow.gif" alt="Menu demonstration" width="35%" align="right"/>IMG_END` ### Menu Adds a developer menu [DevMenu], accessible by a floating cog [CogOverlay] (long-press to drag) or device button sequence [KeySequence]. * ```kotlin * debugImplementation("com.nextfaze.devfun:menu:2.1.0") * ``` Button sequences: *(this are not configurable at the moment but are intended to be eventually)* * ```kotlin * internal val GRAVE_KEY_SEQUENCE = KeySequence.Definition( * keyCodes = intArrayOf(KeyEvent.KEYCODE_GRAVE), * description = R.string.df_menu_grave_sequence, * consumeEvent = true * ) * internal val VOLUME_KEY_SEQUENCE = KeySequence.Definition( * keyCodes = intArrayOf( * KeyEvent.KEYCODE_VOLUME_DOWN, * KeyEvent.KEYCODE_VOLUME_DOWN, * KeyEvent.KEYCODE_VOLUME_UP, * KeyEvent.KEYCODE_VOLUME_DOWN * ), * description = R.string.df_menu_volume_sequence, * consumeEvent = false * ) * ``` Menu controllers implement [MenuController] and can be added via `devFun.module<DevMenu>() += MyMenuController()`. ## Inject Modules Modules to facilitate dependency injection for function invocation. ### Dagger 2 Adds module [InjectFromDagger2] which adds an [InstanceProvider] that can reflectively locate components or (if used) resolve [Dagger2Component] uses. Tested from Dagger 2.4 to 2.17. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-inject-dagger2:2.1.0") * ``` Simply graphs should be well supported. More complex graphs _should_ work (it has been working well in-house). Please report any issues you encounter. The module also provides a variety of utility functions for manually providing your own instance provider using your components. See below for more details. _I'm always looking into better ways to support this, comments/suggestions are welcome._ - Currently kapt doesn't support multi-staged processing of generated Kotlin code. - Possibly consider generating Java `Component` interfaces for some types? - Likely will investigate the new SPI functionality in Dagger 2.17+ once it becomes more stable. #### Supported Versions Dagger has been tested on the demo app from versions 2.4 to 2.17, and various in-house apps on more recent versions, and should function correctly for most simple scopes/graphs. For reference the demo app uses three scopes; Singleton, Retained (fragments), and an Activity scope. It uses both type-annotated scoping and provides scoping. It keeps component instances in the activity and obtains the singleton scope via an extension function. In general this should cover most use cases - if you encounter any problems please create an issue. #### Limitations DevFun uses a number of methods iteratively to introspect the generated components/modules, however depending on scoping, visibility, and instantiation of a type it can be difficult to determine the source/scope in initial (but faster) introspection methods. When all else fails DevFun will use a form of heavy reflection to introspect the generated code - types with a custom scope and no constructor arguments are not necessarily obtainable from Dagger (depends on the version) by any other means. To help with this ensure your scope is `@Retention(RUNTIME)` so that DevFun wont unintentionally create a new instance when it can't find it right away. Due to the way Dagger generates/injects it is not possible to obtain the instance of non-scoped types from the generated component/module as its instance is created/injected once (effectively inlined) at the inject site. It is intended to allow finding instances based on the context of the dev. function in the future (i.e. if the dev. function is in a fragment then check for the injected instance in the fragment etc.) - if this is desirable sooner make a comment in the issue [#26](https://github.com/NextFaze/dev-fun/issues/26). #### Instance and Component Resolution Unless you specify [Dagger2Component] annotations, DevFun will use a heavy-reflection based provider. Where possible DevFun will cache the locations of where it found various types - this is somewhat loose in that the provider cache still attempts to be aware of scoping. ##### Reflection Based By default simply including the module will use the reflection-based component locator. It will attempt to locate your component objects in your application class and/or your activity classes and use aforementioned utility functions. If you place one or more [Dagger2Component] annotations (see below), then the reflective locator wont be used. ##### Annotation Based For more control, or if the above method doesn't (such as if you use top-level extension functions to retrieve your components, or you put them in weird places, or for whatever reason), then you can annotate the functions/getters with [Dagger2Component]. The scope/broadness/priority can be set on the annotation either via [Dagger2Component.scope] or [Dagger2Component.priority]. If unset then the scope will be assumed based on the context of its location (i.e. in Application class > probably the top level component, if static then first argument assumed to be the receiver, etc). Note: For properties you can annotated to property itself (`@Dagger2Component`) or the getter explicitly (`@get:Dagger2Component`) if for some reason on the property doesn't work (which could happen if it can't find your getter - which is done via method name string manipulation due to KAPT limitations. Example usage: - Where a top-level/singleton/application component is retrieved via an extension function _(from the demo)_: * ```kotlin * @Dagger2Component * val Context.applicationComponent: ApplicationComponent? * get() = (applicationContext as DaggerApplication).applicationComponent *``` - Where a component is kept in the activity _(from the demo)_: * ```kotlin * @get:Dagger2Component // if we want to specify getter explicitly * lateinit var activityComponent: ActivityComponent * private set * ``` - Where a differently scoped component is also kept in the activity, we can set the scope manually ([Dagger2Scope]) _(from the demo)_: * ```kotlin * @get:Dagger2Component(Dagger2Scope.RETAINED_FRAGMENT) * lateinit var retainedComponent: RetainedComponent * private set * ``` ##### Custom Instance Provider Since the reflection locator and annotation based still make assumptions and are bit inefficient because of it, sometimes you may need to implement your own instance provider. - Disable the automatic locator: set [useAutomaticDagger2Injector] to `false` (can be done at any time). - Add your own provider using `devFun += MyProvider` (see [InstanceProvider] for more details). - Utility function [tryGetInstanceFromComponent] to help (though again it relies heavily on reflection and don't consider scoping very well). See demo for example implementation: [DemoInstanceProvider](https://github.com/NextFaze/dev-fun/tree/master/demo/src/debug/java/com/nextfaze/devfun/demo/devfun/DevFun.kt#L52) ## Util Modules Modules with frequently used or just handy functions (e.g. show Glide memory use). Developers love reusable utility functions, we all have them, and we usually copy-paste them into new projects. Adding them to modules and leveraging dependency injection allows for non-static, easily invokable code reuse. _Still playing with this concept and naming conventions etc._ ### Glide Module [GlideUtils] provides some utility functions when using Glide. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-util-glide:2.1.0") * ``` Features: - Clear memory cache - Clear disk cache - Log current memory/disk cache usage ### Leak Canary Module [LeakCanaryUtils] provides some utility functions when using Leak Canary. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-util-leakcanary:2.1.0") * ``` Features: - Launch `DisplayLeakActivity` `IMG_START<img src="https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/images/color-picker.png" alt="Invocation UI with custom color picker view" width="35%" align="right"/>IMG_END` ## Invoke Modules Modules to facilitate function invocation. ### Color Picker View Adds a parameter annotation [ColorPicker] that lets the invocation UI render a color picker view for the associated argument. _Note: Only needed if you don't include `devfun-menu` (as it uses/includes the color picker transitively)._ * ```kotlin * debugImplementation("com.nextfaze.devfun-invoke-view-colorpicker:2.1.0") * ``` ## Experimental Modules These modules are mostly for use experimenting with various use-cases. They generally work, but are likely to be buggy and have various limitations and nuances. Having said that, it would be nice to expand upon them and make them nicer/more feature reach in the future. Some future possibilities: - HttpD: Use ktor instead of Nano - HttpD Simple Index: Provide a themed react page or something pretty/nice - Add a Kotlin REPL module ### HttpD Module [DevHttpD] adds a local HTTP server (uses [NanoHttpD](https://github.com/NanoHttpd/nanohttpd)). Provides a single `POST` method `invoke` with one parameter `hashCode` (expecting [FunctionItem.hashCode]) * ```kotlin * debugImplementation("com.nextfaze.devfun:httpd:2.1.0") * ``` Use with HttpD Front-end. _Current port and access instructions are logged on start._ Default port is `23075`. If this is in use another is deterministically generated from your package (this might become the default). If using AVD, forward port: ```bash adb forward tcp:23075 tcp:23075 ``` Then access via IP: [http://127.0.0.1:23075/](http://127.0.0.1:23075/) #### Custom Port Can be set via resources: ```xml <integer name="df_httpd_default_port">12345</integer> ``` Or before initialization [devDefaultPort] (i.e. if not using auto-init content provider): ```kotlin devDefaultPort = 12345 // top level value located in com.nextfaze.devfun.httpd ``` ### Http Front-end Module [HttpFrontEnd] generates an admin interface using SB Admin 2 (similar to [DevMenu]), allowing function invocation from a browser. __Depends on [DevHttpD].__ * ```kotlin * debugImplementation("com.nextfaze.devfun:httpd-frontend:2.1.0") * ``` Page is rather simple at the moment, but in the future it's somewhat intended (as a learning exercise) to create a React front end using Kotlin or something. ![HTTP Server](https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/images/httpd-auth-context.png) ### Stetho Module [DevStetho] allows generated methods to be invoked from Chrome's Dev Tools JavaScript console. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-stetho:2.1.0") * ``` Opening console will show available functions. e.g. `Context_Enable_Account_Creation()` _Extremely experimental and limited functionality._ ![Stetho Integration](https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/images/stetho-auth.png) */ object Components /** Here to ensure the `.call` extension function stays in the import list (Kotlin IDE bug). */ @Suppress("unused") private val dummy = (Any() as FunctionItem).call()
apache-2.0
83a8f7c29fc1dcd808cbdea94accbecd
40.873239
241
0.755522
3.977258
false
false
false
false
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/data/dao/LectureInformationDao.kt
1
3720
package jp.kentan.studentportalplus.data.dao import jp.kentan.studentportalplus.data.component.LectureAttend import jp.kentan.studentportalplus.data.component.PortalContent import jp.kentan.studentportalplus.data.model.LectureInformation import jp.kentan.studentportalplus.data.parser.LectureAttendParser import jp.kentan.studentportalplus.data.parser.LectureInformationParser import jp.kentan.studentportalplus.util.JaroWinklerDistance import org.jetbrains.anko.db.SqlOrderDirection import org.jetbrains.anko.db.delete import org.jetbrains.anko.db.select import org.jetbrains.anko.db.update class LectureInformationDao( private val database: DatabaseOpenHelper, var similarThreshold: Float ) : BaseDao() { companion object { const val TABLE_NAME = "lecture_info" private val PARSER = LectureInformationParser() private val LECTURE_ATTEND_PARSER = LectureAttendParser() private val STRING_DISTANCE = JaroWinklerDistance() } fun getAll(): List<LectureInformation> = database.use { val myClassList = select(MyClassDao.TABLE_NAME, "subject, user").parseList(LECTURE_ATTEND_PARSER) select(TABLE_NAME) .orderBy("updated_date", SqlOrderDirection.DESC) .orderBy("subject") .parseList(PARSER) .map { it.copy(attend = myClassList.calcLectureAttend(it.subject)) } } fun update(data: LectureInformation): Int = database.use { update(TABLE_NAME, "read" to data.isRead.toLong()) .whereArgs("_id = ${data.id}") .exec() } fun updateAll(list: List<LectureInformation>) = database.use { beginTransaction() val updatedContentList = mutableListOf<PortalContent>() var st = compileStatement("INSERT OR IGNORE INTO $TABLE_NAME VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);") // Insert new data list.forEach { st.bindNull(1) st.bindLong(2, it.hash) st.bindString(3, it.grade) st.bindString(4, it.semester) st.bindString(5, it.subject) st.bindString(6, it.instructor) st.bindString(7, it.week) st.bindString(8, it.period) st.bindString(9, it.category) st.bindString(10, it.detailText) st.bindString(11, it.detailHtml) st.bindLong(12, it.createdDate.time) st.bindLong(13, it.updatedDate.time) st.bindLong(14, it.isRead.toLong()) val id = st.executeInsert() if (id > 0) { updatedContentList.add(PortalContent(id, it.subject, it.detailText)) } st.clearBindings() } // Delete old data if (list.isNotEmpty()) { val args = StringBuilder("?") for (i in 2..list.size) { args.append(",?") } st = compileStatement("DELETE FROM $TABLE_NAME WHERE hash NOT IN ($args)") list.forEachIndexed { i, d -> st.bindLong(i + 1, d.hash) } st.executeUpdateDelete() } else { delete(TABLE_NAME) } setTransactionSuccessful() endTransaction() return@use updatedContentList } private fun List<Pair<String, LectureAttend>>.calcLectureAttend(subject: String): LectureAttend { // If match subject firstOrNull { it.first == subject }?.run { return second } // If similar if (any { STRING_DISTANCE.getDistance(it.first, subject) >= similarThreshold }) { return LectureAttend.SIMILAR } return LectureAttend.NOT } }
gpl-3.0
e6c0e504fe066e538d702404a918526d
32.522523
107
0.610753
4.423306
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/ui/StartDateViewModel.kt
1
3333
package com.todoroo.astrid.ui import androidx.lifecycle.ViewModel import com.todoroo.astrid.data.Task import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import org.tasks.R import org.tasks.date.DateTimeUtils.toDateTime import org.tasks.dialogs.StartDatePicker import org.tasks.dialogs.StartDatePicker.Companion.DAY_BEFORE_DUE import org.tasks.dialogs.StartDatePicker.Companion.DUE_DATE import org.tasks.dialogs.StartDatePicker.Companion.DUE_TIME import org.tasks.dialogs.StartDatePicker.Companion.WEEK_BEFORE_DUE import org.tasks.preferences.Preferences import org.tasks.time.DateTimeUtils.millisOfDay import org.tasks.time.DateTimeUtils.startOfDay import javax.inject.Inject @HiltViewModel class StartDateViewModel @Inject constructor( private val preferences: Preferences ) : ViewModel() { private val _selectedDay = MutableStateFlow(StartDatePicker.NO_DAY) val selectedDay: StateFlow<Long> get() = _selectedDay.asStateFlow() private val _selectedTime = MutableStateFlow(StartDatePicker.NO_TIME) val selectedTime: StateFlow<Int> get() = _selectedTime.asStateFlow() fun init(dueDate: Long, startDate: Long, isNew: Boolean) { val dueDay = dueDate.startOfDay() val dueTime = dueDate.millisOfDay() val hideUntil = startDate.takeIf { it > 0 }?.toDateTime() if (hideUntil == null) { if (isNew) { _selectedDay.value = when (preferences.getIntegerFromString(R.string.p_default_hideUntil_key, Task.HIDE_UNTIL_NONE)) { Task.HIDE_UNTIL_DUE -> DUE_DATE Task.HIDE_UNTIL_DUE_TIME -> DUE_TIME Task.HIDE_UNTIL_DAY_BEFORE -> DAY_BEFORE_DUE Task.HIDE_UNTIL_WEEK_BEFORE -> WEEK_BEFORE_DUE else -> 0L } } } else { _selectedDay.value = hideUntil.startOfDay().millis _selectedTime.value = hideUntil.millisOfDay _selectedDay.value = when (_selectedDay.value) { dueDay -> if (_selectedTime.value == dueTime) { _selectedTime.value = StartDatePicker.NO_TIME DUE_TIME } else { DUE_DATE } dueDay.toDateTime().minusDays(1).millis -> DAY_BEFORE_DUE dueDay.toDateTime().minusDays(7).millis -> WEEK_BEFORE_DUE else -> _selectedDay.value } } } fun setSelected(selectedDay: Long, selectedTime: Int) { _selectedDay.value = selectedDay _selectedTime.value = selectedTime } fun getSelectedValue(dueDate: Long): Long { val due = dueDate.takeIf { it > 0 }?.toDateTime() return when (selectedDay.value) { DUE_DATE -> due?.withMillisOfDay(selectedTime.value)?.millis ?: 0 DUE_TIME -> due?.millis ?: 0 DAY_BEFORE_DUE -> due?.minusDays(1)?.withMillisOfDay(selectedTime.value)?.millis ?: 0 WEEK_BEFORE_DUE -> due?.minusDays(7)?.withMillisOfDay(selectedTime.value)?.millis ?: 0 else -> selectedDay.value + selectedTime.value } } }
gpl-3.0
0b703c25caaad750e5a3f774c33aff61
40.160494
134
0.640864
4.328571
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/CopyFilesTask.kt
1
1590
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.tools.places import uk.co.nickthecoder.paratask.AbstractTask import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.parameters.FileParameter import uk.co.nickthecoder.paratask.parameters.MultipleParameter import uk.co.nickthecoder.paratask.util.process.Exec import uk.co.nickthecoder.paratask.util.process.OSCommand class CopyFilesTask : AbstractTask() { override val taskD = TaskDescription("copyFiles") val filesP = MultipleParameter("files", minItems = 1) { FileParameter("file", expectFile = null, mustExist = true) } val toDirectoryP = FileParameter("toDirectory", mustExist = true, expectFile = false) init { taskD.addParameters(filesP, toDirectoryP) } override fun run() { val command = OSCommand("cp", "--archive", "--", filesP.value, toDirectoryP.value!!) Exec(command).start().waitFor() } }
gpl-3.0
ed8dc0f47c97efa28232abb1bf6a140f
35.976744
120
0.759748
4.228723
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/autocomplete/AutocompleteSettingsFragment.kt
1
1864
/* 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: androidx.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
777295098f0528defb430fa4090a2a16
34.169811
113
0.720494
5.092896
false
false
false
false
antoniolg/KataContactsKotlin
src/main/java/com/antonioleiva/kataagenda/ui/SysOutContactsListView.kt
1
1717
/* * Copyright (C) 2015 Antonio Leiva * * 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.antonioleiva.kataagenda.ui import com.antonioleiva.kataagenda.domain.Contact class SysOutContactsListView : ContactsListPresenter.View { override fun showWelcomeMessage() { println("Welcome to your awesome agenda!") println("I'm going to ask you about some of your contacts information :)") } override fun showGoodbyeMessage() { println("\n\nSee you soon!") } override fun showContacts(contactList: List<Contact>) { println() contactList.forEach { println("${it.firstName} - ${it.lastName} - ${it.phone}") } println() } override fun getNewContactFirstName(): String = readLine("First Name: ") override fun getNewContactLastName(): String = readLine("Last Name: ") override fun getNewContactPhoneNumber(): String = readLine("Phone Number: ") override fun showDefaultError() = println("Ups, something went wrong :( Try again!") override fun showEmptyCase() = println("Your agenda is empty!") private fun readLine(message: String): String { print(message) return readLine() ?: "" } }
apache-2.0
c7d95a70fd33c932d16de8522d224aa8
32.038462
89
0.695399
4.413882
false
false
false
false
wiltonlazary/kotlin-native
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/tasks/KonanBuildingTask.kt
1
2099
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.gradle.plugin.tasks import org.gradle.api.tasks.Console import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.jetbrains.kotlin.gradle.plugin.konan.* import org.jetbrains.kotlin.gradle.plugin.model.KonanModelArtifact import org.jetbrains.kotlin.konan.target.KonanTarget import java.io.File /** Base class for both interop and compiler tasks. */ abstract class KonanBuildingTask: KonanArtifactWithLibrariesTask(), KonanBuildingSpec { @get:Internal internal abstract val toolRunner: KonanToolRunner internal abstract fun toModelArtifact(): KonanModelArtifact override fun init(config: KonanBuildingConfig<*>, destinationDir: File, artifactName: String, target: KonanTarget) { dependsOn(project.konanCompilerDownloadTask) super.init(config, destinationDir, artifactName, target) } @Console var dumpParameters: Boolean = false @Input val extraOpts = mutableListOf<String>() val konanHome @Input get() = project.konanHome val konanVersion @Input get() = project.konanVersion.toString(true, true) @TaskAction abstract fun run() // DSL. override fun dumpParameters(flag: Boolean) { dumpParameters = flag } override fun extraOpts(vararg values: Any) = extraOpts(values.toList()) override fun extraOpts(values: List<Any>) { extraOpts.addAll(values.map { it.toString() }) } }
apache-2.0
cf149dde8ee94d630cea2c7d4d3712ab
31.292308
120
0.736065
4.231855
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-github/layout/src/main/java/com/bennyhuo/dsl/layout/v1/DslViewParent.kt
2
2216
package com.bennyhuo.dsl.layout.v1 import android.annotation.TargetApi import android.os.Build.VERSION_CODES import android.view.View import android.view.ViewGroup import kotlin.annotation.AnnotationTarget.* @DslMarker @Target(CLASS, TYPE, TYPEALIAS) annotation class DslViewMarker @DslViewMarker interface DslViewParent<out P : ViewGroup.MarginLayoutParams> { val <T : View> T.lparams: P get() = layoutParams as P var <T : View> T.leftMargin: Int set(value) { lparams.leftMargin = value } get() { return lparams.leftMargin } var <T : View> T.topMargin: Int set(value) { lparams.topMargin = value } get() { return lparams.topMargin } var <T : View> T.rightMargin: Int set(value) { lparams.rightMargin = value } get() { return lparams.rightMargin } var <T : View> T.bottomMargin: Int set(value) { lparams.bottomMargin = value } get() { return lparams.bottomMargin } @get:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) @set:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) var <T : View> T.startMargin: Int set(value) { lparams.marginStart = value } get() { return lparams.marginStart } @get:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) @set:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) var <T : View> T.endMargin: Int set(value) { lparams.marginEnd = value } get() { return lparams.marginEnd } fun <T : View> T.margin(margin: Int) { leftMargin = margin topMargin = margin rightMargin = margin bottomMargin = margin startMargin = margin endMargin = margin } var <T : View> T.layoutWidth: Int set(value) { lparams.width = value } get() { return lparams.width } var <T : View> T.layoutHeight: Int set(value) { lparams.height = value } get() { return lparams.height } }
apache-2.0
c81883bac3efcb5550f35a53a2e4cd3b
22.326316
63
0.550993
4.237094
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/map/MapFragment.kt
1
21040
package com.telenav.osv.map import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.location.Location import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.mapbox.mapboxsdk.geometry.LatLng import com.mapbox.mapboxsdk.maps.MapboxMap import com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.REASON_API_GESTURE import com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION import com.mapbox.mapboxsdk.maps.Style import com.telenav.osv.R import com.telenav.osv.activity.KVActivityTempBase import com.telenav.osv.activity.LocationPermissionsListener import com.telenav.osv.activity.MainActivity import com.telenav.osv.activity.OSVActivity import com.telenav.osv.application.ApplicationPreferences import com.telenav.osv.application.KVApplication import com.telenav.osv.application.PreferenceTypes import com.telenav.osv.common.Injection import com.telenav.osv.common.dialog.KVDialog import com.telenav.osv.databinding.FragmentMapBinding import com.telenav.osv.jarvis.login.utils.LoginUtils import com.telenav.osv.location.LocationService import com.telenav.osv.manager.playback.PlaybackManager import com.telenav.osv.map.model.* import com.telenav.osv.map.model.MapModes import com.telenav.osv.map.render.MapRender import com.telenav.osv.map.render.template.MapRenderTemplateIdentifier import com.telenav.osv.map.viewmodel.MapViewModel import com.telenav.osv.recorder.gpsTrail.ListenerRecordingGpsTrail import com.telenav.osv.tasks.activity.KEY_TASK_ID import com.telenav.osv.tasks.activity.TaskActivity import com.telenav.osv.ui.ScreenComposer import com.telenav.osv.ui.fragment.DisplayFragment import com.telenav.osv.ui.fragment.camera.controls.viewmodel.RecordingViewModel import com.telenav.osv.utils.Log import com.telenav.osv.utils.LogUtils import com.telenav.osv.utils.PermissionUtils import com.telenav.osv.utils.Utils import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_map.* /** * Fragment which represent the map feature. Holds logic in order to render a usable map by using the internal [MapboxMap] and helper [MapRender]. */ class MapFragment(private var mapMode: MapModes = MapModes.IDLE, private var playbackManager: PlaybackManager? = null) : DisplayFragment(), LocationPermissionsListener, ListenerRecordingGpsTrail { init { TAG = MapFragment::class.java.simpleName } private var mapRender: MapRender? = null private lateinit var appPrefs: ApplicationPreferences private var mapboxMap: MapboxMap? = null private lateinit var fragmentMapBinding: FragmentMapBinding private lateinit var locationService: LocationService private lateinit var recordingViewModel: RecordingViewModel private val disposables: CompositeDisposable = CompositeDisposable() private var sessionExpireDialog: KVDialog? = null private val mapClickListener: MapboxMap.OnMapClickListener = MapboxMap.OnMapClickListener { if (LoginUtils.isLoginTypePartner(appPrefs)) { val selectedGridId = mapRender?.mapGridClick(it) if (selectedGridId != null) { val taskDetailsIntent = Intent(context, TaskActivity::class.java) taskDetailsIntent.putExtra(KEY_TASK_ID, selectedGridId) context?.startActivity(taskDetailsIntent) return@OnMapClickListener true } else return@OnMapClickListener mapViewModel.onNearbySequencesClick(it) } else { return@OnMapClickListener mapViewModel.onNearbySequencesClick(it) } } private val onCameraMoveStartedListener: MapboxMap.OnCameraMoveStartedListener = MapboxMap.OnCameraMoveStartedListener { if (it == REASON_API_GESTURE || it == REASON_DEVELOPER_ANIMATION) { onMapMove() } } private val mapViewModel: MapViewModel by lazy { ViewModelProviders.of(this, Injection.provideMapViewFactory(Injection.provideLocationLocalDataSource(context!!), Injection.provideUserRepository(context!!), Injection.provideGridsLoader( Injection.provideFetchAssignedTasksUseCase( Injection.provideTasksApi(true, Injection.provideApplicationPreferences(context!!))), Injection.provideGenericJarvisApiErrorHandler(context!!, Injection.provideApplicationPreferences(context!!))), Injection.provideGeometryRetriever(context!!, Injection.provideNetworkFactoryUrl(Injection.provideApplicationPreferences(context!!))), Injection.provideApplicationPreferences(context!!), recordingViewModel)).get(MapViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate") this.recordingViewModel = ViewModelProviders.of(activity!!).get(RecordingViewModel::class.java) activity?.let { appPrefs = (it.application as KVApplication).appPrefs locationService = Injection.provideLocationService(it.applicationContext) initLocation() } if (savedInstanceState != null) { Log.d(TAG, "onCreate. Status: restore saved instance state.") val savedMapMode = MapModes.getByType(savedInstanceState.getInt(KEY_MAP_MODE)) if (savedMapMode != null) { this.mapMode = savedMapMode } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { fragmentMapBinding = FragmentMapBinding.inflate(inflater, container, false).apply { clickListenerCamera = View.OnClickListener { activity?.let { if (it is MainActivity) { it.goToRecordingScreen() } } } clickListenerCenter = View.OnClickListener { getLastKnowLocationAsync { location -> mapRender?.centerOnCurrentLocation(location) } } lifecycleOwner = this@MapFragment viewModel = mapViewModel } return fragmentMapBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fragmentMapBinding.tvTasks.setOnClickListener { context?.startActivity(Intent(context, TaskActivity::class.java)) } observerOnLoginDialog() observeOnNearbySequences() observeOnEnableProgress() observeOnMapRender() observeOnMapUpdate() observeOnRecordingStateChanged() setMarginForRecordingIfRequired() mapView?.onCreate(savedInstanceState) } override fun onStart() { mapViewModel.enableEventBus(true) super.onStart() mapView?.onStart() } override fun onResume() { super.onResume() mapView?.onResume() if (recordingViewModel.isRecording) { recordingViewModel.setListenerRecordingGpsTrail(this) } switchMapMode(mapMode, playbackManager) } override fun onPause() { super.onPause() mapView?.onPause() recordingViewModel.removeListenerRecordingGpsTrail(this) } override fun setSource(extra: Any?) { } override fun onStop() { mapViewModel.enableEventBus(false) super.onStop() mapView?.onStop() } override fun onLowMemory() { super.onLowMemory() mapView?.onLowMemory() } override fun onDestroy() { disposables.clear() super.onDestroy() } override fun onDestroyView() { this.mapboxMap?.removeOnCameraMoveStartedListener(onCameraMoveStartedListener) mapRender?.clearMap() mapView?.onDestroy() Log.d(TAG, "onDestroyView. Map loaded: ${mapView != null}") super.onDestroyView() } override fun onSaveInstanceState(outState: Bundle) { outState.apply { this.putInt(KEY_MAP_MODE, mapMode.mode) } super.onSaveInstanceState(outState) mapView?.onSaveInstanceState(outState) } override fun onLocationPermissionGranted() { LogUtils.logDebug(TAG, "onLocationPermissionGranted. Initialising map.") getLastKnowLocationAsync { location -> mapRender?.centerOnCurrentLocation(location) } initLocation() } override fun onLocationPermissionDenied() { context?.let { Toast.makeText(context, R.string.enable_location_label, Toast.LENGTH_SHORT).show() } } override fun onGpsTrailChanged(gpsTrail: List<Location>) { onMapMove() mapRender?.updateRecording(gpsTrail) } /** * Switches the map mode for the map. This method only exposes the viewModel logic. * //ToDo: to be removed, recommended inject the view model directly for direct control of the fragment. */ fun switchMapMode(mapMode: MapModes, playbackManager: PlaybackManager? = null) { activity?.let { this.mapMode = mapMode //preserve reference to the playback manager for the case when the fragment is not added yet this.playbackManager = playbackManager mapViewModel.setupMapResource(Injection.provideMapBoxOkHttpClient(appPrefs)) if (isAdded) { Log.d(TAG, "Switching map mode: ${mapMode.mode}.") mapViewModel.switchMode(mapMode, playbackManager) } } } private fun setMarginForRecordingIfRequired() { if (mapMode.mode == MapModes.RECORDING.mode) { context?.let { val set = ConstraintSet() set.clone(fragmentMapBinding.root as ConstraintLayout) set.setMargin(R.id.mapView, ConstraintSet.TOP, 0) set.applyTo(fragmentMapBinding.root as ConstraintLayout) } } } private fun observeOnRecordingStateChanged() { recordingViewModel.let { Log.d(TAG, "observeOnRecordingStateChanged. Recording status: ${it.isRecording}") it.recordingObservable?.observe(this, Observer { recordingStatus -> Log.d(TAG, "recordingObservable. Recording status: $recordingStatus") if (recordingStatus) { recordingViewModel.setListenerRecordingGpsTrail(this) } else { mapRender?.clearGpsTrail() recordingViewModel.removeListenerRecordingGpsTrail(this) mapViewModel.switchMode(mapMode, null) } }) } } private fun observeOnNearbySequences() { mapViewModel.nearbySequences.observe(this, Observer { val activity = activity as OSVActivity if (it != null) { activity.openScreen(ScreenComposer.SCREEN_NEARBY, it) } else { activity.showSnackBar(getString(R.string.nearby_no_result_label), Snackbar.LENGTH_SHORT) } }) } /** * This method displays alert dialog for expired session */ private fun showSessionExpiredDialog(context: Context) { if (sessionExpireDialog == null) { sessionExpireDialog = LoginUtils.getSessionExpiredDialog(context) } sessionExpireDialog?.show() } private fun observeOnEnableProgress() { mapViewModel.enableProgress.observe(this, Observer { (activity as OSVActivity).enableProgressBar(it) }) } private fun observerOnLoginDialog() { mapViewModel.shouldReLogin.observe(this, Observer { shouldReLogin -> if (shouldReLogin) { context?.let { showSessionExpiredDialog(it) } } }) } private fun observeOnMapRender() { mapViewModel.mapRender.observe(this, Observer { Log.d(TAG, "observeOnMapRender. Map status change: $it") if (it.value == MapRenderMode.DISABLED.value) { mapRender?.clearMap() val mapView = fragmentMapBinding.root.findViewById(R.id.mapView) as View mapView.visibility = View.GONE } else { loadMap { when (it.value) { MapRenderMode.DEFAULT.value -> { this.mapboxMap?.uiSettings?.setAllGesturesEnabled(true) this.mapboxMap?.addOnCameraMoveStartedListener(onCameraMoveStartedListener) this.mapboxMap?.addOnMapClickListener(mapClickListener) mapRender?.render(MapRenderTemplateIdentifier.DEFAULT) getLastKnowLocationAsync { location -> mapRender?.centerOnCurrentLocation(location) } } MapRenderMode.DEFAULT_WITH_GRID.value -> { this.mapboxMap?.uiSettings?.setAllGesturesEnabled(true) this.mapboxMap?.addOnCameraMoveStartedListener(onCameraMoveStartedListener) mapRender?.render(MapRenderTemplateIdentifier.GRID) this.mapboxMap?.addOnMapClickListener(mapClickListener) getLastKnowLocationAsync { location -> run { mapRender?.centerOnCurrentLocation(location) onMapMove(true) } } } MapRenderMode.PREVIEW.value -> { this.mapboxMap?.uiSettings?.setAllGesturesEnabled(false) this.mapboxMap?.removeOnMapClickListener(mapClickListener) this.mapboxMap?.removeOnCameraMoveStartedListener(onCameraMoveStartedListener) mapRender?.render(MapRenderTemplateIdentifier.PREVIEW) } MapRenderMode.RECORDING.value -> { Log.d(TAG, "loadMap function. Status: map render recording function. Message: Preparing for recording.") this.mapboxMap?.addOnCameraMoveStartedListener(onCameraMoveStartedListener) this.mapboxMap?.uiSettings?.setAllGesturesEnabled(false) this.mapboxMap?.uiSettings?.isZoomGesturesEnabled = true this.mapboxMap?.removeOnMapClickListener(mapClickListener) mapRender?.render(MapRenderTemplateIdentifier.RECORDING) } else -> { //nothing since it is not required to add disabled } } } } }) } private fun observeOnMapUpdate() { mapViewModel.mapRenderUpdate.observe(this, Observer { Log.d(TAG, "observeOnMapUpdate. Map update change: $it") when (it) { is MapUpdateDefault -> { getLastKnowLocationAsync { location -> mapRender?.updateDefault(it.sequences, location) } } is MapUpdateGrid -> { if (it.tasks.isNotEmpty()) { mapRender?.refreshCoverage(it.tasks[0].createdAt) } mapRender?.updateGrid(it.tasks, it.jarvisUserId, it.includeLabels, it.sequences) } is MapUpdatePreview -> { mapRender?.updatePreview(it.localSequence, it.symbolLocation) } is MapUpdateRecording -> { getLastKnowLocationAsync { location -> Log.d(TAG, "loadMap function. Status: centerOnCurrentPosition callback. Message: Preparing for render map in recording mode. Location: $location. Sequence size: ${it.sequences.size}") run { mapRender?.updateRecording(location, it.sequences) onMapMove() } } } } }) } private fun loadMap(function: () -> Unit) { mapView?.visibility = View.VISIBLE mapView?.getMapAsync { mapBoxMap -> if (this.mapboxMap == null) { Log.d(TAG, "loadMap. Status: initialising map.") this.mapboxMap = mapBoxMap this.mapboxMap?.setStyle(Style.LIGHT) } context?.let { context -> Log.d(TAG, "loadMap. Status: initialising map render.") if (mapRender == null) { mapRender = MapRender(context, mapboxMap!!, Injection.provideNetworkFactoryUrl(appPrefs), Injection.provideCurrencyUtil()) } function() } } } @SuppressLint("CheckResult") @Suppress("IMPLICIT_CAST_TO_ANY") private fun getLastKnowLocationAsync(callback: (LatLng) -> Unit) { activity?.let { val kvActivityTempBase = it as KVActivityTempBase val locationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION if (PermissionUtils.isPermissionGranted(it.applicationContext, locationPermission)) { locationService .lastKnownLocation .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ location -> callback(LatLng(location.latitude, location.longitude)) LogUtils.logDebug(TAG, "getLastKnowLocationAsync. Status: success.") }, { error: Throwable? -> LogUtils.logDebug(TAG, "getLastKnowLocationAsync. Error: ${error?.message}") if (!Utils.isGPSEnabled(it.applicationContext)) { kvActivityTempBase.resolveLocationProblem() } }) } else { PermissionUtils.checkPermissionsForGPS(it as Activity) } } } private fun initLocation() { activity?.let { if (PermissionUtils.isPermissionGranted(it.applicationContext, android.Manifest.permission.ACCESS_FINE_LOCATION)) { if (Utils.isGPSEnabled(it.applicationContext)) { locationService .lastKnownLocation .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ location -> appPrefs.saveBooleanPreference(PreferenceTypes.K_DISTANCE_UNIT_METRIC, !mapViewModel.initMetricBasedOnCcp(location)) }, { error: Throwable? -> LogUtils.logDebug(TAG, "centerOnCurrentPosition. Error: ${error?.message}") }) } } } } private fun onMapMove(forceLoad: Boolean = false) { val loadGrid = mapMode.mode == MapModes.GRID.mode || mapMode.mode == MapModes.IDLE.mode || mapMode.mode == MapModes.RECORDING.mode Log.d(TAG, "onMapMove. Status: performing grid load if required. Required: $loadGrid. Map mode: ${mapMode.mode}. Force loads: $forceLoad") if (loadGrid) { mapboxMap?.let { mapboxMap -> getLastKnowLocationAsync { mapViewModel.onGridsLoadIfAvailable(mapboxMap.cameraPosition.zoom, mapboxMap.projection.visibleRegion.latLngBounds, it, forceLoad) } } } } companion object { lateinit var TAG: String private const val KEY_MAP_MODE = "key_map_mode" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment MapFragment. */ @JvmStatic fun newInstance(mapMode: MapModes = MapModes.IDLE, playbackManager: PlaybackManager? = null) = MapFragment(mapMode, playbackManager) } }
lgpl-3.0
a534251d499ac200432b3a8a7d765d46
42.835417
207
0.621816
5.258685
false
false
false
false
chilangolabs/MDBancomer
app/src/main/java/com/chilangolabs/mdb/customviews/MDBFontManager.kt
1
1913
package com.chilangolabs.mdb.customviews import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import com.chilangolabs.mdb.R /** * @author Gorro. */ class MDBFontManager(private val context: Context?) { /** * Init custom font to view * @param view you want asing font * @param attrs attributeset with value of font can be null */ fun initStyle(view: View, attrs: AttributeSet? = null) { if (attrs != null) { val typedArray = context?.theme?.obtainStyledAttributes(attrs, R.styleable.fontraleway, 0, 0) val tp = when (typedArray?.getInteger(R.styleable.fontraleway_type, 0)) { 0 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-Light.ttf") 1 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-Medium.ttf") 2 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-Regular.ttf") 3 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-SemiBold.ttf") else -> { Typeface.createFromAsset(context?.assets, "fonts/Raleway-Regular.ttf") } } typedArray?.recycle() setTypeFace(view, tp) } else { setTypeFace(view) } } /** * This function asing typeface to view * @param view view you want asing the typeface font * @param tp this is the typeface can be null */ fun setTypeFace(view: View, tp: Typeface = Typeface.createFromAsset(context?.assets, "fonts/Raleway-Regular.ttf")) { when (view) { is TextView -> view.typeface = tp is EditText -> view.typeface = tp is Button -> view.typeface = tp } } }
mit
80d0808bc2ef1dddbb0aba347ebad2e5
33.178571
120
0.624151
4.213656
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/controller/twitter/card/CardBrowserViewController.kt
1
2150
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.view.controller.twitter.card import android.annotation.SuppressLint import android.view.View import android.view.ViewGroup import android.webkit.WebView import android.widget.FrameLayout import de.vanita5.twittnuker.view.ContainerView class CardBrowserViewController : ContainerView.ViewController() { lateinit var url: String override fun onCreateView(parent: ContainerView): View { val webView = WebView(context) webView.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) return webView } override fun onDestroyView(view: View) { (view as WebView).destroy() super.onDestroyView(view) } @SuppressLint("SetJavaScriptEnabled") override fun onCreate() { super.onCreate() val webView = view as WebView webView.settings.apply { javaScriptEnabled = true builtInZoomControls = false } webView.loadUrl(url) } companion object { fun show(url: String): CardBrowserViewController { val vc = CardBrowserViewController() vc.url = url return vc } } }
gpl-3.0
42392a39e1de16f737f14a9c89b9f09f
30.632353
92
0.695349
4.451346
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/TrendsAdapter.kt
1
1752
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.adapter import android.content.Context import android.database.Cursor import android.support.v4.widget.SimpleCursorAdapter import de.vanita5.twittnuker.provider.TwidereDataStore class TrendsAdapter(context: Context) : SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, null, arrayOf(TwidereDataStore.CachedTrends.NAME), intArrayOf(android.R.id.text1), 0) { private var nameIdx: Int = 0 override fun getItem(position: Int): String? { val c = cursor if (c != null && !c.isClosed && c.moveToPosition(position)) return c.getString(nameIdx) return null } override fun swapCursor(c: Cursor?): Cursor? { if (c != null) { nameIdx = c.getColumnIndex(TwidereDataStore.CachedTrends.NAME) } return super.swapCursor(c) } }
gpl-3.0
00ecfb9b0ac323baa1f0431dc7e9ac9a
34.06
95
0.711758
4.036866
false
false
false
false
numa08/Gochisou
app/src/test/java/net/numa08/gochisou/data/service/AuthorizeURLGeneratorTest.kt
1
1161
package net.numa08.gochisou.data.service import android.net.Uri import android.os.Build import net.numa08.gochisou.BuildConfig import net.numa08.gochisou.testtools.MyTestRunner import org.hamcrest.CoreMatchers.`is` import org.junit.Assert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @RunWith(MyTestRunner::class) @Config(constants = BuildConfig::class, sdk = intArrayOf(Build.VERSION_CODES.LOLLIPOP)) class AuthorizeURLGeneratorTest { val generator = AuthorizeURLGenerator() @Test fun generateURL() { val url = Uri.parse(generator.generateAuthorizeURL("clientID", "https://redirect.url")) assertThat(url.scheme, `is`("https")) assertThat(url.authority, `is`(AuthorizeURLGenerator.ENDPOINT)) assertThat(url.getQueryParameter("client_id"), `is`("clientID")) assertThat(url.getQueryParameter("redirect_uri"), `is`("https://redirect.url")) assertThat(url.getQueryParameter("scope"), `is`("write read")) assertThat(url.getQueryParameter("response_type"), `is`("code")) assert(url.getQueryParameter("state") == null) } }
mit
4b50f9ae53429d423ddabbdc480b797d
36.483871
95
0.732127
4.059441
false
true
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/diff/ArticleEditDetailsViewModel.kt
1
11424
package org.wikipedia.diff import android.net.Uri import android.os.Bundle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import kotlinx.coroutines.* import org.wikipedia.analytics.WatchlistFunnel import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.dataclient.restbase.DiffResponse import org.wikipedia.dataclient.restbase.Revision import org.wikipedia.dataclient.rollback.RollbackPostResponse import org.wikipedia.dataclient.watch.WatchPostResponse import org.wikipedia.dataclient.wikidata.EntityPostResponse import org.wikipedia.edit.Edit import org.wikipedia.page.PageTitle import org.wikipedia.util.Resource import org.wikipedia.util.SingleLiveData import org.wikipedia.watchlist.WatchlistExpiry class ArticleEditDetailsViewModel(bundle: Bundle) : ViewModel() { val watchedStatus = MutableLiveData<Resource<MwQueryPage>>() val rollbackRights = MutableLiveData<Resource<Boolean>>() val revisionDetails = MutableLiveData<Resource<Unit>>() val diffText = MutableLiveData<Resource<DiffResponse>>() val singleRevisionText = MutableLiveData<Resource<Revision>>() val thankStatus = SingleLiveData<Resource<EntityPostResponse>>() val watchResponse = SingleLiveData<Resource<WatchPostResponse>>() val undoEditResponse = SingleLiveData<Resource<Edit>>() val rollbackResponse = SingleLiveData<Resource<RollbackPostResponse>>() var watchlistExpiryChanged = false var lastWatchExpiry = WatchlistExpiry.NEVER var pageId = -1 private set val pageTitle = bundle.getParcelable<PageTitle>(ArticleEditDetailsActivity.EXTRA_ARTICLE_TITLE)!! var revisionToId = bundle.getLong(ArticleEditDetailsActivity.EXTRA_EDIT_REVISION_TO, -1) var revisionTo: MwQueryPage.Revision? = null var revisionFromId = bundle.getLong(ArticleEditDetailsActivity.EXTRA_EDIT_REVISION_FROM, -1) var revisionFrom: MwQueryPage.Revision? = null var canGoForward = false var hasRollbackRights = false private var diffRevisionId = 0L val diffSize get() = if (revisionFrom != null) revisionTo!!.size - revisionFrom!!.size else revisionTo!!.size private val watchlistFunnel = WatchlistFunnel() init { getWatchedStatusAndPageId() checkRollbackRights() getRevisionDetails(revisionToId, revisionFromId) } private fun getWatchedStatusAndPageId() { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> watchedStatus.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val page = ServiceFactory.get(pageTitle.wikiSite).getWatchedStatus(pageTitle.prefixedText).query?.firstPage()!! pageId = page.pageId watchedStatus.postValue(Resource.Success(page)) } } } private fun checkRollbackRights() { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> rollbackRights.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val userRights = ServiceFactory.get(pageTitle.wikiSite).userRights().query?.userInfo?.rights hasRollbackRights = userRights?.contains("rollback") == true rollbackRights.postValue(Resource.Success(hasRollbackRights)) } } } fun getRevisionDetails(revisionIdTo: Long, revisionIdFrom: Long = -1) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> revisionDetails.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { if (revisionIdFrom >= 0) { val responseFrom = async { ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsWithInfo(pageTitle.prefixedText, 2, revisionIdFrom) } val responseTo = async { ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsWithInfo(pageTitle.prefixedText, 2, revisionIdTo) } val pageTo = responseTo.await().query?.firstPage()!! revisionFrom = responseFrom.await().query?.firstPage()!!.revisions[0] revisionTo = pageTo.revisions[0] canGoForward = revisionTo!!.revId < pageTo.lastrevid } else { val response = ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsWithInfo(pageTitle.prefixedText, 2, revisionIdTo) val page = response.query?.firstPage()!! val revisions = page.revisions revisionTo = revisions[0] canGoForward = revisions[0].revId < page.lastrevid revisionFrom = revisions.getOrNull(1) } revisionToId = revisionTo!!.revId revisionFromId = if (revisionFrom != null) revisionFrom!!.revId else revisionTo!!.parentRevId revisionDetails.postValue(Resource.Success(Unit)) getDiffText(revisionFromId, revisionToId) } } } fun goBackward() { revisionToId = revisionFromId getRevisionDetails(revisionToId) } fun goForward() { val revisionIdFrom = revisionToId viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> revisionDetails.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val response = ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsAscending(pageTitle.prefixedText, 2, revisionIdFrom) val page = response.query?.firstPage()!! val revisions = page.revisions revisionFrom = revisions[0] revisionTo = revisions.getOrElse(1) { revisions.first() } canGoForward = revisions.size > 1 && revisions[1].revId < page.lastrevid revisionToId = revisionTo!!.revId revisionFromId = if (revisionFrom != null) revisionFrom!!.revId else revisionTo!!.parentRevId revisionDetails.postValue(Resource.Success(Unit)) getDiffText(revisionFromId, revisionToId) } } } private fun getDiffText(oldRevisionId: Long, newRevisionId: Long) { if (diffRevisionId == newRevisionId) { return } viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> diffText.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { if (pageTitle.wikiSite.uri.authority == Uri.parse(Service.WIKIDATA_URL).authority) { // For the special case of Wikidata we return a blank Revision object, since the // Rest API in Wikidata cannot render diffs properly yet. // TODO: wait until Wikidata API returns diffs correctly singleRevisionText.postValue(Resource.Success(Revision())) } else if (oldRevisionId > 0) { diffText.postValue(Resource.Success(ServiceFactory.getCoreRest(pageTitle.wikiSite).getDiff(oldRevisionId, newRevisionId))) } else { singleRevisionText.postValue(Resource.Success(ServiceFactory.getCoreRest(pageTitle.wikiSite).getRevision(newRevisionId))) } diffRevisionId = newRevisionId } } } fun sendThanks(wikiSite: WikiSite, revisionId: Long) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> thankStatus.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val token = ServiceFactory.get(wikiSite).getToken().query?.csrfToken() thankStatus.postValue(Resource.Success(ServiceFactory.get(wikiSite).postThanksToRevision(revisionId, token!!))) } } } fun watchOrUnwatch(isWatched: Boolean, expiry: WatchlistExpiry, unwatch: Boolean) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> watchResponse.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { if (expiry != WatchlistExpiry.NEVER) { watchlistFunnel.logAddExpiry() } else { if (isWatched) { watchlistFunnel.logRemoveArticle() } else { watchlistFunnel.logAddArticle() } } val token = ServiceFactory.get(pageTitle.wikiSite).getWatchToken().query?.watchToken() val response = ServiceFactory.get(pageTitle.wikiSite) .watch(if (unwatch) 1 else null, null, pageTitle.prefixedText, expiry.expiry, token!!) lastWatchExpiry = expiry if (watchlistExpiryChanged && unwatch) { watchlistExpiryChanged = false } if (unwatch) { watchlistFunnel.logRemoveSuccess() } else { watchlistFunnel.logAddSuccess() } watchResponse.postValue(Resource.Success(response)) } } } fun undoEdit(title: PageTitle, user: String, comment: String, revisionId: Long, revisionIdAfter: Long) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> undoEditResponse.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val msgResponse = ServiceFactory.get(title.wikiSite).getMessages("undo-summary", "$revisionId|$user") val undoMessage = msgResponse.query?.allmessages?.find { it.name == "undo-summary" }?.content val summary = if (undoMessage != null) "$undoMessage $comment" else comment val token = ServiceFactory.get(title.wikiSite).getToken().query!!.csrfToken()!! val undoResponse = ServiceFactory.get(title.wikiSite).postUndoEdit(title.prefixedText, summary, null, token, revisionId, if (revisionIdAfter > 0) revisionIdAfter else null) undoEditResponse.postValue(Resource.Success(undoResponse)) } } } fun postRollback(title: PageTitle, user: String) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> rollbackResponse.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val rollbackToken = ServiceFactory.get(title.wikiSite).getToken("rollback").query!!.rollbackToken()!! val rollbackPostResponse = ServiceFactory.get(title.wikiSite).postRollback(title.prefixedText, null, user, rollbackToken) rollbackResponse.postValue(Resource.Success(rollbackPostResponse)) } } } class Factory(private val bundle: Bundle) : ViewModelProvider.Factory { @Suppress("unchecked_cast") override fun <T : ViewModel> create(modelClass: Class<T>): T { return ArticleEditDetailsViewModel(bundle) as T } } }
apache-2.0
cb12acfc7acd959c25b420f21a909cce
45.439024
157
0.645833
5.111409
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/SearchActionProvider.kt
1
2518
package org.wikipedia.views import android.content.Context import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.inputmethod.EditorInfo import androidx.appcompat.widget.SearchView import androidx.core.view.ActionProvider import org.wikipedia.R import org.wikipedia.databinding.GroupSearchBinding import org.wikipedia.util.DeviceUtil.showSoftKeyboard import org.wikipedia.util.ResourceUtil.getThemedColor class SearchActionProvider(context: Context, private val searchHintString: String, private val callback: Callback) : ActionProvider(context) { interface Callback { fun onQueryTextChange(s: String) fun onQueryTextFocusChange() } private val binding = GroupSearchBinding.inflate(LayoutInflater.from(context)) override fun onCreateActionView(): View { binding.searchInput.isFocusable = true binding.searchInput.isIconified = false binding.searchInput.maxWidth = Int.MAX_VALUE binding.searchInput.inputType = EditorInfo.TYPE_CLASS_TEXT binding.searchInput.isSubmitButtonEnabled = false binding.searchInput.queryHint = searchHintString binding.searchInput.setSearchHintTextColor(getThemedColor(context, R.attr.color_group_63)) binding.searchInput.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(s: String): Boolean { return false } override fun onQueryTextChange(s: String): Boolean { binding.searchInput.setCloseButtonVisibility(s) callback.onQueryTextChange(s) return true } }) binding.searchInput.setOnQueryTextFocusChangeListener { _: View?, isFocus: Boolean -> if (!isFocus) { callback.onQueryTextFocusChange() } } // remove focus line from search plate val searchEditPlate = binding.searchInput.findViewById<View>(androidx.appcompat.R.id.search_plate) searchEditPlate.setBackgroundColor(Color.TRANSPARENT) showSoftKeyboard(binding.searchInput) return binding.root } override fun overridesItemVisibility(): Boolean { return true } fun selectAllQueryTexts() { binding.searchInput.selectAllQueryTexts() } fun setQueryText(text: String?) { binding.searchInput.setQuery(text, false) } }
apache-2.0
86c4a3c58a0dfeddf50b360b89dc9636
36.029412
106
0.694996
5.256785
false
false
false
false
slartus/4pdaClient-plus
core-lib/src/main/java/org/softeg/slartus/forpdaplus/core_lib/utils/AppPreferenceDelegate.kt
1
3514
package org.softeg.slartus.forpdaplus.core_lib.utils import android.content.SharedPreferences import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty @Suppress("UNCHECKED_CAST") inline fun <reified T> appPreference( preferences: SharedPreferences, key: String, defaultValue: T ): AppPreference<T> { return when (T::class) { String::class -> AppPreferenceString(preferences, key, defaultValue as String?) Boolean::class -> AppPreferenceBoolean(preferences, key, defaultValue as Boolean) Int::class -> AppPreferenceInt(preferences, key, defaultValue as Int) Float::class -> AppPreferenceFloat(preferences, key, defaultValue as Float) else -> throw Exception("appPreference given unknown class ${T::class}") } as AppPreference<T> } interface AppPreference<T> : ReadWriteProperty<Any?, T> { val value: T } data class AppPreferenceString( private val preferences: SharedPreferences, private val key: String, private val defaultValue: String? ) : AppPreference<String?> { override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) { preferences.edit().putString(key, value).apply() } override operator fun getValue(thisRef: Any?, property: KProperty<*>): String? { return value } override val value get() = preferences.getString(key, defaultValue) ?: defaultValue } data class AppPreferenceBoolean( private val preferences: SharedPreferences, private val key: String, private val defaultValue: Boolean ) : AppPreference<Boolean> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): Boolean { return value } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) { preferences.edit().putBoolean(key, value).apply() } override val value get() = preferences.getBoolean(key, defaultValue) } data class AppPreferenceInt( private val preferences: SharedPreferences, private val key: String, private val defaultValue: Int ) : AppPreference<Int> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): Int { return value } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { preferences.edit().putInt(key, value).apply() } override val value get() = try { preferences.getInt(key, defaultValue) } catch (ex: java.lang.Exception) { val strValue = preferences.getString(key, defaultValue.toString()) ?: defaultValue.toString() strValue.toIntOrNull() ?: defaultValue } } data class AppPreferenceFloat( private val preferences: SharedPreferences, private val key: String, private val defaultValue: Float ) : AppPreference<Float> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): Float { return value } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Float) { preferences.edit().putFloat(key, value).apply() } override val value get() = try { preferences.getFloat(key, defaultValue) } catch (ex: java.lang.Exception) { val strValue = preferences.getString(key, defaultValue.toString()) ?: defaultValue.toString() strValue.toFloatOrNull() ?: defaultValue } }
apache-2.0
a8780b60190c8e4fd4afe7fd1be85f8a
32.160377
91
0.666762
4.767978
false
false
false
false
slartus/4pdaClient-plus
forum/forum-data/src/main/java/org/softeg/slartus/forpdaplus/forum/data/ForumServiceImpl.kt
1
2414
package org.softeg.slartus.forpdaplus.forum.data import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.softeg.slartus.forpdacommon.NameValuePair import org.softeg.slartus.forpdacommon.URIUtils import org.softeg.slartus.forpdaplus.core.services.AppHttpClient import ru.softeg.slartus.forum.api.ForumService import org.softeg.slartus.forpdaplus.forum.data.models.ForumItemResponse import org.softeg.slartus.forpdaplus.forum.data.models.mapToForumItemOrNull import org.softeg.slartus.hosthelper.HostHelper import ru.softeg.slartus.forum.api.ForumItem import javax.inject.Inject class ForumServiceImpl @Inject constructor(private val httpClient: AppHttpClient) : ForumService { override suspend fun getGithubForum(): List<ForumItem> = withContext(Dispatchers.IO) { val response = httpClient .performGet("https://raw.githubusercontent.com/slartus/4pdaClient-plus/master/forum_struct.json") val itemsListType = object : TypeToken<List<ForumItemResponse>>() {}.type val responseItems: List<ForumItemResponse> = Gson().fromJson(response, itemsListType) responseItems.mapNotNull { it.mapToForumItemOrNull() } } override suspend fun getSlartusForum(): List<ForumItem> = withContext(Dispatchers.IO) { val response = httpClient .performGet("http://slartus.ru/4pda/forum_struct.json") val itemsListType = object : TypeToken<List<ForumItemResponse>>() {}.type val responseItems: List<ForumItemResponse> = Gson().fromJson(response, itemsListType) responseItems.mapNotNull { it.mapToForumItemOrNull() } } override suspend fun markAsRead(forumId: String) = withContext(Dispatchers.IO) { val queryParams = mapOf("act" to "login", "CODE" to "04", "f" to forumId, "fromforum" to forumId) .map { NameValuePair(it.key, it.value) } val uri = URIUtils.createURI("http", HostHelper.host, "/forum/index.php", queryParams, "UTF-8") httpClient.performGet(uri) Unit } override fun getForumUrl(forumId: String?): String { val baseUrl = "https://${HostHelper.host}/forum/index.php" return if (forumId == null) baseUrl else "$baseUrl?showforum=$forumId" } }
apache-2.0
172ef70933d4961573143e5f29111c3e
39.932203
109
0.707125
4.235088
false
false
false
false
ivanTrogrlic/LeagueStats
app/src/main/java/com/ivantrogrlic/leaguestats/LeagueStatsApplication.kt
1
1121
package com.ivantrogrlic.leaguestats import android.app.Application import com.ivantrogrlic.leaguestats.dagger.AppComponent import com.ivantrogrlic.leaguestats.dagger.DaggerAppComponent import com.ivantrogrlic.leaguestats.web.NetComponent import com.ivantrogrlic.leaguestats.web.NetModule /** Created by ivanTrogrlic on 12/07/2017. */ class LeagueStatsApplication : Application() { companion object { lateinit var appComponent: AppComponent var netComponent: NetComponent? = null } override fun onCreate() { super.onCreate() appComponent = DaggerAppComponent .builder() .application(this) .build() appComponent.inject(this) } fun component() = appComponent fun netComponent() = netComponent fun createNetComponent(baseUrl: String): NetComponent { netComponent = component() .netComponentBuilder() .netModule(NetModule(baseUrl)) .build() return netComponent!! } fun destroyNetComponent() { netComponent = null } }
apache-2.0
47ee53f4672ca85f406afdbfad617e0c
26.341463
61
0.661017
4.43083
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/ExponentPackage.kt
2
12161
// Copyright 2015-present 650 Industries. All rights reserved. package versioned.host.exp.exponent import android.content.Context import android.os.Looper import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager import expo.modules.adapters.react.ReactModuleRegistryProvider import expo.modules.core.interfaces.Package import expo.modules.core.interfaces.SingletonModule import expo.modules.kotlin.ModulesProvider import expo.modules.random.RandomModule import expo.modules.manifests.core.Manifest import host.exp.exponent.Constants import host.exp.exponent.analytics.EXL import host.exp.exponent.kernel.ExperienceKey // WHEN_VERSIONING_REMOVE_FROM_HERE import host.exp.exponent.kernel.ExponentKernelModuleProvider // WHEN_VERSIONING_REMOVE_TO_HERE import host.exp.exponent.kernel.KernelConstants import host.exp.exponent.utils.ScopedContext import org.json.JSONException import versioned.host.exp.exponent.modules.api.* import versioned.host.exp.exponent.modules.api.appearance.ExpoAppearanceModule import versioned.host.exp.exponent.modules.api.appearance.ExpoAppearancePackage import versioned.host.exp.exponent.modules.api.appearance.rncappearance.RNCAppearanceModule import versioned.host.exp.exponent.modules.api.cognito.RNAWSCognitoModule import versioned.host.exp.exponent.modules.api.components.datetimepicker.RNDateTimePickerPackage import versioned.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerModule import versioned.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerPackage import versioned.host.exp.exponent.modules.api.components.lottie.LottiePackage import versioned.host.exp.exponent.modules.api.components.maps.MapsPackage import versioned.host.exp.exponent.modules.api.components.maskedview.RNCMaskedViewPackage import versioned.host.exp.exponent.modules.api.components.picker.RNCPickerPackage import versioned.host.exp.exponent.modules.api.components.reactnativestripesdk.StripeSdkPackage import versioned.host.exp.exponent.modules.api.components.sharedelement.RNSharedElementModule import versioned.host.exp.exponent.modules.api.components.sharedelement.RNSharedElementPackage import versioned.host.exp.exponent.modules.api.components.slider.ReactSliderPackage import versioned.host.exp.exponent.modules.api.components.svg.SvgPackage import versioned.host.exp.exponent.modules.api.components.pagerview.PagerViewPackage import versioned.host.exp.exponent.modules.api.components.webview.RNCWebViewModule import versioned.host.exp.exponent.modules.api.components.webview.RNCWebViewPackage import versioned.host.exp.exponent.modules.api.netinfo.NetInfoModule import versioned.host.exp.exponent.modules.api.notifications.NotificationsModule import versioned.host.exp.exponent.modules.api.safeareacontext.SafeAreaContextPackage import versioned.host.exp.exponent.modules.api.screens.RNScreensPackage import versioned.host.exp.exponent.modules.api.viewshot.RNViewShotModule import versioned.host.exp.exponent.modules.internal.DevMenuModule import versioned.host.exp.exponent.modules.test.ExponentTestNativeModule import versioned.host.exp.exponent.modules.universal.ExpoModuleRegistryAdapter import versioned.host.exp.exponent.modules.universal.ScopedModuleRegistryAdapter import java.io.UnsupportedEncodingException // This is an Expo module but not a unimodule class ExponentPackage : ReactPackage { private val isKernel: Boolean private val experienceProperties: Map<String, Any?> private val manifest: Manifest private val moduleRegistryAdapter: ScopedModuleRegistryAdapter private constructor( isKernel: Boolean, experienceProperties: Map<String, Any?>, manifest: Manifest, expoPackages: List<Package>, singletonModules: List<SingletonModule>? ) { this.isKernel = isKernel this.experienceProperties = experienceProperties this.manifest = manifest moduleRegistryAdapter = createDefaultModuleRegistryAdapterForPackages(expoPackages, singletonModules) } constructor( experienceProperties: Map<String, Any?>, manifest: Manifest, expoPackages: List<Package>?, delegate: ExponentPackageDelegate?, singletonModules: List<SingletonModule> ) { isKernel = false this.experienceProperties = experienceProperties this.manifest = manifest val packages = expoPackages ?: ExperiencePackagePicker.packages(manifest) // Delegate may not be null only when the app is detached moduleRegistryAdapter = createModuleRegistryAdapter(delegate, singletonModules, packages) } private fun createModuleRegistryAdapter( delegate: ExponentPackageDelegate?, singletonModules: List<SingletonModule>, packages: List<Package> ): ScopedModuleRegistryAdapter { var registryAdapter: ScopedModuleRegistryAdapter? = null if (delegate != null) { registryAdapter = delegate.getScopedModuleRegistryAdapterForPackages(packages, singletonModules) } if (registryAdapter == null) { registryAdapter = createDefaultModuleRegistryAdapterForPackages(packages, singletonModules, ExperiencePackagePicker) } return registryAdapter } override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { val isVerified = manifest.isVerified() ?: false val nativeModules: MutableList<NativeModule> = mutableListOf( URLHandlerModule(reactContext), ShakeModule(reactContext), KeyboardModule(reactContext) ) if (isKernel) { // WHEN_VERSIONING_REMOVE_FROM_HERE nativeModules.add((ExponentKernelModuleProvider.newInstance(reactContext) as NativeModule?)!!) // WHEN_VERSIONING_REMOVE_TO_HERE } if (!isKernel && !Constants.isStandaloneApp()) { // We need DevMenuModule only in non-home and non-standalone apps. nativeModules.add(DevMenuModule(reactContext, experienceProperties, manifest)) } if (isVerified) { try { val experienceKey = ExperienceKey.fromManifest(manifest) val scopedContext = ScopedContext(reactContext, experienceKey) nativeModules.add(NotificationsModule(reactContext, experienceKey, manifest.getStableLegacyID(), manifest.getEASProjectID())) nativeModules.add(RNViewShotModule(reactContext, scopedContext)) nativeModules.add(RandomModule(reactContext)) nativeModules.add(ExponentTestNativeModule(reactContext)) nativeModules.add(PedometerModule(reactContext)) nativeModules.add(ScreenOrientationModule(reactContext)) nativeModules.add(RNGestureHandlerModule(reactContext)) nativeModules.add(RNAWSCognitoModule(reactContext)) nativeModules.add(RNCWebViewModule(reactContext)) nativeModules.add(NetInfoModule(reactContext)) nativeModules.add(RNSharedElementModule(reactContext)) // @tsapeta: Using ExpoAppearanceModule in home app causes some issues with the dev menu, // when home's setting is set to automatic and the system theme is different // than this supported by the experience in which we opened the dev menu. if (isKernel) { nativeModules.add(RNCAppearanceModule(reactContext)) } else { nativeModules.add(ExpoAppearanceModule(reactContext)) } nativeModules.addAll(SvgPackage().createNativeModules(reactContext)) nativeModules.addAll(MapsPackage().createNativeModules(reactContext)) nativeModules.addAll(RNDateTimePickerPackage().createNativeModules(reactContext)) nativeModules.addAll(stripePackage.createNativeModules(reactContext)) // Call to create native modules has to be at the bottom -- // -- ExpoModuleRegistryAdapter uses the list of native modules // to create Bindings for internal modules. nativeModules.addAll( moduleRegistryAdapter.createNativeModules( scopedContext, experienceKey, experienceProperties, manifest, nativeModules ) ) } catch (e: JSONException) { EXL.e(TAG, e.toString()) } catch (e: UnsupportedEncodingException) { EXL.e(TAG, e.toString()) } } return nativeModules } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { val viewManagers = mutableListOf<ViewManager<*, *>>() // Add view manager from 3rd party library packages. addViewManagersFromPackages( reactContext, viewManagers, listOf( SvgPackage(), MapsPackage(), LottiePackage(), RNGestureHandlerPackage(), RNScreensPackage(), RNCWebViewPackage(), SafeAreaContextPackage(), RNSharedElementPackage(), RNDateTimePickerPackage(), RNCMaskedViewPackage(), RNCPickerPackage(), ReactSliderPackage(), PagerViewPackage(), ExpoAppearancePackage(), stripePackage ) ) viewManagers.addAll(moduleRegistryAdapter.createViewManagers(reactContext)) return viewManagers } private fun addViewManagersFromPackages( reactContext: ReactApplicationContext, viewManagers: MutableList<ViewManager<*, *>>, packages: List<ReactPackage> ) { for (pack in packages) { viewManagers.addAll(pack.createViewManagers(reactContext)) } } private fun createDefaultModuleRegistryAdapterForPackages( packages: List<Package>, singletonModules: List<SingletonModule>?, modulesProvider: ModulesProvider? = null ): ExpoModuleRegistryAdapter { return ExpoModuleRegistryAdapter(ReactModuleRegistryProvider(packages, singletonModules), modulesProvider) } companion object { private val TAG = ExponentPackage::class.java.simpleName private val singletonModules = mutableListOf<SingletonModule>() private val singletonModulesClasses = mutableSetOf<Class<*>>() // Need to avoid initializing 2 StripeSdkPackages private val stripePackage = StripeSdkPackage() fun kernelExponentPackage( context: Context, manifest: Manifest, expoPackages: List<Package>, initialURL: String? ): ExponentPackage { val kernelExperienceProperties = mutableMapOf( KernelConstants.LINKING_URI_KEY to "exp://", KernelConstants.IS_HEADLESS_KEY to false ).apply { if (initialURL != null) { this[KernelConstants.INTENT_URI_KEY] = initialURL } } val singletonModules = getOrCreateSingletonModules(context, manifest, expoPackages) return ExponentPackage( true, kernelExperienceProperties, manifest, expoPackages, singletonModules ) } fun getOrCreateSingletonModules( context: Context?, manifest: Manifest?, providedExpoPackages: List<Package>? ): List<SingletonModule> { if (Looper.getMainLooper() != Looper.myLooper()) { throw RuntimeException("Singleton modules must be created on the main thread.") } val expoPackages = providedExpoPackages ?: ExperiencePackagePicker.packages(manifest) for (expoPackage in expoPackages) { // For now we just accumulate more and more singleton modules, // but in fact we should only return singleton modules from the requested // unimodules. This solution also unnecessarily creates singleton modules // which are going to be deallocated in a tick, but there's no better solution // without a bigger-than-minimal refactor. In SDK32 the only singleton module // is TaskService which is safe to initialize more than once. val packageSingletonModules = expoPackage.createSingletonModules(context) for (singletonModule in packageSingletonModules) { if (!singletonModulesClasses.contains(singletonModule.javaClass)) { singletonModules.add(singletonModule) singletonModulesClasses.add(singletonModule.javaClass) } } } return singletonModules } } }
bsd-3-clause
1d05ff58ac22df763565e520bcf803a2
41.670175
133
0.756188
4.818146
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/completion/RsKeywordCompletionProvider.kt
2
2169
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.util.ProcessingContext import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.RsUnitType import org.rust.lang.core.psi.ext.ancestorStrict class RsKeywordCompletionProvider( private vararg val keywords: String ) : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { for (keyword in keywords) { var builder = LookupElementBuilder.create(keyword).bold() builder = addInsertionHandler(keyword, builder, parameters) result.addElement(builder.toKeywordElement()) } } } fun InsertionContext.addSuffix(suffix: String) { document.insertString(selectionEndOffset, suffix) EditorModificationUtil.moveCaretRelatively(editor, suffix.length) } private val ALWAYS_NEEDS_SPACE = setOf("crate", "const", "enum", "extern", "fn", "impl", "let", "mod", "mut", "static", "struct", "trait", "type", "union", "unsafe", "use", "where") private fun addInsertionHandler(keyword: String, builder: LookupElementBuilder, parameters: CompletionParameters): LookupElementBuilder { val suffix = when (keyword) { in ALWAYS_NEEDS_SPACE -> " " "return" -> { val fn = parameters.position.ancestorStrict<RsFunction>() ?: return builder val fnRetType = fn.retType val returnsUnit = fnRetType == null || fnRetType.typeReference is RsUnitType if (returnsUnit) ";" else " " } else -> return builder } return builder.withInsertHandler { ctx, _ -> ctx.addSuffix(suffix) } }
mit
1720906960d5257dad51a97b7eb53b7e
39.924528
137
0.729829
4.585624
false
false
false
false
google/dokka
core/src/main/kotlin/Markdown/MarkdownProcessor.kt
2
1879
package org.jetbrains.dokka import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.LeafASTNode import org.intellij.markdown.ast.getTextInNode import org.intellij.markdown.flavours.commonmark.CommonMarkFlavourDescriptor import org.intellij.markdown.parser.MarkdownParser class MarkdownNode(val node: ASTNode, val parent: MarkdownNode?, val markdown: String) { val children: List<MarkdownNode> = node.children.map { MarkdownNode(it, this, markdown) } val type: IElementType get() = node.type val text: String get() = node.getTextInNode(markdown).toString() fun child(type: IElementType): MarkdownNode? = children.firstOrNull { it.type == type } val previous get() = parent?.children?.getOrNull(parent.children.indexOf(this) - 1) override fun toString(): String = StringBuilder().apply { presentTo(this) }.toString() } fun MarkdownNode.visit(action: (MarkdownNode, () -> Unit) -> Unit) { action(this) { for (child in children) { child.visit(action) } } } fun MarkdownNode.toTestString(): String { val sb = StringBuilder() var level = 0 visit { node, visitChildren -> sb.append(" ".repeat(level * 2)) node.presentTo(sb) sb.appendln() level++ visitChildren() level-- } return sb.toString() } private fun MarkdownNode.presentTo(sb: StringBuilder) { sb.append(type.toString()) sb.append(":" + text.replace("\n", "\u23CE")) } fun parseMarkdown(markdown: String): MarkdownNode { if (markdown.isEmpty()) return MarkdownNode(LeafASTNode(MarkdownElementTypes.MARKDOWN_FILE, 0, 0), null, markdown) return MarkdownNode(MarkdownParser(CommonMarkFlavourDescriptor()).buildMarkdownTreeFromString(markdown), null, markdown) }
apache-2.0
7857bbff59859f5642fb1a53ac4473f7
34.45283
124
0.708356
4.0671
false
false
false
false
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/transform/ConfigureAarAsJar.kt
3
2291
/* * 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.build.transform import com.android.build.api.attributes.BuildTypeAttr import org.gradle.api.Project import org.gradle.api.attributes.Attribute import org.gradle.api.attributes.Usage /** * Creates `testAarAsJar` configuration that can be used for JVM tests that need to Android library * classes on the classpath. */ fun configureAarAsJarForConfiguration(project: Project, configurationName: String) { val testAarsAsJars = project.configurations.create("${configurationName}AarAsJar") { it.isTransitive = false it.isCanBeConsumed = false it.isCanBeResolved = true it.attributes.attribute( BuildTypeAttr.ATTRIBUTE, project.objects.named(BuildTypeAttr::class.java, "release") ) it.attributes.attribute( Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class.java, Usage.JAVA_API) ) } val artifactType = Attribute.of("artifactType", String::class.java) project.dependencies.registerTransform(IdentityTransform::class.java) { spec -> spec.from.attribute(artifactType, "jar") spec.to.attribute(artifactType, "aarAsJar") } project.dependencies.registerTransform(ExtractClassesJarTransform::class.java) { spec -> spec.from.attribute(artifactType, "aar") spec.to.attribute(artifactType, "aarAsJar") } val aarAsJar = testAarsAsJars.incoming.artifactView { viewConfiguration -> viewConfiguration.attributes.attribute(artifactType, "aarAsJar") }.files project.configurations.getByName(configurationName).dependencies.add( project.dependencies.create(aarAsJar) ) }
apache-2.0
a287126c670149be29692afe61607373
37.847458
99
0.721955
4.290262
false
true
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/writer/DatabaseWriter.kt
3
20751
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.VisibilityModifier import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XCodeBlock.Builder.Companion.addLocalVal import androidx.room.compiler.codegen.XFunSpec import androidx.room.compiler.codegen.XPropertySpec import androidx.room.compiler.codegen.XPropertySpec.Companion.apply import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.XTypeSpec import androidx.room.compiler.codegen.XTypeSpec.Builder.Companion.addOriginatingElement import androidx.room.ext.AndroidTypeNames import androidx.room.ext.CommonTypeNames import androidx.room.ext.KotlinTypeNames import androidx.room.ext.RoomTypeNames import androidx.room.ext.SupportDbTypeNames import androidx.room.ext.decapitalize import androidx.room.ext.stripNonJava import androidx.room.solver.CodeGenScope import androidx.room.vo.DaoMethod import androidx.room.vo.Database import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import java.util.Locale import javax.lang.model.element.Modifier /** * Writes implementation of classes that were annotated with @Database. */ class DatabaseWriter( val database: Database, codeLanguage: CodeLanguage ) : TypeWriter(codeLanguage) { override fun createTypeSpecBuilder(): XTypeSpec.Builder { return XTypeSpec.classBuilder(codeLanguage, database.implTypeName).apply { addOriginatingElement(database.element) superclass(database.typeName) setVisibility(VisibilityModifier.PUBLIC) addFunction(createCreateOpenHelper()) addFunction(createCreateInvalidationTracker()) addFunction(createClearAllTables()) addFunction(createCreateTypeConvertersMap()) addFunction(createCreateAutoMigrationSpecsSet()) addFunction(getAutoMigrations()) addDaoImpls(this) } } private fun createCreateTypeConvertersMap(): XFunSpec { val scope = CodeGenScope(this) val classOfAnyTypeName = CommonTypeNames.JAVA_CLASS.parametrizedBy( XTypeName.getProducerExtendsName(KotlinTypeNames.ANY) ) val typeConvertersTypeName = CommonTypeNames.HASH_MAP.parametrizedBy( classOfAnyTypeName, CommonTypeNames.LIST.parametrizedBy(classOfAnyTypeName) ) val body = XCodeBlock.builder(codeLanguage).apply { val typeConvertersVar = scope.getTmpVar("_typeConvertersMap") addLocalVariable( name = typeConvertersVar, typeName = typeConvertersTypeName, assignExpr = XCodeBlock.ofNewInstance(codeLanguage, typeConvertersTypeName) ) database.daoMethods.forEach { addStatement( "%L.put(%L, %T.%L())", typeConvertersVar, XCodeBlock.ofJavaClassLiteral(codeLanguage, it.dao.typeName), it.dao.implTypeName, DaoWriter.GET_LIST_OF_TYPE_CONVERTERS_METHOD ) } addStatement("return %L", typeConvertersVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "getRequiredTypeConverters", visibility = VisibilityModifier.PROTECTED, isOverride = true ).apply { returns( CommonTypeNames.MAP.parametrizedBy( classOfAnyTypeName, CommonTypeNames.LIST.parametrizedBy(classOfAnyTypeName) ) ) addCode(body) }.build() } private fun createCreateAutoMigrationSpecsSet(): XFunSpec { val scope = CodeGenScope(this) val classOfAutoMigrationSpecTypeName = CommonTypeNames.JAVA_CLASS.parametrizedBy( XTypeName.getProducerExtendsName(RoomTypeNames.AUTO_MIGRATION_SPEC) ) val autoMigrationSpecsTypeName = CommonTypeNames.HASH_SET.parametrizedBy(classOfAutoMigrationSpecTypeName) val body = XCodeBlock.builder(codeLanguage).apply { val autoMigrationSpecsVar = scope.getTmpVar("_autoMigrationSpecsSet") addLocalVariable( name = autoMigrationSpecsVar, typeName = autoMigrationSpecsTypeName, assignExpr = XCodeBlock.ofNewInstance(codeLanguage, autoMigrationSpecsTypeName) ) database.autoMigrations.filter { it.isSpecProvided }.map { autoMigration -> val specClassName = checkNotNull(autoMigration.specClassName) addStatement( "%L.add(%L)", autoMigrationSpecsVar, XCodeBlock.ofJavaClassLiteral(codeLanguage, specClassName) ) } addStatement("return %L", autoMigrationSpecsVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "getRequiredAutoMigrationSpecs", visibility = VisibilityModifier.PUBLIC, isOverride = true, ).apply { returns(CommonTypeNames.SET.parametrizedBy(classOfAutoMigrationSpecTypeName)) addCode(body) }.build() } private fun createClearAllTables(): XFunSpec { val scope = CodeGenScope(this) val body = XCodeBlock.builder(codeLanguage).apply { addStatement("super.assertNotMainThread()") val dbVar = scope.getTmpVar("_db") addLocalVal( dbVar, SupportDbTypeNames.DB, when (language) { CodeLanguage.JAVA -> "super.getOpenHelper().getWritableDatabase()" CodeLanguage.KOTLIN -> "super.openHelper.writableDatabase" } ) val deferVar = scope.getTmpVar("_supportsDeferForeignKeys") if (database.enableForeignKeys) { addLocalVal( deferVar, XTypeName.PRIMITIVE_BOOLEAN, "%L.VERSION.SDK_INT >= %L.VERSION_CODES.LOLLIPOP", AndroidTypeNames.BUILD, AndroidTypeNames.BUILD ) } beginControlFlow("try").apply { if (database.enableForeignKeys) { beginControlFlow("if (!%L)", deferVar).apply { addStatement("%L.execSQL(%S)", dbVar, "PRAGMA foreign_keys = FALSE") } endControlFlow() } addStatement("super.beginTransaction()") if (database.enableForeignKeys) { beginControlFlow("if (%L)", deferVar).apply { addStatement("%L.execSQL(%S)", dbVar, "PRAGMA defer_foreign_keys = TRUE") } endControlFlow() } database.entities.sortedWith(EntityDeleteComparator()).forEach { addStatement("%L.execSQL(%S)", dbVar, "DELETE FROM `${it.tableName}`") } addStatement("super.setTransactionSuccessful()") } nextControlFlow("finally").apply { addStatement("super.endTransaction()") if (database.enableForeignKeys) { beginControlFlow("if (!%L)", deferVar).apply { addStatement("%L.execSQL(%S)", dbVar, "PRAGMA foreign_keys = TRUE") } endControlFlow() } addStatement("%L.query(%S).close()", dbVar, "PRAGMA wal_checkpoint(FULL)") beginControlFlow("if (!%L.inTransaction())", dbVar).apply { addStatement("%L.execSQL(%S)", dbVar, "VACUUM") } endControlFlow() } endControlFlow() }.build() return XFunSpec.builder( language = codeLanguage, name = "clearAllTables", visibility = VisibilityModifier.PUBLIC, isOverride = true ).apply { addCode(body) }.build() } private fun createCreateInvalidationTracker(): XFunSpec { val scope = CodeGenScope(this) val body = XCodeBlock.builder(codeLanguage).apply { val shadowTablesVar = "_shadowTablesMap" val shadowTablesTypeName = CommonTypeNames.HASH_MAP.parametrizedBy( CommonTypeNames.STRING, CommonTypeNames.STRING ) val tableNames = database.entities.joinToString(",") { "\"${it.tableName}\"" } val shadowTableNames = database.entities.filter { it.shadowTableName != null }.map { it.tableName to it.shadowTableName } addLocalVariable( name = shadowTablesVar, typeName = shadowTablesTypeName, assignExpr = XCodeBlock.ofNewInstance( codeLanguage, shadowTablesTypeName, "%L", shadowTableNames.size ) ) shadowTableNames.forEach { (tableName, shadowTableName) -> addStatement("%L.put(%S, %S)", shadowTablesVar, tableName, shadowTableName) } val viewTablesVar = scope.getTmpVar("_viewTables") val tablesType = CommonTypeNames.HASH_SET.parametrizedBy(CommonTypeNames.STRING) val viewTablesType = CommonTypeNames.HASH_MAP.parametrizedBy( CommonTypeNames.STRING, CommonTypeNames.SET.parametrizedBy(CommonTypeNames.STRING) ) addLocalVariable( name = viewTablesVar, typeName = viewTablesType, assignExpr = XCodeBlock.ofNewInstance( codeLanguage, viewTablesType, "%L", database.views.size ) ) for (view in database.views) { val tablesVar = scope.getTmpVar("_tables") addLocalVariable( name = tablesVar, typeName = tablesType, assignExpr = XCodeBlock.ofNewInstance( codeLanguage, tablesType, "%L", view.tables.size ) ) for (table in view.tables) { addStatement("%L.add(%S)", tablesVar, table) } addStatement( "%L.put(%S, %L)", viewTablesVar, view.viewName.lowercase(Locale.US), tablesVar ) } addStatement( "return %L", XCodeBlock.ofNewInstance( codeLanguage, RoomTypeNames.INVALIDATION_TRACKER, "this, %L, %L, %L", shadowTablesVar, viewTablesVar, tableNames ) ) }.build() return XFunSpec.builder( language = codeLanguage, name = "createInvalidationTracker", visibility = VisibilityModifier.PROTECTED, isOverride = true ).apply { returns(RoomTypeNames.INVALIDATION_TRACKER) addCode(body) }.build() } private fun addDaoImpls(builder: XTypeSpec.Builder) { val scope = CodeGenScope(this) database.daoMethods.forEach { method -> val name = method.dao.typeName.simpleNames.first() .decapitalize(Locale.US) .stripNonJava() val privateDaoProperty = XPropertySpec.builder( language = codeLanguage, name = scope.getTmpVar("_$name"), typeName = if (codeLanguage == CodeLanguage.KOTLIN) { KotlinTypeNames.LAZY.parametrizedBy(method.dao.typeName) } else { method.dao.typeName }, visibility = VisibilityModifier.PRIVATE, isMutable = codeLanguage == CodeLanguage.JAVA ).apply { // For Kotlin we rely on kotlin.Lazy while for Java we'll memoize the dao impl in // the getter. if (language == CodeLanguage.KOTLIN) { initializer( XCodeBlock.of( language, "lazy { %L }", XCodeBlock.ofNewInstance(language, method.dao.implTypeName, "this") ) ) } }.apply( javaFieldBuilder = { // The volatile modifier is needed since in Java the memoization is generated. addModifiers(Modifier.VOLATILE) }, kotlinPropertyBuilder = { } ).build() builder.addProperty(privateDaoProperty) val overrideProperty = codeLanguage == CodeLanguage.KOTLIN && method.element.isKotlinPropertyMethod() if (overrideProperty) { builder.addProperty(createDaoProperty(method, privateDaoProperty)) } else { builder.addFunction(createDaoGetter(method, privateDaoProperty)) } } } private fun createDaoGetter(method: DaoMethod, daoProperty: XPropertySpec): XFunSpec { val body = XCodeBlock.builder(codeLanguage).apply { // For Java we implement the memoization logic in the Dao getter, meanwhile for Kotlin // we rely on kotlin.Lazy to the getter just delegates to it. when (codeLanguage) { CodeLanguage.JAVA -> { beginControlFlow("if (%N != null)", daoProperty).apply { addStatement("return %N", daoProperty) } nextControlFlow("else").apply { beginControlFlow("synchronized(this)").apply { beginControlFlow("if(%N == null)", daoProperty).apply { addStatement( "%N = %L", daoProperty, XCodeBlock.ofNewInstance( language, method.dao.implTypeName, "this" ) ) } endControlFlow() addStatement("return %N", daoProperty) } endControlFlow() } endControlFlow() } CodeLanguage.KOTLIN -> { addStatement("return %N.value", daoProperty) } } } return XFunSpec.overridingBuilder( language = codeLanguage, element = method.element, owner = database.element.type ).apply { addCode(body.build()) }.build() } private fun createDaoProperty(method: DaoMethod, daoProperty: XPropertySpec): XPropertySpec { // TODO(b/257967987): This has a few flaws that need to be fixed. return XPropertySpec.builder( language = codeLanguage, name = method.element.name.drop(3).replaceFirstChar { it.lowercase(Locale.US) }, typeName = method.dao.typeName, visibility = when { method.element.isPublic() -> VisibilityModifier.PUBLIC method.element.isProtected() -> VisibilityModifier.PROTECTED else -> VisibilityModifier.PUBLIC // Might be internal... ? } ).apply( javaFieldBuilder = { error("Overriding a property in Java is impossible!") }, kotlinPropertyBuilder = { addModifiers(KModifier.OVERRIDE) getter( FunSpec.getterBuilder() .addStatement("return %L.value", daoProperty.name) .build() ) } ).build() } private fun createCreateOpenHelper(): XFunSpec { val scope = CodeGenScope(this) val configParamName = "config" val body = XCodeBlock.builder(codeLanguage).apply { val openHelperVar = scope.getTmpVar("_helper") val openHelperCode = scope.fork() SQLiteOpenHelperWriter(database) .write(openHelperVar, configParamName, openHelperCode) add(openHelperCode.generate()) addStatement("return %L", openHelperVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "createOpenHelper", visibility = VisibilityModifier.PROTECTED, isOverride = true, ).apply { returns(SupportDbTypeNames.SQLITE_OPEN_HELPER) addParameter(RoomTypeNames.ROOM_DB_CONFIG, configParamName) addCode(body) }.build() } private fun getAutoMigrations(): XFunSpec { val scope = CodeGenScope(this) val classOfAutoMigrationSpecTypeName = CommonTypeNames.JAVA_CLASS.parametrizedBy( XTypeName.getProducerExtendsName(RoomTypeNames.AUTO_MIGRATION_SPEC) ) val autoMigrationsListTypeName = CommonTypeNames.ARRAY_LIST.parametrizedBy(RoomTypeNames.MIGRATION) val specsMapParamName = "autoMigrationSpecs" val body = XCodeBlock.builder(codeLanguage).apply { val listVar = scope.getTmpVar("_autoMigrations") addLocalVariable( name = listVar, typeName = CommonTypeNames.LIST.parametrizedBy(RoomTypeNames.MIGRATION), assignExpr = XCodeBlock.ofNewInstance(codeLanguage, autoMigrationsListTypeName) ) database.autoMigrations.forEach { autoMigrationResult -> val implTypeName = autoMigrationResult.getImplTypeName(database.typeName) val newInstanceCode = if (autoMigrationResult.isSpecProvided) { val specClassName = checkNotNull(autoMigrationResult.specClassName) // For Kotlin use getValue() as the Map's values are never null. val getFunction = when (language) { CodeLanguage.JAVA -> "get" CodeLanguage.KOTLIN -> "getValue" } XCodeBlock.ofNewInstance( language, implTypeName, "%L.%L(%L)", specsMapParamName, getFunction, XCodeBlock.ofJavaClassLiteral(language, specClassName) ) } else { XCodeBlock.ofNewInstance(language, implTypeName) } addStatement("%L.add(%L)", listVar, newInstanceCode) } addStatement("return %L", listVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "getAutoMigrations", visibility = VisibilityModifier.PUBLIC, isOverride = true, ).apply { returns(CommonTypeNames.LIST.parametrizedBy(RoomTypeNames.MIGRATION)) addParameter( CommonTypeNames.MAP.parametrizedBy( classOfAutoMigrationSpecTypeName, RoomTypeNames.AUTO_MIGRATION_SPEC, ), specsMapParamName ) addCode(body) }.build() } }
apache-2.0
f4e84194a7d8ad2628ccdfa4a2686838
41.435583
98
0.554672
5.463665
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/selection/handlers/KotlinBlockSelectionHandler.kt
1
2445
package org.jetbrains.kotlin.ui.editors.selection.handlers import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.KtBlockExpression import com.intellij.psi.PsiElement import org.jetbrains.kotlin.lexer.KtTokens import com.intellij.psi.PsiWhiteSpace import com.intellij.openapi.util.TextRange public class KotlinBlockSelectionHandler: KotlinDefaultSelectionHandler() { override fun canSelect(enclosingElement: PsiElement) = enclosingElement is KtBlockExpression || enclosingElement is KtWhenExpression override fun selectEnclosing(enclosingElement: PsiElement, selectedRange: TextRange): TextRange { val elementStart = findBlockContentStart(enclosingElement); val elementEnd = findBlockContentEnd(enclosingElement) if (elementStart >= elementEnd) { return enclosingElement.getTextRange() } val resultRange = TextRange(elementStart, elementEnd) if (resultRange == selectedRange || selectedRange !in resultRange) { return enclosingElement.getTextRange() } return resultRange; } override fun selectPrevious(enclosingElement: PsiElement, selectionCandidate: PsiElement, selectedRange: TextRange): TextRange { if (selectionCandidate.getNode().getElementType() == KtTokens.LBRACE) { return selectEnclosing(enclosingElement, selectedRange) } return selectionWithElementAppendedToBeginning(selectedRange, selectionCandidate) } override fun selectNext(enclosingElement: PsiElement, selectionCandidate: PsiElement, selectedRange: TextRange): TextRange { if (selectionCandidate.getNode().getElementType() == KtTokens.RBRACE) { return selectEnclosing(enclosingElement, selectedRange) } return selectionWithElementAppendedToEnd(selectedRange, selectionCandidate) } private fun findBlockContentStart(block: PsiElement): Int { val element = block.allChildren .dropWhile { it.getNode().getElementType() != KtTokens.LBRACE } .drop(1) .dropWhile { it is PsiWhiteSpace } .firstOrNull() ?: block return element.getTextRange().getStartOffset() } private fun findBlockContentEnd(block: PsiElement): Int { val element = block.allChildren .toList() .reversed() .asSequence() .dropWhile { it.getNode().getElementType() != KtTokens.RBRACE } .drop(1) .dropWhile { it is PsiWhiteSpace } .firstOrNull() ?: block return element.getTextRange().getEndOffset() } }
apache-2.0
57e29e70fda905de5bcdaf45926808cb
39.098361
129
0.757464
4.812992
false
false
false
false
pthomain/SharedPreferenceStore
mumbo/src/test/java/uk/co/glass_software/android/shared_preferences/test/TestUtils.kt
2
5230
/* * Copyright (C) 2017 Glass Software Ltd * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package uk.co.glass_software.android.shared_preferences.test import com.nhaarman.mockitokotlin2.atLeastOnce import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import junit.framework.TestCase.* import org.junit.Assert.assertArrayEquals import org.mockito.internal.verification.VerificationModeFactory fun <E> expectException(exceptionType: Class<E>, message: String, action: () -> Unit, checkCause: Boolean = false) { try { action() } catch (e: Exception) { val toCheck = if (checkCause) e.cause else e if (toCheck != null && exceptionType == toCheck.javaClass) { assertEquals("The exception did not have the right message", message, toCheck.message ) return } else { fail("Expected exception was not caught: $exceptionType, another one was caught instead $toCheck") } } fail("Expected exception was not caught: $exceptionType") } fun assertTrueWithContext(assumption: Boolean, description: String, context: String? = null) = assertTrue(withContext(description, context), assumption) fun assertFalseWithContext(assumption: Boolean, description: String, context: String? = null) = assertFalse(withContext(description, context), assumption) fun <T> assertEqualsWithContext(t1: T, t2: T, description: String, context: String? = null) { val withContext = withContext(description, context) when { t1 is Array<*> && t2 is Array<*> -> assertArrayEquals(withContext, t1, t2) t1 is ByteArray && t2 is ByteArray -> assertByteArrayEqualsWithContext(t1, t2, context) else -> assertEquals(withContext, t1, t2) } } fun <T> assertNullWithContext(value: T?, description: String, context: String? = null) = assertNull(withContext(description, context), value) fun <T> assertNotNullWithContext(value: T?, description: String, context: String? = null) = assertNotNull(withContext(description, context), value) fun failWithContext(description: String, context: String? = null) { fail(withContext(description, context)) } fun withContext(description: String, context: String? = null) = if (context == null) description else "\n$context\n=> $description" internal fun <T> verifyWithContext(target: T, context: String? = null) = verify( target, VerificationModeFactory.description( atLeastOnce(), "\n$context" ) ) internal fun <T> verifyNeverWithContext(target: T, context: String? = null) = verify( target, VerificationModeFactory.description( never(), "\n$context" ) ) fun assertByteArrayEqualsWithContext(expected: ByteArray?, other: ByteArray?, context: String? = null) { when { expected == null -> assertNullWithContext( other, "Byte array should be null", context ) other != null && other.size == expected.size -> { other.forEachIndexed { index, byte -> if (expected[index] != byte) { assertEqualsWithContext( expected[index], byte, "Byte didn't match at index $index", context ) } } } else -> failWithContext( "Byte array had the wrong size", context ) } } inline fun trueFalseSequence(action: (Boolean) -> Unit) { sequenceOf(true, false).forEach(action) }
apache-2.0
c1d4c8c7f49892ccb9a42a0db75ba152
34.344595
110
0.55392
5.112414
false
false
false
false
Soya93/Extract-Refactoring
platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt
4
3078
/* * 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 com.intellij.testFramework import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.* import com.intellij.util.lang.CompoundRuntimeException import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import java.io.IOException import java.nio.file.Path import java.nio.file.Paths import kotlin.properties.Delegates class TemporaryDirectory : ExternalResource() { private val paths = SmartList<Path>() private var sanitizedName: String by Delegates.notNull() override fun apply(base: Statement, description: Description): Statement { sanitizedName = FileUtil.sanitizeFileName(description.methodName, false) return super.apply(base, description) } override fun after() { val errors = SmartList<Throwable>() for (path in paths) { try { path.deleteRecursively() } catch (e: Throwable) { errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) paths.clear() } fun newPath(directoryName: String? = null, refreshVfs: Boolean = false): Path { val path = generatePath(directoryName) if (refreshVfs) { path.refreshVfs() } return path } private fun generatePath(suffix: String?): Path { var fileName = sanitizedName if (suffix != null) { fileName += "_$suffix" } var path = generateTemporaryPath(fileName) paths.add(path) return path } fun newVirtualDirectory(directoryName: String? = null): VirtualFile { val path = generatePath(directoryName) path.createDirectories() val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.systemIndependentPath) VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile) return virtualFile!! } } fun generateTemporaryPath(fileName: String?): Path { val tempDirectory = Paths.get(FileUtilRt.getTempDirectory()) var path = tempDirectory.resolve(fileName) var i = 0 while (path.exists() && i < 9) { path = tempDirectory.resolve("${fileName}_$i") i++ } if (path.exists()) { throw IOException("Cannot generate unique random path") } return path } fun VirtualFile.writeChild(relativePath: String, data: String) = VfsTestUtil.createFile(this, relativePath, data)
apache-2.0
4560cc7818bd49cb0ce322aa57dcaaf5
29.79
113
0.730019
4.378378
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/data/dao/response/PubplansResponse.kt
2
1308
package ru.fantlab.android.data.dao.response import com.github.kittinunf.fuel.core.ResponseDeserializable import com.google.gson.JsonParser import ru.fantlab.android.data.dao.Pageable import ru.fantlab.android.data.dao.model.Pubplans import ru.fantlab.android.provider.rest.DataManager data class PubplansResponse( val editions: Pageable<Pubplans.Object>, val publisherList: List<Pubplans.Publisher> ) { class Deserializer : ResponseDeserializable<PubplansResponse> { override fun deserialize(content: String): PubplansResponse { val jsonObject = JsonParser().parse(content).asJsonObject val items: ArrayList<Pubplans.Object> = arrayListOf() val publishers: ArrayList<Pubplans.Publisher> = arrayListOf() val array = jsonObject.getAsJsonArray("objects") array.map { items.add(DataManager.gson.fromJson(it, Pubplans.Object::class.java)) } val publishersArray = jsonObject.getAsJsonArray("publisher_list") publishersArray.map { publishers.add(DataManager.gson.fromJson(it, Pubplans.Publisher::class.java)) } val totalCount = jsonObject.getAsJsonPrimitive("total_count").asInt val lastPage = jsonObject.getAsJsonPrimitive("page_count").asInt val responses = Pageable(lastPage, totalCount, items) return PubplansResponse(responses, publishers) } } }
gpl-3.0
1e4cd8755b73025776a29e7bdad6d6dd
34.378378
81
0.778287
3.869822
false
false
false
false
ligee/kotlin-jupyter
build-plugin/src/build/util/repositories.kt
1
1429
package build.util import org.gradle.api.Project import org.gradle.kotlin.dsl.maven import org.gradle.kotlin.dsl.repositories const val INTERNAL_TEAMCITY_URL = "https://buildserver.labs.intellij.net" const val PUBLIC_TEAMCITY_URL = "https://teamcity.jetbrains.com" class TeamcityProject( val url: String, val projectId: String ) val INTERNAL_KOTLIN_TEAMCITY = TeamcityProject(INTERNAL_TEAMCITY_URL, "Kotlin_KotlinDev_Artifacts") val PUBLIC_KOTLIN_TEAMCITY = TeamcityProject(PUBLIC_TEAMCITY_URL, "Kotlin_KotlinPublic_Artifacts") const val TEAMCITY_REQUEST_ENDPOINT = "guestAuth/app/rest/builds" fun Project.addAllBuildRepositories() { val kotlinVersion = rootProject.defaultVersionCatalog.versions.devKotlin repositories { mavenLocal() mavenCentral() gradlePluginPortal() // Kotlin Dev releases are published here every night maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/dev") for (teamcity in listOf(INTERNAL_KOTLIN_TEAMCITY, PUBLIC_KOTLIN_TEAMCITY)) { val locator = "buildType:(id:${teamcity.projectId}),number:$kotlinVersion,branch:default:any/artifacts/content/maven" maven("${teamcity.url}/$TEAMCITY_REQUEST_ENDPOINT/$locator") } // Used for TeamCity build val m2LocalPath = file(".m2/repository") if (m2LocalPath.exists()) { maven(m2LocalPath.toURI()) } } }
apache-2.0
94b10addb8d8962c3055830b78d26c78
33.02381
129
0.709587
4.094556
false
false
false
false
bogerchan/National-Geography
app/src/main/java/me/boger/geographic/biz/detailpage/DetailPagePresenterImpl.kt
1
5620
package me.boger.geographic.biz.detailpage import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import com.facebook.common.executors.CallerThreadExecutor import com.facebook.common.references.CloseableReference import com.facebook.datasource.DataSource import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber import com.facebook.imagepipeline.image.CloseableImage import com.facebook.imagepipeline.request.ImageRequest import me.boger.geographic.R import me.boger.geographic.core.NGRumtime import me.boger.geographic.core.NGUtil import me.boger.geographic.biz.common.ContentType import me.boger.geographic.util.Timber import java.io.File import java.io.IOException import java.io.OutputStream import java.util.* /** * Created by BogerChan on 2017/6/30. */ class DetailPagePresenterImpl : IDetailPagePresenter { private var mUI: IDetailPageUI? = null private val mModel: IDetailPageModel by lazy { DetailPageModelImpl() } override fun init(ui: IDetailPageUI) { mUI = ui if (ui.hasOfflineData()) { ui.refreshData(ui.getOfflineData().picture) ui.contentType = ContentType.CONTENT } else { mModel.requestDetailPageData(ui.getDetailPageDataId(), onStart = { ui.contentType = ContentType.LOADING }, onError = { ui.contentType = ContentType.ERROR }, onComplete = { ui.contentType = ContentType.CONTENT }, onNext = { NGRumtime.favoriteNGDataSupplier.syncFavoriteState(it) ui.refreshData(it.picture) }) } } override fun shareDetailPageImage(url: String) { mUI?.showTipMessage(R.string.tip_share_img_start) fetchImage( url, File(NGRumtime.cacheImageDir, NGUtil.toMD5(url)), { val intent = Intent(Intent.ACTION_SEND) intent.type = "image/jpg" intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(it)) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK mUI?.startActivity(Intent.createChooser(intent, mUI?.getResourceString(R.string.title_share))) }, { mUI?.showTipMessage(R.string.tip_share_img_error) }) } override fun saveDetailPageImage(url: String) { mUI?.showTipMessage(R.string.tip_save_img_start) fetchImage( url, File(NGRumtime.externalAlbumDir, "${NGUtil.toMD5(url)}.jpg"), { if (mUI == null) { return@fetchImage } mUI!!.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(it))) mUI!!.showTipMessage( String.format(Locale.US, mUI!!.getResourceString(R.string.template_tip_save_img_complete), it.absolutePath)) }, { mUI?.showTipMessage(R.string.tip_share_img_error) }) } override fun setDetailPageItemFavoriteState(data: DetailPagePictureData) { val supplier = NGRumtime.favoriteNGDataSupplier if (data.favorite) { data.favorite = false if (!supplier.removeDetailPageDataToFavorite(data)) { data.favorite = true } } else { data.favorite = true if (!supplier.addDetailPageDataToFavorite(data)) { data.favorite = false } } mUI?.setFavoriteButtonState(data.favorite) } private fun fetchImage( url: String, dstFile: File, succ: (File) -> Unit, err: () -> Unit) { val imagePipline = Fresco.getImagePipeline() val dataSource = imagePipline.fetchDecodedImage(ImageRequest.fromUri(url), ImageRequest.RequestLevel.FULL_FETCH) dataSource.subscribe(object : BaseBitmapDataSubscriber() { override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>?) { err() } override fun onNewResultImpl(bitmap: Bitmap?) { if (bitmap == null) { err() return } if (!saveBitmap(bitmap, dstFile)) { err() return } succ(dstFile) } }, CallerThreadExecutor.getInstance()) } private fun saveBitmap(bmp: Bitmap, file: File): Boolean { var stream: OutputStream? = null try { stream = file.outputStream() file.createNewFile() bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream) return true } catch (e: IOException) { Timber.e(e) return false } finally { stream?.close() } } override fun destroy() { mModel.cancelPendingCall() } override fun onSaveInstanceState(outState: Bundle?) { mModel.onSaveInstanceState(outState) } override fun restoreDataIfNeed(savedInstanceState: Bundle?) { mModel.restoreDataIfNeed(savedInstanceState) } }
apache-2.0
5ce0c32416feac8156273e6ca7059e78
33.066667
136
0.569929
4.726661
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem1824.kt
1
1206
package leetcode import kotlin.math.min /** * https://leetcode.com/problems/minimum-sideway-jumps/ */ class Problem1824 { fun minSideJumps(obstacles: IntArray): Int { return minSideJumps(obstacles, lane = 2, index = 0, memo = Array(obstacles.size) { IntArray(4) { -1 } }) } private fun minSideJumps(obstacles: IntArray, lane: Int, index: Int, memo: Array<IntArray>): Int { if (obstacles.size == index) { return 0 } if (obstacles[index] == lane) { return Int.MAX_VALUE } if (memo[index][lane] != -1) { return memo[index][lane] } val noSideJump = minSideJumps(obstacles, lane, index + 1, memo) var hasSideJump = Int.MAX_VALUE for (l in 1..3) { if (l == lane || obstacles[index] == l) { continue } var sideJump = minSideJumps(obstacles, l, index + 1, memo) if (sideJump != Int.MAX_VALUE) { sideJump++ } hasSideJump = min(hasSideJump, sideJump) } val min = min(noSideJump, hasSideJump) memo[index][lane] = min return min } }
mit
915db1e8db6ee83ef771acd6a1ba8b08
29.15
102
0.532338
3.63253
false
false
false
false
naturlecso/NaturShutd
app/src/main/java/hu/naturlecso/naturshutd/ui/adapter/HostListAdapter.kt
1
992
package hu.naturlecso.naturshutd.ui.adapter import android.content.Context import android.databinding.ViewDataBinding import java.util.ArrayList import hu.naturlecso.naturshutd.R import hu.naturlecso.naturshutd.databinding.HostItemBinding import hu.naturlecso.naturshutd.host.Host import hu.naturlecso.naturshutd.ui.viewmodel.HostItemViewModel class HostListAdapter(private val context: Context) : BaseMvvmRecyclerAdapter<Host>(R.layout.host_item) { private var items: List<Host> = emptyList() override fun bind(binding: ViewDataBinding, position: Int, item: Host) { (binding as HostItemBinding).viewmodel = HostItemViewModel(context, item) } override fun getItemCount(): Int = items.size override fun getItemId(position: Int): Long { return -1L //TODO items.get(position).id; } override fun getItem(position: Int): Host = items[position] fun swap(items: List<Host>) { this.items = items notifyDataSetChanged() } }
gpl-3.0
fd503ce9fcf1177593b4431d425bbabb
30
105
0.742944
3.743396
false
false
false
false
Jkly/gdx-box2d-kotlin
src/test/kotlin/pro/gramcode/box2d/dsl/BodyFixtureDslSpec.kt
1
1308
package pro.gramcode.box2d.dsl import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Fixture import com.badlogic.gdx.physics.box2d.Shape import com.badlogic.gdx.physics.box2d.World import com.nhaarman.mockito_kotlin.argThat import com.nhaarman.mockito_kotlin.spy import com.nhaarman.mockito_kotlin.verify import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it object BodyFixtureDslSpec : Spek({ describe("a body fixture DSL") { var world: World? = null beforeEachTest { world = World(Vector2.Zero, false) } afterEachTest { world?.dispose() } context("adding a body fixture") { it("should call the callback function with newly created fixture") { val callback = spy({ _:Fixture -> }) val callback2 = spy({ _:Fixture -> }) world!!.createBody { circle(callback) { } polygon(callback2) { } } verify(callback).invoke(argThat { shape.type == Shape.Type.Circle}) verify(callback2).invoke(argThat { shape.type == Shape.Type.Polygon}) } } } })
apache-2.0
50537e989f77a876c364b04ee38bd0b8
33.447368
85
0.619266
4.074766
false
true
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/command/Command.kt
1
2966
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * 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 2 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.maddyhome.idea.vim.command import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.editor.actionSystem.EditorAction import com.maddyhome.idea.vim.handler.EditorActionHandlerBase import java.util.* import javax.swing.KeyStroke /** * This represents a single Vim command to be executed. It may optionally include an argument if appropriate for * the command. The command has a count and a type. */ data class Command( var rawCount: Int, val actionId: String?, var action: AnAction?, val type: Type, var flags: EnumSet<CommandFlags> ) { init { if (action is EditorAction) { val handler = (action as EditorAction).handler if (handler is EditorActionHandlerBase) { handler.process(this) } } } var count: Int get() = rawCount.coerceAtLeast(1) set(value) { rawCount = value } var keys: List<KeyStroke> = emptyList() var argument: Argument? = null enum class Type { /** * Represents undefined commands. */ UNDEFINED, /** * Represents commands that actually move the cursor and can be arguments to operators. */ MOTION, /** * Represents commands that insert new text into the editor. */ INSERT, /** * Represents commands that remove text from the editor. */ DELETE, /** * Represents commands that change text in the editor. */ CHANGE, /** * Represents commands that copy text in the editor. */ COPY, PASTE, RESET, /** * Represents commands that select the register. */ SELECT_REGISTER, OTHER_READONLY, OTHER_WRITABLE, OTHER_READ_WRITE, /** * Represent commands that don't require an outer read or write action for synchronization. */ OTHER_SELF_SYNCHRONIZED, COMPLETION; val isRead: Boolean get() = when (this) { MOTION, COPY, SELECT_REGISTER, OTHER_READONLY, OTHER_READ_WRITE, COMPLETION -> true else -> false } val isWrite: Boolean get() = when (this) { INSERT, DELETE, CHANGE, PASTE, RESET, OTHER_WRITABLE, OTHER_READ_WRITE -> true else -> false } } }
gpl-2.0
6a200132e8a942fe73c7b9b95602344f
26.220183
112
0.667903
4.279942
false
false
false
false
da1z/intellij-community
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PyAddNewEnvironmentPanel.kt
1
3130
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.newProject.steps import com.intellij.openapi.projectRoots.Sdk import com.intellij.ui.ColoredListCellRenderer import com.intellij.util.ui.FormBuilder import com.jetbrains.python.sdk.PySdkSettings import com.jetbrains.python.sdk.add.PyAddNewCondaEnvPanel import com.jetbrains.python.sdk.add.PyAddNewEnvPanel import com.jetbrains.python.sdk.add.PyAddNewVirtualEnvPanel import com.jetbrains.python.sdk.add.PyAddSdkPanel import java.awt.BorderLayout import java.awt.event.ItemEvent import javax.swing.JComboBox import javax.swing.JList /** * @author vlan */ class PyAddNewEnvironmentPanel(existingSdks: List<Sdk>, newProjectPath: String?) : PyAddSdkPanel() { override val panelName = "New environment using" override val nameExtensionComponent: JComboBox<PyAddNewEnvPanel> override var newProjectPath: String? = newProjectPath set(value) { field = value for (panel in panels) { panel.newProjectPath = newProjectPath } } private val panels = listOf(PyAddNewVirtualEnvPanel(null, existingSdks, newProjectPath), PyAddNewCondaEnvPanel(null, existingSdks, newProjectPath)) var selectedPanel = panels.find { it.envName == PySdkSettings.instance.preferredEnvironmentType } ?: panels[0] private val listeners = mutableListOf<Runnable>() init { nameExtensionComponent = JComboBox(panels.toTypedArray()).apply { renderer = object : ColoredListCellRenderer<PyAddNewEnvPanel>() { override fun customizeCellRenderer(list: JList<out PyAddNewEnvPanel>, value: PyAddNewEnvPanel?, index: Int, selected: Boolean, hasFocus: Boolean) { val panel = value ?: return append(panel.envName) icon = panel.icon } } selectedItem = selectedPanel addItemListener { if (it.stateChange == ItemEvent.SELECTED) { val selected = it.item as? PyAddSdkPanel ?: return@addItemListener for (panel in panels) { val isSelected = panel == selected panel.isVisible = isSelected if (isSelected) { selectedPanel = panel } } for (listener in listeners) { listener.run() } } } } layout = BorderLayout() val formBuilder = FormBuilder.createFormBuilder().apply { for (panel in panels) { addComponent(panel) panel.isVisible = panel == selectedPanel } } add(formBuilder.panel, BorderLayout.NORTH) } override fun getOrCreateSdk(): Sdk? { val createdSdk = selectedPanel.getOrCreateSdk() PySdkSettings.instance.preferredEnvironmentType = selectedPanel.envName return createdSdk } override fun validateAll() = selectedPanel.validateAll() override fun addChangeListener(listener: Runnable) { for (panel in panels) { panel.addChangeListener(listener) } listeners += listener } }
apache-2.0
6eb8c7cae39c6fd0f6fe2228e428d8f9
33.395604
140
0.686581
4.860248
false
false
false
false
k9mail/k-9
backend/imap/src/test/java/com/fsck/k9/backend/imap/TestImapFolder.kt
2
5309
package com.fsck.k9.backend.imap import com.fsck.k9.mail.BodyFactory import com.fsck.k9.mail.FetchProfile import com.fsck.k9.mail.Flag import com.fsck.k9.mail.Message import com.fsck.k9.mail.MessageRetrievalListener import com.fsck.k9.mail.Part import com.fsck.k9.mail.store.imap.FetchListener import com.fsck.k9.mail.store.imap.ImapFolder import com.fsck.k9.mail.store.imap.ImapMessage import com.fsck.k9.mail.store.imap.OpenMode import com.fsck.k9.mail.store.imap.createImapMessage import java.util.Date open class TestImapFolder(override val serverId: String) : ImapFolder { override var mode: OpenMode? = null protected set override var messageCount: Int = 0 var wasExpunged: Boolean = false private set val isClosed: Boolean get() = mode == null private val messages = mutableMapOf<Long, Message>() private val messageFlags = mutableMapOf<Long, MutableSet<Flag>>() private var uidValidity: Long? = null fun addMessage(uid: Long, message: Message) { require(!messages.containsKey(uid)) { "Folder '$serverId' already contains a message with the UID $uid" } messages[uid] = message messageFlags[uid] = mutableSetOf() messageCount = messages.size } fun removeAllMessages() { messages.clear() messageFlags.clear() } fun setUidValidity(value: Long) { uidValidity = value } override fun open(mode: OpenMode) { this.mode = mode } override fun close() { mode = null } override fun exists(): Boolean { throw UnsupportedOperationException("not implemented") } override fun getUidValidity() = uidValidity override fun getMessage(uid: String): ImapMessage { return createImapMessage(uid) } override fun getUidFromMessageId(messageId: String): String? { throw UnsupportedOperationException("not implemented") } override fun getMessages( start: Int, end: Int, earliestDate: Date?, listener: MessageRetrievalListener<ImapMessage>? ): List<ImapMessage> { require(start > 0) require(end >= start) require(end <= messages.size) return messages.keys.sortedDescending() .slice((start - 1) until end) .map { createImapMessage(uid = it.toString()) } } override fun areMoreMessagesAvailable(indexOfOldestMessage: Int, earliestDate: Date?): Boolean { throw UnsupportedOperationException("not implemented") } override fun fetch( messages: List<ImapMessage>, fetchProfile: FetchProfile, listener: FetchListener?, maxDownloadSize: Int ) { if (messages.isEmpty()) return for (imapMessage in messages) { val uid = imapMessage.uid.toLong() val flags = messageFlags[uid].orEmpty().toSet() imapMessage.setFlags(flags, true) val storedMessage = this.messages[uid] ?: error("Message $uid not found") for (header in storedMessage.headers) { imapMessage.addHeader(header.name, header.value) } imapMessage.body = storedMessage.body listener?.onFetchResponse(imapMessage, isFirstResponse = true) } } override fun fetchPart( message: ImapMessage, part: Part, bodyFactory: BodyFactory, maxDownloadSize: Int ) { throw UnsupportedOperationException("not implemented") } override fun search( queryString: String?, requiredFlags: Set<Flag>?, forbiddenFlags: Set<Flag>?, performFullTextSearch: Boolean ): List<ImapMessage> { throw UnsupportedOperationException("not implemented") } override fun appendMessages(messages: List<Message>): Map<String, String>? { throw UnsupportedOperationException("not implemented") } override fun setFlags(flags: Set<Flag>, value: Boolean) { if (value) { for (messageFlagSet in messageFlags.values) { messageFlagSet.addAll(flags) } } else { for (messageFlagSet in messageFlags.values) { messageFlagSet.removeAll(flags) } } } override fun setFlags(messages: List<ImapMessage>, flags: Set<Flag>, value: Boolean) { for (message in messages) { val uid = message.uid.toLong() val messageFlagSet = messageFlags[uid] ?: error("Unknown message with UID $uid") if (value) { messageFlagSet.addAll(flags) } else { messageFlagSet.removeAll(flags) } } } override fun copyMessages(messages: List<ImapMessage>, folder: ImapFolder): Map<String, String>? { throw UnsupportedOperationException("not implemented") } override fun moveMessages(messages: List<ImapMessage>, folder: ImapFolder): Map<String, String>? { throw UnsupportedOperationException("not implemented") } override fun expunge() { mode = OpenMode.READ_WRITE wasExpunged = true } override fun expungeUids(uids: List<String>) { throw UnsupportedOperationException("not implemented") } }
apache-2.0
cb17e94768e9444c88cdffe52da721eb
28.659218
102
0.635713
4.537607
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/HasActualMarker.kt
2
1990
// 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.highlighter.markers import com.intellij.ide.util.DefaultPsiElementCellRenderer import com.intellij.psi.PsiElement import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.psi.KtDeclaration fun getPlatformActualTooltip(declaration: KtDeclaration): String? { val actualDeclarations = declaration.actualsForExpected().mapNotNull { it.toDescriptor() } val modulesString = getModulesStringForExpectActualMarkerTooltip(actualDeclarations) ?: return null return KotlinBundle.message("highlighter.prefix.text.has.actuals.in", modulesString) } fun KtDeclaration.allNavigatableActualDeclarations(): Set<KtDeclaration> = actualsForExpected() + findMarkerBoundDeclarations().flatMap { it.actualsForExpected().asSequence() } class ActualExpectedPsiElementCellRenderer : DefaultPsiElementCellRenderer() { override fun getContainerText(element: PsiElement?, name: String?) = "" } @Nls fun KtDeclaration.navigateToActualTitle() = KotlinBundle.message("highlighter.title.choose.actual.for", name.toString()) @Nls fun KtDeclaration.navigateToActualUsagesTitle() = KotlinBundle.message("highlighter.title.actuals.for", name.toString()) fun buildNavigateToActualDeclarationsPopup(element: PsiElement?): NavigationPopupDescriptor? { return element?.markerDeclaration?.let { val navigatableActualDeclarations = it.allNavigatableActualDeclarations() if (navigatableActualDeclarations.isEmpty()) return null return NavigationPopupDescriptor( navigatableActualDeclarations, it.navigateToActualTitle(), it.navigateToActualUsagesTitle(), ActualExpectedPsiElementCellRenderer() ) } }
apache-2.0
cc5f994a50d9b7e289201cae8570976a
44.227273
120
0.78995
4.853659
false
false
false
false
android/connectivity-samples
UwbRanging/app/src/main/java/com/google/apps/hellouwb/ui/home/HomeViewModel.kt
1
3657
/* * * Copyright (C) 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 com.google.apps.hellouwb.ui.home import androidx.core.uwb.RangingPosition import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.google.apps.hellouwb.data.UwbRangingControlSource import com.google.apps.uwbranging.EndpointEvents import com.google.apps.uwbranging.UwbEndpoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* class HomeViewModel(uwbRangingControlSource: UwbRangingControlSource) : ViewModel() { private val _uiState: MutableStateFlow<HomeUiState> = MutableStateFlow(HomeUiStateImpl(listOf(), listOf(), false)) private val endpoints = mutableListOf<UwbEndpoint>() private val endpointPositions = mutableMapOf<UwbEndpoint, RangingPosition>() private var isRanging = false private fun updateUiState(): HomeUiState { return HomeUiStateImpl( endpoints .mapNotNull { endpoint -> endpointPositions[endpoint]?.let { position -> ConnectedEndpoint(endpoint, position) } } .toList(), endpoints.filter { !endpointPositions.containsKey(it) }.toList(), isRanging ) } val uiState = _uiState.asStateFlow() init { uwbRangingControlSource .observeRangingResults() .onEach { result -> when (result) { is EndpointEvents.EndpointFound -> endpoints.add(result.endpoint) is EndpointEvents.UwbDisconnected -> endpointPositions.remove(result.endpoint) is EndpointEvents.PositionUpdated -> endpointPositions[result.endpoint] = result.position is EndpointEvents.EndpointLost -> { endpoints.remove(result.endpoint) endpointPositions.remove(result.endpoint) } else -> return@onEach } _uiState.update { updateUiState() } } .launchIn(viewModelScope) uwbRangingControlSource.isRunning .onEach { running -> isRanging = running if (!running) { endpoints.clear() endpointPositions.clear() } _uiState.update { updateUiState() } } .launchIn(CoroutineScope(Dispatchers.IO)) } private data class HomeUiStateImpl( override val connectedEndpoints: List<ConnectedEndpoint>, override val disconnectedEndpoints: List<UwbEndpoint>, override val isRanging: Boolean, ) : HomeUiState companion object { fun provideFactory( uwbRangingControlSource: UwbRangingControlSource ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return HomeViewModel(uwbRangingControlSource) as T } } } } interface HomeUiState { val connectedEndpoints: List<ConnectedEndpoint> val disconnectedEndpoints: List<UwbEndpoint> val isRanging: Boolean } data class ConnectedEndpoint(val endpoint: UwbEndpoint, val position: RangingPosition)
apache-2.0
c98f3adc52b9bccf6a13b91942a0a75d
31.945946
99
0.713426
4.69448
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/posts/prepublishing/PrepublishingPublishSettingsFragment.kt
1
2610
package org.wordpress.android.ui.posts.prepublishing import android.content.Context import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.lifecycle.ViewModelProvider import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.ui.posts.PrepublishingScreenClosedListener import org.wordpress.android.ui.posts.PublishSettingsFragment import org.wordpress.android.ui.posts.PublishSettingsFragmentType.PREPUBLISHING_NUDGES import org.wordpress.android.ui.posts.PublishSettingsViewModel import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.viewmodel.observeEvent import javax.inject.Inject class PrepublishingPublishSettingsFragment : PublishSettingsFragment() { @Inject lateinit var uiHelpers: UiHelpers private var closeListener: PrepublishingScreenClosedListener? = null override fun getContentLayout() = R.layout.prepublishing_published_settings_fragment override fun getPublishSettingsFragmentType() = PREPUBLISHING_NUDGES override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (requireActivity().applicationContext as WordPress).component().inject(this) viewModel = ViewModelProvider(requireActivity(), viewModelFactory) .get(PrepublishingPublishSettingsViewModel::class.java) } override fun onAttach(context: Context) { super.onAttach(context) closeListener = parentFragment as PrepublishingScreenClosedListener } override fun onDetach() { super.onDetach() closeListener = null } override fun setupContent(rootView: ViewGroup, viewModel: PublishSettingsViewModel) { val backButton = rootView.findViewById<View>(R.id.back_button) val toolbarTitle = rootView.findViewById<TextView>(R.id.toolbar_title) (viewModel as PrepublishingPublishSettingsViewModel).let { backButton.setOnClickListener { viewModel.onBackButtonClicked() } viewModel.navigateToHomeScreen.observeEvent(this, { closeListener?.onBackClicked() }) viewModel.updateToolbarTitle.observe(this, { uiString -> toolbarTitle.text = uiHelpers.getTextOfUiString( requireContext(), uiString ) }) } } companion object { const val TAG = "prepublishing_publish_settings_fragment_tag" fun newInstance() = PrepublishingPublishSettingsFragment() } }
gpl-2.0
f7612841a5e9cf4ff2e5108f153c5516
37.955224
89
0.733333
5.262097
false
false
false
false
danvratil/FBEventSync
app/src/main/java/cz/dvratil/fbeventsync/AllDayReminderPreferenceActivity.kt
1
7041
/* Copyright (C) 2018 Daniel Vrátil <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cz.dvratil.fbeventsync import android.content.Context import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.format.DateFormat import android.view.View import android.view.ViewGroup import android.widget.* import android.view.MenuItem class AllDayReminderPreferenceActivity : AppCompatActivity() { class AllDayReminderAdapter(context: AllDayReminderPreferenceActivity, layoutId: Int, textViewId: Int) : ArrayAdapter<FBReminder>(context, layoutId, textViewId) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = super.getView(position, convertView, parent) view.findViewById<Button>(R.id.allday_reminder_remove_button).setOnClickListener { val activity = context as AllDayReminderPreferenceActivity var reminders = activity.getReminders().toMutableList() reminders.remove(getItem(position)) activity.setReminders(reminders) } return view } } private lateinit var m_listView: ListView private lateinit var m_viewAdapter: AllDayReminderAdapter private lateinit var m_calendarType: FBCalendar.CalendarType override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.pref_allday_reminder_layout) setSupportActionBar(findViewById<View>(R.id.pref_allday_reminder_toolbar) as Toolbar) supportActionBar?.apply { setDisplayShowHomeEnabled(true) setDisplayHomeAsUpEnabled(true) } m_calendarType = when (intent.extras?.getString("calendarType")) { getString(R.string.pref_calendar_attending_allday_reminders) -> FBCalendar.CalendarType.TYPE_ATTENDING getString(R.string.pref_calendar_tentative_allday_reminders) -> FBCalendar.CalendarType.TYPE_MAYBE getString(R.string.pref_calendar_not_responded_allday_reminders) -> FBCalendar.CalendarType.TYPE_NOT_REPLIED getString(R.string.pref_calendar_declined_allday_reminders) -> FBCalendar.CalendarType.TYPE_DECLINED getString(R.string.pref_calendar_birthday_allday_reminders) -> FBCalendar.CalendarType.TYPE_BIRTHDAY else -> throw Exception("Invalid calendar type in intent!") } m_viewAdapter = AllDayReminderAdapter(this, R.layout.allday_reminder_item_layout, R.id.allday_reminder_item_text) m_listView = findViewById<ListView>(R.id.pref_allday_reminders_listView).apply { adapter = m_viewAdapter } findViewById<FloatingActionButton>(R.id.pref_allday_reminders_fab).setOnClickListener { val view = layoutInflater.inflate(R.layout.allday_reminder_dialog, null) val dayPicker = view.findViewById<NumberPicker>(R.id.allday_reminder_day_picker).apply { minValue = 1 // FIXME: Investigate if we can have a reminder on the day of the event value = 1 maxValue = 30 } val timePicker = view.findViewById<TimePicker>(R.id.allday_reminder_time_picker).apply { // TODO: Preselects current time by default, maybe we could round up/down to nearest half-hour? setIs24HourView(DateFormat.is24HourFormat(context)) } AlertDialog.Builder(this) .setView(view) .setPositiveButton(R.string.btn_save) { dialog, _ -> val currentReminders = getReminders().toMutableList() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { currentReminders.add(FBReminder(dayPicker.value, timePicker.hour, timePicker.minute, true)) } else { currentReminders.add(FBReminder(dayPicker.value, timePicker.currentHour, timePicker.currentMinute, true)) } setReminders(currentReminders) dialog.dismiss() } .setNegativeButton(R.string.btn_cancel) { dialog, _ -> dialog.cancel() } .create() .show() } m_viewAdapter.addAll(getReminders()) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { // Workaround an activity stack related crash when navigating back using the // toolbar home button finish() return true } else { return super.onOptionsItemSelected(item) } } private fun getReminders(): List<FBReminder> { var prefs = Preferences(this) return when (m_calendarType) { FBCalendar.CalendarType.TYPE_ATTENDING -> prefs.attendingCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_MAYBE -> prefs.maybeAttendingCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_DECLINED -> prefs.declinedCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_NOT_REPLIED -> prefs.notRespondedCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_BIRTHDAY -> prefs.birthdayCalendarAllDayReminders() } } private fun setReminders(reminders: List<FBReminder>) { var prefs = Preferences(this) when (m_calendarType) { FBCalendar.CalendarType.TYPE_ATTENDING -> prefs.setAttendingCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_MAYBE -> prefs.setMaybeAttendingCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_DECLINED -> prefs.setDeclinedCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_NOT_REPLIED -> prefs.setNotRespondedCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_BIRTHDAY -> prefs.setBirthdayCalendarAllDayReminders(reminders) } m_viewAdapter.clear() m_viewAdapter.addAll(reminders) } }
gpl-3.0
ee962e96ef454a91894868874753a3ad
46.574324
133
0.671023
4.715338
false
false
false
false
IgorGanapolsky/cheesesquare
app/src/main/java/com/support/android/designlibdemo/MainActivity.kt
1
4962
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.support.android.designlibdemo import android.os.Build import android.os.Bundle import android.support.design.widget.NavigationView import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.GravityCompat import android.support.v4.view.ViewPager import android.support.v4.widget.DrawerLayout import android.support.v7.app.AppCompatActivity import android.support.v7.app.AppCompatDelegate import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.include_list_viewpager.* import java.util.* class MainActivity : AppCompatActivity() { private var mDrawerLayout: DrawerLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) val ab = supportActionBar ab!!.setHomeAsUpIndicator(R.drawable.ic_menu) ab.setDisplayHomeAsUpEnabled(true) setupDrawerContent(nav_view) setupViewPager(viewpager) fab.setOnClickListener { view -> Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } tabs.setupWithViewPager(viewpager) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.sample_actions, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { when (AppCompatDelegate.getDefaultNightMode()) { AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM -> menu.findItem(R.id.menu_night_mode_system).isChecked = true AppCompatDelegate.MODE_NIGHT_AUTO -> menu.findItem(R.id.menu_night_mode_auto).isChecked = true AppCompatDelegate.MODE_NIGHT_YES -> menu.findItem(R.id.menu_night_mode_night).isChecked = true AppCompatDelegate.MODE_NIGHT_NO -> menu.findItem(R.id.menu_night_mode_day).isChecked = true } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { mDrawerLayout!!.openDrawer(GravityCompat.START) return true } R.id.menu_night_mode_system -> setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) R.id.menu_night_mode_day -> setNightMode(AppCompatDelegate.MODE_NIGHT_NO) R.id.menu_night_mode_night -> setNightMode(AppCompatDelegate.MODE_NIGHT_YES) R.id.menu_night_mode_auto -> setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO) } return super.onOptionsItemSelected(item) } private fun setNightMode(@AppCompatDelegate.NightMode nightMode: Int) { AppCompatDelegate.setDefaultNightMode(nightMode) if (Build.VERSION.SDK_INT >= 11) { recreate() } } private fun setupViewPager(viewPager: ViewPager) { val adapter = Adapter(supportFragmentManager) adapter.addFragment(CheeseListFragment(), "Category 1") adapter.addFragment(CheeseListFragment(), "Category 2") adapter.addFragment(CheeseListFragment(), "Category 3") viewPager.adapter = adapter } private fun setupDrawerContent(navigationView: NavigationView) { navigationView.setNavigationItemSelectedListener { menuItem -> menuItem.isChecked = true mDrawerLayout!!.closeDrawers() true } } internal class Adapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { private val mFragments = ArrayList<Fragment>() private val mFragmentTitles = ArrayList<String>() fun addFragment(fragment: Fragment, title: String) { mFragments.add(fragment) mFragmentTitles.add(title) } override fun getItem(position: Int): Fragment { return mFragments[position] } override fun getCount(): Int { return mFragments.size } override fun getPageTitle(position: Int): CharSequence { return mFragmentTitles[position] } } }
apache-2.0
cc19c5ec2760f9af1ce3bc5860611796
35.218978
117
0.689037
4.672316
false
false
false
false
abeemukthees/Arena
spectacle/src/main/java/com/abhi/spectacle/data/poko/ImgurEntities.kt
1
5579
package com.abhi.spectacle.data.poko import com.squareup.moshi.Json data class ImgurEntities( val data: List<ImgurData>, val success: Boolean, val status: Int ) { data class ImgurData( val id: String, val title: String, val description: Any?, val datetime: Int, val cover: String, @Json(name = "cover_width") val coverWidth: Int, @Json(name = "cover_height") val coverHeight: Int, @Json(name = "account_url") val accountUrl: String, @Json(name = "account_id") val accountId: Int, val privacy: String, val layout: String, val views: Int, val link: String, val ups: Int, val downs: Int, val points: Int, val score: Int, @Json(name = "is_album") val isAlbum: Boolean, val vote: Any?, val favorite: Boolean, val nsfw: Boolean, val section: String, @Json(name = "comment_count") val commentCount: Int, @Json(name = "favorite_count") val favoriteCount: Int, val topic: String, @Json(name = "topic_id") val topicId: Int, @Json(name = "images_count") val imagesCount: Int, @Json(name = "in_gallery") val inGallery: Boolean, @Json(name = "is_ad") val isAd: Boolean, val tags: List<Tag>, @Json(name = "ad_type") val adType: Int, @Json(name = "ad_url") val adUrl: String, @Json(name = "in_most_viral") val inMostViral: Boolean, @Json(name = "include_album_ads") val includeAlbumAds: Boolean, val images: List<Image>?, val type: String, val animated: Boolean, val width: Int, val height: Int, val size: Int, val bandwidth: Long, @Json(name = "has_sound") val hasSound: Boolean, val mp4: String, val gifv: String, @Json(name = "mp4_size") val mp4Size: Int, val looping: Boolean, val processing: Processing ) { data class Tag( val name: String, @Json(name = "display_name") val displayName: String, val followers: Int, @Json(name = "total_items") val totalItems: Int, val following: Boolean, @Json(name = "background_hash") val backgroundHash: String, @Json(name = "thumbnail_hash") val thumbnailHash: Any?, val accent: String, @Json(name = "background_is_animated") val backgroundIsAnimated: Boolean, @Json(name = "thumbnail_is_animated") val thumbnailIsAnimated: Boolean, @Json(name = "is_promoted") val isPromoted: Boolean, val description: String, @Json(name = "logo_hash") val logoHash: Any?, @Json(name = "logo_destination_url") val logoDestinationUrl: Any?, @Json(name = "description_annotations") val descriptionAnnotations: DescriptionAnnotations ) { data class DescriptionAnnotations(val id: Any ) } data class Image( val id: String, val title: Any?, val description: String, val datetime: Int, val type: String, val animated: Boolean, val width: Int, val height: Int, val size: Int, val views: Int, val bandwidth: Long, val vote: Any?, val favorite: Boolean, val nsfw: Any?, val section: Any?, @Json(name = "account_url") val accountUrl: Any?, @Json(name = "account_id") val accountId: Any?, @Json(name = "is_ad") val isAd: Boolean, @Json(name = "in_most_viral") val inMostViral: Boolean, @Json(name = "has_sound") val hasSound: Boolean, val tags: List<Any>, @Json(name = "ad_type") val adType: Int, @Json(name = "ad_url") val adUrl: String, @Json(name = "in_gallery") val inGallery: Boolean, val link: String, @Json(name = "mp4_size") val mp4Size: Int, val mp4: String, val gifv: String, val processing: Processing, @Json(name = "comment_count") val commentCount: Any?, @Json(name = "favorite_count") val favoriteCount: Any?, val ups: Any?, val downs: Any?, val points: Any?, val score: Any? ) { data class Processing( val status: String ) } data class Processing( val status: String ) } }
apache-2.0
a597b21e3aae88375b9fa340d4fef6ce
33.02439
66
0.448109
4.676446
false
false
false
false
DiUS/pact-jvm
consumer/groovy/src/main/kotlin/au/com/dius/pact/consumer/groovy/Matchers.kt
1
20286
package au.com.dius.pact.consumer.groovy import au.com.dius.pact.core.matchers.UrlMatcherSupport import au.com.dius.pact.core.model.generators.DateGenerator import au.com.dius.pact.core.model.generators.DateTimeGenerator import au.com.dius.pact.core.model.generators.Generator import au.com.dius.pact.core.model.generators.RandomBooleanGenerator import au.com.dius.pact.core.model.generators.RandomDecimalGenerator import au.com.dius.pact.core.model.generators.RandomHexadecimalGenerator import au.com.dius.pact.core.model.generators.RandomIntGenerator import au.com.dius.pact.core.model.generators.RandomStringGenerator import au.com.dius.pact.core.model.generators.RegexGenerator import au.com.dius.pact.core.model.generators.TimeGenerator import au.com.dius.pact.core.model.generators.UuidGenerator import au.com.dius.pact.core.model.matchingrules.MatchingRule import au.com.dius.pact.core.model.matchingrules.MaxTypeMatcher import au.com.dius.pact.core.model.matchingrules.MinMaxTypeMatcher import au.com.dius.pact.core.model.matchingrules.MinTypeMatcher import au.com.dius.pact.core.model.matchingrules.NumberTypeMatcher import au.com.dius.pact.core.model.matchingrules.RegexMatcher import au.com.dius.pact.core.support.isNotEmpty import com.mifmif.common.regex.Generex import mu.KLogging import org.apache.commons.lang3.time.DateFormatUtils import org.apache.commons.lang3.time.DateUtils import java.text.ParseException import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.util.Date import java.util.regex.Pattern const val HEXADECIMAL = "[0-9a-fA-F]+" const val IP_ADDRESS = "(\\d{1,3}\\.)+\\d{1,3}" const val UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" const val TEN = 10 const val TYPE = "type" const val DECIMAL = "decimal" const val DATE_2000 = 949323600000L const val INTEGER = "integer" /** * Exception for handling invalid matchers */ class InvalidMatcherException(message: String) : RuntimeException(message) /** * Marker class for generated values */ data class GeneratedValue(val expression: String, val exampleValue: Any?) /** * Base class for matchers */ open class Matcher @JvmOverloads constructor( open val value: Any? = null, open val matcher: MatchingRule? = null, open val generator: Generator? = null ) /** * Regular Expression Matcher */ class RegexpMatcher @JvmOverloads constructor( val regex: String, value: String? = null ) : Matcher(value, RegexMatcher(regex, value), if (value == null) RegexGenerator(regex) else null) { override val value: Any? get() = super.value ?: Generex(regex).random() } class HexadecimalMatcher @JvmOverloads constructor( value: String? = null ) : Matcher( value ?: "1234a", RegexMatcher(HEXADECIMAL, value), if (value == null) RandomHexadecimalGenerator(10) else null ) /** * Matcher for validating same types */ class TypeMatcher @JvmOverloads constructor( value: Any? = null, val type: String = "type", generator: Generator? = null ) : Matcher( value, when (type) { "integer" -> NumberTypeMatcher(NumberTypeMatcher.NumberType.INTEGER) "decimal" -> NumberTypeMatcher(NumberTypeMatcher.NumberType.DECIMAL) "number" -> NumberTypeMatcher(NumberTypeMatcher.NumberType.NUMBER) else -> au.com.dius.pact.core.model.matchingrules.TypeMatcher }, generator ) class DateTimeMatcher @JvmOverloads constructor( val pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern, value: String? = null, expression: String? = null ) : Matcher( value, au.com.dius.pact.core.model.matchingrules.TimestampMatcher(pattern), if (value == null) DateTimeGenerator(pattern, expression) else null ) { override val value: Any? get() = super.value ?: DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.systemDefault()).format( Date(DATE_2000).toInstant()) } class TimeMatcher @JvmOverloads constructor( val pattern: String = DateFormatUtils.ISO_TIME_FORMAT.pattern, value: String? = null, expression: String? = null ) : Matcher( value, au.com.dius.pact.core.model.matchingrules.TimeMatcher(pattern), if (value == null) TimeGenerator(pattern, expression) else null ) { override val value: Any? get() = super.value ?: DateFormatUtils.format(Date(DATE_2000), pattern) } class DateMatcher @JvmOverloads constructor( val pattern: String = DateFormatUtils.ISO_DATE_FORMAT.pattern, value: String? = null, expression: String? = null ) : Matcher( value, au.com.dius.pact.core.model.matchingrules.DateMatcher(pattern), if (value == null) DateGenerator(pattern, expression) else null ) { override val value: Any? get() = super.value ?: DateFormatUtils.format(Date(DATE_2000), pattern) } /** * Matcher for universally unique IDs */ class UuidMatcher @JvmOverloads constructor( value: Any? = null ) : Matcher( value ?: "e2490de5-5bd3-43d5-b7c4-526e33f71304", RegexMatcher(UUID_REGEX), if (value == null) UuidGenerator else null ) /** * Base class for like matchers */ open class LikeMatcher @JvmOverloads constructor( value: Any? = null, val numberExamples: Int = 1, matcher: MatchingRule? = null ) : Matcher(value, matcher ?: au.com.dius.pact.core.model.matchingrules.TypeMatcher) /** * Each like matcher for arrays */ class EachLikeMatcher @JvmOverloads constructor( value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples) /** * Like matcher with a maximum size */ class MaxLikeMatcher @JvmOverloads constructor( val max: Int, value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples, MaxTypeMatcher(max)) /** * Like matcher with a minimum size */ class MinLikeMatcher @JvmOverloads constructor( val min: Int = 1, value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples, MinTypeMatcher(min)) /** * Like Matcher with a minimum and maximum size */ class MinMaxLikeMatcher @JvmOverloads constructor( val min: Int, val max: Int, value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples, MinMaxTypeMatcher(min, max)) /** * Matcher to match using equality */ class EqualsMatcher(value: Any) : Matcher(value, au.com.dius.pact.core.model.matchingrules.EqualsMatcher) /** * Matcher for string inclusion */ class IncludeMatcher(value: String) : Matcher(value, au.com.dius.pact.core.model.matchingrules.IncludeMatcher(value)) /** * Matcher that matches if any provided matcher matches */ class OrMatcher(example: Any, val matchers: List<Matcher>) : Matcher(example) /** * Matches if all provided matches match */ class AndMatcher(example: Any, val matchers: List<Matcher>) : Matcher(example) /** * Matcher to match null values */ class NullMatcher : Matcher(null, au.com.dius.pact.core.model.matchingrules.NullMatcher) /** * Match a URL by specifying the base and a series of paths. */ class UrlMatcher @JvmOverloads constructor( val basePath: String, val pathFragments: List<Any>, private val urlMatcherSupport: UrlMatcherSupport = UrlMatcherSupport(basePath, pathFragments.map { if (it is RegexpMatcher) it.matcher!! else it }) ) : Matcher(urlMatcherSupport.getExampleValue(), RegexMatcher(urlMatcherSupport.getRegexExpression())) /** * Base class for DSL matcher methods */ open class Matchers { companion object : KLogging() { /** * Match a regular expression * @param re Regular expression pattern * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun regexp(re: Pattern, value: String? = null) = regexp(re.toString(), value) /** * Match a regular expression * @param re Regular expression pattern * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun regexp(regexp: String, value: String? = null): Matcher { if (value != null && !value.matches(Regex(regexp))) { throw InvalidMatcherException("Example \"$value\" does not match regular expression \"$regexp\"") } return RegexpMatcher(regexp, value) } /** * Match a hexadecimal value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun hexValue(value: String? = null): Matcher { if (value != null && !value.matches(Regex(HEXADECIMAL))) { throw InvalidMatcherException("Example \"$value\" is not a hexadecimal value") } return HexadecimalMatcher(value) } /** * Match a numeric identifier (integer) * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun identifier(value: Any? = null): Matcher { return TypeMatcher(value ?: 12345678, INTEGER, if (value == null) RandomIntGenerator(0, Integer.MAX_VALUE) else null) } /** * Match an IP Address * @param value Example value, if not provided 127.0.0.1 will be generated */ @JvmStatic @JvmOverloads fun ipAddress(value: String? = null): Matcher { if (value != null && !value.matches(Regex(IP_ADDRESS))) { throw InvalidMatcherException("Example \"$value\" is not an ip address") } return RegexpMatcher(IP_ADDRESS, value ?: "127.0.0.1") } /** * Match a numeric value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun numeric(value: Number? = null): Matcher { return TypeMatcher(value ?: 100, "number", if (value == null) RandomDecimalGenerator(6) else null) } /** * Match a decimal value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun decimal(value: Number? = null): Matcher { return TypeMatcher(value ?: 100.0, DECIMAL, if (value == null) RandomDecimalGenerator(6) else null) } /** * Match a integer value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun integer(value: Long? = null): Matcher { return TypeMatcher(value ?: 100, INTEGER, if (value == null) RandomIntGenerator(0, Integer.MAX_VALUE) else null) } /** * Match a timestamp * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current date and time will be used */ @Deprecated("use datetime instead") @JvmStatic @JvmOverloads fun timestamp(pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern, value: String? = null): Matcher { return datetime(pattern, value) } /** * Match a timestamp generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the timestamp */ @Deprecated("use datetime instead") @JvmStatic @JvmOverloads fun timestampExpression(expression: String, pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern): Matcher { return datetimeExpression(expression, pattern) } /** * Match a datetime * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current date and time will be used */ @JvmStatic @JvmOverloads fun datetime(pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern, value: String? = null): Matcher { validateDateTimeValue(value, pattern) return DateTimeMatcher(pattern, value) } /** * Match a datetime generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the datetime */ fun datetimeExpression(expression: String, pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern): Matcher { return DateTimeMatcher(pattern, null, expression) } private fun validateTimeValue(value: String?, pattern: String?) { if (value.isNotEmpty() && pattern.isNotEmpty()) { try { DateUtils.parseDateStrictly(value, pattern) } catch (e: ParseException) { throw InvalidMatcherException("Example \"$value\" does not match pattern \"$pattern\"") } } } private fun validateDateTimeValue(value: String?, pattern: String?) { if (value.isNotEmpty() && pattern.isNotEmpty()) { try { ZonedDateTime.parse(value, DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.systemDefault())) } catch (e: DateTimeParseException) { logger.error(e) { "Example \"$value\" does not match pattern \"$pattern\"" } throw InvalidMatcherException("Example \"$value\" does not match pattern \"$pattern\"") } } } /** * Match a time * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current time will be used */ @JvmStatic @JvmOverloads fun time(pattern: String = DateFormatUtils.ISO_TIME_FORMAT.pattern, value: String? = null): Matcher { validateTimeValue(value, pattern) return TimeMatcher(pattern, value) } /** * Match a time generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the time */ @JvmStatic @JvmOverloads fun timeExpression(expression: String, pattern: String = DateFormatUtils.ISO_TIME_FORMAT.pattern): Matcher { return TimeMatcher(pattern, null, expression) } /** * Match a date * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current date will be used */ @JvmStatic @JvmOverloads fun date(pattern: String = DateFormatUtils.ISO_DATE_FORMAT.pattern, value: String? = null): Matcher { validateTimeValue(value, pattern) return DateMatcher(pattern, value) } /** * Match a date generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the date */ @JvmStatic @JvmOverloads fun dateExpression(expression: String, pattern: String = DateFormatUtils.ISO_DATE_FORMAT.pattern): Matcher { return DateMatcher(pattern, null, expression) } /** * Match a universally unique identifier (UUID) * @param value optional value to use for examples */ @JvmStatic @JvmOverloads fun uuid(value: String? = null): Matcher { if (value != null && !value.matches(Regex(UUID_REGEX))) { throw InvalidMatcherException("Example \"$value\" is not a UUID") } return UuidMatcher(value) } /** * Match any string value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun string(value: String? = null): Matcher { return if (value != null) { TypeMatcher(value) } else { TypeMatcher("string", generator = RandomStringGenerator(10)) } } /** * Match any boolean * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun bool(value: Boolean? = null): Matcher { return if (value != null) { TypeMatcher(value) } else { TypeMatcher(true, generator = RandomBooleanGenerator) } } /** * Array where each element like the following object * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun eachLike(numberExamples: Int = 1, arg: Any): Matcher { return EachLikeMatcher(arg, numberExamples) } /** * Array with maximum size and each element like the following object * @param max The maximum size of the array * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun maxLike(max: Int, numberExamples: Int = 1, arg: Any): Matcher { if (numberExamples > max) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "greater than the maximum ($max)") } return MaxLikeMatcher(max, arg, numberExamples) } /** * Array with minimum size and each element like the following object * @param min The minimum size of the array * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun minLike(min: Int, numberExamples: Int = 1, arg: Any): Matcher { if (numberExamples > 1 && numberExamples < min) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "less than the minimum ($min)") } return MinLikeMatcher(min, arg, numberExamples) } /** * Array with minimum and maximum size and each element like the following object * @param min The minimum size of the array * @param max The maximum size of the array * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun minMaxLike(min: Int, max: Int, numberExamples: Int = 1, arg: Any): Matcher { if (min > max) { throw InvalidMatcherException("The minimum you have specified ($min) is " + "greater than the maximum ($max)") } else if (numberExamples > 1 && numberExamples < min) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "less than the minimum ($min)") } else if (numberExamples > 1 && numberExamples > max) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "greater than the maximum ($max)") } return MinMaxLikeMatcher(min, max, arg, numberExamples) } /** * Match Equality * @param value Value to match to */ @JvmStatic fun equalTo(value: Any): Matcher { return EqualsMatcher(value) } /** * Matches if the string is included in the value * @param value String value that must be present */ @JvmStatic fun includesStr(value: String): Matcher { return IncludeMatcher(value) } /** * Matches if any of the provided matches match * @param example Example value to use */ @JvmStatic fun or(example: Any, vararg values: Any): Matcher { return OrMatcher(example, values.map { if (it is Matcher) { it } else { EqualsMatcher(it) } }) } /** * Matches if all of the provided matches match * @param example Example value to use */ @JvmStatic fun and(example: Any, vararg values: Any): Matcher { return AndMatcher(example, values.map { if (it is Matcher) { it } else { EqualsMatcher(it) } }) } /** * Matches a null value */ @JvmStatic fun nullValue(): Matcher { return NullMatcher() } /** * Matches a URL composed of a base path and a list of path fragments */ @JvmStatic fun url(basePath: String, vararg pathFragments: Any): Matcher { return UrlMatcher(basePath, pathFragments.toList()) } /** * Array of arrays where each element like the following object * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun eachArrayLike(numberExamples: Int = 1, arg: Any): Matcher { return EachLikeMatcher(EachLikeMatcher(arg, numberExamples), numberExamples) } } }
apache-2.0
d820f145813203c375a9e2486489e781
31.825243
121
0.680617
4.105647
false
false
false
false
greenspand/kotlin-extensions
kotlin-ext/src/main/java/com/sorinirimies/kotlinx/animUtils.kt
1
3045
@file:JvmName("AnimUtils") package com.sorinirimies.kotlinx import android.support.v4.view.ViewCompat import android.view.View import android.view.animation.AccelerateInterpolator import android.view.animation.Interpolator /** * Extension function for simple view fade in and out animations. * @param duration of the animation * @param scale of the the view * @param alpha visibility of the the view * @param interpolator the Bezier curve animation of the view * @param visibility of the animated view */ fun View.animateScaleAlpha(delay: Long = 0, duration: Long = 300, scale: Float = 0.7f, alpha: Float = 0f, interpolator: Interpolator = AccelerateInterpolator(), visibility: Int = View.GONE) { ViewCompat.animate(this) .setStartDelay(delay) .setDuration(duration) .scaleX(scale) .scaleY(scale) .alpha(alpha) .setInterpolator(interpolator) .withEndAction { this.visibility = visibility } } /** * Animates a view upwards. * @param translateY the vertical vector * @param duration the default duration * @param interpolator the default interpolator */ fun View.animateUp(translateY: Float = 0f, duration: Long = 300, interpolator: Interpolator = AccelerateInterpolator()) { visible() ViewCompat.animate(this) .setDuration(duration) .translationY(translateY) .interpolator = interpolator } /** * Animates a view to a visible state, with an alpha transition. * @param duration the default duration * @param alpha the given opacity level * @param interpolator the default interpolator */ fun View.animateVisible(duration: Long = 300, alpha: Float = 1f) { visible() ViewCompat.animate(this) .setDuration(duration) .alpha(alpha) } /** * Animates a view to gone, with an alpha transition. * @param duration the default duration * @param alpha the given opacity level * @param interpolator the default interpolator */ fun View.animateGone(duration: Long = 300, alpha: Float = 0f, visibility: Int = View.GONE) { ViewCompat.animate(this) .setDuration(duration) .alpha(alpha) .withEndAction { this.visibility = visibility } } /** * Animates a view downwards. * @param translateY the vertical vector * @param duration the default duration * @param interpolator the default interpolator */ fun View.animateDown(translateY: Float = 400f, duration: Long = 300, visibility: Int = View.GONE) { ViewCompat.animate(this) .setDuration(duration) .translationY(translateY) .withEndAction { this.visibility = visibility } }
mit
f93d1e86cce4b47efd4652a5166b77f1
30.071429
81
0.608539
4.802839
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/domains/DomainSuggestionsAdapter.kt
1
1011
package org.wordpress.android.ui.domains import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter class DomainSuggestionsAdapter( private val itemSelectionListener: (DomainSuggestionItem?) -> Unit ) : ListAdapter<DomainSuggestionItem, DomainSuggestionsViewHolder>(DomainSuggestionItemDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = DomainSuggestionsViewHolder(parent, itemSelectionListener) override fun onBindViewHolder(holder: DomainSuggestionsViewHolder, position: Int) { holder.bind(getItem(position)) } private class DomainSuggestionItemDiffCallback : DiffUtil.ItemCallback<DomainSuggestionItem>() { override fun areItemsTheSame(old: DomainSuggestionItem, new: DomainSuggestionItem) = old.domainName == new.domainName override fun areContentsTheSame(old: DomainSuggestionItem, new: DomainSuggestionItem) = old == new } }
gpl-2.0
d92012a3ae82f6f522f9c74883ba8044
42.956522
106
0.777448
5.21134
false
false
false
false
android/nowinandroid
core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/NewsResource.kt
1
4169
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.model.data import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Codelab import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Video import kotlinx.datetime.Instant import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toInstant /* ktlint-disable max-line-length */ /** * External data layer representation of a fully populated NiA news resource */ data class NewsResource( val id: String, val title: String, val content: String, val url: String, val headerImageUrl: String?, val publishDate: Instant, val type: NewsResourceType, val authors: List<Author>, val topics: List<Topic> ) val previewNewsResources = listOf( NewsResource( id = "1", title = "Android Basics with Compose", content = "We released the first two units of Android Basics with Compose, our first free course that teaches Android Development with Jetpack Compose to anyone; you do not need any prior programming experience other than basic computer literacy to get started. You’ll learn the fundamentals of programming in Kotlin while building Android apps using Jetpack Compose, Android’s modern toolkit that simplifies and accelerates native UI development. These two units are just the beginning; more will be coming soon. Check out Android Basics with Compose to get started on your Android development journey", url = "https://android-developers.googleblog.com/2022/05/new-android-basics-with-compose-course.html", headerImageUrl = "https://developer.android.com/images/hero-assets/android-basics-compose.svg", authors = listOf(previewAuthors[0]), publishDate = LocalDateTime( year = 2022, monthNumber = 5, dayOfMonth = 4, hour = 23, minute = 0, second = 0, nanosecond = 0 ).toInstant(TimeZone.UTC), type = Codelab, topics = listOf(previewTopics[1]) ), NewsResource( id = "2", title = "Thanks for helping us reach 1M YouTube Subscribers", content = "Thank you everyone for following the Now in Android series and everything the " + "Android Developers YouTube channel has to offer. During the Android Developer " + "Summit, our YouTube channel reached 1 million subscribers! Here’s a small video to " + "thank you all.", url = "https://youtu.be/-fJ6poHQrjM", headerImageUrl = "https://i.ytimg.com/vi/-fJ6poHQrjM/maxresdefault.jpg", publishDate = Instant.parse("2021-11-09T00:00:00.000Z"), type = Video, authors = listOf(previewAuthors[1]), topics = listOf(previewTopics[0], previewTopics[1]) ), NewsResource( id = "3", title = "Transformations and customisations in the Paging Library", content = "A demonstration of different operations that can be performed " + "with Paging. Transformations like inserting separators, when to " + "create a new pager, and customisation options for consuming " + "PagingData.", url = "https://youtu.be/ZARz0pjm5YM", headerImageUrl = "https://i.ytimg.com/vi/ZARz0pjm5YM/maxresdefault.jpg", publishDate = Instant.parse("2021-11-01T00:00:00.000Z"), type = Video, authors = listOf(previewAuthors[0], previewAuthors[1]), topics = listOf(previewTopics[2]) ) )
apache-2.0
42b188e79e8c2ab3e2385beab62bb21c
44.747253
612
0.689647
4.256646
false
false
false
false
florent37/Flutter-AssetsAudioPlayer
android/src/main/kotlin/com/github/florent37/assets_audio_player/stopwhencall/StopWhenCallAudioFocus.kt
1
2781
package com.github.florent37.assets_audio_player.stopwhencall import android.content.Context import android.media.AudioManager import androidx.media.AudioAttributesCompat import androidx.media.AudioFocusRequestCompat import androidx.media.AudioManagerCompat class StopWhenCallAudioFocus(private val context: Context) : StopWhenCall() { private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager private val focusLock = Any() private var request: AudioFocusRequestCompat? = null private fun generateListener() : ((Int) -> Unit) = { focusChange -> when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> synchronized(focusLock) { pingListeners(AudioState.AUTHORIZED_TO_PLAY) } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> synchronized(focusLock) { pingListeners(AudioState.REDUCE_VOLUME) } else -> { synchronized(focusLock) { pingListeners(AudioState.FORBIDDEN) } } } } override fun requestAudioFocus(audioFocusStrategy: AudioFocusStrategy) : AudioState { if(audioFocusStrategy is AudioFocusStrategy.None) return AudioState.FORBIDDEN val strategy = audioFocusStrategy as AudioFocusStrategy.Request request?.let { AudioManagerCompat.abandonAudioFocusRequest(audioManager, it) } val requestType = if(strategy.resumeOthersPlayersAfterDone){ AudioManagerCompat.AUDIOFOCUS_GAIN_TRANSIENT } else { AudioManagerCompat.AUDIOFOCUS_GAIN } val listener = generateListener() this.request = AudioFocusRequestCompat.Builder(requestType).also { it.setAudioAttributes(AudioAttributesCompat.Builder().run { setUsage(AudioAttributesCompat.USAGE_MEDIA) setContentType(AudioAttributesCompat.CONTENT_TYPE_MUSIC) build() }) it.setOnAudioFocusChangeListener(listener) }.build() val result: Int = AudioManagerCompat.requestAudioFocus(audioManager, request!!) synchronized(focusLock) { listener(result) } return when(result){ AudioManager.AUDIOFOCUS_GAIN, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT -> AudioState.AUTHORIZED_TO_PLAY AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> AudioState.REDUCE_VOLUME else -> AudioState.FORBIDDEN } } override fun stop() { this.request?.let { AudioManagerCompat.abandonAudioFocusRequest(audioManager, it) } } }
apache-2.0
922fd9a4967293597990ac93bb15b256
36.093333
113
0.640058
5.37911
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinBuildScriptManipulator.kt
1
28526
// 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 com.intellij.openapi.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
10e28589583a41b55491e4a477bea2c2
45.763934
167
0.670757
5.8419
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/keywords/OverrideKeywordHandler.kt
1
7689
// 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.completion.contributors.keywords import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.lookup.LookupElement import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.ui.RowIcon import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.completion.* import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandler import org.jetbrains.kotlin.idea.core.overrideImplement.* import org.jetbrains.kotlin.idea.core.overrideImplement.KtClassMember import org.jetbrains.kotlin.idea.core.overrideImplement.KtGenerateMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.KtOverrideMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.idea.KtIconProvider.getIcon import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.symbols.nameOrAnonymous import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import com.intellij.openapi.application.runWriteAction internal class OverrideKeywordHandler( private val basicContext: FirBasicCompletionContext ) : CompletionKeywordHandler<KtAnalysisSession>(KtTokens.OVERRIDE_KEYWORD) { @OptIn(ExperimentalStdlibApi::class) override fun KtAnalysisSession.createLookups( parameters: CompletionParameters, expression: KtExpression?, lookup: LookupElement, project: Project ): Collection<LookupElement> { val result = mutableListOf(lookup) val position = parameters.position val isConstructorParameter = position.getNonStrictParentOfType<KtPrimaryConstructor>() != null val classOrObject = position.getNonStrictParentOfType<KtClassOrObject>() ?: return result val members = collectMembers(classOrObject, isConstructorParameter) for (member in members) { result += createLookupElementToGenerateSingleOverrideMember(member, classOrObject, isConstructorParameter, project) } return result } private fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject, isConstructorParameter: Boolean): List<KtClassMember> { val allMembers = KtOverrideMembersHandler().collectMembersToGenerate(classOrObject) return if (isConstructorParameter) { allMembers.mapNotNull { member -> if (member.memberInfo.isProperty) { member.copy(bodyType = BodyType.FromTemplate, preferConstructorParameter = true) } else null } } else allMembers.toList() } @OptIn(KtAllowAnalysisOnEdt::class) private fun KtAnalysisSession.createLookupElementToGenerateSingleOverrideMember( member: KtClassMember, classOrObject: KtClassOrObject, isConstructorParameter: Boolean, project: Project ): OverridesCompletionLookupElementDecorator { val memberSymbol = member.symbol check(memberSymbol is KtNamedSymbol) val text = getSymbolTextForLookupElement(memberSymbol) val baseIcon = getIcon(memberSymbol) val isImplement = (memberSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT val additionalIcon = if (isImplement) AllIcons.Gutter.ImplementingMethod else AllIcons.Gutter.OverridingMethod val icon = RowIcon(baseIcon, additionalIcon) val baseClass = classOrObject.getClassOrObjectSymbol() val baseClassIcon = getIcon(baseClass) val isSuspendFunction = (memberSymbol as? KtFunctionSymbol)?.isSuspend == true val baseClassName = baseClass.nameOrAnonymous.asString() val memberPointer = memberSymbol.createPointer() val baseLookupElement = with(basicContext.lookupElementFactory) { createLookupElement(memberSymbol, basicContext.importStrategyDetector) } ?: error("Lookup element should be available for override completion") return OverridesCompletionLookupElementDecorator( baseLookupElement, declaration = null, text, isImplement, icon, baseClassName, baseClassIcon, isConstructorParameter, isSuspendFunction, generateMember = { generateMemberInNewAnalysisSession(classOrObject, memberPointer, member, project) }, shortenReferences = { element -> val shortenings = allowAnalysisOnEdt { analyze(classOrObject) { collectPossibleReferenceShortenings(element.containingKtFile, element.textRange) } } runWriteAction { shortenings.invokeShortening() } } ) } private fun KtAnalysisSession.getSymbolTextForLookupElement(memberSymbol: KtCallableSymbol): String = buildString { append(KtTokens.OVERRIDE_KEYWORD.value) .append(" ") .append(memberSymbol.render(renderingOptionsForLookupElementRendering)) if (memberSymbol is KtFunctionSymbol) { append(" {...}") } } @OptIn(KtAllowAnalysisOnEdt::class) private fun generateMemberInNewAnalysisSession( classOrObject: KtClassOrObject, memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember, project: Project ) = allowAnalysisOnEdt { analyze(classOrObject) { val memberInCorrectAnalysisSession = createCopyInCurrentAnalysisSession(memberPointer, member) generateMember( project, memberInCorrectAnalysisSession, classOrObject, copyDoc = false, mode = MemberGenerateMode.OVERRIDE ) } } //todo temporary hack until KtSymbolPointer is properly implemented private fun KtAnalysisSession.createCopyInCurrentAnalysisSession( memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember ) = KtClassMember( KtClassMemberInfo( memberPointer.restoreSymbol() ?: error("Cannot restore symbol from $memberPointer"), member.memberInfo.memberText, member.memberInfo.memberIcon, member.memberInfo.containingSymbolText, member.memberInfo.containingSymbolIcon, ), member.bodyType, member.preferConstructorParameter, ) companion object { private val renderingOptionsForLookupElementRendering = KtGenerateMembersHandler.renderOption.copy( renderUnitReturnType = false, renderDeclarationHeader = true ) } }
apache-2.0
d9fcf059aa687669e27f77dcd9c7702f
43.97076
158
0.716348
5.612409
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/detector/NotificationBundleAndroidTextDetector.kt
1
1820
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.detector import android.app.Notification import android.os.Bundle import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.warn /** * Created by abertschi on 17.04.17. */ class NotificationBundleAndroidTextDetector : AbstractSpStatusBarDetector(), AnkoLogger { override fun canHandle(payload: AdPayload): Boolean = super.canHandle(payload) && payload?.statusbarNotification?.notification != null override fun flagAsAdvertisement(payload: AdPayload): Boolean { try { val bundle = getNotificationBundle(payload!!.statusbarNotification!!.notification) var flagAsAd = false bundle.let { val androidText: CharSequence? = bundle?.get("android.text") as CharSequence? flagAsAd = androidText == null && payload!!.statusbarNotification!!.notification!! .tickerText?.isNotEmpty() ?: false } return flagAsAd } catch (e: Exception) { warn(e) } return false } private fun getNotificationBundle(notification: Notification): Bundle? { try { //NoSuchFieldException val f = notification.javaClass.getDeclaredField("extras") f.isAccessible = true return f.get(notification) as Bundle } catch (e: Exception) { error("Can not access notification bundle with reflection, $e") } } override fun getMeta(): AdDetectorMeta = AdDetectorMeta( "Notification bundle", "spotify generic inspection of notification bundle", category = "Spotify" ) }
apache-2.0
8fbd864b68912eee4242e35d52dbde0e
31.517857
94
0.636264
4.892473
false
false
false
false
ktorio/ktor
ktor-utils/common/src/io/ktor/util/pipeline/DebugPipelineContext.kt
1
2311
/* * 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.util.pipeline import io.ktor.util.* import kotlin.coroutines.* /** * Represents running execution of a pipeline * @param context object representing context in which pipeline executes * @param interceptors list of interceptors to execute * @param subject object representing subject that goes along the pipeline */ @KtorDsl internal class DebugPipelineContext<TSubject : Any, TContext : Any> constructor( context: TContext, private val interceptors: List<PipelineInterceptorFunction<TSubject, TContext>>, subject: TSubject, override val coroutineContext: CoroutineContext ) : PipelineContext<TSubject, TContext>(context) { /** * Subject of this pipeline execution */ override var subject: TSubject = subject private var index = 0 /** * Finishes current pipeline execution */ override fun finish() { index = -1 } /** * Continues execution of the pipeline with the given subject */ override suspend fun proceedWith(subject: TSubject): TSubject { this.subject = subject return proceed() } /** * Continues execution of the pipeline with the same subject */ override suspend fun proceed(): TSubject { val index = index if (index < 0) return subject if (index >= interceptors.size) { finish() return subject } return proceedLoop() } override suspend fun execute(initial: TSubject): TSubject { index = 0 subject = initial return proceed() } private suspend fun proceedLoop(): TSubject { do { val index = index if (index == -1) { break } val interceptors = interceptors if (index >= interceptors.size) { finish() break } val executeInterceptor = interceptors[index] this.index = index + 1 @Suppress("UNCHECKED_CAST") (executeInterceptor as PipelineInterceptor<TSubject, TContext>).invoke(this, subject) } while (true) return subject } }
apache-2.0
6b43a78d821ff77a5709ca504bf2bff6
26.188235
118
0.617482
5.045852
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/gradle/ui/LegacyIsResolveModulePerSourceSetNotification.kt
1
6425
// 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.gradle.ui import com.intellij.notification.* import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.* import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.util.PlatformUtils import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import java.lang.ref.WeakReference private var previouslyShownNotification = WeakReference<Notification>(null) fun notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(projectPath: String) { notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded( ProjectManager.getInstance().openProjects.firstOrNull { it.basePath == projectPath } ?: return ) } fun notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(project: Project) { notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded( project = project, notificationSuppressState = SuppressResolveModulePerSourceSetNotificationState.default(project), isResolveModulePerSourceSetSetting = IsResolveModulePerSourceSetSetting.default(project), ) } fun notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded( project: Project, notificationSuppressState: SuppressResolveModulePerSourceSetNotificationState, isResolveModulePerSourceSetSetting: IsResolveModulePerSourceSetSetting ) { if (KotlinPlatformUtils.isAndroidStudio || PlatformUtils.isMobileIde() || PlatformUtils.isAppCode()) return if (notificationSuppressState.isSuppressed) return if (isResolveModulePerSourceSetSetting.isResolveModulePerSourceSet) return if (previouslyShownNotification.get()?.isExpired == false) return val notification = createNotification(notificationSuppressState, isResolveModulePerSourceSetSetting) notification.notify(project) previouslyShownNotification = WeakReference(notification) } private fun createNotification( notificationSuppressState: SuppressResolveModulePerSourceSetNotificationState, isResolveModulePerSourceSetSetting: IsResolveModulePerSourceSetSetting ): Notification { NotificationsConfiguration.getNotificationsConfiguration().register( KOTLIN_UPDATE_IS_RESOLVE_MODULE_PER_SOURCE_SET_GROUP_ID, NotificationDisplayType.STICKY_BALLOON, true ) return Notification( KOTLIN_UPDATE_IS_RESOLVE_MODULE_PER_SOURCE_SET_GROUP_ID, KotlinBundle.message("configuration.is.resolve.module.per.source.set"), KotlinBundle.htmlMessage("configuration.update.is.resolve.module.per.source.set"), NotificationType.WARNING ).apply { isSuggestionType = true addAction(createUpdateGradleProjectSettingsAction(isResolveModulePerSourceSetSetting)) addAction(createSuppressNotificationAction(notificationSuppressState)) isImportant = true } } private fun createUpdateGradleProjectSettingsAction( isResolveModulePerSourceSetSetting: IsResolveModulePerSourceSetSetting ) = NotificationAction.create( KotlinBundle.message("configuration.apply.is.resolve.module.per.source.set"), ) { event: AnActionEvent, notification: Notification -> notification.expire() val project = event.project ?: return@create if (project.isDisposed) return@create runWriteAction { isResolveModulePerSourceSetSetting.isResolveModulePerSourceSet = true ExternalSystemUtil.refreshProjects(ImportSpecBuilder(project, GRADLE_SYSTEM_ID)) } } private fun createSuppressNotificationAction( notificationSuppressState: SuppressResolveModulePerSourceSetNotificationState ) = NotificationAction.create( KotlinBundle.message("configuration.do.not.suggest.update.is.resolve.module.per.source.set") ) { event: AnActionEvent, notification: Notification -> notification.expire() val project = event.project ?: return@create if (project.isDisposed) return@create runWriteAction { notificationSuppressState.isSuppressed = true } } private val Project.gradleProjectSettings: List<GradleProjectSettings> get() = GradleSettings.getInstance(this).linkedProjectsSettings.toList() /* Accessing "isResolveModulePerSourceSet" setting */ interface IsResolveModulePerSourceSetSetting { var isResolveModulePerSourceSet: Boolean companion object { fun default(project: Project): IsResolveModulePerSourceSetSetting = ProjectIsResolveModulePerSourceSetSetting(project) } } private class ProjectIsResolveModulePerSourceSetSetting(private val project: Project) : IsResolveModulePerSourceSetSetting { override var isResolveModulePerSourceSet: Boolean get() = project.gradleProjectSettings.all { it.isResolveModulePerSourceSet } set(value) = project.gradleProjectSettings.forEach { it.isResolveModulePerSourceSet = value } } /* Storing State about Notification Suppress */ interface SuppressResolveModulePerSourceSetNotificationState { var isSuppressed: Boolean companion object { fun default(project: Project): SuppressResolveModulePerSourceSetNotificationState = IdeResolveModulePerSourceSetComponent.getInstance(project).state } } private class IdeSuppressResolveModulePerSourceSetNotificationState : BaseState(), SuppressResolveModulePerSourceSetNotificationState { override var isSuppressed: Boolean by property(false) } @Service @State(name = "SuppressResolveModulePerSourceSetNotification") private class IdeResolveModulePerSourceSetComponent : SimplePersistentStateComponent<IdeSuppressResolveModulePerSourceSetNotificationState>( IdeSuppressResolveModulePerSourceSetNotificationState() ) { companion object { fun getInstance(project: Project): IdeResolveModulePerSourceSetComponent = project.service() } } const val KOTLIN_UPDATE_IS_RESOLVE_MODULE_PER_SOURCE_SET_GROUP_ID = "Update isResolveModulePerSourceSet setting"
apache-2.0
b210d65149479d221c3c52862610040b
41.549669
135
0.807315
5.50557
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/gutter/ReplIcons.kt
5
2032
// 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.console.gutter import com.intellij.icons.AllIcons import com.intellij.openapi.util.NlsContexts import org.jetbrains.kotlin.KotlinIdeaReplBundle import org.jetbrains.kotlin.idea.KotlinIcons import javax.swing.Icon data class IconWithTooltip(val icon: Icon, @NlsContexts.Tooltip val tooltip: String?) object ReplIcons { val BUILD_WARNING_INDICATOR: IconWithTooltip = IconWithTooltip(AllIcons.General.Warning, null) val HISTORY_INDICATOR: IconWithTooltip = IconWithTooltip( AllIcons.Vcs.History, KotlinIdeaReplBundle.message("icon.tool.tip.history.of.executed.commands") ) val EDITOR_INDICATOR: IconWithTooltip = IconWithTooltip( KotlinIcons.LAUNCH, KotlinIdeaReplBundle.message("icon.tool.tip.write.your.commands.here") ) val EDITOR_READLINE_INDICATOR: IconWithTooltip = IconWithTooltip( AllIcons.General.Balloon, KotlinIdeaReplBundle.message("icon.tool.tip.waiting.for.input") ) val COMMAND_MARKER: IconWithTooltip = IconWithTooltip( AllIcons.RunConfigurations.TestState.Run, KotlinIdeaReplBundle.message("icon.tool.tip.executed.command") ) val READLINE_MARKER: IconWithTooltip = IconWithTooltip( AllIcons.Debugger.PromptInput, KotlinIdeaReplBundle.message("icon.tool.tip.input.line") ) // command result icons val SYSTEM_HELP: IconWithTooltip = IconWithTooltip(AllIcons.Actions.Help, KotlinIdeaReplBundle.message("icon.tool.tip.system.help")) val RESULT: IconWithTooltip = IconWithTooltip(AllIcons.Vcs.Equal, KotlinIdeaReplBundle.message("icon.tool.tip.result")) val COMPILER_ERROR: Icon = AllIcons.General.Error val RUNTIME_EXCEPTION: IconWithTooltip = IconWithTooltip( AllIcons.General.BalloonWarning, KotlinIdeaReplBundle.message("icon.tool.tip.runtime.exception") ) }
apache-2.0
050ec932b18da76138ff09566d0cccfd
41.354167
158
0.75689
4.351178
false
false
false
false
mikepenz/FastAdapter
app/src/main/java/com/mikepenz/fastadapter/app/view/RecyclerViewBackgroundDrawable.kt
1
1447
package com.mikepenz.fastadapter.app.view import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.drawable.Drawable import androidx.recyclerview.widget.RecyclerView // Based on https://stackoverflow.com/a/49825927/1800174 class RecyclerViewBackgroundDrawable internal constructor(private val color: Int) : Drawable() { private var recyclerView: RecyclerView? = null private val paint: Paint = Paint().apply { color = [email protected] } fun attachTo(recyclerView: RecyclerView?) { this.recyclerView = recyclerView recyclerView?.background = this } override fun draw(canvas: Canvas) { val recyclerView = recyclerView ?: return if (recyclerView.childCount == 0) { return } var bottom = recyclerView.getChildAt(recyclerView.childCount - 1).bottom if (bottom >= recyclerView.bottom) { bottom = recyclerView.bottom } canvas.drawRect( recyclerView.left.toFloat(), recyclerView.top.toFloat(), recyclerView.right.toFloat(), bottom.toFloat(), paint ) } override fun setAlpha(alpha: Int) = Unit override fun setColorFilter(colorFilter: ColorFilter?) = Unit override fun getOpacity(): Int = PixelFormat.OPAQUE }
apache-2.0
e9b2638f1c569e48d4ac5affeb800f9c
29.787234
96
0.680028
5.09507
false
false
false
false
phylame/jem
commons/src/main/kotlin/jclp/vdm/VdmSpec.kt
1
3025
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jclp.vdm import jclp.KeyedService import jclp.ServiceManager import jclp.VariantMap import jclp.io.Flob import jclp.text.Text import java.io.Closeable import java.io.InputStream import java.io.OutputStream import java.nio.charset.Charset interface VdmEntry { val name: String val comment: String? val lastModified: Long val isDirectory: Boolean } interface VdmReader : Closeable { val name: String val comment: String? fun getEntry(name: String): VdmEntry? fun getInputStream(entry: VdmEntry): InputStream val entries: Iterator<VdmEntry> val size: Int } fun VdmReader.openStream(name: String) = getEntry(name)?.let { getInputStream(it) } fun VdmReader.readBytes(name: String, estimatedSize: Int = DEFAULT_BUFFER_SIZE): ByteArray? = openStream(name)?.use { it.readBytes(estimatedSize) } fun VdmReader.readText(name: String, charset: Charset = Charsets.UTF_8): String? = openStream(name)?.use { it.reader(charset).readText() } interface VdmWriter : Closeable { fun setComment(comment: String) fun newEntry(name: String): VdmEntry fun putEntry(entry: VdmEntry): OutputStream fun closeEntry(entry: VdmEntry) } inline fun <R> VdmWriter.useStream(name: String, block: (OutputStream) -> R): R { return with(newEntry(name)) { val stream = putEntry(this) try { block(stream) } finally { closeEntry(this) } } } fun VdmWriter.writeBytes(name: String, data: ByteArray) = useStream(name) { it.write(data) } fun VdmWriter.writeFlob(name: String, flob: Flob) = useStream(name) { flob.writeTo(it) it.flush() } fun VdmWriter.writeText(name: String, text: Text, charset: Charset = Charsets.UTF_8) = useStream(name) { with(it.writer(charset)) { text.writeTo(this) flush() } } interface VdmFactory : KeyedService { fun getReader(input: Any, props: VariantMap): VdmReader fun getWriter(output: Any, props: VariantMap): VdmWriter } object VdmManager : ServiceManager<VdmFactory>(VdmFactory::class.java) { fun openReader(name: String, input: Any, props: VariantMap = emptyMap()): VdmReader? = get(name)?.getReader(input, props) fun openWriter(name: String, output: Any, props: VariantMap = emptyMap()): VdmWriter? = get(name)?.getWriter(output, props) }
apache-2.0
e48a47f9ebda94785a076fd9fbbb7d2f
26.008929
104
0.695537
3.640193
false
false
false
false
openium/auvergne-webcams-droid
app/src/debug/java/fr/openium/auvergnewebcams/di/DebugModules.kt
1
4315
package fr.openium.auvergnewebcams.di import android.content.Context import com.google.gson.ExclusionStrategy import com.google.gson.FieldAttributes import com.google.gson.GsonBuilder import fr.openium.auvergnewebcams.model.AWClient import fr.openium.auvergnewebcams.rest.AWApi import fr.openium.auvergnewebcams.rest.MockApi import fr.openium.auvergnewebcams.rest.model.SectionList import io.reactivex.Single import io.reactivex.schedulers.Schedulers import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.instance import org.kodein.di.generic.provider import org.kodein.di.generic.singleton import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.mock.Calls import retrofit2.mock.MockRetrofit import retrofit2.mock.NetworkBehavior import java.io.InputStreamReader import java.util.concurrent.TimeUnit /** * Created by Openium on 19/02/2019. */ object DebugModules { const val mock = false val configModule = Kodein.Module("Config module") { } val serviceModule = Kodein.Module("Service module") { } val databaseService = Kodein.Module("Database Module") { bind<AWClient>(overrides = true) with provider { AWClient.getInstance(instance()) } } val restModule = Kodein.Module("REST module") { bind<OkHttpClient>(overrides = true) with provider { OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .cache(instance()) .build() } bind<Retrofit>(overrides = true) with singleton { Retrofit.Builder() .baseUrl(instance<HttpUrl>()).client(instance()) .addConverterFactory(GsonConverterFactory.create(instance())) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .build() } bind<AWApi>(overrides = true) with provider { if (mock) { val networkBehaviour = NetworkBehavior.create() networkBehaviour.setDelay(0, TimeUnit.MILLISECONDS) networkBehaviour.setFailurePercent(0) networkBehaviour.setVariancePercent(0) val apiMock = object : MockApi() { override fun getSections(): Single<SectionList> { val thisValue = instance<Context>().assets.open("aw-config.json") val reader = InputStreamReader(thisValue) val sObjectMapper = GsonBuilder() .setExclusionStrategies(object : ExclusionStrategy { override fun shouldSkipClass(clazz: Class<*>?): Boolean { return false } override fun shouldSkipField(f: FieldAttributes): Boolean { return f.declaredClass == SectionList::class.java } }) .serializeNulls() .create() val listLoaded = sObjectMapper.fromJson(reader, SectionList::class.java) as SectionList return delegate.returning(Calls.response(listLoaded)).getSections() } } apiMock.delegate = MockRetrofit.Builder( Retrofit.Builder() .baseUrl(instance<HttpUrl>()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() ) .networkBehavior(networkBehaviour) .build().create(AWApi::class.java) apiMock } else { instance<Retrofit>().create(AWApi::class.java) } } } val repositoryModule = Kodein.Module("Repository Module") { } }
mit
28be61d1318a16c984b5683fef5169bf
36.206897
111
0.601159
5.39375
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/util/PrimitiveUtils.kt
1
2774
package jp.juggler.util //////////////////////////////////////////////////////////////////// // Comparable fun <T : Comparable<T>> clipRange(min: T, max: T, src: T) = if (src < min) min else if (src > max) max else src //////////////////////////////////////////////////////////////////// // usage: number.notZero() ?: fallback // equivalent: if(this != 0 ) this else null fun Int.notZero(): Int? = if (this != 0) this else null fun Long.notZero(): Long? = if (this != 0L) this else null fun Float.notZero(): Float? = if (this != 0f) this else null fun Double.notZero(): Double? = if (this != .0) this else null // usage: boolean.truth() ?: fallback() // equivalent: if(this != 0 ) this else null // fun Boolean.truth() : Boolean? = if(this) this else null //////////////////////////////////////////////////////////////////// // long //////////////////////////////////////////////////////////////////// // float fun Float.abs(): Float = kotlin.math.abs(this) //@SuppressLint("DefaultLocale") //fun Long.formatTimeDuration() : String { // var t = this // val sb = StringBuilder() // var n : Long // // day // n = t / 86400000L // if(n > 0) { // sb.append(String.format(Locale.JAPAN, "%dd", n)) // t -= n * 86400000L // } // // h // n = t / 3600000L // if(n > 0 || sb.isNotEmpty()) { // sb.append(String.format(Locale.JAPAN, "%dh", n)) // t -= n * 3600000L // } // // m // n = t / 60000L // if(n > 0 || sb.isNotEmpty()) { // sb.append(String.format(Locale.JAPAN, "%dm", n)) // t -= n * 60000L // } // // s // val f = t / 1000f // sb.append(String.format(Locale.JAPAN, "%.03fs", f)) // // return sb.toString() //} //private val bytesSizeFormat = DecimalFormat("#,###") //fun Long.formatBytesSize() = Utils.bytesSizeFormat.format(this) // StringBuilder sb = new StringBuilder(); // long n; // // giga // n = t / 1000000000L; // if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%dg", n ) ); // t -= n * 1000000000L; // } // // Mega // n = t / 1000000L; // if( sb.length() > 0 ){ // sb.append( String.format( Locale.JAPAN, "%03dm", n ) ); // t -= n * 1000000L; // }else if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%dm", n ) ); // t -= n * 1000000L; // } // // kilo // n = t / 1000L; // if( sb.length() > 0 ){ // sb.append( String.format( Locale.JAPAN, "%03dk", n ) ); // t -= n * 1000L; // }else if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%dk", n ) ); // t -= n * 1000L; // } // // length // if( sb.length() > 0 ){ // sb.append( String.format( Locale.JAPAN, "%03d", t ) ); // }else if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%d", t ) ); // } // // return sb.toString();
apache-2.0
956bb5e1b14e0c1bfa65dac8e188cd2b
26.895833
68
0.482336
2.685382
false
false
false
false
opst-miyatay/LightCalendarView
library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/CellLayout.kt
2
4213
/* * Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.recruit_mp.android.lightcalendarview import android.content.Context import android.support.v4.view.ViewCompat import android.view.View import android.view.ViewGroup /** * 子ビューをグリッド状に配置する {@link ViewGroup} * Created by masayuki-recruit on 8/19/16. */ abstract class CellLayout(context: Context, protected val settings: CalendarSettings) : ViewGroup(context) { abstract val rowNum: Int abstract val colNum: Int override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val (specWidthSize, specWidthMode) = Measure.createFromSpec(widthMeasureSpec) val (specHeightSize, specHeightMode) = Measure.createFromSpec(heightMeasureSpec) // 自分の大きさを確定 val minSide = when { specWidthMode == MeasureSpec.UNSPECIFIED && specHeightMode == MeasureSpec.UNSPECIFIED -> throw IllegalStateException("CellLayout can never be left to determine its size") specWidthMode == MeasureSpec.UNSPECIFIED -> specHeightSize / rowNum specHeightMode == MeasureSpec.UNSPECIFIED -> specWidthSize / colNum else -> Math.min(specWidthSize / colNum, specHeightSize / rowNum) } val minWidth = minSide * colNum val minHeight = minSide * rowNum val selfMeasuredWidth = when (specWidthMode) { MeasureSpec.EXACTLY -> specWidthSize MeasureSpec.AT_MOST -> Math.min(minWidth, specWidthSize) MeasureSpec.UNSPECIFIED -> minWidth else -> specWidthSize } val selfMeasuredHeight = when (specHeightMode) { MeasureSpec.EXACTLY -> specHeightSize MeasureSpec.AT_MOST -> Math.min(minHeight, specHeightSize) MeasureSpec.UNSPECIFIED -> minHeight else -> specHeightSize } setMeasuredDimension(selfMeasuredWidth, selfMeasuredHeight) // 子ビューを measure val childMeasuredWidth = selfMeasuredWidth / colNum val childMeasuredHeight = selfMeasuredHeight / rowNum val childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasuredWidth, MeasureSpec.AT_MOST) val childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasuredHeight, MeasureSpec.AT_MOST) childList.forEach { it.measure(childWidthMeasureSpec, childHeightMeasureSpec) } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { // セルを中央に配置する為に、上下左右のマージンを計算 val offsetTop: Int = (measuredHeight % rowNum) / 2 val offsetStart: Int = (measuredWidth % colNum) / 2 val parentTop: Int = paddingTop val parentStart: Int = ViewCompat.getPaddingStart(this) // RTL かどうか判定 val isRtl: Boolean = (layoutDirection == View.LAYOUT_DIRECTION_RTL) // 各セルを配置 childList.forEachIndexed { i, child -> val x: Int = i % colNum val y: Int = i / colNum val childWidth: Int = child.measuredWidth val childHeight: Int = child.measuredHeight val childTop: Int = parentTop + offsetTop + (y * childHeight) val childStart: Int = parentStart + offsetStart + (x * childWidth) val childLeft: Int = if (isRtl) { r - childStart - childWidth } else { childStart } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight) } } }
apache-2.0
c21fd24d97dacb7dce02a13ce8a26ec0
39.009804
108
0.665768
4.378755
false
false
false
false