repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mikkokar/styx
components/proxy/src/test/kotlin/com/hotels/styx/services/FileMonitoringServiceTest.kt
1
4261
/* Copyright (C) 2013-2019 Expedia Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.hotels.styx.services import io.kotlintest.Spec import io.kotlintest.TestCase import io.kotlintest.eventually import io.kotlintest.seconds import io.kotlintest.shouldBe import io.kotlintest.specs.StringSpec import org.slf4j.LoggerFactory import java.io.File import java.nio.charset.StandardCharsets.UTF_8 import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference class FileMonitoringServiceTest : StringSpec() { val LOGGER = LoggerFactory.getLogger(FileMonitoringServiceTest::class.java) val tempDir = createTempDir(suffix = "-${this.javaClass.simpleName}") val monitoredFile = File("${tempDir.absolutePath}/config.yml") override fun beforeSpec(spec: Spec) { LOGGER.info("Temp directory: " + tempDir.absolutePath) } override fun beforeTest(testCase: TestCase) { monitoredFile.writeText("Hello, world!") } override fun afterSpec(spec: Spec) { tempDir.deleteRecursively() } init { "Triggers action when starts" { val result = AtomicReference("") val service = FileMonitoringService("FileMonitoringService", monitoredFile.absolutePath) { result.set(it) } try { service.start() eventually(2.seconds, AssertionError::class.java) { result.get() shouldBe "Hello, world!" } } finally { service.stop() } } "When starts, fails to read file (file doesn't exist)" { val result = AtomicReference("") kotlin.runCatching { val service = FileMonitoringService("FileMonitoringService", "/abc") { result.set(it) } }.let { it.isFailure shouldBe true } } "Notifies listener when file content changes." { val result = AtomicReference("") val service = FileMonitoringService("FileMonitoringService", monitoredFile.absolutePath) { result.set(it) } try { service.start() eventually(2.seconds, AssertionError::class.java) { result.get() shouldBe "Hello, world!" } monitoredFile.writeText("New Content Populated!", UTF_8) eventually(2.seconds, AssertionError::class.java) { result.get() shouldBe "New Content Populated!" } } finally { service.stop() } } // TODO: Investigate this: "!Doesn't notify listeners when file is updated but MD5 checksum doesn't change." { val result = AtomicReference("") val updateCount = AtomicInteger(0) val service = FileMonitoringService("FileMonitoringService", monitoredFile.absolutePath) { result.set(it) updateCount.incrementAndGet() } try { service.start() eventually(2.seconds, AssertionError::class.java) { result.get() shouldBe "Hello, world!" } monitoredFile.writeText("Hello, world!", UTF_8) Thread.sleep(2.seconds.toMillis()) // TODO: Fails due to underlying FileChangeMonitor bug. It emits a change even if md5 sum stays the same. result.get() shouldBe "Hello, world!" updateCount.get() shouldBe (1) } finally { service.stop() } } } }
apache-2.0
7d45d0cc0317a8db98f58609fa9b55a3
31.534351
121
0.594227
5.042604
false
true
false
false
jayrave/falkon
falkon-mapper-basic/src/main/kotlin/com/jayrave/falkon/mapper/TableConfigurationImpl.kt
1
3966
package com.jayrave.falkon.mapper import com.jayrave.falkon.engine.Engine import com.jayrave.falkon.engine.TypeTranslator import java.lang.reflect.Type import java.util.concurrent.ConcurrentHashMap class TableConfigurationImpl( override val engine: Engine, override val typeTranslator: TypeTranslator, override val nameFormatter: NameFormatter = CamelCaseToSnakeCaseFormatter()) : TableConfiguration { private val convertersForNonNullTypes = ConcurrentHashMap<Type, Converter<*>?>() private val convertersForNullableTypes = ConcurrentHashMap<Type, Converter<*>?>() override fun <R> getConverterForNullableValuesOf(clazz: Class<R>): Converter<R>? { return getConverterForNullableValuesOf(clazz as Type) } override fun <R> getConverterForNullableValuesOf(type: Type): Converter<R>? { return convertersForNullableTypes.forType(type) } override fun <R : Any> getConverterForNonNullValuesOf(clazz: Class<R>): Converter<R>? { return getConverterForNonNullValuesOf(clazz as Type) } override fun <R : Any> getConverterForNonNullValuesOf(type: Type): Converter<R>? { return convertersForNonNullTypes.forType(type) } /** * Registers a [Converter] for the nullable form of [R]. Converters registered via this * method can be retrieved via both `getConverterForNullableValuesOf` for class & type * * *CAUTION:* Overwrites converters that were previously registered for the same form of [R] * * @param wrapForNonNullValuesIfRequired - If `true` & if the non-null form of [R] * doesn't have any registered converter, the passed in [converter] will be wrapped * up in a [NullableToNonNullConverter] & used for non-null form of [R] */ fun <R> registerForNullableValues( clazz: Class<R>, converter: Converter<R?>, wrapForNonNullValuesIfRequired: Boolean) { registerForNullableValues(clazz as Type, converter, wrapForNonNullValuesIfRequired) } /** * A more flexible, less strict version of [registerForNullableValues] that takes * in a class. Prefer to use this only if [registerForNullableValues] doesn't cut it * as this method is not type-safe * * Converters registered via this method can be retrieved via both * `getConverterForNullableValuesOf` for class & type * * @see registerForNullableValues */ fun <R> registerForNullableValues( type: Type, converter: Converter<R?>, wrapForNonNullValuesIfRequired: Boolean) { convertersForNullableTypes[type] = converter if (wrapForNonNullValuesIfRequired) { convertersForNonNullTypes.putIfAbsent(type, NullableToNonNullConverter(converter)) } } /** * Registers a [Converter] for the non-null form of [R]. Converters registered via this * method can be retrieved via both `getConverterForNonNullValuesOf` for class & type * * *CAUTION:* Overwrites converters that were previously registered for the same form of [R] */ fun <R : Any> registerForNonNullValues(clazz: Class<R>, converter: Converter<R>) { registerForNonNullValues(clazz as Type, converter) } /** * A more flexible, less strict version of [registerForNonNullValues] that takes * in a class. Prefer to use this only if [registerForNonNullValues] doesn't cut it * as this method is not type-safe. * * Converters registered via this method can be retrieved via both * `getConverterForNonNullValuesOf` for class & type */ fun <R : Any> registerForNonNullValues(type: Type, converter: Converter<R>) { convertersForNonNullTypes[type] = converter } companion object { @Suppress("UNCHECKED_CAST") private fun <R> Map<Type, Converter<*>?>.forType(type: Type): Converter<R>? { return get(type) as Converter<R>? } } }
apache-2.0
c47568b5478c03b0a0222d88810ac700
36.074766
96
0.695159
4.715815
false
false
false
false
Takhion/android-extras-delegates
library/src/main/java/me/eugeniomarletti/extras/intent/base/ArrayListGeneric.kt
1
1926
package me.eugeniomarletti.extras.intent.base import android.content.Intent import android.os.Parcelable import me.eugeniomarletti.extras.TypeReader import me.eugeniomarletti.extras.TypeWriter import me.eugeniomarletti.extras.intent.Generic import me.eugeniomarletti.extras.intent.IntentExtra import java.util.ArrayList inline fun <T> IntentExtra.IntArrayList( crossinline reader: TypeReader<T, ArrayList<Int?>?>, crossinline writer: TypeWriter<T, ArrayList<Int?>?>, name: String? = null, customPrefix: String? = null ) = Generic( Intent::getIntegerArrayListExtra, Intent::putIntegerArrayListExtra, reader, writer, name, customPrefix) inline fun <T> IntentExtra.CharSequenceArrayList( crossinline reader: TypeReader<T, ArrayList<CharSequence?>?>, crossinline writer: TypeWriter<T, ArrayList<CharSequence?>?>, name: String? = null, customPrefix: String? = null ) = Generic( Intent::getCharSequenceArrayListExtra, Intent::putCharSequenceArrayListExtra, reader, writer, name, customPrefix) inline fun <T> IntentExtra.StringArrayList( crossinline reader: TypeReader<T, ArrayList<String?>?>, crossinline writer: TypeWriter<T, ArrayList<String?>?>, name: String? = null, customPrefix: String? = null ) = Generic( Intent::getStringArrayListExtra, Intent::putStringArrayListExtra, reader, writer, name, customPrefix) inline fun <T, R : Parcelable> IntentExtra.ParcelableArrayList( crossinline reader: TypeReader<T, ArrayList<R?>?>, crossinline writer: TypeWriter<T, ArrayList<R?>?>, name: String? = null, customPrefix: String? = null ) = Generic( Intent::getParcelableArrayListExtra, Intent::putParcelableArrayListExtra, reader, writer, name, customPrefix)
mit
31a02a57f2be5aba233e614741c45e29
28.630769
65
0.685358
4.458333
false
false
false
false
jonnyzzz/TeamCity.Node
common/src/main/java/com/jonnyzzz/teamcity/plugins/node/common/YarnBean.kt
1
1324
/* * Copyright 2013-2017 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.common /** * Created by Florian Krauthan ([email protected]) * Date: 19.01.17 */ class YarnBean { val nodeJSYarnConfigurationParameter: String = "node.js.yarn" val runTypeName: String = "jonnyzzz.yarn" val commandLineParameterKey: String = "yarn_execution_args" val yarnCommandsKey: String = "yarn_commands" val yarnCommandsDefault: String = "install\r\ntest" val toolPathKey : String = "yarn_toolPath" fun parseCommands(text: String?): Collection<String> { if (text == null || text.isEmpty()) return listOf() else return text .lines() .map { it.trim() } .filterNot { it.isEmptyOrSpaces() } } }
apache-2.0
b2e9d96512e12d5d18379091f5d45dff
30.52381
75
0.696375
3.860058
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/SpeedCommand.kt
1
3333
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.essentials.bukkit.command import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class SpeedCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender.hasPermission("rpkit.essentials.command.speed")) { var player: Player? = null if (sender is Player) { player = sender } var speed = 0f if (args.size >= 2 && plugin.server.getPlayer(args[0]) != null) { player = plugin.server.getPlayer(args[0]) try { speed = java.lang.Float.parseFloat(args[1]) } catch (exception: NumberFormatException) { sender.sendMessage(plugin.messages["speed-invalid-speed-number"]) } } else if (args.isNotEmpty()) { try { speed = java.lang.Float.parseFloat(args[0]) } catch (exception: NumberFormatException) { sender.sendMessage(plugin.messages["speed-invalid-speed-number"]) } } else { if (player != null) { player.flySpeed = 0.1f sender.sendMessage(plugin.messages["speed-reset-valid", mapOf( "player" to player.name )]) player.sendMessage(plugin.messages["speed-reset-notification", mapOf( "player" to sender.name )]) } return true } if (player != null) { if (speed >= -1 && speed <= 1) { player.flySpeed = speed sender.sendMessage(plugin.messages["speed-set-valid", mapOf( "player" to player.name, "speed" to speed.toString() )]) player.sendMessage(plugin.messages["speed-set-notification", mapOf( "player" to sender.name, "speed" to speed.toString() )]) } else { sender.sendMessage(plugin.messages["speed-invalid-speed-bounds"]) } } else { sender.sendMessage(plugin.messages["speed-usage-console"]) } } else { sender.sendMessage(plugin.messages["no-permission-speed"]) } return true } }
apache-2.0
01dad6e003cde28d54aaa8d033cceb3d
38.678571
114
0.552055
4.908689
false
false
false
false
droibit/quickly
app/src/main/kotlin/com/droibit/quickly/data/repository/appinfo/AppInfoRepositoryImpl.kt
1
2611
package com.droibit.quickly.data.repository.appinfo import android.support.annotation.VisibleForTesting import com.droibit.quickly.data.repository.source.AppInfoDataSource import com.github.gfx.android.orma.annotation.OnConflict import rx.Observable import rx.Single import rx.lang.kotlin.toSingletonObservable import java.util.* class AppInfoRepositoryImpl( private val orma: OrmaDatabase, private val appInfoSource: AppInfoDataSource) : AppInfoRepository { @VisibleForTesting internal val cache: MutableMap<String, AppInfo> = LinkedHashMap() // TODO: need lock override val hasCache: Boolean get() = cache.isNotEmpty() override fun loadAll(forceReload: Boolean): Observable<List<AppInfo>> { if (!forceReload && cache.isNotEmpty()) { return cache.values.toList().toSingletonObservable() } val storedAppInfo = getStoredAppInfo() if (forceReload) { return storedAppInfo } return Observable.concat(getLocalAppInfo(), storedAppInfo) .first { it.isNotEmpty() } .onErrorReturn { Collections.emptyList() } } override fun addOrUpdate(packageName: String): Single<Boolean> { return appInfoSource.get(packageName) .flatMap { appInfo -> orma.prepareInsertIntoAppInfoAsObservable(OnConflict.REPLACE) .flatMap { it.executeAsObservable(appInfo) } .map { it > 0 } .doOnSuccess { if (cache.isNotEmpty()) cache.clear() } } } override fun delete(packageName: String): Single<Boolean> { return orma.deleteFromAppInfo() .packageNameEq(packageName) .executeAsObservable() .map { it > 0 } .doOnSuccess { if (cache.isNotEmpty()) cache.clear() } } private fun getLocalAppInfo(): Observable<List<AppInfo>> { return orma.selectFromAppInfo() .executeAsObservable() .doOnNext { cache[it.packageName] = it } .toList() } private fun getStoredAppInfo(): Observable<List<AppInfo>> { return appInfoSource.getAll() .doOnNext { cache[it.packageName] = it } .toList() .doOnNext { storeSync(appInfoList = it) } } private fun storeSync(appInfoList: List<AppInfo>) { orma.transactionSync { orma.prepareInsertIntoAppInfo(OnConflict.REPLACE) .executeAll(appInfoList) } } }
apache-2.0
f035bd7b9b942e9ffff568f0efcb8c45
34.297297
82
0.611643
4.945076
false
false
false
false
zypus/eliza
src/main/kotlin/com/zypus/eliza/Scripts.kt
1
14819
package com.zypus.eliza import com.zypus.eliza.dsl.script /** * Object holding all predefined scripts. * * @author Zypus * * @created 10.10.17 */ object Scripts { // The famous DOCTOR script val doctor = script { initial = "How do you do. Please tell me your problem." final = "Goodbye. Thank you for talking to me." onQuit("bye", "goodbye", "quit") pre( "dont" to "don't", "cant" to "can't", "wont" to "won't", "recollect" to "remember", "dreamt" to "dreamed", "dreams" to "dream", "maybe" to "perhaps", "how" to "what", "when" to "what", "certainly" to "yes", "machine" to "computer", "computers" to "computer", "were" to "was", "you're" to "you are", "i'm" to "i am", "same" to "alike" ) post( "am" to "are", "your" to "my", "me" to "you", "myself" to "yourself", "yourself" to "myself", "i" to "you", "you" to "I", "my" to "your", "i'm" to "you are" ) val belief = synonym("belief", "feel", "think", "believe", "wish") val family = synonym("family", "mother", "mom", "father", "dad", "sister", "brother", "wife", "children", "child") val desire = synonym("desire", "want", "need") val sad = synonym("sad", "unhappy", "depressed", "sick") val happy = synonym("happy", "elated", "glad", "better") val cannot = synonym("cannot", "can't") val everyone = synonym("everyone", "everybody", "nobody", "none") val be = synonym("be", "am", "is", "are", "was") key("xnone") { decompose("^(.*)$") { assemble("I'm not sure I understand you fully.") assemble("Please go on.") assemble("What does that suggest to you?") assemble("Do you feel strongly about discussing such things?") } } key("sorry") { decompose("^(.*)$") { assemble("Please don't apologise.") assemble("Apologies are not necessary.") assemble("I've told you that apologies are not required.") } } key("apologise") { decompose("^(.*)$") { goto("sorry") } } key("remember", weight = 5) { decompose("^(.*)i remember (.*)$") { assemble("Do you often think of \$2?") assemble("Does thinking of \$2 bring anything else to mind?") assemble("What else do you recollect?") assemble("Why do you recollect \$2 just now?") assemble("What in the present situation reminds you of \$2?") assemble("What is the connection between me and \$2?") } decompose("^(.*)do you remember (.*)$") { assemble("Did you think I would forget \$2?") assemble("Why do you think I should recall \$2 now?") assemble("What about \$2?") goto("what") assemble("You mentioned \$2?") } } key("if", weight = 3) { decompose("^(.*)if (.*)$") { assemble("Do you think its likely that \$2?") assemble("Do you wish that \$2?") assemble("What do you know about \$2?") assemble("Really, if \$2?") } } key("dreamed", weight = 4) { decompose("^(.*)i dreamed (.*)$") { assemble("Really, \$2?") assemble("Have you ever fantasized \$2 while you were awake?") assemble("Have you ever dreamed \$2 before?") goto("dream") } } key("dream", weight = 3) { decompose("^(.*)$") { assemble("What does that dream suggest to you?") assemble("Do you dream often?") assemble("What persons appear in your dreams?") assemble("Do you believe that dreams have something to do with your problems?") } } key("perhaps") { decompose("^(.*)$") { assemble("You don't seem quite certain.") assemble("Why the uncertain tone?") assemble("Can't you be more positive?") assemble("You aren't sure?") assemble("Don't you know?") } } key("name", weight = 15) { decompose("^(.*)$") { assemble("I am not interested in names.") assemble("I've told you before, I don't care about names -- please continue.") } } key("deutsch") { decompose("^(.*)$") { goto("xforeign") assemble("I told you before, I don't understand German.") } } key("francais") { decompose("^(.*)$") { goto("xforeign") assemble("I told you before, I don't understand French.") } } key("italiano") { decompose("^(.*)$") { goto("xforeign") assemble("I told you before, I don't understand Italian.") } } key("espanol") { decompose("^(.*)$") { goto("xforeign") assemble("I told you before, I don't understand Spanish.") } } key("xforeign") { decompose("^(.*)$") { assemble("I speak only English.") } } key("hello") { decompose("^(.*)$") { assemble("How do you do. Please state your problem.") assemble("Hi. What seems to be your problem?") } } key("computer", weight = 50) { decompose("^(.*)$") { assemble("Do computers worry you?") assemble("Why do you mention computers?") assemble("What do you think machines have to do with your problem?") assemble("Don't you think computers can help people?") assemble("What about machines worries you?") assemble("What do you think about machines?") } } key("am") { decompose("^(.*)am i (.*)$") { assemble("Do you believe you are \$2?") assemble("Would you want to be \$2?") assemble("Do you wish I would tell you you are \$2?") assemble("What would it mean if you were \$2?") goto("what") } decompose("^(.*)$") { assemble("Why do you say 'am'?") assemble("I don't understand that.") } } key("are") { decompose("^(.*)are you (.*)$") { assemble("Why are you interested in whether I am \$2 or not?") assemble("Would you prefer if I weren't \$2?") assemble("Perhaps I am \$2 in your fantasies.") assemble("Do you sometimes think I am \$2?") goto("what") } decompose("^(.*)are (.*)$") { assemble("Did you think they might not be \$2?") assemble("Would you like it if they were not \$2?") assemble("What if they were not \$2?") assemble("Possibly they are \$2.") } } key("your") { decompose("^(.*)your (.*)$") { assemble("Why are you concerned over my \$2?") assemble("What about your own \$2?") assemble("Are you worried about someone else's \$2?") assemble("Really, my \$2?") } } key("was", weight = 2) { decompose("^(.*)was i (.*)$") { assemble("What if you were \$2?") assemble("Do you think you were \$2?") assemble("Were you \$2?") assemble("What would it mean if you were \$2?") assemble("What does \$2 suggest to you?") goto("what") } decompose("^(.*)i was (.*)$") { assemble("Were you really?") assemble("Why do you tell me you were \$2 now?") assemble("Perhaps I already know you were \$2.") } decompose("^(.*)was you (.*)$") { assemble("Would you like to believe I was \$2?") assemble("What suggests that I was \$2?") assemble("What do you think?") assemble("Perhaps I was \$2.") assemble("What if I had been \$2?") } } key("i") { decompose("^(.*)i $desire (.*)$") { assemble("What would it mean to you if you got \$2?") assemble("Why do you want \$2?") assemble("Suppose you got \$2 soon?") assemble("What if you never got \$2?") assemble("What would getting \$2 mean to you?") assemble("What does wanting \$2 have to do with this discussion?") } decompose("^(.*)i am(.*) $sad (.*)$") { assemble("I am sorry to hear that you are \$3.") assemble("Do you think that coming here will help you not to be \$3?") assemble("I'm sure it's not pleasant to be \$3.") assemble("Can you explain what made you \$3?") } decompose("^(.*)i am(.*) $happy (.*)$") { assemble("How have I helped you to be \$3?") assemble("Has your treatment made you \$3?") assemble("What makes you \$3 just now?") assemble("Can you explain why you are suddenly \$3?") } decompose("^(.*)i was (.*)$") { goto("was") } decompose("^(.*)i $belief (.*) i (.*)$") { assemble("Do you really think so?") assemble("But you are not sure you \$3.") assemble("Do you really doubt you \$3?") } decompose("^(.*)i(.*) $belief (.*)you (.*)$") { goto("you") } decompose("^(.*)i am (.*)$") { assemble("Is it because you are \$2 that you came to me?") assemble("How long have you been \$2?") assemble("Do you believe it is normal to be \$2?") assemble("Do you enjoy being \$2?") } decompose("^(.*)i $cannot (.*)$") { assemble("How do you think that you can't \$2?") assemble("Have you tried?") assemble("Perhaps you could \$2 now.") assemble("Do you really want to be able to \$2?") } decompose("^(.*)i don't (.*)$") { assemble("Don't you really \$2?") assemble("Why don't you \$2?") assemble("Do you wish to be able to \$2?") assemble("Does that trouble you?") } decompose("^(.*)do i feel (.*)$") { assemble("Tell me more about such feelings.") assemble("Do you often feel \$2?") assemble("Do you enjoy feeling \$2?") assemble("Of what does feeling \$2 remind you?") } decompose("^(.*)i (.*) you (.*)$") { assemble("Perhaps in your fantasies we \$2 each other.") assemble("Do you wish to \$2 me?") assemble("You seem to need to \$2 me.") assemble("Do you \$2 anyone else?") } decompose("^(.*)$") { assemble("You say \$1?") assemble("Can you elaborate on that?") assemble("Do you say \$1 for some special reason?") assemble("That's quite interesting.") } } key("you") { decompose("^(.*)you remind me of (.*)$") { goto("alike") } decompose("^(.*)you are (.*)$") { assemble("What makes you think I am \$2?") assemble("Does it please you to believe I am \$2?") assemble("Do you sometimes wish you were \$2?") assemble("Perhaps you would like to be \$2.") } decompose("^(.*)you(.*) me (.*)$") { assemble("Why do you think I \$2 you?") assemble("You like to think I \$2 you -- don't you?") assemble("What makes you think I \$2 you?") assemble("Really, I \$2 you?") assemble("Do you wish to believe I \$2 you?") assemble("Suppose I did \$2 you -- what would that mean?") assemble("Does someone else believe I \$2 you?") } decompose("^(.*)you (.*)$") { assemble("We were discussing you -- not me.") assemble("Oh, I \$2?") assemble("You're not really talking about me -- are you?") assemble("What are your feelings now?") } } key("yes") { decompose("^(.*)$") { assemble("You seem to be quite positive.") assemble("You are sure.") assemble("I see.") assemble("I understand.") } } key("no") { decompose("^(.*)$") { assemble("Are you saying no just to be negative?") assemble("You are being a bit negative.") assemble("Why not?") assemble("Why 'no'?") } } key("my", weight = 2) { decompose("(.*) my (.*)", memorising = true) { assemble("Lets discuss further why your \$2.") assemble("Earlier you said your \$2.") assemble("But your \$2.") assemble("Does that have anything to do with the fact that your \$2?") } decompose("^(.*)my(.*) $family (.*)$") { assemble("Tell me more about your family.") assemble("Who else in your family \$3?") assemble("Your \$2?") assemble("What else comes to mind when you think of your \$2?") } decompose("^(.*)my (.*)$") { assemble("Your \$2?") assemble("Why do you say your \$2?") assemble("Does that suggest anything else which belongs to you?") assemble("Is it important that your \$2?") } } key("can") { decompose("^(.*)can you (.*)$") { assemble("You believe I can \$2 don't you?") goto("what") assemble("You want me to be able to \$2.") assemble("Perhaps you would like to be able to \$2 yourself.") } decompose("^(.*)can i (.*)$") { assemble("Whether or not you can \$2 depends on you more than me.") assemble("Do you want to be able to \$2?") assemble("Perhaps you don't want to \$2.") goto("what") } } key("what") { decompose("^(.*)$") { assemble("Why do you ask?") assemble("Does that question interest you?") assemble("What is it you really wanted to know?") assemble("Are such questions much on your mind?") assemble("What type would please you most?") assemble("What do you think?") assemble("What comes to mind when you ask that?") assemble("Have you asked such questions before?") assemble("Have you asked anyone else?") } } key("because") { decompose("^(.*)$") { assemble("Is that the real reason?") assemble("Don't any other reasons come to mind?") assemble("Does that reason seem to explain anything else?") assemble("What other reasons might there be?") } } key("why") { decompose("^(.*)why don't you (.*)$") { assemble("Do you believe I don't \$2?") assemble("Perhaps I will \$2 in good time.") assemble("Should you \$2 yourself?") assemble("You want me to \$2?") goto("what") } decompose("^(.*)why can't i (.*)$") { assemble("Do you think you should be able to \$2?") assemble("Do you want to be able to \$2?") assemble("Do you believe this will help you to \$2?") assemble("Have you any idea why you can't \$2?") goto("what") } decompose("^(.*)$") { goto("what") } } key("everyone", weight = 2) { decompose("^(.*)$everyone (.*)$") { assemble("Really, \$2?") assemble("Surely not \$2.") assemble("Can you think of anyone in particular?") assemble("Who, for example?") assemble("Are you thinking of a very special person?") assemble("Who, may I ask?") assemble("Someone special perhaps?") assemble("You have a particular person in mind, don't you?") assemble("Who do you think you're talking about?") } } key("everybody", weight = 2) { decompose("^(.*)$") { goto("everyone") } } key("nobody", weight = 2) { decompose("^(.*)$") { goto("everyone") } } key("noone", weight = 2) { decompose("^(.*)$") { goto("everyone") } } key("always", weight = 1) { decompose("^(.*)$") { assemble("Can you think of a specific example?") assemble("When?") assemble("What incident are you thinking of?") assemble("Really, always?") } } key("alike", weight = 10) { decompose("^(.*)$") { assemble("In what way?") assemble("What resemblance do you see?") assemble("What does that similarity suggest to you?") assemble("What other connections do you see?") assemble("What do you suppose that resemblance means?") assemble("What is the connection, do you suppose?") assemble("Could here really be some connection?") assemble("How?") } } key("like", weight = 10) { decompose("^(.*)$be (.*)like (.*)$") { goto("alike") } } } }
apache-2.0
9685e8e4e8ab32dc9660179d1ed32397
29.68323
116
0.573723
3.27709
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/DonateRoute.kt
1
1692
package net.perfectdreams.loritta.morenitta.website.routes import com.github.salomonbrys.kotson.jsonArray import com.github.salomonbrys.kotson.jsonObject import net.perfectdreams.loritta.morenitta.dao.DonationKey import net.perfectdreams.loritta.morenitta.tables.DonationKeys import net.perfectdreams.loritta.common.locale.BaseLocale import io.ktor.server.application.ApplicationCall import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.website.utils.extensions.lorittaSession import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondHtml import net.perfectdreams.loritta.morenitta.website.views.DonateView import org.jetbrains.exposed.sql.and class DonateRoute(loritta: LorittaBot) : LocalizedRoute(loritta, "/donate") { override val isMainClusterOnlyRoute = true override suspend fun onLocalizedRequest(call: ApplicationCall, locale: BaseLocale) { val userIdentification = call.lorittaSession.getUserIdentification(loritta, call) val keys = jsonArray() if (userIdentification != null) { val donationKeys = loritta.newSuspendedTransaction { // Pegar keys ativas DonationKey.find { (DonationKeys.expiresAt greaterEq System.currentTimeMillis()) and (DonationKeys.userId eq userIdentification.id.toLong()) }.toMutableList() } for (donationKey in donationKeys) { keys.add( jsonObject( "id" to donationKey.id.value, "value" to donationKey.value, "expiresAt" to donationKey.expiresAt ) ) } } call.respondHtml( DonateView( loritta, locale, getPathWithoutLocale(call), userIdentification, keys ).generateHtml() ) } }
agpl-3.0
52fc6f354bab51c00a562da889c5d64b
31.557692
126
0.77305
4.077108
false
false
false
false
gotev/recycler-adapter
recycleradapter-paging/src/main/java/net/gotev/recycleradapter/paging/DataSourceExtensions.kt
1
1803
package net.gotev.recycleradapter.paging import androidx.paging.ItemKeyedDataSource import androidx.paging.PageKeyedDataSource import androidx.paging.PositionalDataSource import net.gotev.recycleradapter.AdapterItem fun <E> PageKeyedDataSource.LoadInitialCallback<E, AdapterItem<*>>.withEmptyItem( emptyItem: AdapterItem<*>, data: List<AdapterItem<*>> = emptyList(), previousPageKey: E? = null, nextPageKey: E? = null ) { onResult(data.empty(emptyItem), previousPageKey, nextPageKey) } fun <E> PageKeyedDataSource.LoadInitialCallback<E, AdapterItem<*>>.withEmptyItem( emptyItem: AdapterItem<*>, data: List<AdapterItem<*>> = emptyList(), position: Int, totalCount: Int, previousPageKey: E? = null, nextPageKey: E? = null ) { onResult(data.empty(emptyItem), position, totalCount, previousPageKey, nextPageKey) } fun ItemKeyedDataSource.LoadInitialCallback<AdapterItem<*>>.withEmptyItem( emptyItem: AdapterItem<*>, data: List<AdapterItem<*>> = emptyList(), position: Int, totalCount: Int ) { onResult(data.empty(emptyItem), position, totalCount) } fun PositionalDataSource.LoadInitialCallback<AdapterItem<*>>.withEmptyItem( emptyItem: AdapterItem<*>, data: List<AdapterItem<*>> = emptyList(), position: Int, totalCount: Int ) { onResult(data.empty(emptyItem), position, totalCount) } fun PositionalDataSource.LoadInitialCallback<AdapterItem<*>>.withEmptyItem( emptyItem: AdapterItem<*>, data: List<AdapterItem<*>> = emptyList(), position: Int ) { onResult(data.empty(emptyItem), position) } private fun List<AdapterItem<*>>.empty(emptyItem: AdapterItem<*>) = takeIf { isNotEmpty() } ?: listOf(emptyItem)
apache-2.0
ba5bbaab68cdf32671f249af5c44991f
31.8
87
0.690516
4.820856
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/DelegatedGradlePropertiesExtensionsTest.kt
1
7339
package org.gradle.kotlin.dsl import org.gradle.api.Project import org.gradle.api.InvalidUserCodeException import org.gradle.api.initialization.Settings import org.gradle.api.internal.DynamicObjectAware import org.gradle.internal.metaobject.DynamicObject import org.gradle.internal.metaobject.DynamicInvokeResult import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.inOrder import com.nhaarman.mockito_kotlin.mock import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.nullValue import org.junit.Assert.assertThat import org.junit.Assert.fail import org.junit.Test class DelegatedGradlePropertiesExtensionsTest { @Test fun `non-nullable delegated property access of existing non-null gradle property`() { withMockForSettings(existing = "p" to 42) { val p: Int by settings assertThat(p, equalTo(42)) } withMockForProject(existing = "p" to 42) { val p: Int by project assertThat(p, equalTo(42)) } } @Test fun `non-nullable delegated property access of existing null gradle property throws`() { withMockForSettings(existing = "p" to null) { val p: Any by settings try { p.toString() fail("InvalidUserCodeException not thrown") } catch (ex: InvalidUserCodeException) { assertThat(ex.message, equalTo("Cannot get non-null property 'p' on settings as it is null")) } } withMockForProject(existing = "p" to null) { val p: Any by project try { p.toString() fail("InvalidUserCodeException not thrown") } catch (ex: InvalidUserCodeException) { assertThat(ex.message, equalTo("Cannot get non-null property 'p' on project as it is null")) } } } @Test fun `non-nullable delegated property access of non-existing gradle property throws`() { withMockForSettings(absent = "p") { val p: Any by settings try { p.toString() fail("InvalidUserCodeException not thrown") } catch (ex: InvalidUserCodeException) { assertThat(ex.message, equalTo("Cannot get non-null property 'p' on settings as it does not exist")) } } withMockForProject(absent = "p") { val p: Any by project try { p.toString() fail("InvalidUserCodeException not thrown") } catch (ex: InvalidUserCodeException) { assertThat(ex.message, equalTo("Cannot get non-null property 'p' on project as it does not exist")) } } } @Test fun `nullable delegated property access of existing non-null gradle property`() { withMockForSettings(existing = "p" to 42) { val p: Int? by settings assertThat(p, equalTo(42)) } withMockForProject(existing = "p" to 42) { val p: Int? by project assertThat(p, equalTo(42)) } } @Test fun `nullable delegated property access of existing null gradle property`() { withMockForSettings(existing = "p" to null) { val p: Int? by settings assertThat(p, nullValue()) } withMockForProject(existing = "p" to null) { val p: Int? by project assertThat(p, nullValue()) } } @Test fun `nullable delegated property access of non-existing gradle property`() { withMockForSettings(absent = "p") { val p: Int? by settings assertThat(p, nullValue()) } withMockForProject(absent = "p") { val p: Int? by project assertThat(p, nullValue()) } } private fun withMockForSettings(existing: Pair<String, Any?>? = null, absent: String? = null, action: DynamicDelegatedPropertiesMock.SettingsMock.() -> Unit) { mockForSettings(existing, absent).run { action() verifyTryGetProperty(existing, absent) } } private fun withMockForProject(existing: Pair<String, Any?>? = null, absent: String? = null, action: DynamicDelegatedPropertiesMock.ProjectMock.() -> Unit) { mockForProject(existing, absent).run { action() verifyTryGetProperty(existing, absent) } } private fun mockForSettings(existing: Pair<String, Any?>? = null, absent: String? = null): DynamicDelegatedPropertiesMock.SettingsMock = dynamicObjectMockFor(existing, absent).let { dynamicObject -> DynamicDelegatedPropertiesMock.SettingsMock( mock<DynamicAwareSettingsMockType>(name = "settings") { on { asDynamicObject } doReturn dynamicObject }, dynamicObject) } private fun mockForProject(existing: Pair<String, Any?>? = null, absent: String? = null): DynamicDelegatedPropertiesMock.ProjectMock = dynamicObjectMockFor(existing, absent).let { dynamicObject -> DynamicDelegatedPropertiesMock.ProjectMock( mock<DynamicAwareProjectMockType>(name = "project") { on { asDynamicObject } doReturn dynamicObject }, dynamicObject) } private interface DynamicAwareSettingsMockType : Settings, DynamicObjectAware private interface DynamicAwareProjectMockType : Project, DynamicObjectAware private sealed class DynamicDelegatedPropertiesMock<out T : Any>(private val target: T, private val dynamicObject: DynamicObject) { fun verifyTryGetProperty(existing: Pair<String, Any?>?, absent: String?) { existing?.let { verifyTryGetProperty(existing.first) } absent?.let { verifyTryGetProperty(absent) } } private fun verifyTryGetProperty(propertyName: String) = inOrder(target, dynamicObject) { verify(target as DynamicObjectAware).asDynamicObject verify(dynamicObject).tryGetProperty(propertyName) verifyNoMoreInteractions() } class SettingsMock(val settings: Settings, dynamicObject: DynamicObject) : DynamicDelegatedPropertiesMock<Settings>(settings, dynamicObject) class ProjectMock(val project: Project, dynamicObject: DynamicObject) : DynamicDelegatedPropertiesMock<Project>(project, dynamicObject) } private fun dynamicObjectMockFor(existing: Pair<String, Any?>?, absent: String?) = mock<DynamicObject> { existing?.let { (name, value) -> val existingMock = mock<DynamicInvokeResult> { on { this.isFound } doReturn true on { this.value } doReturn value } on { tryGetProperty(name) } doReturn existingMock } absent?.let { val absentMock = mock<DynamicInvokeResult> { on { this.isFound } doReturn false } on { tryGetProperty(absent) } doReturn absentMock } } }
apache-2.0
e698c442378af19cbc5bddc17be8d525
31.763393
155
0.605532
4.850628
false
false
false
false
siosio/upsource-kotlin-api
src/main/java/com/github/siosio/upsource/bean/ProjectSettings.kt
1
819
package com.github.siosio.upsource.bean data class ProjectSettings( val projectName: String, val vcsSettings: String? = null, val checkIntervalSeconds: Long? = null, val projectModel: ProjectModel, val codeReviewIdPattern: String, val runInspections: Boolean? = null, val mavenSettings: String? = null, val mavenProfiles: String? = null, val mavenJdkName: String? = null, val externalLinks: List<ExternalLink> = emptyList(), val createUserGroups: Boolean? = null, val issueTrackerProviderSettings: IssueTrackerProviderSettings? = null, val userManagementUrl: String? = null, val defaultEncoding: String? = null, val defaultBranch: String? = null, val autoAddRevisionsToReview: Boolean? = null, val ignoredFilesInReview: List<String> = emptyList() )
mit
0c6bed075aee69860873d82ae6da65f6
36.227273
75
0.721612
4.265625
false
false
false
false
AIDEA775/UNCmorfi
app/src/main/java/com/uncmorfi/servings/ServingsFragment.kt
1
4318
package com.uncmorfi.servings import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.github.mikephil.charting.data.Entry import com.uncmorfi.R import com.uncmorfi.models.Serving import com.uncmorfi.servings.StyledLineDataSet.Companion.ChartStyle.CUMULATIVE import com.uncmorfi.servings.StyledLineDataSet.Companion.ChartStyle.RATIONS import com.uncmorfi.shared.StatusCode.BUSY import com.uncmorfi.shared.clearDate import com.uncmorfi.shared.init import com.uncmorfi.shared.startBrowser import com.uncmorfi.viewmodel.MainViewModel import kotlinx.android.synthetic.main.fragment_servings.* /** * Medidor de raciones. * Administra la UI con todas sus features. */ class ServingsFragment : Fragment() { private lateinit var mRootView: View private lateinit var mViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_servings, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mRootView = view mViewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java) swipeRefresh.init { refreshServings() } servingTimeChart.init(requireContext()) servingAccumulatedChart.init(requireContext()) servingTimeChart.onChartGestureListener = SyncChartsGestureListener( servingTimeChart, servingAccumulatedChart) servingAccumulatedChart.onChartGestureListener = SyncChartsGestureListener( servingAccumulatedChart, servingTimeChart) // Parametros especiales de ambos LineChart servingAccumulatedChart.xAxis.setDrawGridLines(false) mViewModel.getServings().observe(viewLifecycleOwner, Observer { servingsPieChart.set(it) updateCharts(it) }) refreshServings() } override fun onResume() { super.onResume() requireActivity().setTitle(R.string.navigation_servings) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.servings, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.serving_update -> { refreshServings(); true } R.id.serving_browser -> requireActivity().startBrowser(URL) else -> super.onOptionsItemSelected(item) } } private fun refreshServings() { mViewModel.updateServings() } private fun updateCharts(items: List<Serving>) { if (items.isNotEmpty()) { val data = items.map { s -> Entry(s.date.clearDate().toFloat(), s.serving.toFloat()) } if (data.size > 1) { // Algunas veces el medidor se cae, y las raciones aparecen cargadas a las 00:00hs // así que al primer elemento lo ponemos 1 min antes del segundo elemento // para que no haya un espacio vacío en el medio. data[0].x = data[1].x - 60f } val timeData = StyledLineDataSet(requireContext(), data, getString(R.string.servings_chart_label_time), RATIONS) val cumulativeData = StyledLineDataSet(requireContext(), accumulate(data), getString(R.string.servings_chart_label_accumulated), CUMULATIVE) servingTimeChart.update(timeData) servingAccumulatedChart.update(cumulativeData) } else { servingTimeChart.clear() servingAccumulatedChart.clear() } } private fun accumulate(data: List<Entry>): List<Entry> { var sum = 0f val accumulated = ArrayList<Entry>() for (entry in data) { sum += entry.y accumulated.add(Entry(entry.x, sum)) } return accumulated } companion object { private const val URL = "http://comedor.unc.edu.ar/cocina.php" } }
gpl-3.0
5d710830db3fc4afbbc5fa9b8e1cf835
34.975
152
0.679796
4.32032
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/executors/moderation/infraction/CommandInfractions.kt
1
11178
package me.mrkirby153.KirBot.command.executors.moderation.infraction import com.mrkirby153.bfs.model.Model import com.mrkirby153.bfs.query.DB import me.mrkirby153.KirBot.command.CommandCategory import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist import me.mrkirby153.KirBot.command.annotations.LogInModlogs import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.database.models.DiscordUser import me.mrkirby153.KirBot.infraction.Infraction import me.mrkirby153.KirBot.infraction.Infractions import me.mrkirby153.KirBot.listener.WaitUtils import me.mrkirby153.KirBot.logger.LogEvent import me.mrkirby153.KirBot.user.CLEARANCE_ADMIN import me.mrkirby153.KirBot.user.CLEARANCE_MOD import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.checkPermissions import me.mrkirby153.KirBot.utils.getClearance import me.mrkirby153.KirBot.utils.kirbotGuild import me.mrkirby153.KirBot.utils.nameAndDiscrim import me.mrkirby153.kcutils.Time import me.mrkirby153.kcutils.utils.TableBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.sharding.ShardManager import javax.inject.Inject import kotlin.system.measureTimeMillis class CommandInfractions @Inject constructor(private val infractions: Infractions, private val shardManager: ShardManager) { @Command(name = "infraction", aliases = ["inf"], clearance = CLEARANCE_MOD, category = CommandCategory.MODERATION) @CommandDescription("Infraction related commands") fun inf() { // Dummy command to support aliases } @Command(name = "search", clearance = CLEARANCE_MOD, arguments = ["[query:string...]"], parent = "infraction", category = CommandCategory.MODERATION) @LogInModlogs @CommandDescription("Search for an infraction with the given query") @IgnoreWhitelist fun search(context: Context, cmdContext: CommandContext) { val query = cmdContext.get<String>("query") ?: "" val infractions = DB.raw( "SELECT DISTINCT * FROM infractions WHERE (`user_id` = ? AND `guild` = ?) OR (`issuer` = ? AND `guild` = ?) OR (`id` = ?) OR (`reason` LIKE ? AND `guild` = ?) ORDER BY `id` DESC LIMIT 5", query, context.guild.id, query, context.guild.id, query, "%$query%", context.guild.id).map { val inf = Infraction() inf.hydrate(it) return@map inf } val header = arrayOf("ID", "Created", "Type", "User", "Moderator", "Reason", "Active", "Expires") val table = TableBuilder(header) val users = mutableMapOf<String, String>() infractions.forEach { val moderator = if (it.issuerId == null) "Unknown" else users.computeIfAbsent( it.issuerId!!) { Model.where(DiscordUser::class.java, "id", it).first()?.nameAndDiscrim ?: it } val username = users.computeIfAbsent(it.userId) { Model.where(DiscordUser::class.java, "id", it).first()?.nameAndDiscrim ?: it } val reason = if (it.reason != null) if (it.reason!!.length >= 256) it.reason!!.substring( 0..255) + "..." else it.reason else "" table.addRow( arrayOf(it.id.toString(), it.createdAt.toString(), it.type.toString(), username, moderator, reason, if (it.active) "yes" else "no", it.expiresAt?.toString() ?: "NULL")) } val builtTable = table.buildTable() if (builtTable.length < 2000) { context.channel.sendMessage("```$builtTable```").queue() } else { if(!context.channel.checkPermissions(Permission.MESSAGE_ATTACH_FILES)) { throw CommandException("The output was too long and I do not have permission to attach files") } context.channel.sendFile(builtTable.toByteArray(), "infractions.txt").queue() } } @Command(name = "info", clearance = CLEARANCE_MOD, arguments = ["<id:int>"], parent = "infraction", category = CommandCategory.MODERATION, permissions = [Permission.MESSAGE_EMBED_LINKS]) @LogInModlogs @CommandDescription("Gets detailed information about an infraction") @IgnoreWhitelist fun info(context: Context, cmdContext: CommandContext) { val id = cmdContext.get<Int>("id")!! val infraction = Model.where(Infraction::class.java, "id", id).first() if (infraction == null || infraction.guild != context.guild.id) throw CommandException("Infraction not found!") val user = Model.where(DiscordUser::class.java, "id", infraction.userId).first() val moderator = Model.where(DiscordUser::class.java, "id", infraction.issuerId).first() context.send().embed("#${id} - ${infraction.type.internalName.capitalize()}") { timestamp { millis(infraction.createdAt.time) } author { name = user.nameAndDiscrim val jdaUser = shardManager.getUserById(user.id) if(jdaUser != null) { iconUrl = jdaUser.effectiveAvatarUrl } } fields { field { title = "User" description { if (user != null) +user.nameAndDiscrim else +infraction.userId } inline = true } field { title = "Moderator" description { if (moderator != null) +moderator.nameAndDiscrim else +infraction.userId } inline = true } field { title = "Reason" description = infraction.reason ?: "" } } }.rest().queue() } @Command(name = "clear", clearance = CLEARANCE_MOD, arguments = ["<id:int>", "[reason:string...]"], category = CommandCategory.MODERATION, parent = "infraction", aliases = ["delete"], permissions = [Permission.MESSAGE_ADD_REACTION]) @LogInModlogs @CommandDescription("Clears an infraction (Deletes it from the database)") @IgnoreWhitelist fun clearInfraction(context: Context, cmdContext: CommandContext) { val id = cmdContext.get<Int>("id")!! val reason = cmdContext.get<String>("reason") ?: "No reason specified" val infraction = Model.where(Infraction::class.java, "id", id).first() ?: throw CommandException( "Infraction not found") if (infraction.issuerId == null || infraction.issuerId != context.author.id) { if (context.author.getClearance(context.guild) < CLEARANCE_ADMIN) throw CommandException("You do not have permission to clear this infraction") } context.channel.sendMessage( "Are you sure you want to delete this infraction? This cannot be undone").queue { msg -> WaitUtils.confirmYesNo(msg, context.author, { infraction.delete() context.channel.sendMessage("Infraction `$id` deleted!").queue() context.guild.kirbotGuild.logManager.genericLog(LogEvent.ADMIN_COMMAND, ":warning:", "Infraction `$id` deleted by ${context.author.nameAndDiscrim} (`${context.author.id}`): `$reason`") }, { msg.editMessage("Canceled!").queue() }) } } @Command(name = "reason", clearance = CLEARANCE_MOD, arguments = ["<id:number>", "<reason:string...>"], category = CommandCategory.MODERATION, parent = "infraction", aliases = ["update"]) @LogInModlogs @CommandDescription("Sets the reason of an infraction") @IgnoreWhitelist fun reason(context: Context, cmdContext: CommandContext) { val id = cmdContext.get<Int>("id")!! val reason = cmdContext.get<String>("reason")!! val infraction = Model.where(Infraction::class.java, "id", id).first() ?: throw CommandException("That infraction doesn't exist") // Prevent modifying infractions from different guilds if (infraction.guild != context.guild.id) throw CommandException("That infraction doesn't exist") infraction.reason = reason infraction.save() context.send().success("Updated reason of `$id`").queue() } @Command(name = "import-banlist", clearance = CLEARANCE_ADMIN, category = CommandCategory.MODERATION, parent = "infraction", permissions = [Permission.MESSAGE_ADD_REACTION]) @LogInModlogs @CommandDescription("Imports the banlist as infractions") @IgnoreWhitelist fun importBanlist(context: Context, cmdContext: CommandContext) { context.channel.sendMessage("Are you sure you want to import the banlist?").queue { msg -> WaitUtils.confirmYesNo(msg, context.author, { context.channel.sendMessage(":timer: Importing from the banlist...").queue { val timeTaken = measureTimeMillis { infractions.importFromBanlist(context.guild.kirbotGuild) } it.editMessage("Completed in ${Time.format(1, timeTaken)}").queue() } }, { msg.editMessage("Canceled!").queue() }) } } @Command(name = "export", clearance = CLEARANCE_MOD, category = CommandCategory.MODERATION, parent = "infraction", permissions = [Permission.MESSAGE_ATTACH_FILES]) @LogInModlogs @IgnoreWhitelist @CommandDescription("Exports a CSV of infractions") fun export(context: Context, cmdContext: CommandContext) { val infractions = Model.where(Infraction::class.java, "guild", context.guild.id).get() val infString = buildString { appendln("id,user,issuer,reason,timestamp") infractions.forEach { append(it.id) append(",") append(it.userId) append(",") append(it.issuerId) append(",") if (it.reason?.contains(",") == true) { append("\"") append(it.reason) append("\"") } else { append(it.reason ?: "NULL") } append(",") appendln(it.createdAt.toString()) } } context.channel.sendMessage("Exported ${infractions.size} infractions").addFile( infString.toByteArray(), "infractions.csv").queue() } }
mit
c9728644a8b67fb44f397ffaac0c5d0f
44.259109
203
0.594382
4.579271
false
false
false
false
toastkidjp/Yobidashi_kt
rss/src/test/java/jp/toastkid/rss/ParserTest.kt
2
2733
package jp.toastkid.rss import jp.toastkid.rss.model.Parser import okio.buffer import okio.source import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import java.io.InputStream /** * @author toastkidjp */ class ParserTest { private lateinit var parser: Parser @Before fun setUp() { parser = Parser() } @Test fun test() { val rssText = readStream("rss/sample.xml").source().use { source -> source.buffer().use { it.readUtf8() } } val rss = parser.parse(rssText.split("\n")) assertNull(rss.creator) assertEquals("This instance has only 1 item.", rss.description) assertEquals("http://www.yahoo.co.jp/", rss.link) assertEquals("RSS title", rss.title) assertNull(rss.url) assertTrue(rss.subjects.isEmpty()) val items = rss.items assertFalse(items.isEmpty()) val item = items.get(0) assertTrue(item.content.isEmpty()) assertEquals("This item is a mere mock.", item.description) assertEquals("http://www.yahoo.co.jp", item.link) assertEquals("Item title", item.title) } @Test fun testAtom() { val rssText = readStream("rss/sample.atom").source().use { source -> source.buffer().use { it.readUtf8() } } val rss = parser.parse(rssText.split("\n")) assertEquals("Private Feed for toastkidjp", rss.title) assertEquals(30, rss.items.size) val item = rss.items[0] assertEquals("MWGuy starred Turaiiao/crush", item.title) assertEquals("https://github.com/Turaiiao/crush", item.link) } @Test fun testRdf() { val rssText = readStream("rss/sample.rdf").source().use { source -> source.buffer().use { it.readUtf8() } } val rss = parser.parse(rssText.split("\n")) assertEquals("なんJ(まとめては)いかんのか?", rss.title) assertEquals(3, rss.items.size) val item = rss.items[0] assertEquals("ヤクルト・塩見、ダーツを破壊wwww", item.title) assertEquals("http://blog.livedoor.jp/livejupiter2/archives/9541826.html", item.link) assertEquals("なんJ(まとめては)いかんのか?", item.source) assertEquals("2019-12-30T21:17:13+09:00", item.date) println(item.content) } private fun readStream(filePath: String): InputStream = javaClass.classLoader?.getResourceAsStream(filePath) ?: throw RuntimeException() }
epl-1.0
6bc744508e70b3773ccf02ee6ae44881
27.989011
93
0.620402
3.729844
false
true
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_uart/src/main/java/no/nordicsemi/android/uart/db/Configuration.kt
1
2034
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.uart.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "configurations") internal data class Configuration( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") val _id: Int?, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "xml") val xml: String, @ColumnInfo(name = "deleted", defaultValue = "0") val deleted: Int )
bsd-3-clause
abf1ad681a7e14d0479b9ede2bdb1fd9
44.2
89
0.761062
4.540179
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/headToHead/HeadToHeadMatchItemView.kt
1
2379
package com.garpr.android.features.headToHead import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import androidx.annotation.ColorInt import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import com.garpr.android.R import com.garpr.android.data.models.HeadToHeadMatch import com.garpr.android.data.models.LitePlayer import com.garpr.android.data.models.MatchResult import com.garpr.android.extensions.getAttrColor import kotlinx.android.synthetic.main.item_head_to_head_match.view.* class HeadToHeadMatchItemView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : ConstraintLayout(context, attrs) { @ColorInt private val exclusionColor: Int = context.getAttrColor(android.R.attr.textColorSecondary) @ColorInt private val loseColor: Int = ContextCompat.getColor(context, R.color.lose) @ColorInt private val winColor: Int = ContextCompat.getColor(context, R.color.win) init { if (isInEditMode) { setContent( match = HeadToHeadMatch( result = MatchResult.WIN, player = LitePlayer("0", "Shroomed"), opponent = LitePlayer("1", "PewPewU") ), playerIsIdentity = true, opponentIsIdentity = false ) } } fun setContent(match: HeadToHeadMatch, playerIsIdentity: Boolean, opponentIsIdentity: Boolean) { playerName.text = match.player.name opponentName.text = match.opponent.name playerName.typeface = if (playerIsIdentity) Typeface.DEFAULT_BOLD else Typeface.DEFAULT opponentName.typeface = if (opponentIsIdentity) Typeface.DEFAULT_BOLD else Typeface.DEFAULT when (match.result) { MatchResult.EXCLUDED -> { playerName.setTextColor(exclusionColor) opponentName.setTextColor(exclusionColor) } MatchResult.LOSE -> { playerName.setTextColor(loseColor) opponentName.setTextColor(winColor) } MatchResult.WIN -> { playerName.setTextColor(winColor) opponentName.setTextColor(loseColor) } } } }
unlicense
3850f4e0d8784fde6e7bbeba89353bb1
33.478261
100
0.651114
4.78672
false
false
false
false
poisondminds/poll-vaults-android
PollVaults/app/src/main/java/com/pollvaults/deming/fragments/TrendingFragment.kt
1
1667
package com.pollvaults.deming.fragments import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.pollvaults.deming.R import com.pollvaults.deming.adapters.PollAdapter import com.pollvaults.deming.models.firebase.PollModel import com.pollvaults.deming.models.firebase.toFirebaseModel class TrendingFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater.inflate(R.layout.fragment_trending, container, false) val polls = ArrayList<PollModel>() val pollsRecyclerView: RecyclerView = v.findViewById(R.id.pollsRecyclerView) as RecyclerView // TOOD: no more val ref = FirebaseDatabase.getInstance().getReference("polls").addListenerForSingleValueEvent(object: ValueEventListener { override fun onCancelled(p0: DatabaseError?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onDataChange(snapshot: DataSnapshot) { snapshot.children.forEach { polls.add(it.toFirebaseModel()) } val adapter = PollAdapter(polls) pollsRecyclerView.adapter = adapter pollsRecyclerView.layoutManager = LinearLayoutManager(activity) } }) return v } }
gpl-3.0
b70843311efe906dd8c2229a05354077
31.686275
122
0.797241
4.105911
false
false
false
false
pabiagioli/gopro-showcase
app/src/test/java/com/aajtech/mobile/goproshowcase/GoProCommandsUnitTest.kt
1
10251
package com.aajtech.mobile.goproshowcase import android.net.ConnectivityManager import android.support.v4.net.ConnectivityManagerCompat import com.squareup.moshi.Moshi import okhttp3.OkHttpClient import okhttp3.ResponseBody import org.junit.Test import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query import java.util.concurrent.TimeUnit /** * Created by pablo.biagioli on 7/19/16. */ class GoProCommandsUnitTest { val okHttpClient: OkHttpClient by lazy { OkHttpClient().newBuilder() .connectTimeout(120, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build()!! } val moshi: Moshi by lazy { Moshi.Builder().build()!! } val retrofit: Retrofit by lazy { Retrofit.Builder() .baseUrl("http://10.5.5.9/gp/gpControl/") .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build()!! } @Test fun testWoL() { val macStr = "F4DD9E0DE0F7" val ipStr = "10.5.5.9" try { val macStr1 = MagicPacket.cleanMac(macStr) println("Sending to: " + macStr) MagicPacket.send(macStr1, ipStr) } catch(e: IllegalArgumentException) { e.printStackTrace() } catch(e: Exception) { System.out.println("Failed to send Wake-on-LAN packet:" + e.message) } } /** * "info": { * "model_number": 16, * "model_name": "HERO4 Session", * "firmware_version": "HX1.01.01.00", * "serial_number": "C3141324949509", * "board_type": "0x07", * "ap_mac": "F4DD9E0DE0F7", * "ap_ssid": "aajGoPro", * "ap_has_default_credentials": "0", * "git_sha1": "e4c3eabd3ab8d3f53067e986458ef04652222fd4" * } */ @Test() fun testGoProInfo() { val ssid = "aajGoPro" val pass = "44JT3ch01" testWoL() val service = retrofit.create(GoProInfoService::class.java) //Requests/Responses //I'm using execute, since it's really hard to Test an Async Method //TODO: how do I plug JUnit to bg Thread??? var responseStatus = service.status().execute() var retryCount = 1; val totalRetries = 4; //I may have to retry the request a couple of times until the camera is fully initialized if (responseStatus.code() == 500) { do { println("First attempt failed!\nAttempting retry #$retryCount") responseStatus = service.status().execute() retryCount++ } while (responseStatus.code() != 200 && (retryCount < totalRetries)) } val responseBody = responseStatus.body() assert(responseStatus.isSuccessful) println(responseBody.toString()) val batteryPercentage = responseBody.batteryLvlPercentage() for ((property, id) in GoProConstants.status) { val propValue = responseBody.status[id]; println("$property = $propValue") } println("Battery Level [0..3]: $batteryPercentage%") //assert(service.powerOff().execute().isSuccessful) } @Test fun testGetAnalytics() { testWoL() val service = retrofit.create(GoProAnalyticsService::class.java) var response = service.analytics().execute() if (!response.isSuccessful && response.code() == 500) { response = service.analytics().execute() } assert(response.isSuccessful) //println("Analytics File toString()"+response.body().byteStream()) println("Analytics File Content-Type " + response.body().contentType()?.type()) println("Analytics File String(byteArray)" + String(response.body().bytes())) /*.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) { assert(response != null) if(response != null) assert(response.isSuccessful) } override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) { assert(false) } })*/ } @Test fun testGoProTakeSinglePhoto() { testWoL() val primaryMode = retrofit.create(GoProPrimaryModeService::class.java) var response = primaryMode.setPrimaryMode(GoProPrimaryModes.PHOTO.mode).execute() if (!response.isSuccessful && response.code() == 500) response = primaryMode.setPrimaryMode(GoProPrimaryModes.PHOTO.mode).execute() assert(response.isSuccessful) println(response.body().string()) val secondaryMode = retrofit.create(GoProSecondaryModeService::class.java) val response2 = secondaryMode.setSubMode( GoProSecondaryModes.SINGLE_PHOTO.mode, GoProSecondaryModes.SINGLE_PHOTO.subMode).execute() assert(response2.isSuccessful) println(response2.body().string()) val trigger = retrofit.create(GoProShutterService::class.java) val response3 = trigger.shutterToggle(GoProShutterModes.TRIGGER_SHUTTER.mode).execute() assert(response3.isSuccessful) println(response3.body().string()) } } data class GoProStatusResponse(val status: Map<Int, Any>, val settings: Map<Int, Any>) { /** * Returns the battery level percentage * The Battery Level is between [0..3], * The value is rounded up from its first digit from the left. */ fun batteryLvlPercentage(): Long { val batLvlK = GoProConstants.status[GoProConstants.batteryLevel]!! val batLvl = status[batLvlK] val result = when (batLvl) { is String -> Math.round(batLvl.toDouble() * 10 / 3) * 10 else -> Math.round(batLvl.toString().toDouble() * 10 / 3) * 10 } return result; } } object GoProConstants { /** * Go Pro Hero 4 Session's Internal Battery Level */ val batteryLevel = "InternalBatteryLevel" val status: Map<String, Int> get() = mapOf( "InternalBatteryPresent" to 1, "InternalBatteryLevel" to 2, "ExternalBatteryPresent" to 3, "ExternalBatteryLevel" to 4, "CurrentTemperature" to 5, "SystemHot" to 6, "SystemBusy" to 8, "QuickCaptureActive" to 9, "EncodingActive" to 10, "LcdLockActive" to 11, "CameraLocateActive" to 45, "Mode" to 43, "SubMode" to 44, "Xmode" to 12, "VideoProgressCounter" to 13, "VideoProtuneDefault" to 46, "PhotoProtuneDefault" to 47, "MultiShotProtuneDefault" to 48, "MultiShotCountDown" to 49, "BroadcastProgressCounter" to 14, "BroadcastViewersCount" to 15, "BroadcastBstatus" to 16, "WirelessEnable" to 17, "WirelessPairState" to 19, "WirelessPairType" to 20, "WirelessScanState" to 22, "WirelessScanTime" to 23, "WirelessScanCurrentTime" to 18, "WirelessPairing" to 28, "WirelessRemoveControlVersion" to 26, "WirelessRemoveControlConnected" to 27, "WirelessAppCount" to 31, "WirelessProvisionStatus" to 24, "WirelessRssiBars" to 25, "WirelessWlanSsid" to 29, "WirelessApSsid" to 30, "SdStatus" to 33, "RemainingPhotos" to 34, "RemainingVideoTime" to 35, "NumGroupPhotos" to 36, "NumGroupVideos" to 37, "NumTotalPhotos" to 38, "NumTotalVideos" to 39, "DateTime" to 40, "FWUpdateOtaStatus" to 41, "FWUpdateDownloadCancelRequestPending" to 42 ) } enum class GoProPrimaryModes(val mode: Int) { VIDEO(0), PHOTO(1), MULTI_SHOT(2) } enum class GoProSecondaryModes(val mode: Int, val subMode: Int) { VIDEO_VIDEO(0, 0), TIME_LAPSE_VIDEO(0, 1), VIDEO_PLUS_PHOTO(0, 2), LOOPING_VIDEO(0, 3), SINGLE_PHOTO(1, 0), CONTINUOUS_PHOTO(1, 1), NIGHT_PHOTO(1, 2), BURST_MULTI_SHOT(2, 0), TIME_LAPSE_MULTI_SHOT(2, 1), NIGHT_LAPSE_MULTI_SHOT(2, 2) } enum class GoProShutterModes(val mode: Int) { TRIGGER_SHUTTER(1), STOP_SHUTTER(0) } interface GoProInfoService { /** * get Status codes */ @GET("status") fun status(): Call<GoProStatusResponse> @GET("command/system/sleep") fun powerOff(): Call<Any> @GET("command/wireless/ap/ssid") fun nameCmd(@Query("ssid") ssid: String, @Query("pw") pass: String): Call<ResponseBody> } interface GoProAnalyticsService { /** * Acquire the analytics file as an octet-stream. */ @Headers("Content-Type: application/octet-stream") @GET("analytics/get") fun analytics(): Call<ResponseBody> } interface GoProPrimaryModeService { @GET("command/mode") fun setPrimaryMode(@Query("p") mode: Int): Call<ResponseBody> } interface GoProSecondaryModeService { @GET("command/sub_mode") fun setSubMode(@Query("mode") mode: Int, @Query("sub_mode") subMode: Int): Call<ResponseBody> } interface GoProShutterService { /** * Trigger command */ @GET("command/shutter") fun shutterToggle(@Query("p") toggle: Int): Call<ResponseBody> } enum class GoProStreamingModes(val param1: String, val command: String) { START_STREAMING("gpStream", "restart"), STOP_STREAMING("gpStream", "stop") } interface GoProLiveStreaming { /** * Toggle real-time A/V stream using LTP */ @GET("execute?p1=gpStream&c1=restart") fun toggleLiveStreamingLTP(@Query("p1") param1: String, @Query("c1") command: String) }
gpl-3.0
9fa9019fc2dd1ddb2522fbd3d917957c
31.034375
99
0.597015
4.064631
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/Migrations.kt
2
2353
package eu.kanade.tachiyomi import eu.kanade.tachiyomi.data.library.LibraryUpdateJob import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.updater.UpdaterJob import java.io.File object Migrations { /** * Performs a migration when the application is updated. * * @param preferences Preferences of the application. * @return true if a migration is performed, false otherwise. */ fun upgrade(preferences: PreferencesHelper): Boolean { val context = preferences.context val oldVersion = preferences.lastVersionCode().getOrDefault() if (oldVersion < BuildConfig.VERSION_CODE) { preferences.lastVersionCode().set(BuildConfig.VERSION_CODE) if (oldVersion == 0) return false if (oldVersion < 14) { // Restore jobs after upgrading to evernote's job scheduler. if (BuildConfig.INCLUDE_UPDATER && preferences.automaticUpdates()) { UpdaterJob.setupTask() } LibraryUpdateJob.setupTask() } if (oldVersion < 15) { // Delete internal chapter cache dir. File(context.cacheDir, "chapter_disk_cache").deleteRecursively() } if (oldVersion < 19) { // Move covers to external files dir. val oldDir = File(context.externalCacheDir, "cover_disk_cache") if (oldDir.exists()) { val destDir = context.getExternalFilesDir("covers") if (destDir != null) { oldDir.listFiles().forEach { it.renameTo(File(destDir, it.name)) } } } } if (oldVersion < 26) { // Delete external chapter cache dir. val extCache = context.externalCacheDir if (extCache != null) { val chapterCache = File(extCache, "chapter_disk_cache") if (chapterCache.exists()) { chapterCache.deleteRecursively() } } } return true } return false } }
apache-2.0
a4c8527b93fb7babc68fe01e3f993a76
36.365079
84
0.548236
5.359909
false
false
false
false
outadoc/Twistoast-android
twistoast/src/main/kotlin/fr/outadev/twistoast/background/PebbleWatchReceiver.kt
1
8353
/* * Twistoast - PebbleWatchReceiver.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast 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. * * Twistoast 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 fr.outadev.twistoast.background import android.content.Context import android.graphics.Color import android.net.ConnectivityManager import android.util.Log import com.getpebble.android.kit.PebbleKit import com.getpebble.android.kit.PebbleKit.PebbleDataReceiver import com.getpebble.android.kit.util.PebbleDictionary import fr.outadev.android.transport.timeo.TimeoRequestHandler import fr.outadev.android.transport.timeo.TimeoSingleSchedule import fr.outadev.android.transport.timeo.TimeoStopSchedule import fr.outadev.twistoast.ConfigurationManager import fr.outadev.twistoast.Database import fr.outadev.twistoast.DatabaseOpenHelper import fr.outadev.twistoast.TimeFormatter import org.jetbrains.anko.doAsync import java.util.* /** * Receives and handles the Twistoast Pebble app requests in the background. * * @author outadoc */ class PebbleWatchReceiver : PebbleDataReceiver(PebbleWatchReceiver.PEBBLE_UUID) { private val requestHandler: TimeoRequestHandler private lateinit var database: Database init { requestHandler = TimeoRequestHandler() } override fun receiveData(context: Context, transactionId: Int, data: PebbleDictionary) { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager Log.d(TAG, "received a message from pebble " + PEBBLE_UUID) // open the database and count the stops database = Database(DatabaseOpenHelper(context)) val stopsCount = database.stopsCount val messageType : Byte = data.getInteger(KEY_TWISTOAST_MESSAGE_TYPE).toByte() // if we want a schedule and we have buses in the database if (messageType === BUS_STOP_REQUEST && stopsCount > 0 && cm.activeNetworkInfo != null && cm.activeNetworkInfo.isConnected) { Log.d(TAG, "pebble request acknowledged") PebbleKit.sendAckToPebble(context, transactionId) // get the bus index (modulo the number of stops there is in the db) val busIndex = (data.getInteger(KEY_STOP_INDEX)!!.toShort() % stopsCount).toShort() // get the stop that interests us val stop = database.getStopAtIndex(busIndex.toInt()) Log.d(TAG, "loading data for stop #$busIndex...") // fetch schedule doAsync { try { val schedule = requestHandler.getSingleSchedule(stop!!) Log.d(TAG, "got data for stop: " + schedule) craftAndSendSchedulePacket(context, schedule) } catch (e: Exception) { e.printStackTrace() PebbleKit.sendNackToPebble(context, transactionId) } } } else { PebbleKit.sendNackToPebble(context, transactionId) } } /** * Sens a response packet to the Pebble. * * @param context a context * @param schedule the schedule to send back */ private fun craftAndSendSchedulePacket(context: Context, schedule: TimeoStopSchedule) { val config = ConfigurationManager(context) val res = PebbleDictionary() res.addInt8(KEY_TWISTOAST_MESSAGE_TYPE, BUS_STOP_DATA_RESPONSE) res.addString(KEY_BUS_LINE_NAME, processStringForPebble(schedule.stop.line.name, 10)) res.addString(KEY_BUS_DIRECTION_NAME, processStringForPebble(schedule.stop.line.direction.name, 15)) res.addString(KEY_BUS_STOP_NAME, processStringForPebble(schedule.stop.name, 15)) // Add first schedule time and direction to the buffer if (!schedule.schedules.isEmpty()) { // Time at which the next bus is planned val nextSchedule = schedule.schedules[0].scheduleTime // Convert to milliseconds and add to the buffer res.addInt32(KEY_BUS_NEXT_SCHEDULE, TimeFormatter.getDurationUntilBus(nextSchedule).millis.toInt()) // Get a short version of the destination if required - e.g. A or B for the tram res.addString(KEY_BUS_NEXT_SCHEDULE_DIR, getOptionalShortDirection(schedule.schedules[0])) } else { res.addInt32(KEY_BUS_NEXT_SCHEDULE, -1) res.addString(KEY_BUS_NEXT_SCHEDULE_DIR, " ") } // Add the second schedule, same process if (schedule.schedules.size > 1) { val nextSchedule = schedule.schedules[1].scheduleTime res.addInt32(KEY_BUS_SECOND_SCHEDULE, TimeFormatter.getDurationUntilBus(nextSchedule).millis.toInt()) res.addString(KEY_BUS_SECOND_SCHEDULE_DIR, getOptionalShortDirection(schedule.schedules[1])) } else { res.addInt32(KEY_BUS_SECOND_SCHEDULE, -1) res.addString(KEY_BUS_SECOND_SCHEDULE_DIR, " ") } if (!schedule.schedules.isEmpty()) { val scheduleTime = schedule.schedules[0].scheduleTime val displayMode = TimeFormatter.getTimeDisplayMode(scheduleTime, context) if (displayMode === TimeFormatter.TimeDisplayMode.ARRIVAL_IMMINENT || displayMode === TimeFormatter.TimeDisplayMode.CURRENTLY_AT_STOP) { res.addInt8(KEY_SHOULD_VIBRATE, 1.toByte()) } } var color = 0x0 if (config.useColorInPebbleApp) { color = Color.parseColor(schedule.stop.line.color) } res.addInt32(KEY_BACKGROUND_COLOR, color) Log.d(TAG, "sending back: " + res) PebbleKit.sendDataToPebble(context, PEBBLE_UUID, res) } private fun getOptionalShortDirection(schedule: TimeoSingleSchedule): String { if (schedule.direction != null && (schedule.direction as String).matches("(A|B) .+".toRegex())) { return (schedule.direction as String)[0].toString() } else { return " " } } /** * Processes a string for the Pebble's screen. * * @param str the string to process * @param maxLength the max length of the string * * @return the processed string, or the original string if no action was required */ private fun processStringForPebble(str: String?, maxLength: Int): String { if (str == null) { return "" } if (str.length <= maxLength) { //if the string is shorter than the max length, just return the string untouched return str } try { //truncate the string to [maxLength] characters, and add an ellipsis character at the end return str.substring(0, maxLength).trim { it <= ' ' } + "…" } catch (e: IndexOutOfBoundsException) { return str } } companion object { val TAG: String = PebbleWatchReceiver::class.java.simpleName private val PEBBLE_UUID = UUID.fromString("020f9398-c407-454b-996c-6ac341337281") // message type key const val KEY_TWISTOAST_MESSAGE_TYPE = 0x00 // message type value const val BUS_STOP_REQUEST: Byte = 0x10 const val BUS_STOP_DATA_RESPONSE: Byte = 0x11 // message keys const val KEY_STOP_INDEX = 0x20 const val KEY_BUS_STOP_NAME = 0x21 const val KEY_BUS_DIRECTION_NAME = 0x22 const val KEY_BUS_LINE_NAME = 0x23 const val KEY_BUS_NEXT_SCHEDULE = 0x24 const val KEY_BUS_NEXT_SCHEDULE_DIR = 0x25 const val KEY_BUS_SECOND_SCHEDULE = 0x26 const val KEY_BUS_SECOND_SCHEDULE_DIR = 0x27 const val KEY_SHOULD_VIBRATE = 0x30 const val KEY_BACKGROUND_COLOR = 0x31 } }
gpl-3.0
7b9dedca0a0dae3bba19845e2d1f9e94
37.307339
113
0.654532
4.215548
false
false
false
false
lavong/FlickrImageSearchDemo
app/src/main/java/com/ingloriousmind/android/flickrimagesearchdemo/photowall/flickr/model/Photos.kt
1
1066
package com.ingloriousmind.android.flickrimagesearchdemo.photowall.flickr.model import com.google.gson.annotations.SerializedName data class PhotosResult( @SerializedName("photos") var photos: Photos, @SerializedName("stat") var status: String ) data class Photos( @SerializedName("page") var page: Int = 0, @SerializedName("pages") var pages: Int = 0, @SerializedName("perpage") var perPage: Int = 0, @SerializedName("total") var total: String = "", @SerializedName("photo") var photos: List<Photo> = emptyList() ) data class Photo( @SerializedName("id") var id: String, @SerializedName("owner") var owner: String, @SerializedName("secret") var secret: String, @SerializedName("server") var server: String, @SerializedName("farm") var farmId: Int, @SerializedName("title") var title: String, @SerializedName("ispublic") var isPublic: Int, @SerializedName("isfriend") var isFriend: Int, @SerializedName("isfamily") var isFamily: Int )
apache-2.0
212d03a6712aecb9997830cb57ac5da2
37.107143
79
0.665103
4.19685
false
false
false
false
http4k/http4k
http4k-core/src/test/kotlin/org/http4k/filter/ClientCookiesTest.kt
1
3974
package org.http4k.filter import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.cookie.Cookie import org.http4k.core.cookie.cookie import org.http4k.core.then import org.http4k.filter.cookie.BasicCookieStorage import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasHeader import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail import java.time.Clock import java.time.Duration import java.time.Instant import java.time.ZoneId import java.time.ZoneOffset.UTC class ClientCookiesTest { @Test fun `can store and send cookies across multiple calls`() { val server = { request: Request -> Response(OK).counterCookie(request.counterCookie() + 1) } val client = ClientFilters.Cookies().then(server) (0..3).forEach { val response = client(Request(GET, "/")) assertThat(response, hasHeader("Set-Cookie", """counter="${it + 1}"; """)) } } @Test fun `expired cookies are removed from storage and not sent`() { val server = { request: Request -> when (request.uri.path) { "/set" -> Response(OK).cookie(Cookie("foo", "bar", 5)) else -> Response(OK).body(request.cookie("foo")?.value ?: "gone") } } val cookieStorage = BasicCookieStorage() val clock = object : Clock() { var millis: Long = 0 override fun withZone(zone: ZoneId?): Clock = TODO() override fun getZone(): ZoneId = ZoneId.of("GMT") override fun instant(): Instant = Instant.ofEpochMilli(millis) fun add(seconds: Int) { millis += seconds * 1000 } } val client = ClientFilters.Cookies(clock, cookieStorage).then(server) client(Request(GET, "/set")) assertThat(cookieStorage.retrieve().size, equalTo(1)) assertThat(client(Request(GET, "/get")), hasBody("bar")) clock.add(10) assertThat(client(Request(GET, "/get")), hasBody("gone")) } @Test fun `cookie expiry uses the same timezone as cookie parsing`() { val zoneId = ZoneId.of("Europe/London") val cookie = Cookie.parse("foo=bar;Path=/;Expires=Thu, 25-Oct-2018 10:00:00 GMT;HttpOnly") ?: fail("Couldn't parse cookie") // this was 11:00:00 in Europe/London due to daylight savings val server = { request: Request -> when (request.uri.path) { "/set" -> Response(OK).cookie(cookie) else -> Response(OK).body(request.cookie("foo")?.value ?: "gone") } } val cookieStorage = BasicCookieStorage() val clock = object : Clock() { var instant = cookie.expires!!.atZone(UTC).toInstant() - Duration.ofMinutes(50) override fun withZone(zone: ZoneId?): Clock = TODO() override fun getZone(): ZoneId = zoneId override fun instant(): Instant = instant fun add(hours: Long) { instant += Duration.ofHours(hours) } } val client = ClientFilters.Cookies(clock, cookieStorage).then(server) client(Request(GET, "/set")) assertThat(cookieStorage.retrieve().size, equalTo(1)) // if the parser uses UTC and the expiry checker uses local time then this will be 'gone' assertThat(client(Request(GET, "/get")), hasBody("bar")) clock.add(1) // if the parser uses local time and the expiry checker uses UTC then this will be 'bar' assertThat(client(Request(GET, "/get")), hasBody("gone")) } fun Request.counterCookie() = cookie("counter")?.value?.toInt() ?: 0 fun Response.counterCookie(value: Int) = cookie(Cookie("counter", value.toString())) }
apache-2.0
5d6b2f384e217a8b0d4e6422ace78d2b
33.556522
100
0.619779
4.139583
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/QuestSourceIsSurveyChecker.kt
1
4131
package de.westnordost.streetcomplete.map import android.content.Context import android.location.Location import android.view.LayoutInflater import androidx.appcompat.app.AlertDialog import androidx.core.view.isGone import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.geometry.ElementGeometry import de.westnordost.streetcomplete.data.osm.geometry.ElementPolygonsGeometry import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.data.osm.mapdata.LatLon import de.westnordost.streetcomplete.databinding.QuestSourceDialogLayoutBinding import de.westnordost.streetcomplete.util.distanceToArcs import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import javax.inject.Inject import kotlin.coroutines.resume /** Checks if the quest was solved on a survey, either by looking at the GPS position or asking * the user */ class QuestSourceIsSurveyChecker @Inject constructor() { suspend fun checkIsSurvey( context: Context, geometry: ElementGeometry, locations: List<Location> ): Boolean { if (dontShowAgain || isWithinSurveyDistance(geometry, locations)) { return true } return suspendCancellableCoroutine { cont -> val dialogBinding = QuestSourceDialogLayoutBinding.inflate(LayoutInflater.from(context)) dialogBinding.checkBoxDontShowAgain.isGone = timesShown < 1 AlertDialog.Builder(context) .setTitle(R.string.quest_source_dialog_title) .setView(dialogBinding.root) .setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> ++timesShown dontShowAgain = dialogBinding.checkBoxDontShowAgain.isChecked if(cont.isActive) cont.resume(true) } .setNegativeButton(android.R.string.cancel) { _, _ -> if(cont.isActive) cont.resume(false) } .setOnCancelListener { if(cont.isActive) cont.resume(false) } .show() } } private suspend fun isWithinSurveyDistance( geometry: ElementGeometry, locations: List<Location> ): Boolean = withContext(Dispatchers.Default) { // suspending because distanceToArcs is slow locations.any { location -> val pos = LatLon(location.latitude, location.longitude) val polylines: List<List<LatLon>> = when (geometry) { is ElementPolylinesGeometry -> geometry.polylines is ElementPolygonsGeometry -> geometry.polygons else -> listOf(listOf(geometry.center)) } polylines.any { polyline -> pos.distanceToArcs(polyline) < location.accuracy + MAX_DISTANCE_TO_ELEMENT_FOR_SURVEY } } } companion object { /* Considerations for choosing these values: - users should be encouraged to *really* go right there and check even if they think they see it from afar already - just having walked by something should though still count as survey though. (It might be inappropriate or awkward to stop and flip out the smartphone directly there) - GPS position might not be updated right after they fetched it out of their pocket, but GPS position should be reset to "unknown" (instead of "wrong") when switching back to the app - the distance is the minimum distance between the quest geometry (i.e. a road) and the line between the user's position when he opened the quest form and the position when he pressed "ok", MINUS the current GPS accuracy, so it is a pretty forgiving calculation already */ private const val MAX_DISTANCE_TO_ELEMENT_FOR_SURVEY = 80f //m // "static" values persisted per application start private var dontShowAgain = false private var timesShown = 0 } }
gpl-3.0
a22cf1d6cc0e9b0f9f0d48e87a57ba24
42.484211
101
0.678528
5.01335
false
false
false
false
dleppik/EgTest
kotlin-generator/src/main/kotlin/com/vocalabs/egtest/codegenerator/AbstractSourceFileBuilder.kt
1
1439
package com.vocalabs.egtest.codegenerator import java.io.File import kotlin.collections.List import kotlin.* abstract class AbstractSourceFileBuilder(private val packageStr: String) : SourceFileBuilder, AbstractCodeBuilding() { private var classes: List<ClassBuilderImpl> = listOf() private var imports: String = "" override fun addImport(importName: String){ imports += when { imports.isEmpty() -> "import $importName" else -> "\nimport $importName" } } override fun addClass(name: String): ClassBuilder { val cl = ClassBuilderImpl(name) classes += cl return cl } fun buildString(): String { val functionStr: String = functions.joinToString("\n") { it.build() } val classesString = classes.joinToString("\n") { it.build() } return listOf("package $packageStr", imports, functionStr, classesString).joinToString("\n\n") } } class FileSourceFileBuilder(private val file: File, packageStr: String): AbstractSourceFileBuilder(packageStr) { override fun build() { file.bufferedWriter().use { out -> out.write(buildString()) } } } class StringSourceFileBuilder(packageStr: String): AbstractSourceFileBuilder(packageStr) { override fun build() { throw UnsupportedOperationException("Call buildString instead") } override fun toString(): String { return buildString() } }
apache-2.0
3978675ae17a184736d8af92a8f0facf
31.727273
118
0.676164
4.597444
false
false
false
false
WindSekirun/RichUtilsKt
RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RReflection.kt
1
3722
@file:JvmName("RichUtils") @file:JvmMultifileClass import java.lang.reflect.Field import java.lang.reflect.Method import kotlin.reflect.KClass /** * get list of Field which attached any annotation in Runtime * * @param target target instance to search Annotation'd field * @param includeSuperClass optional, true - increase scope into their superclass. default is true */ fun getAnnotationFieldList(target: Any, includeSuperClass: Boolean = true): List<Field> { var cls: Class<in Any>? = target.javaClass val list = mutableListOf<Field>() do { if (cls == null) break list.addAll(cls.declaredFields.filter { it.declaredAnnotations.isNotEmpty() }.toList()) cls = if (includeSuperClass) cls.superclass else null } while (cls != null) return list } /** * get list of Method which attached any annotation in Runtime * * @param target target instance to search Annotation'd method * @param includeSuperClass optional, true - increase scope into their superclass. default is true */ fun getAnnotationMethodList(target: Any, includeSuperClass: Boolean = true): List<Method> { var cls: Class<in Any>? = target.javaClass val list = mutableListOf<Method>() do { if (cls == null) break list.addAll(cls.declaredMethods.filter { it.declaredAnnotations.isNotEmpty() }.toList()) cls = if (includeSuperClass) cls.superclass else null } while (cls != null) return list } /** * get list of Field which attached given annotation in Runtime * * @param target target instance to search Annotation'd field * @param annotation target class of annotation * @param includeSuperClass optional, true - increase scope into their superclass, default is true */ fun <T : Annotation> findAnnotationInFields(target: Any, annotation: Class<T>, includeSuperClass: Boolean = true): List<Field> { return mutableListOf<Field>().apply { getAnnotationFieldList(target, includeSuperClass).forEach { field -> if (field.declaredAnnotations.filterIsInstance(annotation).isNotEmpty()) add(field) } } } /** * get list of field which attached given annotation in Runtime * * @param target target instance to search Annotation'd field * @param annotation target KClass of annotation * @param includeSuperClass optional, true - increase scope into their superclass, default is true */ fun <T : Annotation> findAnnotationInFields(target: Any, annotation: KClass<T>, includeSuperClass: Boolean = true) = findAnnotationInFields(target, annotation.java, includeSuperClass) /** * get list of Method which attached given annotation in Runtime * * @param target target instance to search Annotation'd method * @param annotation target class of annotation * @param includeSuperClass optional, true - increase scope into their superclass, default is true */ fun <T : Annotation> findAnnotationInMethods(target: Any, annotation: Class<T>, includeSuperClass: Boolean = true): List<Method> { return mutableListOf<Method>().apply { getAnnotationMethodList(target, includeSuperClass).forEach { method -> if (method.declaredAnnotations.filterIsInstance(annotation).isNotEmpty()) add(method) } } } /** * get list of Method which attached given annotation in Runtime * * @param target target instance to search Annotation'd method * @param annotation target KClass of annotation * @param includeSuperClass optional, true - increase scope into their superclass, default is true */ fun <T : Annotation> findAnnotationInMethods(target: Any, annotation: KClass<T>, includeSuperClass: Boolean = true) = findAnnotationInMethods(target, annotation.java, includeSuperClass)
apache-2.0
591e34f5996eb6fc96365dbee76f400e
38.178947
130
0.731865
4.533496
false
false
false
false
SpartaHack/SpartaHack-Android
app/src/main/java/com/spartahack/spartahack_android/scripts/faq_activity.kt
1
2062
package com.spartahack.spartahack_android.scripts import kotlinx.coroutines.* import com.spartahack.spartahack_android.tools.* fun getQuestion(str: String): String { /** Takes a string formatted as a JSON and extracts the string representing the question. */ var returnStr = "" val splitStr = str.split(",\"") for(i in splitStr){ val header = i.split("\":") if (header[0] == "question"){ returnStr = header[1].removeSuffix("\"").removePrefix("\"") } } return returnStr } // getQuestion. fun getAnswer(str: String): String { /** Takes a string formatted as a JSON and extracts the string representing the answer. */ var returnStr = "" val splitStr = str.split("{\"") for(i in splitStr){ val header = i.split("\":") if (header[0] == "answer"){ returnStr = header[1].removeSuffix("\",\"display").removePrefix("\"") } } // Takes out the test strings in the FAQ response. if (returnStr == "What are exfdsact nufgddmbers?"){ returnStr = "skip" } return returnStr } // getAnswer. suspend fun faqMain(): String = withContext(Dispatchers.Default){ /** The main structure of the script. Uses getQuestion and getAnswer. */ // Makes a call to the api to get the FAQ information as a raw string and splits the raw FAQ // string into a list. var faqRawStr = APICall("faqs").sendGet() faqRawStr = faqRawStr.removeRange(0, 1) val faqList = faqRawStr.split("},") var displayStr = "" // Takes every entry in the FAQ list, then formats it in such a way that it is easy to display. for (i in faqList) { val question = getQuestion(i) val answer = getAnswer(i) // Does not make an addition to the display string if the current answer is // "What are exfdsact nufgddmbers?" if (answer != "skip"){ displayStr += ("<h2>" + question + "</h2>\n" + "<p>" + answer + "</p>\n") } } return@withContext displayStr } // faqMain.
mit
fc3b2c12c970f0ff6c72496dceade517
27.652778
99
0.610572
3.854206
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/miscimg/MiscImage.kt
1
7494
package miscimg import cc.cfig.io.Struct import cfig.helper.Helper import org.slf4j.LoggerFactory import java.io.FileInputStream data class MiscImage( var bcb: BootloaderMessage = BootloaderMessage(), var virtualAB: VirtualABMessage? = null ) { companion object { private val log = LoggerFactory.getLogger(MiscImage::class.java) fun parse(fileName: String): MiscImage { val ret = MiscImage() FileInputStream(fileName).use { fis -> ret.bcb = BootloaderMessage(fis) } FileInputStream(fileName).use { fis -> fis.skip(32 * 1024) try { ret.virtualAB = VirtualABMessage(fis) } catch (e: IllegalArgumentException) { log.info(e.toString()) } } return ret } } //offset 0, size 2k data class BootloaderMessage( var command: String = "", var status: String = "", var recovery: String = "", var stage: String = "", var reserved: ByteArray = byteArrayOf() ) { constructor(fis: FileInputStream) : this() { val info = Struct(FORMAT_STRING).unpack(fis) this.command = info[0] as String this.status = info[1] as String this.recovery = info[2] as String this.stage = info[3] as String this.reserved = info[4] as ByteArray } fun encode(): ByteArray { return Struct(FORMAT_STRING).pack( this.command, this.stage, this.recovery, this.stage, this.reserved, ) } fun updateBootloaderMessageInStruct(options: Array<String>) { this.command = "boot-recovery" this.recovery = "recovery\n" options.forEach { this.recovery += if (it.endsWith("\n")) { it } else { it + "\n" } } } fun updateBootloaderMessage(command: String, recovery: String, options: Array<String>?) { this.command = command this.recovery = "$recovery\n" options?.forEach { this.recovery += if (it.endsWith("\n")) { it } else { it + "\n" } } } companion object { private const val FORMAT_STRING = "32s32s768s32s1184b" const val SIZE = 2048 init { check(SIZE == Struct(FORMAT_STRING).calcSize()) } /* https://android-review.googlesource.com/c/platform/bootable/recovery/+/735984 */ fun rebootFastboot1(): BootloaderMessage { return BootloaderMessage().apply { command = "boot-fastboot" } } fun rebootFastboot2(): BootloaderMessage { return BootloaderMessage().apply { updateBootloaderMessageInStruct(arrayOf("--fastboot")) } } fun rebootBootloader(): BootloaderMessage { return BootloaderMessage().apply { command = "bootonce-bootloader" } } fun rebootRecovery(): BootloaderMessage { return BootloaderMessage().apply { this.updateBootloaderMessageInStruct(arrayOf()) } } fun rebootCrash(): BootloaderMessage { return BootloaderMessage().apply { //@formatter:off updateBootloaderMessageInStruct(arrayOf( "--prompt_and_wipe_data", "--reason=RescueParty", "--locale=en_US")) //@formatter:on } } fun rebootOTA(): BootloaderMessage { return BootloaderMessage().apply { updateBootloaderMessageInStruct(arrayOf("--update_package=/cache/update.zip", "--security")) } } fun rebootWipeData(): BootloaderMessage { return BootloaderMessage().apply { //@formatter:off updateBootloaderMessageInStruct(arrayOf( "--wipe_data", "--reason=convert_fbe", "--locale=en_US")) //@formatter:on } } fun rebootWipeAb(): BootloaderMessage { return BootloaderMessage().apply { //@formatter:off updateBootloaderMessageInStruct(arrayOf( "--wipe_ab", "--wipe_package_size=1024", "--locale=en_US")) //@formatter:on } } fun generateSamples(): MutableList<BootloaderMessage> { return mutableListOf( rebootFastboot1(), rebootFastboot2(), rebootBootloader(), rebootRecovery(), rebootCrash(), rebootOTA(), rebootWipeData(), rebootWipeAb() ) } } } //offset 32KB, size 64B data class VirtualABMessage( var version: Int = 0, var magic: ByteArray = byteArrayOf(), var mergeStatus: Int = 0, var sourceSlot: Int = 0, var reserved: ByteArray = byteArrayOf() ) { companion object { private const val FORMAT_STRING = "b4bbb57b" private val log = LoggerFactory.getLogger("VirtualABMsg") private const val MAGIC = "b00a7456" const val SIZE = 64 init { check(SIZE == Struct(FORMAT_STRING).calcSize()) } } constructor(fis: FileInputStream) : this() { val info = Struct(FORMAT_STRING).unpack(fis) this.version = (info[0] as ByteArray)[0].toInt() this.magic = info[1] as ByteArray this.mergeStatus = (info[2] as ByteArray)[0].toInt() this.sourceSlot = (info[3] as ByteArray)[0].toInt() this.reserved = info[4] as ByteArray if (MAGIC != Helper.Companion.toHexString(this.magic)) { throw IllegalArgumentException("stream is not VirtualAB message") } } fun encode(): ByteArray { return Struct(FORMAT_STRING).pack( byteArrayOf(this.version.toByte()), this.magic, byteArrayOf(this.mergeStatus.toByte()), byteArrayOf(this.sourceSlot.toByte()), byteArrayOf(0) ) } override fun toString(): String { return "VABMsg(v=$version, magic=${Helper.toHexString(magic)}, mergeStatus=$mergeStatus:${ MergeStatus.values().get(this.mergeStatus) }, sourceSlot=$sourceSlot)" } enum class MergeStatus(val status: Int) { NONE(0), UNKNOWN(1), SNAPSHOTTED(2), MERGING(3), CANCELLED(4) } } }
apache-2.0
b45c1715a462395c5da5dc0fbda04840
32.013216
112
0.479984
5.211405
false
false
false
false
PaulWoitaschek/Voice
playbackScreen/src/main/kotlin/voice/playbackScreen/BookPlayController.kt
1
4815
package voice.playbackScreen import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.Settings import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import com.squareup.anvil.annotations.ContributesTo import voice.common.AppScope import voice.common.BookId import voice.common.compose.ComposeController import voice.common.rootComponentAs import voice.data.getBookId import voice.data.putBookId import voice.logging.core.Logger import voice.sleepTimer.SleepTimerDialogController import javax.inject.Inject private const val NI_BOOK_ID = "niBookId" class BookPlayController(bundle: Bundle) : ComposeController(bundle) { constructor(bookId: BookId) : this(Bundle().apply { putBookId(NI_BOOK_ID, bookId) }) @Inject lateinit var viewModel: BookPlayViewModel private val bookId: BookId = bundle.getBookId(NI_BOOK_ID)!! init { rootComponentAs<Component>().inject(this) this.viewModel.bookId = bookId } @Composable override fun Content() { val windowSizeClass: WindowSizeClass = calculateWindowSizeClass(activity = activity!!) val snackbarHostState = remember { SnackbarHostState() } val dialogState = viewModel.dialogState.value val viewState = remember(viewModel) { viewModel.viewState() } .collectAsState(initial = null).value ?: return val context = LocalContext.current LaunchedEffect(viewModel) { viewModel.viewEffects.collect { viewEffect -> when (viewEffect) { BookPlayViewEffect.BookmarkAdded -> { snackbarHostState.showSnackbar(message = context.getString(R.string.bookmark_added)) } BookPlayViewEffect.RequestIgnoreBatteryOptimization -> { val result = snackbarHostState.showSnackbar( message = context.getString(R.string.battery_optimization_rationale), duration = SnackbarDuration.Long, actionLabel = context.getString(R.string.battery_optimization_action), ) if (result == SnackbarResult.ActionPerformed) { toBatteryOptimizations() } } BookPlayViewEffect.ShowSleepTimeDialog -> { openSleepTimeDialog() } } } } BookPlayView( viewState, onPlayClick = viewModel::playPause, onFastForwardClick = viewModel::fastForward, onRewindClick = viewModel::rewind, onSeek = viewModel::seekTo, onBookmarkClick = viewModel::onBookmarkClicked, onBookmarkLongClick = viewModel::onBookmarkLongClicked, onSkipSilenceClick = viewModel::toggleSkipSilence, onSleepTimerClick = viewModel::toggleSleepTimer, onVolumeBoostClick = viewModel::onVolumeGainIconClicked, onSpeedChangeClick = viewModel::onPlaybackSpeedIconClicked, onCloseClick = { router.popController(this@BookPlayController) }, onSkipToNext = viewModel::next, onSkipToPrevious = viewModel::previous, onCurrentChapterClick = viewModel::onCurrentChapterClicked, useLandscapeLayout = windowSizeClass.widthSizeClass != WindowWidthSizeClass.Compact, snackbarHostState = snackbarHostState, ) if (dialogState != null) { when (dialogState) { is BookPlayDialogViewState.SpeedDialog -> { SpeedDialog(dialogState, viewModel) } is BookPlayDialogViewState.VolumeGainDialog -> { VolumeGainDialog(dialogState, viewModel) } is BookPlayDialogViewState.SelectChapterDialog -> { SelectChapterDialog(dialogState, viewModel) } } } } private fun toBatteryOptimizations() { val intent = Intent() .apply { @Suppress("BatteryLife") action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS data = Uri.parse("package:${activity!!.packageName}") } try { startActivity(intent) } catch (e: ActivityNotFoundException) { Logger.e(e, "Can't request ignoring battery optimizations") } } private fun openSleepTimeDialog() { SleepTimerDialogController(bookId) .showDialog(router) } @ContributesTo(AppScope::class) interface Component { fun inject(target: BookPlayController) } }
gpl-3.0
d26311430920bd42f124ae7cc3bd9056
34.145985
96
0.726272
4.893293
false
false
false
false
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/fragment/FavouriteSongsFragment.kt
2
8106
package org.worshipsongs.fragment import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.* import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.woxthebox.draglistview.DragItem import com.woxthebox.draglistview.DragListView import org.apache.commons.lang3.StringUtils import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.activity.SongContentViewActivity import org.worshipsongs.adapter.FavouriteSongAdapter import org.worshipsongs.domain.Setting import org.worshipsongs.domain.SongDragDrop import org.worshipsongs.listener.SongContentViewListener import org.worshipsongs.service.FavouriteService import org.worshipsongs.service.PopupMenuService import org.worshipsongs.service.SongService import org.worshipsongs.service.UserPreferenceSettingService import org.worshipsongs.utils.CommonUtils import java.util.* /** * Author : Madasamy * Version : 0.1.0 */ class FavouriteSongsFragment : Fragment(), FavouriteSongAdapter.FavouriteListener { private var configureDragDrops: MutableList<SongDragDrop>? = null private var favouriteSongAdapter: FavouriteSongAdapter? = null private var songContentViewListener: SongContentViewListener? = null private var favouriteService: FavouriteService? = null private var songService: SongService? = null private val popupMenuService = PopupMenuService() private val userPreferenceSettingService = UserPreferenceSettingService() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) favouriteService = FavouriteService() songService = SongService(context!!.applicationContext) val serviceName = arguments!!.getString(CommonConstants.SERVICE_NAME_KEY) val favourite = favouriteService!!.find(serviceName!!) configureDragDrops = favourite.dragDrops setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.favourite_song_layout, container, false) setDragListView(view) return view } private fun setDragListView(view: View) { val dragListView = view.findViewById<View>(R.id.drag_list_view) as DragListView dragListView.recyclerView.isVerticalScrollBarEnabled = true dragListView.setLayoutManager(LinearLayoutManager(context)) favouriteSongAdapter = FavouriteSongAdapter(configureDragDrops!!) favouriteSongAdapter!!.setFavouriteListener(this) dragListView.setAdapter(favouriteSongAdapter!!, true) dragListView.setCanDragHorizontally(false) dragListView.setCustomDragItem(MyDragItem(context!!, R.layout.favourite_song_adapter)) dragListView.setDragListListener(FavouriteDragListListener()) } override fun onRemove(dragDrop: SongDragDrop) { val builder = AlertDialog.Builder(ContextThemeWrapper(context, R.style.DialogTheme)) builder.setTitle(getString(R.string.remove_favourite_song_title)) builder.setMessage(getString(R.string.remove_favourite_song_message)) builder.setPositiveButton(R.string.yes) { dialog, which -> favouriteService!!.removeSong(arguments!!.getString(CommonConstants.SERVICE_NAME_KEY)!!, dragDrop.title!!) configureDragDrops!!.remove(dragDrop) favouriteSongAdapter!!.itemList = configureDragDrops favouriteSongAdapter!!.notifyDataSetChanged() dialog.dismiss() } builder.setNegativeButton(R.string.no) { dialog, which -> dialog.dismiss() } builder.show() } override fun onClick(dragDrop: SongDragDrop) { val song = songService!!.findContentsByTitle(dragDrop.title!!) if (song != null) { val titles = ArrayList<String>() titles.add(dragDrop.title!!) if (CommonUtils.isPhone(context!!)) { val intent = Intent(activity, SongContentViewActivity::class.java) val bundle = Bundle() bundle.putStringArrayList(CommonConstants.TITLE_LIST_KEY, titles) bundle.putInt(CommonConstants.POSITION_KEY, 0) Setting.instance.position = 0 intent.putExtras(bundle) activity!!.startActivity(intent) } else { Setting.instance.position = favouriteSongAdapter!!.getPositionForItem(dragDrop) songContentViewListener!!.displayContent(dragDrop.title!!, titles, favouriteSongAdapter!!.getPositionForItem(dragDrop)) } } else { val bundle = Bundle() bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.warning)) bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.message_song_not_available, "\"" + getTitle(dragDrop) + "\"")) val alertDialogFragment = AlertDialogFragment.newInstance(bundle) alertDialogFragment.setVisibleNegativeButton(false) alertDialogFragment.show(activity!!.supportFragmentManager, "WarningDialogFragment") } } private fun getTitle(dragDrop: SongDragDrop): String { return if (userPreferenceSettingService.isTamil && StringUtils.isNotBlank(dragDrop.tamilTitle)) dragDrop.tamilTitle!! else dragDrop.title!! } private class MyDragItem internal constructor(context: Context, layoutId: Int) : DragItem(context, layoutId) { override fun onBindDragView(clickedView: View, dragView: View) { val text = (clickedView.findViewById<View>(R.id.text) as TextView).text (dragView.findViewById<View>(R.id.text) as TextView).text = text //dragView.findViewById(R.id.item_layout).setBackgroundColor(dragView.getResources().getColor(R.color.list_item_background)); } } private inner class FavouriteDragListListener : DragListView.DragListListener { override fun onItemDragStarted(position: Int) { //Do nothing } override fun onItemDragging(itemPosition: Int, x: Float, y: Float) { //Do nothing } override fun onItemDragEnded(fromPosition: Int, toPosition: Int) { favouriteService!!.save(arguments!!.getString(CommonConstants.SERVICE_NAME_KEY)!!, favouriteSongAdapter!!.itemList) } } fun setSongContentViewListener(songContentViewListener: SongContentViewListener) { this.songContentViewListener = songContentViewListener } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.clear() if (CommonUtils.isPhone(context!!)) { inflater!!.inflate(R.menu.action_bar_options, menu) } super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { Log.i(FavouriteSongsFragment::class.java.simpleName, "Menu item " + item.itemId + " " + R.id.options) when (item.itemId) { android.R.id.home -> { activity!!.finish() return true } R.id.options -> { popupMenuService.shareFavouritesInSocialMedia(activity as Activity, activity!!.findViewById(R.id.options), arguments!!.getString(CommonConstants.SERVICE_NAME_KEY)!!) return true } else -> return super.onOptionsItemSelected(item) } } companion object { fun newInstance(bundle: Bundle): FavouriteSongsFragment { val favouriteSongsFragment = FavouriteSongsFragment() favouriteSongsFragment.arguments = bundle return favouriteSongsFragment } } }
gpl-3.0
6dda39462e0eb05dcf1ff233fcb92130
38.15942
181
0.690229
5.012987
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/objectdetection/ObjectDotGraphic.kt
1
1956
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md.objectdetection import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Paint.Style import android.graphics.PointF import com.google.mlkit.md.camera.GraphicOverlay import com.google.mlkit.md.camera.GraphicOverlay.Graphic import com.google.mlkit.md.R /** A dot to indicate a detected object used by multiple objects detection mode. */ internal class ObjectDotGraphic( overlay: GraphicOverlay, detectedObject: DetectedObjectInfo, private val animator: ObjectDotAnimator ) : Graphic(overlay) { private val paint: Paint private val center: PointF private val dotRadius: Int private val dotAlpha: Int init { val box = detectedObject.boundingBox center = PointF( overlay.translateX((box.left + box.right) / 2f), overlay.translateY((box.top + box.bottom) / 2f) ) paint = Paint().apply { style = Style.FILL color = Color.WHITE } dotRadius = context.resources.getDimensionPixelOffset(R.dimen.object_dot_radius) dotAlpha = paint.alpha } override fun draw(canvas: Canvas) { paint.alpha = (dotAlpha * animator.alphaScale).toInt() canvas.drawCircle(center.x, center.y, dotRadius * animator.radiusScale, paint) } }
apache-2.0
69c2659dd8bd12a1270e10aeaf548bdd
31.6
88
0.707566
4.24295
false
false
false
false
FHannes/intellij-community
plugins/git4idea/src/git4idea/repo/GitModulesFileReader.kt
6
1931
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.repo import com.intellij.openapi.diagnostic.logger import org.ini4j.Ini import java.io.File import java.io.IOException import java.util.regex.Pattern class GitModulesFileReader { private val LOG = logger<GitModulesFileReader>() private val MODULE_SECTION = Pattern.compile("submodule \"(.*)\"") fun read(file: File): Collection<GitSubmoduleInfo> { if (!file.exists()) return listOf() val ini: Ini try { ini = loadIniFile(file) } catch (e: IOException) { return listOf() } val classLoader = findClassLoader() val modules = mutableSetOf<GitSubmoduleInfo>() for ((sectionName, section) in ini) { val matcher = MODULE_SECTION.matcher(sectionName) if (matcher.matches() && matcher.groupCount() == 1) { val bean = section.`as`(ModuleBean::class.java, classLoader) val path = bean.getPath() val url = bean.getUrl() if (path == null || url == null) { LOG.warn("Partially defined submodule: " + section.toString()) } else { val module = GitSubmoduleInfo(path, url) LOG.debug("Found submodule " + module) modules.add(module) } } } return modules } private interface ModuleBean { fun getPath(): String? fun getUrl(): String? } }
apache-2.0
35bbf8800f92a65754e199c6ba5bdf34
29.1875
75
0.663905
4.07384
false
false
false
false
android/animation-samples
Motion/app/src/main/java/com/example/android/motion/demo/stagger/StaggerActivity.kt
1
3696
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.motion.demo.stagger import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.view.WindowCompat import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.RecyclerView import androidx.transition.TransitionManager import com.example.android.motion.R import com.example.android.motion.ui.EdgeToEdge /** * Shows a list of items. The items are loaded asynchronously, and they appear with stagger. * * Stagger refers to applying temporal offsets to a group of elements in sequence, like a list. * Stagger creates a cascade effect that focuses attention briefly on each item. It can reveal * significant content or highlight affordances within a group. * * See * [Stagger](https://material.io/design/motion/customization.html#sequencing) * for the detail. */ class StaggerActivity : AppCompatActivity() { private val viewModel: CheeseListViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.stagger_activity) val toolbar: Toolbar = findViewById(R.id.toolbar) val list: RecyclerView = findViewById(R.id.list) setSupportActionBar(toolbar) WindowCompat.setDecorFitsSystemWindows(window, false) EdgeToEdge.setUpAppBar(findViewById(R.id.app_bar), toolbar) EdgeToEdge.setUpScrollingContent(list) val adapter = CheeseListAdapter() list.adapter = adapter // We animate item additions on our side, so disable it in RecyclerView. list.itemAnimator = object : DefaultItemAnimator() { override fun animateAdd(holder: RecyclerView.ViewHolder?): Boolean { dispatchAddFinished(holder) dispatchAddStarting(holder) return false } } // This is the transition for the stagger effect. val stagger = Stagger() viewModel.cheeses.observe(this) { cheeses -> // Delay the stagger effect until the list is updated. TransitionManager.beginDelayedTransition(list, stagger) adapter.submitList(cheeses) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.stagger, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_refresh -> { // In real-life apps, refresh feature would just overwrite the existing list with // the new list. In this demo, we clear the list and repopulate to demonstrate the // stagger effect again. viewModel.empty() viewModel.refresh() true } else -> super.onOptionsItemSelected(item) } } }
apache-2.0
4bb3a25885bb3356b0cc80ab52b7850a
36.714286
98
0.697511
4.762887
false
false
false
false
clangen/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/playback/impl/streaming/StreamProxy.kt
1
5701
package io.casey.musikcube.remote.service.playback.impl.streaming import android.content.Context import android.content.SharedPreferences import android.net.Uri import android.util.Base64 import com.danikula.videocache.CacheListener import com.danikula.videocache.HttpProxyCacheServer import com.danikula.videocache.file.Md5FileNameGenerator import io.casey.musikcube.remote.Application import io.casey.musikcube.remote.injection.DaggerServiceComponent import io.casey.musikcube.remote.service.gapless.db.GaplessDb import io.casey.musikcube.remote.service.gapless.db.GaplessTrack import io.casey.musikcube.remote.ui.settings.constants.Prefs import io.casey.musikcube.remote.ui.shared.util.NetworkUtil import java.io.File import javax.inject.Inject class StreamProxy(private val context: Context) { @Inject lateinit var gaplessDb: GaplessDb private lateinit var proxy: HttpProxyCacheServer private val prefs: SharedPreferences = context.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) init { DaggerServiceComponent.builder() .appComponent(Application.appComponent) .build().inject(this) gaplessDb.prune() restart() } @Synchronized fun registerCacheListener(cl: CacheListener, uri: String) { proxy.registerCacheListener(cl, uri) /* let it throw */ } @Synchronized fun unregisterCacheListener(cl: CacheListener) { proxy.unregisterCacheListener(cl) } @Synchronized fun isCached(url: String): Boolean { return proxy.isCached(url) } @Synchronized fun getProxyUrl(url: String): String { return proxy.getProxyUrl(url) } @Synchronized fun getProxyFilename(url: String): String { return proxy.cacheDirectory.canonicalPath + "/" + FILENAME_GENERATOR(url) } @Synchronized fun reload() { proxy.shutdown() restart() } private fun restart() { if (this.prefs.getBoolean(Prefs.Key.CERT_VALIDATION_DISABLED, Prefs.Default.CERT_VALIDATION_DISABLED)) { NetworkUtil.disableCertificateValidation() } else { NetworkUtil.enableCertificateValidation() } var diskCacheIndex = this.prefs.getInt( Prefs.Key.DISK_CACHE_SIZE_INDEX, Prefs.Default.DISK_CACHE_SIZE_INDEX) if (diskCacheIndex < 0 || diskCacheIndex > CACHE_SETTING_TO_BYTES.size) { diskCacheIndex = 0 } val cachePath = File(context.externalCacheDir, "audio") proxy = HttpProxyCacheServer.Builder(context.applicationContext) .cacheDirectory(cachePath) .maxCacheSize(CACHE_SETTING_TO_BYTES[diskCacheIndex] ?: MINIMUM_CACHE_SIZE_BYTES) .headerInjector { val headers = HashMap<String, String>() val userPass = "default:" + prefs.getString(Prefs.Key.PASSWORD, Prefs.Default.PASSWORD)!! val encoded = Base64.encodeToString(userPass.toByteArray(), Base64.NO_WRAP) headers["Authorization"] = "Basic $encoded" headers } .headerReceiver { url: String, headers: Map<String, List<String>> -> /* if we have a 'X-musikcube-Estimated-Content-Length' header in the response, that means the on-demand transcoder is running, therefore gapless information won't be available yet. track this download so we can patch up the header later, once the file finishes transcoding */ val estimated = headers[ESTIMATED_LENGTH] if (estimated?.firstOrNull() == "true") { synchronized (proxy) { val dao = gaplessDb.dao() if (dao.queryByUrl(url).isEmpty()) { dao.insert(GaplessTrack(null, url, GaplessTrack.DOWNLOADING)) } } } } .fileNameGenerator(FILENAME_GENERATOR) .build() } companion object { private const val BYTES_PER_MEGABYTE = 1048576L private const val BYTES_PER_GIGABYTE = 1073741824L private const val ESTIMATED_LENGTH = "X-musikcube-Estimated-Content-Length" const val MINIMUM_CACHE_SIZE_BYTES = BYTES_PER_MEGABYTE * 128 val CACHE_SETTING_TO_BYTES: MutableMap<Int, Long> = mutableMapOf( 0 to MINIMUM_CACHE_SIZE_BYTES, 1 to BYTES_PER_GIGABYTE / 2, 2 to BYTES_PER_GIGABYTE, 3 to BYTES_PER_GIGABYTE * 2, 4 to BYTES_PER_GIGABYTE * 3, 5 to BYTES_PER_GIGABYTE * 4) private val DEFAULT_FILENAME_GENERATOR = Md5FileNameGenerator() private val FILENAME_GENERATOR: (String) -> String = gen@ { url -> try { val uri = Uri.parse(url) /* format matches: audio/external_id/<id> */ val segments = uri.pathSegments if (segments.size == 3 && "external_id" == segments[1]) { /* url params, hyphen separated */ val params = when (uri?.query.isNullOrBlank()) { true -> "" false -> "-" + uri!!.query!! .replace("?", "-") .replace("&", "-") .replace("=", "-") } return@gen "${segments[2]}$params" } } catch (ex: Exception) { /* eh... */ } return@gen DEFAULT_FILENAME_GENERATOR.generate(url) } } }
bsd-3-clause
baf504d9e6816550db57693d2dc882f0
37.261745
112
0.597088
4.535402
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/data/provider/blitzortung/BlitzortungHttpDataProvider.kt
1
8006
/* Copyright 2015-2016 Andreas Würl 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.blitzortung.android.data.provider.blitzortung import android.content.SharedPreferences import android.util.Log import org.blitzortung.android.app.Main import org.blitzortung.android.app.view.PreferenceKey import org.blitzortung.android.app.view.get import org.blitzortung.android.data.Parameters import org.blitzortung.android.data.beans.Station import org.blitzortung.android.data.beans.Strike import org.blitzortung.android.data.provider.DataProvider import org.blitzortung.android.data.provider.DataProviderType import org.blitzortung.android.data.provider.result.ResultEvent import java.io.BufferedReader import java.io.FileNotFoundException import java.net.Authenticator import java.net.PasswordAuthentication import java.net.URL import java.util.* import java.util.zip.GZIPInputStream class BlitzortungHttpDataProvider @JvmOverloads constructor( preferences: SharedPreferences, private val urlFormatter: UrlFormatter = UrlFormatter(), mapBuilderFactory: MapBuilderFactory = MapBuilderFactory() ) : DataProvider(preferences, PreferenceKey.USERNAME, PreferenceKey.PASSWORD) { private val strikeMapBuilder: MapBuilder<Strike> private val stationMapBuilder: MapBuilder<Station> private var latestTime: Long = 0 private var strikes: List<Strike> = emptyList() private var parameters: Parameters? = null private lateinit var username: String private lateinit var password: String init { strikeMapBuilder = mapBuilderFactory.createAbstractStrikeMapBuilder() stationMapBuilder = mapBuilderFactory.createStationMapBuilder() } private fun readFromUrl(type: Type, region: Int, intervalTime: Calendar? = null): BufferedReader? { val useGzipCompression = type == Type.STATIONS val reader: BufferedReader val urlString = urlFormatter.getUrlFor(type, region, intervalTime, useGzipCompression) Log.v(Main.LOG_TAG, "BlitzortungHttpDataProvider.readFromUrl() $urlString") try { val url: URL url = URL(urlString) val connection = url.openConnection() connection.connectTimeout = 60000 connection.readTimeout = 60000 connection.allowUserInteraction = false var inputStream = connection.inputStream if (useGzipCompression) { inputStream = GZIPInputStream(inputStream) } reader = inputStream.bufferedReader() } catch (e: FileNotFoundException) { Log.w(Main.LOG_TAG, "BlitzortungHttpDataProvider.readFromUrl() URL $urlString not found") return null } return reader } /** * Used to retrieve Data from Blitzortung * @param readerSeq A sequence of nullable BufferedReader, which the data is read from * @param parse A Lambda which receives a sequence of lines from a buffered reader and transforms them into a sequence of T * @return Returns a list of parsed T's */ private fun <T : Any> retrieveData(logMessage: String, readerSeq: Sequence<BufferedReader?>, parse: (String) -> T?): List<T> { var size = 0 val strikeSequence: Sequence<T> = readerSeq.filterNotNull().flatMap { reader -> reader.lineSequence().mapNotNull { line -> size += line.length parse(line) } } val strikeList = strikeSequence.toList() Log.v(Main.LOG_TAG, logMessage.format(size, strikeList.count())) return strikeList } override val type: DataProviderType = DataProviderType.HTTP override fun reset() { latestTime = 0L strikes = emptyList() } override val isCapableOfHistoricalData: Boolean = false enum class Type { STRIKES, STATIONS } override fun <T> retrieveData(retrieve: DataRetriever.() -> T): T { return Retriever().retrieve() } private inner class Retriever : DataRetriever { override fun getStrikes(parameters: Parameters, result: ResultEvent): ResultEvent { var resultVar = result if (parameters != [email protected]) { [email protected] = parameters reset() } val intervalDuration = parameters.intervalDuration val region = parameters.region val tz = TimeZone.getTimeZone("UTC") val intervalTime = GregorianCalendar(tz) val millisecondsPerMinute = 60 * 1000L val currentTime = System.currentTimeMillis() val startTime = currentTime - intervalDuration * millisecondsPerMinute val intervalSequence = createTimestampSequence(10 * millisecondsPerMinute, Math.max(startTime, latestTime)) Authenticator.setDefault(MyAuthenticator()) val strikes = retrieveData("BlitzortungHttpDataProvider.getStrikes() read %d bytes (%d new strikes) from region $region", intervalSequence.map { intervalTime.timeInMillis = it return@map readFromUrl(Type.STRIKES, region, intervalTime) }, { strikeMapBuilder.buildFromLine(it) }) if (latestTime > 0L) { resultVar = resultVar.copy(incrementalData = true) } if (latestTime > 0L) { resultVar = resultVar.copy(incrementalData = true) val expireTime = resultVar.referenceTime - (parameters.intervalDuration - parameters.intervalOffset) * 60 * 1000 [email protected] = [email protected] { it.timestamp > expireTime } [email protected] += strikes } else { [email protected] = strikes } if (strikes.count() > 0) { latestTime = currentTime - millisecondsPerMinute Log.v(Main.LOG_TAG, "BlitzortungHttpDataProvider.getStrikes() set latest time to $latestTime") } resultVar = resultVar.copy(strikes = strikes, totalStrikes = [email protected]) return resultVar } override fun getStrikesGrid(parameters: Parameters, result: ResultEvent): ResultEvent { return result } override fun getStations(region: Int): List<Station> { Authenticator.setDefault(MyAuthenticator()) return retrieveData("BlitzortungHttpDataProvider.getStations() read %d bytes (%d stations) from region $region", sequenceOf(readFromUrl(Type.STATIONS, region))) { stationMapBuilder.buildFromLine(it) } } } private inner class MyAuthenticator : Authenticator() { override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication(username, password.toCharArray()) } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) { when (key) { PreferenceKey.USERNAME -> username = sharedPreferences.get(key, "") PreferenceKey.PASSWORD -> password = sharedPreferences.get(key, "") else -> { } } } }
apache-2.0
9496d0977b3aac52c9204a29b729d6d2
36.232558
136
0.669332
5.060051
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/base/OkHttpNovelContext.kt
1
7117
package cc.aoeiuv020.panovel.api.base import cc.aoeiuv020.anull.notNull import cc.aoeiuv020.log.debug import cc.aoeiuv020.log.error import cc.aoeiuv020.log.info import cc.aoeiuv020.okhttp.OkHttpUtils import cc.aoeiuv020.okhttp.sslAllowAll import cc.aoeiuv020.panovel.api.LoggerInputStream import cc.aoeiuv020.panovel.api.NovelContext import okhttp3.* import okio.Buffer import java.io.InputStream /** * Created by AoEiuV020 on 2018.06.01-20:43:49. */ abstract class OkHttpNovelContext : NovelContext() { protected val defaultUserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"; protected val defaultUserAgentMobile = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Mobile Safari/537.36" protected val defaultHeaders: MutableMap<String, String> by lazy { mutableMapOf( "Referer" to site.baseUrl, "User-Agent" to defaultUserAgent ) } // 子类可以继承自己的clientBuilder, 然后不能影响得到client, 要用lazy, protected open val client: OkHttpClient by lazy { clientBuilder.build() } // 子类可以继承,只在第一次使用client时使用一次, protected open val clientBuilder: OkHttpClient.Builder // 每次都生成新的builder,以免一个网站加的设置影响到其他网站, get() = OkHttpUtils.client.newBuilder() /* .proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("localhost", 8080))) */ .sslAllowAll() .addInterceptor(LogInterceptor()) .addInterceptor(HeaderInterceptor()) .cookieJar(cookieJar) // 一个网站20M缓存, // 还不清楚缓存会被具体用在什么地方, .cache(mCacheDir?.let { Cache(it, 20 * 1000 * 1000) }) // 只在第一次使用client时使用一次,传入client中, private val cookieJar get() = object : CookieJar { override fun saveFromResponse(url: HttpUrl, cookies: MutableList<Cookie>) { logger.debug { "save cookies $cookies" } putCookies(cookies) } override fun loadForRequest(url: HttpUrl): MutableList<Cookie> { return cookies.values.toMutableList().let { logger.debug { "load cookies $it" } cookieFilter(url, it).also { logger.debug { "after filter cookies $it" } } } } } /** * 有的网站有的页面不能传指定cookie,// 或者必须拥有指定cookie, */ protected open fun cookieFilter(url: HttpUrl, cookies: MutableList<Cookie>): MutableList<Cookie> { // 默认不过滤, return cookies } protected fun Response.requestHeaders(): Headers = networkResponse().notNull().request().headers() /** * okhttp有时候需要传入httpUrl,但是其实具体是什么地址都可以, */ @Suppress("MemberVisibilityCanBePrivate") protected val baseHttpUrl: HttpUrl by lazy { HttpUrl.parse(site.baseUrl).notNull() } protected fun Headers.requestCookies(): List<Cookie> = get("Cookie")?.split(";")?.mapNotNull { // 只有键值对, 不管传入什么地址,都能解析, Cookie.parse(baseHttpUrl, it) } ?: listOf() protected fun Headers.responseCookies(): List<Cookie> = Cookie.parseAll(baseHttpUrl, this) /** * 取出指定name的cookie, */ protected operator fun List<Cookie>.get(name: String): String? = firstOrNull { it.name() == name }?.value() // close基本上有重复,但是可以重复关闭, protected fun <T> Response.inputStream( listener: ((Long, Long) -> Unit)? = null, block: (InputStream) -> T ): T = body().notNull().use { val maxSize = it.contentLength() LoggerInputStream(it.byteStream(), maxSize, listener).use(block) } protected fun Response.charset(): String? = body()?.contentType()?.charset()?.name() protected fun Response.url(): String = this.request().url().toString() protected fun connect(url: String, post: Boolean = false): Call { val request = Request.Builder() .url(url) .apply { defaultHeaders.forEach { (key, value) -> header(key, value) } if (post) { @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") post(RequestBody.create(null, "")) } } .build() return client.newCall(request) } protected fun response(call: Call): Response { val response = call.execute() if (!check(response.url())) { // 可能网络需要登录之类的,会跳到不认识的地址, // 可能误伤,比如网站自己换域名, // TODO: 日志要支持发行版上传bugly, // 目前这样如果后面解析失败,上传失败日志时会带上这条日志, logger.error { "网络被重定向,<${call.request().url()}> -> <${response.url()}>" } // throw IOException("网络被重定向,检查网络是否可用,") } return response } protected fun responseBody(call: Call): ResponseBody { // 不可能为空,execute得到的response一定有body, return response(call).body().notNull() } private inner class LogInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() logger.info { "connect ${request.url()}" } logger.debug { val buffer = Buffer() request.body()?.writeTo(buffer) "body ${buffer.readUtf8()}" } val response = chain.proceed(request) logger.debug { "response ${response.request().url()}" } // 应该没有不是网络请求的情况,但是不了解okhttp的缓存,但还是不要在这里用可能抛异常的拓展方法requestHeaders, logger.debug { "request.headers ${response.networkResponse()?.request()?.headers()}" } logger.debug { "response.headers ${response.headers()}" } return response } } private inner class HeaderInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { var request = chain.request() if (headers.isNotEmpty()) { val requestBuilder = request.newBuilder() headers.map { (name, value) -> requestBuilder.header(name, value) } request = requestBuilder.build() } val response = chain.proceed(request) return response } } }
gpl-3.0
93dca10b072739bc09f5e10f631667df
35.674286
179
0.587658
4.158782
false
false
false
false
lambdasoup/watchlater
app/src/main/java/com/lambdasoup/watchlater/data/AccountRepository.kt
1
4664
/* * Copyright (c) 2015 - 2022 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later 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. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.watchlater.data import android.accounts.Account import android.accounts.AccountManager import android.accounts.AuthenticatorException import android.accounts.OperationCanceledException import android.content.Intent import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import androidx.annotation.MainThread import androidx.annotation.WorkerThread import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.lambdasoup.watchlater.data.AccountRepository.ErrorType.AccountRemoved import com.lambdasoup.watchlater.data.AccountRepository.ErrorType.Network import com.lambdasoup.watchlater.data.AccountRepository.ErrorType.Other import java.io.IOException class AccountRepository( private val accountManager: AccountManager, private val sharedPreferences: SharedPreferences, ) : OnSharedPreferenceChangeListener { private val liveData = MutableLiveData<Account?>() init { sharedPreferences.registerOnSharedPreferenceChangeListener(this) updateLiveData() } private fun getAccount(): Account? { val name = sharedPreferences.getString(PREF_KEY_DEFAULT_ACCOUNT_NAME, null) ?: return null return Account(name, ACCOUNT_TYPE_GOOGLE) } @MainThread private fun updateLiveData() { val account = getAccount() liveData.value = account } fun put(account: Account) { val prefEditor = sharedPreferences.edit() prefEditor.putString(PREF_KEY_DEFAULT_ACCOUNT_NAME, account.name) prefEditor.apply() } fun get(): LiveData<Account?> { return liveData } @WorkerThread fun getAuthToken(): AuthTokenResult { val account = getAccount() val accounts = accountManager.getAccountsByType(ACCOUNT_TYPE_GOOGLE) val isAccountOk = listOf(*accounts).contains(account) if (!isAccountOk) { val prefEditor = sharedPreferences.edit() prefEditor.remove(PREF_KEY_DEFAULT_ACCOUNT_NAME) prefEditor.apply() return AuthTokenResult.Error(AccountRemoved) } val future = accountManager.getAuthToken(account, SCOPE_YOUTUBE, null, false, null, null) try { val result = future.result val intent = result.getParcelable<Intent>(AccountManager.KEY_INTENT) if (intent != null) { return AuthTokenResult.HasIntent(intent) } return AuthTokenResult.AuthToken(result.getString(AccountManager.KEY_AUTHTOKEN)!!) } catch (e: OperationCanceledException) { return AuthTokenResult.Error(Other(e.message.orEmpty())) } catch (e: IOException) { return AuthTokenResult.Error(Network) } catch (e: AuthenticatorException) { return AuthTokenResult.Error(Other(e.message.orEmpty())) } } fun invalidateToken(token: String?) { accountManager.invalidateAuthToken(ACCOUNT_TYPE_GOOGLE, token) } override fun onSharedPreferenceChanged(prefs: SharedPreferences, key: String) { updateLiveData() } sealed class AuthTokenResult { data class Error(val errorType: ErrorType) : AuthTokenResult() data class AuthToken(val token: String) : AuthTokenResult() data class HasIntent(val intent: Intent) : AuthTokenResult() } sealed class ErrorType { object AccountRemoved : ErrorType() object Network : ErrorType() data class Other(val msg: String) : ErrorType() } companion object { private const val PREF_KEY_DEFAULT_ACCOUNT_NAME = "pref_key_default_account_name" private const val SCOPE_YOUTUBE = "oauth2:https://www.googleapis.com/auth/youtube" private const val ACCOUNT_TYPE_GOOGLE = "com.google" } }
gpl-3.0
90f2e152a2f39b7fc6d410708880082c
35.4375
98
0.707333
4.764045
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/formatter/blocks/RsFmtBlock.kt
1
3604
package org.rust.ide.formatter.blocks import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.formatter.FormatterUtil import org.rust.ide.formatter.RsFmtContext import org.rust.ide.formatter.RsFormattingModelBuilder import org.rust.ide.formatter.impl.* import org.rust.lang.core.psi.RsElementTypes.* class RsFmtBlock( private val node: ASTNode, private val alignment: Alignment?, private val indent: Indent?, private val wrap: Wrap?, val ctx: RsFmtContext ) : ASTBlock { override fun getNode(): ASTNode = node override fun getTextRange(): TextRange = node.textRange override fun getAlignment(): Alignment? = alignment override fun getIndent(): Indent? = indent override fun getWrap(): Wrap? = wrap override fun getSubBlocks(): List<Block> = mySubBlocks private val mySubBlocks: List<Block> by lazy { buildChildren() } private fun buildChildren(): List<Block> { val sharedAlignment = when (node.elementType) { in FN_DECLS -> Alignment.createAlignment() VALUE_PARAMETER_LIST -> ctx.sharedAlignment METHOD_CALL_EXPR -> if (node.treeParent.elementType == METHOD_CALL_EXPR) ctx.sharedAlignment else Alignment.createAlignment() else -> null } var metLBrace = false val alignment = getAlignmentStrategy() val children = node.getChildren(null) .filter { !it.isWhitespaceOrEmpty() } .map { childNode: ASTNode -> if (node.isFlatBlock && childNode.isBlockDelim(node)) { metLBrace = true } val childCtx = ctx.copy( metLBrace = metLBrace, sharedAlignment = sharedAlignment) RsFormattingModelBuilder.createBlock( node = childNode, alignment = alignment.getAlignment(childNode, node, childCtx), indent = computeIndent(childNode, childCtx), wrap = null, ctx = childCtx) } // Create fake `.sth` block here, so child indentation will // be relative to it when it starts from new line. // In other words: foo().bar().baz() => foo().baz()[.baz()] // We are using dot as our representative. // The idea is nearly copy-pasted from Kotlin's formatter. if (node.elementType == METHOD_CALL_EXPR) { val dotIndex = children.indexOfFirst { it.node.elementType == DOT } if (dotIndex != -1) { val dotBlock = children[dotIndex] val syntheticBlock = SyntheticRsFmtBlock( representative = dotBlock, subBlocks = children.subList(dotIndex, children.size), ctx = ctx) return children.subList(0, dotIndex).plusElement(syntheticBlock) } } return children } override fun getSpacing(child1: Block?, child2: Block): Spacing? = computeSpacing(child1, child2, ctx) override fun getChildAttributes(newChildIndex: Int): ChildAttributes = ChildAttributes(newChildIndent(newChildIndex), null) override fun isLeaf(): Boolean = node.firstChildNode == null override fun isIncomplete(): Boolean = myIsIncomplete private val myIsIncomplete: Boolean by lazy { FormatterUtil.isIncomplete(node) } override fun toString() = "${node.text} $textRange" }
mit
94b9a1fd20a5e2eb914019041ef1e325
37.752688
106
0.616815
4.876861
false
false
false
false
Ribesg/anko
dsl/static/src/sqlite/Database.kt
1
5981
/* * Copyright 2015 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.anko.db import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import java.util.concurrent.atomic.AtomicInteger import java.util.regex.Pattern enum class SqlOrderDirection { ASC, DESC } class TransactionAbortException : RuntimeException() fun SQLiteDatabase.insert(tableName: String, vararg values: Pair<String, Any>): Long { return insert(tableName, null, values.toContentValues()) } fun SQLiteDatabase.insertOrThrow(tableName: String, vararg values: Pair<String, Any>): Long { return insertOrThrow(tableName, null, values.toContentValues()) } fun SQLiteDatabase.replace(tableName: String, vararg values: Pair<String, Any>): Long { return replace(tableName, null, values.toContentValues()) } fun SQLiteDatabase.replaceOrThrow(tableName: String, vararg values: Pair<String, Any>): Long { return replaceOrThrow(tableName, null, values.toContentValues()) } fun SQLiteDatabase.transaction(code: SQLiteDatabase.() -> Unit) { try { beginTransaction() code() setTransactionSuccessful() } catch (e: TransactionAbortException) { // Do nothing, just stop the transaction } finally { endTransaction() } } fun SQLiteDatabase.select(tableName: String): SelectQueryBuilder { return SelectQueryBuilder(this, tableName) } fun SQLiteDatabase.select(tableName: String, vararg columns: String): SelectQueryBuilder { val builder = SelectQueryBuilder(this, tableName) builder.columns(*columns) return builder } fun SQLiteDatabase.update(tableName: String, vararg values: Pair<String, Any>): UpdateQueryBuilder { return UpdateQueryBuilder(this, tableName, values) } fun SQLiteDatabase.delete(tableName: String, whereClause: String = "", vararg args: Pair<String, Any>): Int { return delete(tableName, applyArguments(whereClause, *args), null) } fun SQLiteDatabase.createTable(tableName: String, ifNotExists: Boolean = false, vararg columns: Pair<String, SqlType>) { val escapedTableName = tableName.replace("`", "``") val ifNotExistsText = if (ifNotExists) "IF NOT EXISTS" else "" execSQL( columns.map { col -> "${col.first} ${col.second}" }.joinToString(", ", prefix = "CREATE TABLE $ifNotExistsText `$escapedTableName`(", postfix = ");") ) } fun SQLiteDatabase.dropTable(tableName: String, ifExists: Boolean = false) { val escapedTableName = tableName.replace("`", "``") val ifExistsText = if (ifExists) "IF EXISTS" else "" execSQL("DROP TABLE $ifExistsText `$escapedTableName`;") } private val ARG_PATTERN: Pattern = Pattern.compile("([^\\\\])\\{([^\\{}]+)\\}") internal fun applyArguments(whereClause: String, vararg args: Pair<String, Any>): String { val argsMap = args.fold(hashMapOf<String, Any>()) { map, arg -> map.put(arg.first, arg.second) map } return applyArguments(whereClause, argsMap) } internal fun applyArguments(whereClause: String, args: Map<String, Any>): String { val matcher = ARG_PATTERN.matcher(whereClause) val buffer = StringBuffer(whereClause.length) while (matcher.find()) { val key = matcher.group(2) val value = args.get(key) ?: throw IllegalStateException("Can't find a value for key $key") val valueString = if (value is Int || value is Long || value is Byte || value is Short) { value.toString() } else if (value is Boolean) { if (value) "1" else "0" } else if (value is Float || value is Double) { value.toString() } else { '\'' + value.toString().replace("'", "''") + '\'' } matcher.appendReplacement(buffer, matcher.group(1) + valueString) } matcher.appendTail(buffer) return buffer.toString() } internal fun Array<out Pair<String, Any>>.toContentValues(): ContentValues { val values = ContentValues() for ((key, value) in this) { when(value) { is Boolean -> values.put(key, value) is Byte -> values.put(key, value) is ByteArray -> values.put(key, value) is Double -> values.put(key, value) is Float -> values.put(key, value) is Int -> values.put(key, value) is Long -> values.put(key, value) is Short -> values.put(key, value) is String -> values.put(key, value) else -> throw IllegalArgumentException("Non-supported value type: ${value.javaClass.name}") } } return values } abstract class ManagedSQLiteOpenHelper( ctx: Context, name: String, factory: SQLiteDatabase.CursorFactory? = null, version: Int = 1 ): SQLiteOpenHelper(ctx, name, factory, version) { private val counter = AtomicInteger() private var db: SQLiteDatabase? = null fun <T> use(f: SQLiteDatabase.() -> T): T { try { return openDatabase().f() } finally { closeDatabase() } } @Synchronized private fun openDatabase(): SQLiteDatabase { if (counter.incrementAndGet() == 1) { db = writableDatabase } return db!! } @Synchronized private fun closeDatabase() { if (counter.decrementAndGet() == 0) { db?.close() } } }
apache-2.0
78e79f459a0e2788e48ada80c2cfbbeb
33.177143
120
0.661929
4.290531
false
false
false
false
stripe/stripe-android
identity/src/main/java/com/stripe/android/identity/networking/Resource.kt
1
998
package com.stripe.android.identity.networking import android.os.Parcelable import kotlinx.parcelize.Parcelize import kotlinx.parcelize.RawValue /** * A generic class that holds a value with its loading status. * @param <T> */ @Parcelize internal data class Resource<out T>( val status: Status, val data: @RawValue T?, val message: String? = null, val throwable: Throwable? = null ) : Parcelable { companion object { fun <T> success(data: T?): Resource<T> { return Resource(Status.SUCCESS, data) } fun <T> error( msg: String? = null, throwable: Throwable? = null, data: T? = null ): Resource<T> { return Resource(Status.ERROR, data, msg, throwable) } fun <T> loading(data: T? = null): Resource<T> { return Resource(Status.LOADING, data) } fun <T> idle(): Resource<T> { return Resource(Status.IDLE, null) } } }
mit
253e14663b437ce339e9c18027d9596f
24.589744
63
0.58517
3.976096
false
false
false
false
andimage/PCBridge
src/test/com/projectcitybuild/stubs/IPBanMock.kt
1
316
package com.projectcitybuild.stubs import com.projectcitybuild.entities.IPBan import java.time.LocalDateTime fun IPBanMock(ip: String? = null): IPBan { return IPBan( ip = ip ?: "127.0.0.1", bannerName = "banner_name", reason = "reason", createdAt = LocalDateTime.now(), ) }
mit
ba4ceba818682c4737653e68e0815412
23.307692
42
0.642405
3.632184
false
false
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/handlers/RequestHandler.kt
1
6674
package au.com.codeka.warworlds.server.handlers import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.server.json.WireTypeAdapterFactory import com.google.common.hash.Hashing import com.google.common.io.BaseEncoding import com.google.gson.GsonBuilder import com.squareup.wire.Message import java.io.IOException import java.net.URI import java.nio.charset.Charset import java.util.* import java.util.regex.Matcher import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * This is the base class for the game's request handlers. It handles some common tasks such as * extracting protocol buffers from the request body, and so on. */ open class RequestHandler { private val log = Log("RequestHandler") protected lateinit var request: HttpServletRequest private set protected lateinit var response: HttpServletResponse private set private lateinit var routeMatcher: Matcher /** Gets the "extra" option that was passed in the route configuration. */ protected var extraOption: String? = null private set /** Set up this [RequestHandler], must be called before any other methods. */ fun setup( routeMatcher: Matcher, extraOption: String?, request: HttpServletRequest, response: HttpServletResponse) { this.routeMatcher = routeMatcher this.extraOption = extraOption this.request = request this.response = response } protected fun getUrlParameter(name: String): String? { return try { routeMatcher.group(name) } catch (e: IllegalArgumentException) { null } } open fun handle() { // start off with status 200, but the handler might change it response.status = 200 try { if (!onBeforeHandle()) { return } when (request.method) { "GET" -> get() "POST" -> post() "PUT" -> put() "DELETE" -> delete() else -> throw RequestException(501) } } catch (e: RequestException) { handleException(e) } catch (e: Throwable) { log.error("Unexpected exception", e) handleException(RequestException(e)) } } protected open fun handleException(e: RequestException) { log.error("Unhandled exception", e) throw e } /** * This is called before the get(), put(), etc methods but after the request is set up, ready to * go. * * @return true if we should continue processing the request, false if not. If you return false * then you should have set response headers, status code and so on already. */ protected open fun onBeforeHandle(): Boolean { return true } protected open fun get() { throw RequestException(501) } protected fun put() { throw RequestException(501) } protected open fun post() { throw RequestException(501) } protected fun delete() { throw RequestException(501) } /** * Sets the required headers so that the client will know this response can be cached for the * given number of hours. The default response includes no caching headers. * * @param hours Time, in hours, to cache this response. * @param etag An optional value to include in the ETag header. This can be any string at all, * and we will hash and base-64 encode it for you. */ protected fun setCacheTime(hours: Float, etag: String? = null) { response.setHeader( "Cache-Control", String.format(Locale.US, "private, max-age=%d", (hours * 3600).toInt())) if (etag != null) { val encodedETag = BaseEncoding.base64().encode( Hashing.sha256().hashString(etag, Charset.defaultCharset()).asBytes()) response.setHeader("ETag", "\"${encodedETag}\"") } } protected fun setResponseText(text: String) { response.contentType = "text/plain" response.characterEncoding = "utf-8" try { response.writer.write(text) } catch (e: IOException) { // Ignore? } } protected fun setResponseJson(pb: Message<*, *>) { response.contentType = "application/json" response.characterEncoding = "utf-8" try { val writer = response.writer val gson = GsonBuilder() .registerTypeAdapterFactory(WireTypeAdapterFactory()) .serializeSpecialFloatingPointValues() .disableHtmlEscaping() .create() var json = gson.toJson(pb) // serializeSpecialFloatingPointValues() will insert literal "Infinity" "-Infinity" and "NaN" // which is not valid JSON. We'll replace those with nulls in a kind-naive way. json = json .replace(":Infinity".toRegex(), ":null") .replace(":-Infinity".toRegex(), ":null") .replace(":NaN".toRegex(), ":null") writer.write(json) writer.flush() } catch (e: IOException) { // Ignore. } } protected fun setResponseGson(obj: Any) { response.contentType = "application/json" response.characterEncoding = "utf-8" try { val writer = response.writer val gson = GsonBuilder() .disableHtmlEscaping() .create() writer.write(gson.toJson(obj)) writer.flush() } catch (e: IOException) { // Ignore. } } protected fun redirect(url: String) { response.status = 302 response.addHeader("Location", url) } protected val requestUrl: String get() { val requestURI = URI(request.requestURL.toString()) // TODO(dean): is hard-coding the https part for game.war-worlds.com the best way? no... var url = if (requestURI.host == "game.war-worlds.com") { "https://game.war-worlds.com" + requestURI.path } else { requestURI.toString() } if (request.queryString != "") { url += "?" + request.queryString } return url } private fun <T> getRequestJson(protoType: Class<T>): T { val scanner = Scanner(request.inputStream, request.characterEncoding) .useDelimiter("\\A") val json = if (scanner.hasNext()) scanner.next() else "" return fromJson(json, protoType) } protected fun <T> fromJson(json: String, protoType: Class<T>): T { val gson = GsonBuilder() .registerTypeAdapterFactory(WireTypeAdapterFactory()) .disableHtmlEscaping() .create() return gson.fromJson(json, protoType) } /** Get details about the given request as a string (for debugging). */ private fun getRequestDebugString(request: HttpServletRequest): String { return """ ${request.requestURI} X-Real-IP: ${request.getHeader("X-Real-IP")} User-Agent: ${request.getHeader("User-Agent")} """.trimIndent() } }
mit
d3f3bf9f8a411c486056cf4cf77550b7
29.199095
99
0.653731
4.272727
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/commands/Youtube.kt
1
4718
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.commands import io.sentry.Sentry import moe.kyubey.akatsuki.Akatsuki import moe.kyubey.akatsuki.EventListener import moe.kyubey.akatsuki.annotations.Alias import moe.kyubey.akatsuki.annotations.Argument import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.entities.* import moe.kyubey.akatsuki.utils.Http import moe.kyubey.akatsuki.utils.I18n import moe.kyubey.akatsuki.utils.ItemPicker import net.dv8tion.jda.core.entities.Guild import net.dv8tion.jda.core.entities.Member import okhttp3.HttpUrl import org.json.JSONObject import java.awt.Color @Load @Argument("query", "string") @Alias("yt") class Youtube : Command() { override val desc = "Search for videos on YouTube" override val guildOnly = true override fun run(ctx: Context) { val picker = ItemPicker(EventListener.waiter, ctx.member as Member, ctx.guild as Guild) val search = ctx.args["query"] as String Http.get(HttpUrl.Builder().apply { scheme("https") host("www.googleapis.com") addPathSegment("youtube") addPathSegment("v3") addPathSegment("search") addQueryParameter("key", Akatsuki.config.api.google) addQueryParameter("part", "snippet") addQueryParameter("maxResults", "10") addQueryParameter("type", "video") addQueryParameter("q", search) }.build()).thenAccept { res -> val body = res.body()!!.string() val obj = JSONObject(body) if (!obj.has("items")) { return@thenAccept ctx.send( I18n.parse( ctx.lang.getString("video_search_fail"), mapOf( "user" to ctx.author.name, "search" to search ) ) ) } val items = obj.getJSONArray("items") if (items.length() == 0) { return@thenAccept ctx.send( I18n.parse( ctx.lang.getString("video_search_fail"), mapOf( "user" to ctx.author.name, "search" to search ) ) ) } for (i in 0 until items.length()) { val item = items.getJSONObject(i) val id = item .getJSONObject("id") .getString("videoId") val snippet = item.getJSONObject("snippet") val title = snippet.getString("title") val thumb = snippet .getJSONObject("thumbnails") .getJSONObject("medium") .getString("url") val desc = snippet.getString("description") val channel = snippet.getString("channelTitle") picker.addItem(PickerItem(id, title, desc, channel, thumb, url = "https://youtu.be/$id")) } picker.color = Color(255, 0, 0) picker.build(ctx.channel) res.close() }.thenApply {}.exceptionally { ctx.logger.error("Error while trying to get info from YouTube", it) ctx.sendError(it) Sentry.capture(it) } } }
mit
a7e600ae1b00e5a0fee1bf970ca64bcd
35.867188
105
0.566978
4.799593
false
false
false
false
TeamWizardry/LibrarianLib
modules/core/src/main/kotlin/com/teamwizardry/librarianlib/core/util/Client.kt
1
3163
package com.teamwizardry.librarianlib.core.util import com.teamwizardry.librarianlib.math.Vec2d import dev.thecodewarrior.mirror.Mirror import net.minecraft.client.MinecraftClient import net.minecraft.client.font.TextRenderer import net.minecraft.client.gui.screen.Screen import net.minecraft.client.network.ClientPlayerEntity import net.minecraft.client.render.Tessellator import net.minecraft.client.texture.TextureManager import net.minecraft.client.util.Window import net.minecraft.resource.ResourceManager import net.minecraft.util.Identifier import net.minecraft.util.math.Vec3d import java.io.IOException import java.io.InputStream import java.util.concurrent.CompletableFuture public object Client { @JvmStatic public val minecraft: MinecraftClient get() = MinecraftClient.getInstance() @JvmStatic public val player: ClientPlayerEntity? get() = minecraft.player @JvmStatic public val window: Window get() = minecraft.window @JvmStatic public val scaleFactor: Double get() = window.scaleFactor @JvmStatic public val resourceManager: ResourceManager get() = minecraft.resourceManager @JvmStatic public val textureManager: TextureManager get() = minecraft.textureManager @JvmStatic public val textRenderer: TextRenderer get() = minecraft.textRenderer @JvmStatic public val tessellator: Tessellator get() = Tessellator.getInstance() /** * The game time, as measured from the game launch */ @JvmStatic public val time: GameTime = GameTime() /** * The world time, as measured from the game launch. This timer pauses when the game is paused. */ @JvmStatic public val worldTime: GameTime = GameTime() @JvmStatic public fun openScreen(screen: Screen?) { minecraft.setScreen(screen) } public class GameTime { public var ticks: Int = 0 private set public var tickDelta: Float = 0f private set public val time: Float get() = ticks + tickDelta public val seconds: Float get() = time / 20 public fun interp(previous: Double, current: Double): Double { return previous + (current - previous) * tickDelta } @Suppress("NOTHING_TO_INLINE") public inline fun interp(previous: Number, current: Number): Double = interp(previous.toDouble(), current.toDouble()) public fun interp(previous: Vec2d, current: Vec2d): Vec2d { return vec(interp(previous.x, current.x), interp(previous.y, current.y)) } public fun interp(previous: Vec3d, current: Vec3d): Vec3d { return vec(interp(previous.x, current.x), interp(previous.y, current.y), interp(previous.z, current.z)) } public fun updateTime(ticks: Int, tickDelta: Float) { this.ticks = ticks this.tickDelta = tickDelta } public fun trackTick() { ticks++ } public fun updateTickDelta(tickDelta: Float) { this.tickDelta = tickDelta } } }
lgpl-3.0
ff311c7489e13b396aa5849c811a71c0
28.287037
125
0.668037
4.411437
false
false
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/data/Setting.kt
1
1297
package com.twitter.meil_mitu.twitter4hk.data import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getBoolean import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getString import org.json.JSONObject class Setting { val language: String val screenName: String val isProtected: Boolean @Throws(Twitter4HKException::class) constructor(obj: JSONObject) { language = getString(obj, "language") isProtected = getBoolean(obj, "protected") screenName = getString(obj, "screen_name") } override fun toString(): String { return "Setting{Language='$language', ScreenName='$screenName', IsProtected=$isProtected}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Setting) return false if (isProtected != other.isProtected) return false if (language != other.language) return false if (screenName != other.screenName) return false return true } override fun hashCode(): Int { var result = language.hashCode() result = 31 * result + screenName.hashCode() result = 31 * result + (if (isProtected) 1 else 0) return result } }
mit
4a0760cdda4d1a8aeb11c6044f37b881
29.880952
98
0.674634
4.367003
false
false
false
false
tenebras/Spero
src/main/kotlin/TestApp.kt
1
1830
import com.tenebras.spero.DbConnectionManager import com.tenebras.spero.Repository import com.tenebras.spero.SperoApp import com.tenebras.spero.route.* import java.time.ZonedDateTime fun main(args: Array<String>) { SperoApp { injection { DbConnectionManager::class with ::ConnectionManager } routes { "/hello/{:\\d+}-{:\\d+}-{second:\\d+}" with Controller::numbers "/hello/{name:[a-z]+}" with Controller::hello "/hello" with Controller::index } } // bind(DbConnectionManager("jdbc:postgresql://localhost/money")) // bind(::DbConnectionManager) // bind<DbConnectionManager>() // DbConnectionManager::class with ::ConnectionManager // DbConnectionManager::class with DbConnectionManager("jdbc:postgresql://localhost/money") // ProfileRepository::class with ProfileRepository(instance()) //val ap = app.injector.instance<SperoApp>() // val profileRepository = app.injector.instance<ProfileRepository>() // // profileRepository.all() println("Hello") } @Target(AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER) annotation class ConfigValue(val name: String) open class ProfileRepository(connectionManager: DbConnectionManager) : Repository<Profile>(::Profile, connectionManager) class Rep(connectionManager: DbConnectionManager) : ProfileRepository(connectionManager) class ConnectionManager(connectionString: String = "jdbc:postgresql://localhost/money") : DbConnectionManager(connectionString) class Profile(var id: String, var email: String, var password: String, var createdAt: ZonedDateTime, var lastLoginAt: ZonedDateTime) class ProfileTransformer(val profile: Profile) class Controller { fun hello() = "" fun numbers(r: Request) = "" fun index() = Response("Hello") }
mit
a1b4143cdd89e065c87a50ac48f72fee
32.888889
132
0.720765
4.206897
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/backup/MyBackupManager.kt
1
8955
/* * Copyright (C) 2019 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.backup import android.app.Activity import android.app.backup.BackupAgent import android.content.Context import android.os.Environment import androidx.documentfile.provider.DocumentFile import io.vavr.control.Try import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.MyPreferences import org.andstatus.app.util.MyLog import org.andstatus.app.util.TryUtils import java.io.FileNotFoundException import java.io.IOException import java.util.* import java.util.function.UnaryOperator /** * Creates backups in the local file system: * 1. Using stock Android [BackupAgent] interface * 2. Or using custom interface, launched from your application * * One backup consists of: * 1. Backup descriptor file * 2. Folder with: * For each backup "key": header file and data file * @author yvolk (Yuri Volkov), http://yurivolkov.com */ internal class MyBackupManager(private val activity: Activity?, progressListener: ProgressLogger.ProgressListener?) { private var dataFolder: DocumentFile? = null private var newDescriptor: MyBackupDescriptor = MyBackupDescriptor.getEmpty() private var backupAgent: MyBackupAgent? = null private val progressLogger: ProgressLogger = ProgressLogger(progressListener) fun prepareForBackup(backupFolder: DocumentFile) { progressLogger.logProgress("Data folder will be created inside: '" + backupFolder.getUri() + "'") if (backupFolder.exists() && getExistingDescriptorFile(backupFolder).isSuccess()) { throw FileNotFoundException("Wrong folder, backup descriptor file '" + DESCRIPTOR_FILE_NAME + "'" + " already exists here: '" + backupFolder.getUri().path + "'") } val appInstanceName = MyPreferences.getAppInstanceName() val dataFolderName = MyLog.currentDateTimeFormatted() + "-AndStatusBackup-" + (if (appInstanceName.isEmpty()) "" else "$appInstanceName-") + MyPreferences.getDeviceBrandModelString() val dataFolderToBe = backupFolder.createDirectory(dataFolderName) ?: throw IOException("Couldn't create subfolder '" + dataFolderName + "'" + " inside '" + backupFolder.getUri() + "'") if (dataFolderToBe.listFiles().size > 0) { throw IOException("Data folder is not empty: '" + dataFolderToBe.uri + "'") } val descriptorFile = dataFolderToBe.createFile("", DESCRIPTOR_FILE_NAME) ?: throw IOException("Couldn't create descriptor file '" + DESCRIPTOR_FILE_NAME + "'" + " inside '" + dataFolderToBe.uri + "'") dataFolder = dataFolderToBe } fun getDataFolder(): DocumentFile? { return dataFolder } fun backup() { progressLogger.logProgress("Starting backup to data folder:'" + dataFolder?.getUri() + "'") backupAgent = MyBackupAgent().also { agent -> agent.setActivity(activity) dataFolder?.let { folder -> val dataOutput = MyBackupDataOutput(agent, folder) getExistingDescriptorFile(folder) .map { df: DocumentFile? -> newDescriptor = MyBackupDescriptor.fromEmptyDocumentFile(agent, df, progressLogger) agent.onBackup(MyBackupDescriptor.getEmpty(), dataOutput, newDescriptor) progressLogger.logSuccess() true } .get() // Return Try instead of throwing } } } fun prepareForRestore(dataFolder: DocumentFile?) { if (dataFolder == null) { throw FileNotFoundException("Data folder is not selected") } if (!dataFolder.exists()) { throw FileNotFoundException("Data folder doesn't exist:'" + dataFolder.uri + "'") } val descriptorFile = getExistingDescriptorFile(dataFolder) if (descriptorFile.isFailure()) { throw FileNotFoundException("Descriptor file " + DESCRIPTOR_FILE_NAME + " doesn't exist: '" + descriptorFile.getCause().message + "'") } this.dataFolder = dataFolder newDescriptor = descriptorFile.map { df: DocumentFile? -> val descriptor: MyBackupDescriptor = MyBackupDescriptor.fromOldDocFileDescriptor( MyContextHolder.myContextHolder.getNow().baseContext, df, progressLogger) if (descriptor.getBackupSchemaVersion() != MyBackupDescriptor.BACKUP_SCHEMA_VERSION) { throw FileNotFoundException( "Unsupported backup schema version: ${descriptor.getBackupSchemaVersion()}" + "; created with ${descriptor.appVersionNameAndCode()}" + "\nData folder:'${dataFolder.getUri().path}'." + "\nPlease use older AndStatus version to restore this backup." ) } descriptor }.getOrElseThrow(UnaryOperator.identity()) } fun restore() { backupAgent = MyBackupAgent().also { agent -> agent.setActivity(activity) dataFolder?.let { folder -> val dataInput = MyBackupDataInput(agent, folder) if (dataInput.listKeys().size < 3) { throw FileNotFoundException("Not enough keys in the backup: " + Arrays.toString(dataInput.listKeys().toTypedArray())) } progressLogger.logProgress("Starting restoring from data folder:'" + folder.getUri().path + "', created with " + newDescriptor.appVersionNameAndCode()) agent.onRestore(dataInput, newDescriptor.getApplicationVersionCode(), newDescriptor) } } progressLogger.logSuccess() } fun getBackupAgent(): MyBackupAgent? { return backupAgent } companion object { val DESCRIPTOR_FILE_NAME: String = "_descriptor.json" fun backupInteractively(backupFolder: DocumentFile, activity: Activity, progressListener: ProgressLogger.ProgressListener?) { val backupManager = MyBackupManager(activity, progressListener) try { backupManager.prepareForBackup(backupFolder) backupManager.backup() } catch (e: Throwable) { backupManager.progressLogger.logProgress(e.message ?: "(some error)") backupManager.progressLogger.logFailure() MyLog.w(backupManager, "Backup failed", e) } } fun isDataFolder(dataFolder: DocumentFile?): Boolean { return if (dataFolder != null && dataFolder.exists() && dataFolder.isDirectory) { getExistingDescriptorFile(dataFolder).isSuccess() } else false } fun getExistingDescriptorFile(dataFolder: DocumentFile): Try<DocumentFile> { return TryUtils.ofNullableCallable { dataFolder.findFile(DESCRIPTOR_FILE_NAME) } } fun restoreInteractively(dataFolder: DocumentFile, activity: Activity, progressListener: ProgressLogger.ProgressListener?) { val backupManager = MyBackupManager(activity, progressListener) try { backupManager.prepareForRestore(dataFolder) backupManager.restore() val backupFolder = dataFolder.getParentFile() if (backupFolder != null) { MyPreferences.setLastBackupUri(backupFolder.uri) } } catch (e: Throwable) { MyLog.ignored(backupManager, e) backupManager.progressLogger.logProgress(e.message ?: "(some error)") backupManager.progressLogger.logFailure() } } fun getDefaultBackupFolder(context: Context): DocumentFile { val backupFolder = DocumentFile.fromTreeUri(context, MyPreferences.getLastBackupUri()) return if (backupFolder == null || !backupFolder.exists()) DocumentFile.fromFile(Environment.getExternalStoragePublicDirectory("")) else backupFolder } } }
apache-2.0
543165a56625b108820dc871ae12c203
45.640625
132
0.629369
5.359066
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/models/Meta.kt
1
529
package nerd.tuxmobil.fahrplan.congress.models import info.metadude.android.eventfahrplan.database.contract.FahrplanContract.MetasTable import org.threeten.bp.ZoneId data class Meta( @Deprecated("To be removed. Access from AppRepository only. Left here only for data transfer.") var eTag: String = "", var numDays: Int = MetasTable.Defaults.NUM_DAYS_DEFAULT, var subtitle: String = "", var timeZoneId: ZoneId? = null, var title: String = "", var version: String = "" )
apache-2.0
7cbb8863d89de263ac4ebdf3de195ec8
32.0625
103
0.68431
4.198413
false
false
false
false
wordpress-mobile/AztecEditor-Android
aztec/src/main/kotlin/org/wordpress/aztec/watchers/event/sequence/UserOperationEvent.kt
1
3721
package org.wordpress.aztec.watchers.event.sequence import org.wordpress.aztec.spans.AztecCodeSpan import org.wordpress.aztec.spans.AztecHeadingSpan import org.wordpress.aztec.spans.AztecListItemSpan import org.wordpress.aztec.spans.AztecPreformatSpan import org.wordpress.aztec.watchers.event.text.BeforeTextChangedEventData import org.wordpress.aztec.watchers.event.text.TextWatcherEvent abstract class UserOperationEvent(var sequence: EventSequence<TextWatcherEvent> = EventSequence()) { enum class ObservedOperationResultType { SEQUENCE_FOUND, SEQUENCE_NOT_FOUND, SEQUENCE_FOUND_CLEAR_QUEUE } fun isFound(resultType: ObservedOperationResultType) : Boolean { return resultType == ObservedOperationResultType.SEQUENCE_FOUND } fun needsClear(resultType: ObservedOperationResultType) : Boolean { return resultType == ObservedOperationResultType.SEQUENCE_FOUND_CLEAR_QUEUE } fun addSequenceStep(event: TextWatcherEvent) { sequence.add(event) } fun clear() { sequence.clear() } fun isUserOperationPartiallyObservedInSequence(sequence: EventSequence<TextWatcherEvent>): Boolean { for (i in sequence.indices) { val eventHolder = this.sequence[i] val observableEvent = sequence[i] // if time distance between any of the events is longer than 50 millis, discard this as this pattern is // likely not produced by the platform, but rather the user. // WARNING! When debugging with breakpoints, you should disable this check as time can exceed the 50 MS limit and // create undesired behavior. if (i > 0) { // only try to compare when we have at least 2 events, so we can compare with the previous one val timestampForPreviousEvent = sequence[i - 1].timestamp val timeDistance = observableEvent.timestamp - timestampForPreviousEvent if (timeDistance > ObservationQueue.MAXIMUM_TIME_BETWEEN_EVENTS_IN_PATTERN_MS) { return false } } eventHolder.beforeEventData = observableEvent.beforeEventData eventHolder.onEventData = observableEvent.onEventData eventHolder.afterEventData = observableEvent.afterEventData // return immediately as soon as we realize the pattern diverges if (!eventHolder.testFitsBeforeOnAndAfter()) { return false } } return true } fun isEventFoundWithinABlock(data: BeforeTextChangedEventData) : Boolean { // ok finally let's make sure we are not within a Block element val inputStart = data.start + data.count val inputEnd = data.start + data.count + 1 val text = data.textBefore!! val isInsideList = text.getSpans(inputStart, inputEnd, AztecListItemSpan::class.java).isNotEmpty() val isInsidePre = text.getSpans(inputStart, inputEnd, AztecPreformatSpan::class.java).isNotEmpty() val isInsideCode = text.getSpans(inputStart, inputEnd, AztecCodeSpan::class.java).isNotEmpty() var insideHeading = text.getSpans(inputStart, inputEnd, AztecHeadingSpan::class.java).isNotEmpty() if (insideHeading && (text.length > inputEnd && text[inputEnd] == '\n')) { insideHeading = false } return isInsideList || insideHeading || isInsidePre || isInsideCode } abstract fun isUserOperationObservedInSequence(sequence: EventSequence<TextWatcherEvent>) : ObservedOperationResultType abstract fun buildReplacementEventWithSequenceData(sequence: EventSequence<TextWatcherEvent>) : TextWatcherEvent }
mpl-2.0
29e13b736d4611127e18b82a3324240c
42.267442
125
0.698737
4.740127
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/wpmangastream/mangaraworg/src/MangaRawOrg.kt
1
3083
package eu.kanade.tachiyomi.extension.ja.mangaraworg import eu.kanade.tachiyomi.multisrc.wpmangastream.WPMangaStream import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.util.asJsoup import rx.Observable import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import java.util.concurrent.TimeUnit import okhttp3.OkHttpClient class MangaRawOrg : WPMangaStream("Manga Raw.org", "https://mangaraw.org", "ja") { // Formerly "Manga Raw" from WPMangaStream override val id = 6223520752496636410 private val rateLimitInterceptor = RateLimitInterceptor(4) override val client: OkHttpClient = network.cloudflareClient.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .addNetworkInterceptor(rateLimitInterceptor) .build() override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/search?order=popular&page=$page", headers) override fun popularMangaSelector() = "div.bsx" override fun popularMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("div.bigor > a").let { setUrlWithoutDomain(it.attr("href")) title = it.text() } thumbnail_url = element.select("img").attr("abs:src") } } override fun popularMangaNextPageSelector() = "a[rel=next]" override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/search?order=update&page=$page", headers) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = GET("$baseUrl/search?s=$query&page=$page") override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun mangaDetailsParse(document: Document): SManga = super.mangaDetailsParse(document) .apply { description = document.select("div.bottom").firstOrNull()?.ownText() } override fun fetchPageList(chapter: SChapter): Observable<List<Page>> { return client.newCall(pageListRequest(chapter)) .asObservableSuccess() .map { response -> pageListParse(response, baseUrl + chapter.url.removeSuffix("/")) } } private fun pageListParse(response: Response, chapterUrl: String): List<Page> { return response.asJsoup().select("span.page-link").first().ownText().substringAfterLast(" ").toInt() .let { lastNum -> IntRange(1, lastNum) } .map { num -> Page(num, "$chapterUrl/$num") } } override fun imageUrlParse(document: Document): String = document.select("a.img-block img").attr("abs:src") override fun getFilterList(): FilterList = FilterList() }
apache-2.0
58d3bf2e9de4a6dc31d5d4d9671ce910
47.171875
115
0.713591
4.410587
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/updatenote/UpdateNoteCard.kt
1
2486
package de.tum.`in`.tumcampusapp.component.ui.updatenote import android.content.Context import android.content.SharedPreferences import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import de.tum.`in`.tumcampusapp.BuildConfig import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener import de.tum.`in`.tumcampusapp.component.ui.overview.CardManager import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils class UpdateNoteCard(context: Context) : Card(CardManager.CARD_UPDATE_NOTE, context, "update_note") { override fun updateViewHolder(viewHolder: RecyclerView.ViewHolder) { super.updateViewHolder(viewHolder) val version = BuildConfig.VERSION_NAME val updateMessage = Utils.getSetting(context, Const.UPDATE_MESSAGE, "") (viewHolder as UpdateNoteViewHolder).bind(updateMessage, version) } override fun shouldShow(prefs: SharedPreferences): Boolean { return Utils.getSettingBool(context, Const.SHOW_UPDATE_NOTE, false) && Utils.getSetting(context, Const.UPDATE_MESSAGE, "").isNotEmpty() } override fun discard(editor: SharedPreferences.Editor) { Utils.setSetting(context, Const.SHOW_UPDATE_NOTE, false) } companion object { @JvmStatic fun inflateViewHolder( parent: ViewGroup, interactionListener: CardInteractionListener ): CardViewHolder { val card = LayoutInflater.from(parent.context) .inflate(R.layout.card_update_note, parent, false) return UpdateNoteViewHolder(card, interactionListener) } } class UpdateNoteViewHolder( view: View, interactionListener: CardInteractionListener ) : CardViewHolder(view, interactionListener) { internal var subtitleView: TextView = view.findViewById(R.id.update_note_subtitle) internal var messageView: TextView = view.findViewById(R.id.update_note_message) fun bind(updateMessage: String, version: String) { subtitleView.text = activity.getString(R.string.update_note_version, version) messageView.text = updateMessage } } }
gpl-3.0
e77ce61f86b56ba1453519603665a825
39.754098
101
0.727273
4.495479
false
false
false
false
Shockah/Godwit
android/src/pl/shockah/godwit/android/AndroidSafeAreaProvider.kt
1
786
package pl.shockah.godwit.android import android.app.Activity import android.support.v4.view.ViewCompat import pl.shockah.godwit.geom.EdgeInsets import pl.shockah.godwit.platform.SafeAreaProvider class AndroidSafeAreaProvider( activity: Activity ) : AndroidProvider(activity), SafeAreaProvider { override var safeAreaInsets = EdgeInsets() private set init { ViewCompat.setOnApplyWindowInsetsListener(activity.window.decorView.rootView) { _, insets -> insets.displayCutout?.let { cutout -> safeAreaInsets = EdgeInsets( top = cutout.safeInsetTop.toFloat(), right = cutout.safeInsetRight.toFloat(), bottom = cutout.safeInsetBottom.toFloat(), left = cutout.safeInsetLeft.toFloat() ) } return@setOnApplyWindowInsetsListener insets } } }
apache-2.0
0706be33008dab8d8cab68374bb0279e
28.148148
94
0.75827
3.93
false
false
false
false
Jakeler/UT61E-Toolkit
Application/src/main/java/jk/ut61eTool/FileSelectActivity.kt
1
4020
package jk.ut61eTool import android.app.Activity import android.content.Intent import android.database.Cursor import android.net.Uri import android.os.Bundle import android.provider.DocumentsContract import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.* import androidx.preference.PreferenceManager import java.util.* class FileSelectActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_select_file) actionBar?.setDisplayHomeAsUpEnabled(true) populateListView() } private fun populateListView() { val uriEnc = PreferenceManager.getDefaultSharedPreferences(this).getString("log_folder", null) if (uriEnc == null) { Toast.makeText(this, getString(R.string.error_folder_not_setup), Toast.LENGTH_LONG).show() finish() return } val uri = Uri.parse(uriEnc) val dUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)) val proj = arrayOf( DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_SIZE, DocumentsContract.Document.COLUMN_LAST_MODIFIED, DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_MIME_TYPE, ) // filter not working on fs: // https://stackoverflow.com/questions/56263620/contentresolver-query-on-documentcontract-lists-all-files-disregarding-selection val sel = "text/comma-separated-values" val order = DocumentsContract.Document.COLUMN_SIZE + " ASC" var cursor: Cursor? = null; try { cursor = contentResolver.query(dUri, proj, sel, null, order) } catch (e: Exception) { Log.w("FILE SELECT", "Error: ${e.message}") Toast.makeText(this, getString(R.string.error_folder_missing), Toast.LENGTH_SHORT).show() finish() return } val files = arrayListOf<FileEntry>() cursor?.use { while (it.moveToNext()) { // Workaround: manual filter if (it.getString(4) != sel) continue FileEntry( it.getString(0), it.getLong(1), Date(it.getLong(2)), it.getString(3) ).let {fileEntry -> files.add(fileEntry) } } } if (files.isEmpty()) Toast.makeText(this, getString(R.string.error_folder_empty), Toast.LENGTH_SHORT).show() val arrayAdapter = object : ArrayAdapter<FileEntry>(this, R.layout.listitem_files, R.id.filename, files) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = super.getView(position, convertView, parent) val file = getItem(position) ?: return view view.findViewById<TextView>(R.id.filename)?.text = file.name view.findViewById<TextView>(R.id.logfile_info)?.text = "Filesize: ${file.size/1000.0} KB\nModified: ${file.lastMod}" return view } } val fileListView = findViewById<ListView>(R.id.fileList) fileListView.adapter = arrayAdapter fileListView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> val intent = Intent(this@FileSelectActivity, ViewLogActivity::class.java) DocumentsContract.buildDocumentUriUsingTree(uri, files[position].id).let { intent.putExtra("filename", it) } startActivity(intent) } } } data class FileEntry( val name: String, val size: Long, val lastMod: Date, val id: String, )
apache-2.0
faddda8484b63134a02750f7aa19210a
36.222222
136
0.613184
4.594286
false
false
false
false
Maccimo/intellij-community
plugins/settings-sync/tests/com/intellij/settingsSync/GitSettingsLogTest.kt
1
6542
package com.intellij.settingsSync import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.util.io.createDirectories import com.intellij.util.io.createFile import com.intellij.util.io.readText import org.eclipse.jgit.revwalk.RevCommit import org.eclipse.jgit.revwalk.RevWalk import org.eclipse.jgit.storage.file.FileRepositoryBuilder import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.nio.file.Path import kotlin.io.path.div import kotlin.io.path.writeText @RunWith(JUnit4::class) internal class GitSettingsLogTest { private val tempDirManager = TemporaryDirectory() private val disposableRule = DisposableRule() @Rule @JvmField val ruleChain: RuleChain = RuleChain.outerRule(tempDirManager).around(disposableRule) private lateinit var configDir: Path private lateinit var settingsSyncStorage: Path @Before fun setUp() { val mainDir = tempDirManager.createDir() configDir = mainDir.resolve("rootconfig").createDirectories() settingsSyncStorage = configDir.resolve("settingsSync") } @Test fun `copy files initially`() { val keymapContent = "keymapContent" val keymapsFolder = configDir / "keymaps" (keymapsFolder / "mykeymap.xml").createFile().writeText(keymapContent) val editorContent = "editorContent" val editorXml = (configDir / "options" / "editor.xml").createFile() editorXml.writeText(editorContent) val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) { listOf(keymapsFolder, editorXml) } settingsLog.initialize() settingsLog.logExistingSettings() settingsLog.collectCurrentSnapshot().assertSettingsSnapshot { fileState("keymaps/mykeymap.xml", keymapContent) fileState("options/editor.xml", editorContent) } } @Test fun `merge conflict should be resolved as last modified`() { val editorXml = (configDir / "options" / "editor.xml").createFile() editorXml.writeText("editorContent") val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) { listOf(editorXml) } settingsLog.initialize() settingsLog.applyIdeState(settingsSnapshot { fileState("options/editor.xml", "ideEditorContent") }) settingsLog.applyCloudState(settingsSnapshot { fileState("options/editor.xml", "cloudEditorContent") }) settingsLog.advanceMaster() assertEquals("Incorrect content", "cloudEditorContent", (settingsSyncStorage / "options" / "editor.xml").readText()) assertMasterIsMergeOfIdeAndCloud() } @Test fun `delete-modify merge conflict should be resolved as last modified`() { val editorXml = (configDir / "options" / "editor.xml").createFile() editorXml.writeText("editorContent") val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) { listOf(editorXml) } settingsLog.initialize() settingsLog.applyIdeState(settingsSnapshot { fileState(FileState.Deleted("options/editor.xml")) }) settingsLog.applyCloudState(settingsSnapshot { fileState("options/editor.xml", "cloudEditorContent") }) settingsLog.advanceMaster() assertEquals("Incorrect content", "cloudEditorContent", (settingsSyncStorage / "options" / "editor.xml").readText()) assertMasterIsMergeOfIdeAndCloud() } @Test fun `modify-delete merge conflict should be resolved as last modified`() { val editorXml = (configDir / "options" / "editor.xml").createFile() editorXml.writeText("editorContent") val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) { listOf(editorXml) } settingsLog.initialize() settingsLog.applyCloudState(settingsSnapshot { fileState("options/editor.xml", "moreCloudEditorContent") }) settingsLog.applyIdeState(settingsSnapshot { fileState(FileState.Deleted("options/editor.xml")) }) settingsLog.advanceMaster() assertEquals("Incorrect deleted file content", DELETED_FILE_MARKER, (settingsSyncStorage / "options" / "editor.xml").readText()) assertMasterIsMergeOfIdeAndCloud() } //@Test // todo requires a more previse merge conflict strategy implementation @Suppress("unused") fun `merge conflict should be resolved as last modified for the particular file`() { val editorXml = (configDir / "options" / "editor.xml").createFile() editorXml.writeText("editorContent") val lafXml = (configDir / "options" / "laf.xml").createFile() editorXml.writeText("lafContent") val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) { listOf(lafXml, editorXml) } settingsLog.initialize() settingsLog.applyIdeState(settingsSnapshot { fileState("editor.xml", "ideEditorContent") }) settingsLog.applyCloudState(settingsSnapshot { fileState("laf.xml", "cloudLafContent") }) settingsLog.applyCloudState(settingsSnapshot { fileState("editor.xml", "cloudEditorContent") }) settingsLog.applyIdeState(settingsSnapshot { fileState("laf.xml", "ideEditorContent") }) settingsLog.advanceMaster() assertEquals("Incorrect content", "cloudEditorContent", editorXml.readText()) assertEquals("Incorrect content", "ideLafContent", lafXml.readText()) assertMasterIsMergeOfIdeAndCloud() } private fun assertMasterIsMergeOfIdeAndCloud() { val dotGit = settingsSyncStorage.resolve(".git") FileRepositoryBuilder.create(dotGit.toFile()).use { repository -> val walk = RevWalk(repository) try { val commit: RevCommit = walk.parseCommit(repository.findRef("master").objectId) walk.markStart(commit) val parents = commit.parents assertEquals(2, parents.size) val ide = repository.findRef("ide")!! val cloud = repository.findRef("cloud")!! val (parent1, parent2) = parents if (parent1.id == ide.objectId) { assertTrue(parent2.id == cloud.objectId) } else if (parent1.id == cloud.objectId) { assertTrue(parent2.id == ide.objectId) } else { fail("Neither ide nor cloud are parents of master") } walk.dispose() } finally { walk.dispose() walk.close() } } } }
apache-2.0
f8c65022341b079e350885bd6688768b
33.436842
132
0.717365
4.390604
false
true
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AutocryptPreferEncryptPreference.kt
2
1759
package com.fsck.k9.ui.settings.account import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import androidx.core.content.res.TypedArrayUtils import androidx.core.content.withStyledAttributes import androidx.preference.PreferenceViewHolder import androidx.preference.TwoStatePreference import com.fsck.k9.ui.R import com.takisoft.preferencex.PreferenceFragmentCompat @SuppressLint("RestrictedApi") class AutocryptPreferEncryptPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = TypedArrayUtils.getAttr( context, androidx.preference.R.attr.preferenceStyle, android.R.attr.preferenceStyle ), defStyleRes: Int = 0 ) : TwoStatePreference(context, attrs, defStyleAttr, defStyleRes) { init { context.withStyledAttributes(attrs, R.styleable.AutocryptPreferEncryptPreference, defStyleAttr, defStyleRes) { summaryOn = getString(R.styleable.AutocryptPreferEncryptPreference_summaryOn) summaryOff = getString(R.styleable.AutocryptPreferEncryptPreference_summaryOff) } } override fun onClick() { preferenceManager.showDialog(this) } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) syncSummaryView(holder) } fun userChangedValue(newValue: Boolean) { if (callChangeListener(newValue)) { isChecked = newValue } } companion object { init { PreferenceFragmentCompat.registerPreferenceFragment( AutocryptPreferEncryptPreference::class.java, AutocryptPreferEncryptDialogFragment::class.java ) } } }
apache-2.0
e2fb38a52bc33f14e19ab1cb86ca4047
30.981818
118
0.733371
4.84573
false
false
false
false
AcornUI/Acorn
acornui-core/src/test/kotlin/com/acornui/signal/SignalTest.kt
1
4104
/* * Copyright 2014 Nicholas Bilyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UNUSED_ANONYMOUS_PARAMETER") package com.acornui.signal import com.acornui.function.as1 import com.acornui.test.assertListEquals import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.fail class SignalTest { @Test fun dispatch() { var actual = -1 val s = unmanagedSignal<Int>() s.listen { actual = it } s.dispatch(3) assertEquals(3, actual) s.dispatch(4) assertEquals(4, actual) } @Test fun remove() { var actual = -1 val s = unmanagedSignal<Int>() val handler = { it: Int -> actual = it } val sub = s.listen(handler) s.dispatch(3) assertEquals(3, actual) sub.dispose() s.dispatch(4) assertEquals(3, actual) } @Test fun addMany() { val arr = Array(5) { -1 } var i = 0 val handler1 = { it: Int -> arr[i++] = 1 } val handler2 = { it: Int -> arr[i++] = 2 } val handler3 = { it: Int -> arr[i++] = 3 } val handler4 = { it: Int -> arr[i++] = 4 } val handler5 = { it: Int -> arr[i++] = 5 } val s = unmanagedSignal<Int>() s.listen(handler1) s.listen(handler2) s.listen(handler3) s.listen(handler4) s.listen(handler5) s.dispatch(0) assertListEquals(arrayOf(1, 2, 3, 4, 5), arr) } @Test fun addOnceMany() { val arr = Array(5) { -1 } var i = 0 val handler1 = { it: Int -> arr[i++] = 1 } val handler2 = { it: Int -> arr[i++] = 2 } val handler3 = { it: Int -> arr[i++] = 3 } val handler4 = { it: Int -> arr[i++] = 4 } val handler5 = { it: Int -> arr[i++] = 5 } val s = unmanagedSignal<Int>() s.listen(true, handler1) s.listen(true, handler2) s.listen(true, handler3) s.listen(true, handler4) s.listen(true, handler5) s.dispatch(0) s.dispatch(0) s.dispatch(0) s.dispatch(0) assertListEquals(arrayOf(1, 2, 3, 4, 5), arr) } @Test fun concurrentAdd() { val arr = arrayListOf<Int>() val s = unmanagedSignal<Unit>() s.once { arr.add(1) s.once { arr.add(4) s.once { arr.add(7) s.once { arr.add(8) } } } } s.once { arr.add(2) s.once { arr.add(5) } s.once { arr.add(6) } } s.once { arr.add(3) } // Adding a handler within a handler should not invoke the inner handler until next dispatch. s.dispatch(Unit) assertListEquals(arrayOf(1, 2, 3), arr) s.dispatch(Unit) assertListEquals(arrayOf(1, 2, 3, 4, 5, 6), arr) s.dispatch(Unit) assertListEquals(arrayOf(1, 2, 3, 4, 5, 6, 7), arr) s.dispatch(Unit) assertListEquals(arrayOf(1, 2, 3, 4, 5, 6, 7, 8), arr) } @Test fun concurrentRemove() { TestConcurrentRemove() } @Test fun disposeHandle() { val s = unmanagedSignal<Unit>() var c = 0 val handle = s.listen { c++ } s.dispatch(Unit) assertEquals(1, c) handle.dispose() s.dispatch(Unit) assertEquals(1, c) } } private class TestConcurrentRemove { private var sub2: SignalSubscription private var sub4: SignalSubscription private val s = unmanagedSignal<Unit>() private val arr = arrayListOf<Int>() init { s.listen(::testHandler1.as1) sub2 = s.listen(::testHandler2.as1) s.listen(::testHandler3.as1) sub4 = s.listen(::testHandler4.as1) s.dispatch(Unit) s.dispatch(Unit) assertListEquals(arrayOf(1, 2, 3, 1, 3), arr) } private fun testHandler1() { arr.add(1) } private fun testHandler2() { arr.add(2) sub2.dispose() } private fun testHandler3() { arr.add(3) sub4.dispose() } private fun testHandler4() { fail("testHandler4 should not have been invoked.") } }
apache-2.0
0bf56bd92042e141dbc9172b3b610d8c
20.375
95
0.632797
2.834254
false
true
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/attention/attentionnetwork/AttentionNetworksPool.kt
1
1763
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.deeplearning.attention.attentionnetwork import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.utils.ItemsPool /** * A pool of [AttentionNetwork]s which allows to allocate and release one when needed, without creating a new one. * It is useful to optimize the creation of new structures every time a new network is created. * * @property model the model of the [AttentionNetwork]s of the pool * @property inputType the type of the input arrays * @property dropout the probability of dropout (default 0.0) * @param propagateToInput whether to propagate the errors to the input during the backward */ class AttentionNetworksPool<InputNDArrayType : NDArray<InputNDArrayType>>( private val model: AttentionNetworkParameters, private val inputType: LayerType.Input, private val dropout: Double = 0.0, private val propagateToInput: Boolean ) : ItemsPool<AttentionNetwork<InputNDArrayType>>() { /** * The factory of a new [AttentionNetwork]. * * @param id the unique id of the item to create * * @return a new [AttentionNetwork] with the given [id] */ override fun itemFactory(id: Int) = AttentionNetwork<InputNDArrayType>( model = this.model, inputType = this.inputType, dropout = this.dropout, propagateToInput = this.propagateToInput, id = id ) }
mpl-2.0
9373e86e3a101f56979cdea746ee7048
39.068182
114
0.721497
4.4075
false
false
false
false
DiUS/pact-jvm
core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/QualifiedName.kt
1
1665
package au.com.dius.pact.core.matchers import org.w3c.dom.Node /** * Namespace-aware XML node qualified names. * * Used for comparison and display purposes. Uses the XML namespace and local name if present in the [Node]. * Falls back to using the default node name if a namespace isn't present. */ class QualifiedName(node: Node) { val namespaceUri: String? = node.namespaceURI val localName: String? = node.localName val nodeName: String = node.nodeName /** * When both do not have a namespace, check equality using node name. * Otherwise, check equality using both namespace and local name. */ override fun equals(other: Any?): Boolean = when (other) { is QualifiedName -> { when { this.namespaceUri == null && other.namespaceUri == null -> other.nodeName == nodeName else -> other.namespaceUri == namespaceUri && other.localName == localName } } else -> false } /** * When a namespace isn't present, return the hash of the node name. * Otherwise, return the hash of the namespace and local name. */ override fun hashCode(): Int = when (namespaceUri) { null -> nodeName.hashCode() else -> 31 * (31 + namespaceUri.hashCode()) + localName.hashCode() } /** * Returns the qualified name using Clark-notation if * a namespace is present, otherwise returns the node name. * * Clark-notation uses the format `{namespace}localname` * per https://sabre.io/xml/clark-notation/. * * @see Node.getNodeName */ override fun toString(): String { return when (namespaceUri) { null -> nodeName else -> "{$namespaceUri}$localName" } } }
apache-2.0
5c3173ed6b4aecf8837593a82ed6f0ff
29.833333
108
0.666667
4.080882
false
false
false
false
ingokegel/intellij-community
java/java-impl/src/com/intellij/internal/statistic/libraryUsage/DumpLibraryUsageStatisticsAction.kt
7
1067
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.libraryUsage import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.Messages internal class DumpLibraryUsageStatisticsAction : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project != null } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val statistics = LibraryUsageStatisticsStorageService.getInstance(project).state.statistics val message = statistics.entries.joinToString(prefix = "Registered usages:\n", separator = "\n") { (libraryUsage, count) -> "$libraryUsage -> $count" } Messages.showMessageDialog(project, message, "Library Usage Statistics", null) } }
apache-2.0
a30436ad4a397fa39d353f6f34c07541
38.518519
127
0.776007
4.679825
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionEngine.kt
1
5180
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.ui.awt.RelativePoint import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.nonBlocking import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.safeAs import javax.swing.event.HyperlinkEvent abstract class ExtractionEngineHelper(@NlsContexts.DialogTitle val operationName: String) { open fun adjustExtractionData(data: ExtractionData): ExtractionData = data fun doRefactor(config: ExtractionGeneratorConfiguration, onFinish: (ExtractionResult) -> Unit = {}) { val project = config.descriptor.extractionData.project onFinish(project.executeWriteCommand<ExtractionResult>(operationName) { config.generateDeclaration() }) } open fun validate(descriptor: ExtractableCodeDescriptor): ExtractableCodeDescriptorWithConflicts = descriptor.validate() abstract fun configureAndRun( project: Project, editor: Editor, descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, onFinish: (ExtractionResult) -> Unit = {} ) } class ExtractionEngine( val helper: ExtractionEngineHelper ) { fun run( editor: Editor, extractionData: ExtractionData, onFinish: (ExtractionResult) -> Unit = {} ) { val project = extractionData.project val adjustExtractionData = helper.adjustExtractionData(extractionData) val analysisResult = ActionUtil.underModalProgress(project, KotlinBundle.message("progress.title.analyze.extraction.data")) { adjustExtractionData.performAnalysis() } if (isUnitTestMode() && analysisResult.status != AnalysisResult.Status.SUCCESS) { throw BaseRefactoringProcessor.ConflictsInTestsException(analysisResult.messages.map { it.renderMessage() }) } fun validateAndRefactor() { nonBlocking(project, { try { helper.validate(analysisResult.descriptor!!) } catch (e: RuntimeException) { ExtractableCodeDescriptorWithException(e) } }) { result -> result.safeAs<ExtractableCodeDescriptorWithException>()?.let { throw it.exception } val validationResult = result.cast<ExtractableCodeDescriptorWithConflicts>() project.checkConflictsInteractively(validationResult.conflicts) { helper.configureAndRun(project, editor, validationResult) { try { onFinish(it) } finally { it.dispose() extractionData.dispose() } } } } } val message = analysisResult.messages.joinToString("\n") { it.renderMessage() } when (analysisResult.status) { AnalysisResult.Status.CRITICAL_ERROR -> { showErrorHint(project, editor, message, helper.operationName) } AnalysisResult.Status.NON_CRITICAL_ERROR -> { val anchorPoint = RelativePoint( editor.contentComponent, editor.visualPositionToXY(editor.selectionModel.selectionStartPosition!!) ) @NlsSafe val htmlContent = "$message<br/><br/><a href=\"EXTRACT\">${KotlinBundle.message("text.proceed.with.extraction")}</a>" JBPopupFactory.getInstance()!! .createHtmlTextBalloonBuilder( htmlContent, MessageType.WARNING ) { event -> if (event?.eventType == HyperlinkEvent.EventType.ACTIVATED) { validateAndRefactor() } } .setHideOnClickOutside(true) .setHideOnFrameResize(false) .setHideOnLinkClick(true) .createBalloon() .show(anchorPoint, Balloon.Position.below) } AnalysisResult.Status.SUCCESS -> validateAndRefactor() } } }
apache-2.0
3130b35f5756c8a718fc10db3434c3dc
43.273504
158
0.646718
5.56391
false
true
false
false
Major-/Vicis
util/src/main/kotlin/rs/emulate/util/crypto/xtea/XteaKey.kt
1
1267
package rs.emulate.util.crypto.xtea import java.security.SecureRandom data class XteaKey(private val key: List<Int>) : Iterable<Int> { init { require(key.size == PARTS) } val isZero: Boolean get() = key.all { it == 0 } fun toIntArray(): IntArray { return key.toIntArray() } operator fun get(part: Int): Int = key[part] override fun iterator(): Iterator<Int> { return key.iterator() } override fun toString(): String { return key.joinToString(separator = "") { Integer.toHexString(it).padStart(8, '0') } } companion object { const val PARTS = 4 val NONE = XteaKey(List(PARTS) { 0 }) private val random = SecureRandom() fun create(init: (Int) -> Int): XteaKey { return XteaKey(List(PARTS, init)) } fun createRandom(): XteaKey = create { random.nextInt() } fun fromString(hex: String): XteaKey { require(hex.length == 8 * PARTS) return create { Integer.parseUnsignedInt(hex.substring(it * 8, (it + 1) * 8), 16) } } fun fromArray(key: IntArray): XteaKey = XteaKey(key.toList()) } }
isc
d204f82cb8284b3e3e8000fa09482a94
22.90566
81
0.543015
3.996845
false
false
false
false
Abdel-RhmanAli/Inventory-App
app/src/main/java/com/example/android/inventory/ui/ItemsActivity.kt
1
4599
package com.example.android.inventory.ui import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.helper.ItemTouchHelper import android.view.Menu import android.view.MenuItem import com.example.android.inventory.R import com.example.android.inventory.model.Item import com.example.android.inventory.presenter.ItemsActivityPresenter import com.example.android.inventory.presenter.ItemsActivityPresenter.View import com.example.android.inventory.repository.ItemsViewModel import com.example.android.inventory.ui.ItemsRecyclerViewAdapter.ListInteractionListener import com.example.android.inventory.ui.ItemsRecyclerViewAdapter.RecyclerViewResources import com.example.android.inventory.util.StringHelper import com.example.android.inventory.util.setItem import kotlinx.android.synthetic.main.activity_items.* class ItemsActivity : AppCompatActivity(), ListInteractionListener, RecyclerViewResources, View { private lateinit var mViewModel: ItemsViewModel private lateinit var mItemRecyclerViewAdapter: ItemsRecyclerViewAdapter private lateinit var mPresenter: ItemsActivityPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_items) mViewModel = ViewModelProviders.of(this).get(ItemsViewModel::class.java) mItemRecyclerViewAdapter = ItemsRecyclerViewAdapter( mViewModel.getAllItems()?.value?.toMutableList(), this, this ) mPresenter = ItemsActivityPresenter( mRecyclerViewAdapter = mItemRecyclerViewAdapter, mViewModel = mViewModel, mView = this ) rv_items_recycler_view.adapter = mItemRecyclerViewAdapter rv_items_recycler_view.layoutManager = LinearLayoutManager(this) val swipeToDeleteCallback = mPresenter.createSwipeToDeleteCallback() ItemTouchHelper(swipeToDeleteCallback).attachToRecyclerView(rv_items_recycler_view) mViewModel.getAllItems()?.observe(this, Observer { items -> mItemRecyclerViewAdapter.setItems(items) }) fab_add_item.setOnClickListener { val intent = Intent(this@ItemsActivity, ItemActivity::class.java) intent.putExtra(StringHelper.IS_ACTIVITY_FOR_EDIT, false) startActivity(intent) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_items, menu) val deleteAllMenuItem = menu?.findItem(R.id.action_delete_all) mViewModel.getAllItems()?.observe(this, Observer { items -> items?.isNotEmpty()?.let { deleteAllMenuItem?.setEnabled(it) } }) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == R.id.action_delete_all) { mPresenter.confirmDeletion() return true } return super.onOptionsItemSelected(item) } override fun onRecyclerViewItemClickListener(item: Item) { val intent = Intent(this@ItemsActivity, ItemActivity::class.java) intent.setItem(item) intent.putExtra(StringHelper.IS_ACTIVITY_FOR_EDIT, true) startActivity(intent) } override fun showAlertDialogue(message: String, isCancellable: Boolean, positiveButtonClickListener: () -> Unit) { AlertDialog.Builder(this).apply { setMessage(message) setCancelable(isCancellable) setPositiveButton(getString(R.string.yes)) { _, _ -> positiveButtonClickListener() } setNegativeButton(getString(R.string.no)) { dialogue, _ -> dialogue.dismiss() } }.show() } override fun showSnakeBar(text: String, length: Int, callbackOnDismissed: () -> Unit, actionText: String, actionClickListener: () -> Unit) { val callback = SnakeBarCallback(callbackOnDismissed) Snackbar.make(cl_items, text, length).apply { addCallback(callback) setAction(actionText) { [email protected](callback) actionClickListener() } }.show() } }
apache-2.0
121d9f5e4493b5c3f1a9ddc5315263a4
39.0625
144
0.694064
4.934549
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/notifications/manual/models/NotificationProfileSelection.kt
2
5395
package org.thoughtcrime.securesms.components.settings.app.notifications.manual.models import android.view.View import android.widget.TextView import androidx.constraintlayout.widget.Group import com.airbnb.lottie.SimpleColorFilter import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.emoji.EmojiImageView import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.PreferenceModel import org.thoughtcrime.securesms.notifications.profiles.NotificationProfile import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder import org.thoughtcrime.securesms.util.formatHours import org.thoughtcrime.securesms.util.visible import java.time.LocalDateTime import java.time.LocalTime /** * Notification Profile selection preference. */ object NotificationProfileSelection { private const val TOGGLE_EXPANSION = 0 private const val UPDATE_TIMESLOT = 1 fun register(adapter: MappingAdapter) { adapter.registerFactory(New::class.java, LayoutFactory(::NewViewHolder, R.layout.new_notification_profile_pref)) adapter.registerFactory(Entry::class.java, LayoutFactory(::EntryViewHolder, R.layout.notification_profile_entry_pref)) } class Entry( val isOn: Boolean, override val summary: DSLSettingsText, val notificationProfile: NotificationProfile, val isExpanded: Boolean, val timeSlotB: LocalDateTime, val onRowClick: (NotificationProfile) -> Unit, val onTimeSlotAClick: (NotificationProfile) -> Unit, val onTimeSlotBClick: (NotificationProfile, LocalDateTime) -> Unit, val onViewSettingsClick: (NotificationProfile) -> Unit, val onToggleClick: (NotificationProfile) -> Unit ) : PreferenceModel<Entry>() { override fun areItemsTheSame(newItem: Entry): Boolean { return notificationProfile.id == newItem.notificationProfile.id } override fun areContentsTheSame(newItem: Entry): Boolean { return super.areContentsTheSame(newItem) && isOn == newItem.isOn && notificationProfile == newItem.notificationProfile && isExpanded == newItem.isExpanded && timeSlotB == newItem.timeSlotB } override fun getChangePayload(newItem: Entry): Any? { return if (notificationProfile == newItem.notificationProfile && isExpanded != newItem.isExpanded) { TOGGLE_EXPANSION } else if (notificationProfile == newItem.notificationProfile && timeSlotB != newItem.timeSlotB) { UPDATE_TIMESLOT } else { null } } } class EntryViewHolder(itemView: View) : MappingViewHolder<Entry>(itemView) { private val image: EmojiImageView = findViewById(R.id.notification_preference_image) private val chevron: View = findViewById(R.id.notification_preference_chevron) private val name: TextView = findViewById(R.id.notification_preference_name) private val status: TextView = findViewById(R.id.notification_preference_status) private val expansion: Group = findViewById(R.id.notification_preference_expanded) private val timeSlotA: TextView = findViewById(R.id.notification_preference_1hr) private val timeSlotB: TextView = findViewById(R.id.notification_preference_6pm) private val viewSettings: View = findViewById(R.id.notification_preference_view_settings) override fun bind(model: Entry) { itemView.setOnClickListener { model.onRowClick(model.notificationProfile) } chevron.setOnClickListener { model.onToggleClick(model.notificationProfile) } chevron.rotation = if (model.isExpanded) 180f else 0f timeSlotA.setOnClickListener { model.onTimeSlotAClick(model.notificationProfile) } timeSlotB.setOnClickListener { model.onTimeSlotBClick(model.notificationProfile, model.timeSlotB) } viewSettings.setOnClickListener { model.onViewSettingsClick(model.notificationProfile) } expansion.visible = model.isExpanded timeSlotB.text = context.getString( R.string.NotificationProfileSelection__until_s, LocalTime.from(model.timeSlotB).formatHours(context) ) if (TOGGLE_EXPANSION in payload || UPDATE_TIMESLOT in payload) { return } image.background.colorFilter = SimpleColorFilter(model.notificationProfile.color.colorInt()) if (model.notificationProfile.emoji.isNotEmpty()) { image.setImageEmoji(model.notificationProfile.emoji) } else { image.setImageResource(R.drawable.ic_moon_24) } name.text = model.notificationProfile.name presentStatus(model) timeSlotB.text = context.getString( R.string.NotificationProfileSelection__until_s, LocalTime.from(model.timeSlotB).formatHours(context) ) itemView.isSelected = model.isOn } private fun presentStatus(model: Entry) { status.isEnabled = model.isOn status.text = model.summary.resolve(context) } } class New(val onClick: () -> Unit) : PreferenceModel<New>() { override fun areItemsTheSame(newItem: New): Boolean { return true } } class NewViewHolder(itemView: View) : MappingViewHolder<New>(itemView) { override fun bind(model: New) { itemView.setOnClickListener { model.onClick() } } } }
gpl-3.0
0ffba44915df113c667ec01bf74d53ac
39.261194
122
0.747915
4.533613
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/megaphone/MegaphoneText.kt
2
714
package org.thoughtcrime.securesms.megaphone import android.content.Context import androidx.annotation.StringRes /** * Allows setting of megaphone text by string resource or string literal. */ data class MegaphoneText(@StringRes private val stringRes: Int = 0, private val string: String? = null) { @get:JvmName("hasText") val hasText = stringRes != 0 || string != null fun resolve(context: Context): String? { return if (stringRes != 0) context.getString(stringRes) else string } companion object { @JvmStatic fun from(@StringRes stringRes: Int): MegaphoneText = MegaphoneText(stringRes) @JvmStatic fun from(string: String): MegaphoneText = MegaphoneText(string = string) } }
gpl-3.0
7b5a6e2818c0255608e8704bd5c0549c
30.043478
105
0.731092
3.880435
false
false
false
false
jk1/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInstaller.kt
1
5922
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl import com.intellij.ide.IdeBundle import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ArrayUtil import com.intellij.util.Restarter import com.intellij.util.io.HttpRequests import java.io.File import java.io.IOException import java.net.URL import java.nio.file.Files import java.nio.file.Paths import javax.swing.UIManager object UpdateInstaller { private val patchesUrl: String get() = System.getProperty("idea.patches.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.patchesUrl @JvmStatic @Throws(IOException::class) fun downloadPatchFile(patch: PatchInfo, toBuild: BuildNumber, forceHttps: Boolean, indicator: ProgressIndicator): File { indicator.text = IdeBundle.message("update.downloading.patch.progress") val product = ApplicationInfo.getInstance().build.productCode val from = patch.fromBuild.asStringWithoutProductCode() val to = toBuild.asStringWithoutProductCode() val jdk = if (System.getProperty("idea.java.redist", "").lastIndexOf("NoJavaDistribution") >= 0) "-no-jdk" else "" val patchName = "${product}-${from}-${to}-patch${jdk}-${patch.osSuffix}.jar" val baseUrl = patchesUrl val url = URL(URL(if (baseUrl.endsWith('/')) baseUrl else "${baseUrl}/"), patchName) val patchFile = File(getTempDir(), "patch.jar") HttpRequests.request(url.toString()).gzip(false).forceHttps(forceHttps).saveToFile(patchFile, indicator) return patchFile } @JvmStatic fun installPluginUpdates(downloaders: Collection<PluginDownloader>, indicator: ProgressIndicator): Boolean { indicator.text = IdeBundle.message("update.downloading.plugins.progress") UpdateChecker.saveDisabledToUpdatePlugins() val disabledToUpdate = UpdateChecker.disabledToUpdatePlugins val readyToInstall = mutableListOf<PluginDownloader>() for (downloader in downloaders) { try { if (downloader.pluginId !in disabledToUpdate && downloader.prepareToInstall(indicator)) { readyToInstall += downloader } indicator.checkCanceled() } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } var installed = false ProgressManager.getInstance().executeNonCancelableSection { for (downloader in readyToInstall) { try { downloader.install() installed = true } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } } return installed } @JvmStatic fun cleanupPatch() { val tempDir = getTempDir() if (tempDir.exists()) FileUtil.delete(tempDir) } @JvmStatic @Throws(IOException::class) fun preparePatchCommand(patchFile: File): Array<String> { val log4j = findLib("log4j.jar") val jna = findLib("jna.jar") val jnaUtils = findLib("jna-platform.jar") val tempDir = getTempDir() if (FileUtil.isAncestor(PathManager.getHomePath(), tempDir.path, true)) { throw IOException("Temp directory inside installation: $tempDir") } if (!(tempDir.exists() || tempDir.mkdirs())) { throw IOException("Cannot create temp directory: $tempDir") } val log4jCopy = log4j.copyTo(File(tempDir, log4j.name), true) val jnaCopy = jna.copyTo(File(tempDir, jna.name), true) val jnaUtilsCopy = jnaUtils.copyTo(File(tempDir, jnaUtils.name), true) var java = System.getProperty("java.home") if (FileUtil.isAncestor(PathManager.getHomePath(), java, true)) { val javaCopy = File(tempDir, "jre") FileUtil.copyDir(File(java), javaCopy) java = javaCopy.path } val args = arrayListOf<String>() if (SystemInfo.isWindows && !Files.isWritable(Paths.get(PathManager.getHomePath()))) { val launcher = PathManager.findBinFile("launcher.exe") val elevator = PathManager.findBinFile("elevator.exe") // "launcher" depends on "elevator" if (launcher != null && elevator != null && launcher.canExecute() && elevator.canExecute()) { args += Restarter.createTempExecutable(launcher).path Restarter.createTempExecutable(elevator) } } args += File(java, if (SystemInfo.isWindows) "bin\\java.exe" else "bin/java").path args += "-Xmx750m" args += "-cp" args += arrayOf(patchFile.path, log4jCopy.path, jnaCopy.path, jnaUtilsCopy.path).joinToString(File.pathSeparator) args += "-Djna.nosys=true" args += "-Djna.boot.library.path=" args += "-Djna.debug_load=true" args += "-Djna.debug_load.jna=true" args += "-Djava.io.tmpdir=${tempDir.path}" args += "-Didea.updater.log=${PathManager.getLogPath()}" args += "-Dswing.defaultlaf=${UIManager.getSystemLookAndFeelClassName()}" args += "com.intellij.updater.Runner" args += "install" args += PathManager.getHomePath() return ArrayUtil.toStringArray(args) } private fun findLib(libName: String): File { val libFile = File(PathManager.getLibPath(), libName) return if (libFile.exists()) libFile else throw IOException("Missing: ${libFile}") } private fun getTempDir() = File(PathManager.getTempPath(), "patch-update") }
apache-2.0
3f0320eddcace4546e605edb01a6860f
36.726115
140
0.702297
4.285094
false
false
false
false
NiciDieNase/chaosflix
common/src/main/java/de/nicidienase/chaosflix/common/viewmodel/BrowseViewModel.kt
1
5841
package de.nicidienase.chaosflix.common.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.nicidienase.chaosflix.R import de.nicidienase.chaosflix.common.ChaosflixDatabase import de.nicidienase.chaosflix.common.OfflineItemManager import de.nicidienase.chaosflix.common.PreferencesManager import de.nicidienase.chaosflix.common.ResourcesFacade import de.nicidienase.chaosflix.common.mediadata.MediaRepository import de.nicidienase.chaosflix.common.mediadata.StreamingRepository import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Conference import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.ConferenceGroup import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event import de.nicidienase.chaosflix.common.mediadata.entities.streaming.LiveConference import de.nicidienase.chaosflix.common.util.LiveDataMerger import de.nicidienase.chaosflix.common.util.LiveEvent import de.nicidienase.chaosflix.common.util.SingleLiveEvent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class BrowseViewModel( val offlineItemManager: OfflineItemManager, private val mediaRepository: MediaRepository, private val database: ChaosflixDatabase, private val streamingRepository: StreamingRepository, private val preferencesManager: PreferencesManager, private val resources: ResourcesFacade ) : ViewModel() { val state: SingleLiveEvent<LiveEvent<State, Event, String>> = SingleLiveEvent() enum class State { ShowEventDetails } init { viewModelScope.launch { val downloadRefs: List<Long> = mediaRepository.getAllOfflineEvents() offlineItemManager.addDownloadRefs(downloadRefs) } } fun getConferenceGroups(): LiveData<List<ConferenceGroup>> = database.conferenceGroupDao().getAll() fun getConferencesByGroup(groupId: Long) = database.conferenceDao().findConferenceByGroup(groupId) fun getEventsforConference(conference: Conference): LiveData<List<Event>> = database.eventDao().getEventsWithConferenceForConfernce(conference.id) fun getUpdateState() = mediaRepository.updateConferencesAndGroups() fun updateEventsForConference(conference: Conference): LiveData<LiveEvent<MediaRepository.State, List<Event>, String>> = LiveDataMerger<List<Event>, LiveEvent<MediaRepository.State, List<Event>, String>, LiveEvent<MediaRepository.State, List<Event>, String>>() .merge( getEventsforConference(conference), mediaRepository.updateEventsForConference(conference) ) { list: List<Event>?, liveEvent: LiveEvent<MediaRepository.State, List<Event>, String>? -> return@merge LiveEvent(liveEvent?.state ?: MediaRepository.State.DONE, list ?: liveEvent?.data, liveEvent?.error) } fun getBookmarkedEvents(): LiveData<List<Event>> { val itemDao = database.watchlistItemDao() viewModelScope.launch(Dispatchers.IO) { itemDao.getAllSync().forEach { mediaRepository.updateSingleEvent(it.eventGuid) } } return itemDao.getWatchlistEvents() } @JvmOverloads fun getInProgressEvents(filterFinished: Boolean = false): LiveData<List<Event>> { val dao = database.playbackProgressDao() viewModelScope.launch(Dispatchers.IO) { dao.getAllSync().forEach { mediaRepository.updateSingleEvent(it.eventGuid) } } return Transformations.map(dao.getAllWithEvent()) { list -> return@map if (filterFinished) { val result = list.partition { it.progress.progress / 1000 + 10 < it.event?.length ?: 0 } Log.i(TAG, "Could not load events for ${list.filter { it.event == null }.map{it.progress.eventGuid}}") Log.i(TAG, "Filtered ${result.first.size} finished items: ${result.first.map { "${it.progress.progress / 1000}-${it.event?.length}|" }}") result.second.mapNotNull { it.event.apply { it.event?.progress = it.progress.progress } } } else { list.mapNotNull { it.event?.apply { it.event?.progress = it.progress.progress } } } } } fun getPromotedEvents(): LiveData<List<Event>> = database.eventDao().findPromotedEvents() fun getLivestreams(): LiveData<List<LiveConference>> = streamingRepository.streamingConferences fun updateLiveStreams() = viewModelScope.launch { streamingRepository.update() } fun getOfflineDisplayEvents() = database.offlineEventDao().getOfflineEventsDisplay() fun updateDownloadStatus() = viewModelScope.launch(Dispatchers.IO) { offlineItemManager.updateDownloadStatus(database.offlineEventDao().getAllSync()) } fun showDetailsForEvent(guid: String) = viewModelScope.launch(Dispatchers.IO) { val event = database.eventDao().findEventByGuidSync(guid) if (event != null) { state.postValue(LiveEvent(State.ShowEventDetails, event)) } else { state.postValue(LiveEvent(State.ShowEventDetails, error = resources.getString(R.string.error_event_not_found))) } } fun deleteOfflineItem(guid: String) { viewModelScope.launch(Dispatchers.IO) { offlineItemManager.deleteOfflineItem(guid) } } fun getAutoselectStream() = preferencesManager.autoselectStream companion object { private val TAG = BrowseViewModel::class.simpleName } }
mit
35371664c9e5c1e5975b89b8169205f8
42.917293
153
0.70416
4.827273
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/badges/gifts/flow/GiftFlowViewModel.kt
1
8392
package org.thoughtcrime.securesms.badges.gifts.flow import android.content.Intent import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.google.android.gms.wallet.PaymentData import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import io.reactivex.rxjava3.subjects.PublishSubject import org.signal.core.util.logging.Log import org.signal.core.util.money.FiatMoney import org.signal.donations.GooglePayApi import org.thoughtcrime.securesms.badges.gifts.Gifts import org.thoughtcrime.securesms.badges.models.Badge import org.thoughtcrime.securesms.components.settings.app.subscription.DonationEvent import org.thoughtcrime.securesms.components.settings.app.subscription.DonationPaymentRepository import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationError import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationErrorSource import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.InternetConnectionObserver import org.thoughtcrime.securesms.util.rx.RxStore import java.util.Currency /** * Maintains state as a user works their way through the gift flow. */ class GiftFlowViewModel( val repository: GiftFlowRepository, val donationPaymentRepository: DonationPaymentRepository ) : ViewModel() { private var giftToPurchase: Gift? = null private val store = RxStore( GiftFlowState( currency = SignalStore.donationsValues().getOneTimeCurrency() ) ) private val disposables = CompositeDisposable() private val eventPublisher: PublishSubject<DonationEvent> = PublishSubject.create() private val networkDisposable: Disposable val state: Flowable<GiftFlowState> = store.stateFlowable val events: Observable<DonationEvent> = eventPublisher val snapshot: GiftFlowState get() = store.state init { refresh() networkDisposable = InternetConnectionObserver .observe() .distinctUntilChanged() .subscribe { isConnected -> if (isConnected) { retry() } } } fun retry() { if (!disposables.isDisposed && store.state.stage == GiftFlowState.Stage.FAILURE) { store.update { it.copy(stage = GiftFlowState.Stage.INIT) } refresh() } } fun refresh() { disposables.clear() disposables += SignalStore.donationsValues().observableOneTimeCurrency.subscribe { currency -> store.update { it.copy( currency = currency ) } } disposables += repository.getGiftPricing().subscribe { giftPrices -> store.update { it.copy( giftPrices = giftPrices, stage = getLoadState(it, giftPrices = giftPrices) ) } } disposables += repository.getGiftBadge().subscribeBy( onSuccess = { (giftLevel, giftBadge) -> store.update { it.copy( giftLevel = giftLevel, giftBadge = giftBadge, stage = getLoadState(it, giftBadge = giftBadge) ) } }, onError = { throwable -> Log.w(TAG, "Could not load gift badge", throwable) store.update { it.copy( stage = GiftFlowState.Stage.FAILURE ) } } ) } override fun onCleared() { disposables.clear() } fun setSelectedContact(selectedContact: ContactSearchKey.RecipientSearchKey) { store.update { it.copy(recipient = Recipient.resolved(selectedContact.recipientId)) } } fun getSupportedCurrencyCodes(): List<String> { return store.state.giftPrices.keys.map { it.currencyCode } } fun requestTokenFromGooglePay(label: String) { val giftLevel = store.state.giftLevel ?: return val giftPrice = store.state.giftPrices[store.state.currency] ?: return val giftRecipient = store.state.recipient?.id ?: return this.giftToPurchase = Gift(giftLevel, giftPrice) store.update { it.copy(stage = GiftFlowState.Stage.RECIPIENT_VERIFICATION) } disposables += donationPaymentRepository.verifyRecipientIsAllowedToReceiveAGift(giftRecipient) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onComplete = { store.update { it.copy(stage = GiftFlowState.Stage.TOKEN_REQUEST) } donationPaymentRepository.requestTokenFromGooglePay(giftToPurchase!!.price, label, Gifts.GOOGLE_PAY_REQUEST_CODE) }, onError = this::onPaymentFlowError ) } fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent? ) { val gift = giftToPurchase giftToPurchase = null val recipient = store.state.recipient?.id donationPaymentRepository.onActivityResult( requestCode, resultCode, data, Gifts.GOOGLE_PAY_REQUEST_CODE, object : GooglePayApi.PaymentRequestCallback { override fun onSuccess(paymentData: PaymentData) { if (gift != null && recipient != null) { eventPublisher.onNext(DonationEvent.RequestTokenSuccess) store.update { it.copy(stage = GiftFlowState.Stage.PAYMENT_PIPELINE) } donationPaymentRepository.continuePayment(gift.price, paymentData, recipient, store.state.additionalMessage?.toString(), gift.level).subscribeBy( onError = this@GiftFlowViewModel::onPaymentFlowError, onComplete = { store.update { it.copy(stage = GiftFlowState.Stage.READY) } eventPublisher.onNext(DonationEvent.PaymentConfirmationSuccess(store.state.giftBadge!!)) } ) } else { store.update { it.copy(stage = GiftFlowState.Stage.READY) } } } override fun onError(googlePayException: GooglePayApi.GooglePayException) { store.update { it.copy(stage = GiftFlowState.Stage.READY) } DonationError.routeDonationError(ApplicationDependencies.getApplication(), DonationError.getGooglePayRequestTokenError(DonationErrorSource.GIFT, googlePayException)) } override fun onCancelled() { store.update { it.copy(stage = GiftFlowState.Stage.READY) } } } ) } private fun onPaymentFlowError(throwable: Throwable) { store.update { it.copy(stage = GiftFlowState.Stage.READY) } val donationError: DonationError = if (throwable is DonationError) { throwable } else { Log.w(TAG, "Failed to complete payment or redemption", throwable, true) DonationError.genericBadgeRedemptionFailure(DonationErrorSource.GIFT) } DonationError.routeDonationError(ApplicationDependencies.getApplication(), donationError) } private fun getLoadState( oldState: GiftFlowState, giftPrices: Map<Currency, FiatMoney>? = null, giftBadge: Badge? = null, ): GiftFlowState.Stage { if (oldState.stage != GiftFlowState.Stage.INIT) { return oldState.stage } if (giftPrices?.isNotEmpty() == true) { return if (oldState.giftBadge != null) { GiftFlowState.Stage.READY } else { GiftFlowState.Stage.INIT } } if (giftBadge != null) { return if (oldState.giftPrices.isNotEmpty()) { GiftFlowState.Stage.READY } else { GiftFlowState.Stage.INIT } } return GiftFlowState.Stage.INIT } fun setAdditionalMessage(additionalMessage: CharSequence) { store.update { it.copy(additionalMessage = additionalMessage) } } companion object { private val TAG = Log.tag(GiftFlowViewModel::class.java) } class Factory( private val repository: GiftFlowRepository, private val donationPaymentRepository: DonationPaymentRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast( GiftFlowViewModel( repository, donationPaymentRepository ) ) as T } } }
gpl-3.0
bab2b1c18711313eef00aa5add4e7e7c
32.434263
175
0.703885
4.480513
false
false
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Byte/MutableByteVec3.kt
1
28882
package glm data class MutableByteVec3(var x: Byte, var y: Byte, var z: Byte) { // Initializes each element by evaluating init from 0 until 2 constructor(init: (Int) -> Byte) : this(init(0), init(1), init(2)) operator fun get(idx: Int): Byte = when (idx) { 0 -> x 1 -> y 2 -> z else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } operator fun set(idx: Int, value: Byte) = when (idx) { 0 -> x = value 1 -> y = value 2 -> z = value else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators operator fun inc(): MutableByteVec3 = MutableByteVec3(x.inc(), y.inc(), z.inc()) operator fun dec(): MutableByteVec3 = MutableByteVec3(x.dec(), y.dec(), z.dec()) operator fun unaryPlus(): MutableIntVec3 = MutableIntVec3(+x, +y, +z) operator fun unaryMinus(): MutableIntVec3 = MutableIntVec3(-x, -y, -z) operator fun plus(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(x + rhs.x, y + rhs.y, z + rhs.z) operator fun minus(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(x - rhs.x, y - rhs.y, z - rhs.z) operator fun times(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(x * rhs.x, y * rhs.y, z * rhs.z) operator fun div(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(x / rhs.x, y / rhs.y, z / rhs.z) operator fun rem(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(x % rhs.x, y % rhs.y, z % rhs.z) operator fun plus(rhs: Byte): MutableIntVec3 = MutableIntVec3(x + rhs, y + rhs, z + rhs) operator fun minus(rhs: Byte): MutableIntVec3 = MutableIntVec3(x - rhs, y - rhs, z - rhs) operator fun times(rhs: Byte): MutableIntVec3 = MutableIntVec3(x * rhs, y * rhs, z * rhs) operator fun div(rhs: Byte): MutableIntVec3 = MutableIntVec3(x / rhs, y / rhs, z / rhs) operator fun rem(rhs: Byte): MutableIntVec3 = MutableIntVec3(x % rhs, y % rhs, z % rhs) inline fun map(func: (Byte) -> Byte): MutableByteVec3 = MutableByteVec3(func(x), func(y), func(z)) fun toList(): List<Byte> = listOf(x, y, z) // Predefined vector constants companion object Constants { val zero: MutableByteVec3 get() = MutableByteVec3(0.toByte(), 0.toByte(), 0.toByte()) val ones: MutableByteVec3 get() = MutableByteVec3(1.toByte(), 1.toByte(), 1.toByte()) val unitX: MutableByteVec3 get() = MutableByteVec3(1.toByte(), 0.toByte(), 0.toByte()) val unitY: MutableByteVec3 get() = MutableByteVec3(0.toByte(), 1.toByte(), 0.toByte()) val unitZ: MutableByteVec3 get() = MutableByteVec3(0.toByte(), 0.toByte(), 1.toByte()) } // Conversions to Float fun toVec(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toVec(conv: (Byte) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat()) inline fun toVec2(conv: (Byte) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toVec3(conv: (Byte) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec4(w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w) inline fun toVec4(w: Float = 0f, conv: (Byte) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w) // Conversions to Float fun toMutableVec(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toMutableVec(conv: (Byte) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat()) inline fun toMutableVec2(conv: (Byte) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toMutableVec3(conv: (Byte) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w) inline fun toMutableVec4(w: Float = 0f, conv: (Byte) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toDoubleVec(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toDoubleVec(conv: (Byte) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble()) inline fun toDoubleVec2(conv: (Byte) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toDoubleVec3(conv: (Byte) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w) inline fun toDoubleVec4(w: Double = 0.0, conv: (Byte) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toMutableDoubleVec(conv: (Byte) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble()) inline fun toMutableDoubleVec2(conv: (Byte) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toMutableDoubleVec3(conv: (Byte) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w) inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Byte) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toIntVec(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toIntVec(conv: (Byte) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt()) inline fun toIntVec2(conv: (Byte) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toIntVec3(conv: (Byte) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w) inline fun toIntVec4(w: Int = 0, conv: (Byte) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toMutableIntVec(conv: (Byte) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt()) inline fun toMutableIntVec2(conv: (Byte) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toMutableIntVec3(conv: (Byte) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w) inline fun toMutableIntVec4(w: Int = 0, conv: (Byte) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toLongVec(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toLongVec(conv: (Byte) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec2(conv: (Byte) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toLongVec3(conv: (Byte) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w) inline fun toLongVec4(w: Long = 0L, conv: (Byte) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toMutableLongVec(conv: (Byte) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec2(conv: (Byte) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toMutableLongVec3(conv: (Byte) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w) inline fun toMutableLongVec4(w: Long = 0L, conv: (Byte) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toShortVec(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toShortVec(conv: (Byte) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec2(conv: (Byte) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toShortVec3(conv: (Byte) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w) inline fun toShortVec4(w: Short = 0.toShort(), conv: (Byte) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toMutableShortVec(conv: (Byte) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec2(conv: (Byte) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toMutableShortVec3(conv: (Byte) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w) inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Byte) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toByteVec(): ByteVec3 = ByteVec3(x, y, z) inline fun toByteVec(conv: (Byte) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec2(): ByteVec2 = ByteVec2(x, y) inline fun toByteVec2(conv: (Byte) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec3(): ByteVec3 = ByteVec3(x, y, z) inline fun toByteVec3(conv: (Byte) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x, y, z, w) inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Byte) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(x, y, z) inline fun toMutableByteVec(conv: (Byte) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x, y) inline fun toMutableByteVec2(conv: (Byte) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x, y, z) inline fun toMutableByteVec3(conv: (Byte) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x, y, z, w) inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Byte) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Char fun toCharVec(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toCharVec(conv: (Byte) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec2(conv: (Byte) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toCharVec3(conv: (Byte) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) fun toCharVec4(w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w) inline fun toCharVec4(w: Char, conv: (Byte) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w) // Conversions to Char fun toMutableCharVec(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toMutableCharVec(conv: (Byte) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec2(conv: (Byte) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toMutableCharVec3(conv: (Byte) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) fun toMutableCharVec4(w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w) inline fun toMutableCharVec4(w: Char, conv: (Byte) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toBoolVec(): BoolVec3 = BoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toBoolVec(conv: (Byte) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.toByte(), y != 0.toByte()) inline fun toBoolVec2(conv: (Byte) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toBoolVec3(conv: (Byte) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w) inline fun toBoolVec4(w: Boolean = false, conv: (Byte) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toMutableBoolVec(conv: (Byte) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.toByte(), y != 0.toByte()) inline fun toMutableBoolVec2(conv: (Byte) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toMutableBoolVec3(conv: (Byte) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w) inline fun toMutableBoolVec4(w: Boolean = false, conv: (Byte) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec(conv: (Byte) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (Byte) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec3(conv: (Byte) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toStringVec4(w: String = "", conv: (Byte) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec(conv: (Byte) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (Byte) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec3(conv: (Byte) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toMutableStringVec4(w: String = "", conv: (Byte) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toTVec(conv: (Byte) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec2(conv: (Byte) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(conv: (Byte) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec4(w: T2, conv: (Byte) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (Byte) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec2(conv: (Byte) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(conv: (Byte) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec4(w: T2, conv: (Byte) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: MutableByteVec2 get() = MutableByteVec2(x, x) var xy: MutableByteVec2 get() = MutableByteVec2(x, y) set(value) { x = value.x y = value.y } var xz: MutableByteVec2 get() = MutableByteVec2(x, z) set(value) { x = value.x z = value.y } var yx: MutableByteVec2 get() = MutableByteVec2(y, x) set(value) { y = value.x x = value.y } val yy: MutableByteVec2 get() = MutableByteVec2(y, y) var yz: MutableByteVec2 get() = MutableByteVec2(y, z) set(value) { y = value.x z = value.y } var zx: MutableByteVec2 get() = MutableByteVec2(z, x) set(value) { z = value.x x = value.y } var zy: MutableByteVec2 get() = MutableByteVec2(z, y) set(value) { z = value.x y = value.y } val zz: MutableByteVec2 get() = MutableByteVec2(z, z) val xxx: MutableByteVec3 get() = MutableByteVec3(x, x, x) val xxy: MutableByteVec3 get() = MutableByteVec3(x, x, y) val xxz: MutableByteVec3 get() = MutableByteVec3(x, x, z) val xyx: MutableByteVec3 get() = MutableByteVec3(x, y, x) val xyy: MutableByteVec3 get() = MutableByteVec3(x, y, y) var xyz: MutableByteVec3 get() = MutableByteVec3(x, y, z) set(value) { x = value.x y = value.y z = value.z } val xzx: MutableByteVec3 get() = MutableByteVec3(x, z, x) var xzy: MutableByteVec3 get() = MutableByteVec3(x, z, y) set(value) { x = value.x z = value.y y = value.z } val xzz: MutableByteVec3 get() = MutableByteVec3(x, z, z) val yxx: MutableByteVec3 get() = MutableByteVec3(y, x, x) val yxy: MutableByteVec3 get() = MutableByteVec3(y, x, y) var yxz: MutableByteVec3 get() = MutableByteVec3(y, x, z) set(value) { y = value.x x = value.y z = value.z } val yyx: MutableByteVec3 get() = MutableByteVec3(y, y, x) val yyy: MutableByteVec3 get() = MutableByteVec3(y, y, y) val yyz: MutableByteVec3 get() = MutableByteVec3(y, y, z) var yzx: MutableByteVec3 get() = MutableByteVec3(y, z, x) set(value) { y = value.x z = value.y x = value.z } val yzy: MutableByteVec3 get() = MutableByteVec3(y, z, y) val yzz: MutableByteVec3 get() = MutableByteVec3(y, z, z) val zxx: MutableByteVec3 get() = MutableByteVec3(z, x, x) var zxy: MutableByteVec3 get() = MutableByteVec3(z, x, y) set(value) { z = value.x x = value.y y = value.z } val zxz: MutableByteVec3 get() = MutableByteVec3(z, x, z) var zyx: MutableByteVec3 get() = MutableByteVec3(z, y, x) set(value) { z = value.x y = value.y x = value.z } val zyy: MutableByteVec3 get() = MutableByteVec3(z, y, y) val zyz: MutableByteVec3 get() = MutableByteVec3(z, y, z) val zzx: MutableByteVec3 get() = MutableByteVec3(z, z, x) val zzy: MutableByteVec3 get() = MutableByteVec3(z, z, y) val zzz: MutableByteVec3 get() = MutableByteVec3(z, z, z) val xxxx: MutableByteVec4 get() = MutableByteVec4(x, x, x, x) val xxxy: MutableByteVec4 get() = MutableByteVec4(x, x, x, y) val xxxz: MutableByteVec4 get() = MutableByteVec4(x, x, x, z) val xxyx: MutableByteVec4 get() = MutableByteVec4(x, x, y, x) val xxyy: MutableByteVec4 get() = MutableByteVec4(x, x, y, y) val xxyz: MutableByteVec4 get() = MutableByteVec4(x, x, y, z) val xxzx: MutableByteVec4 get() = MutableByteVec4(x, x, z, x) val xxzy: MutableByteVec4 get() = MutableByteVec4(x, x, z, y) val xxzz: MutableByteVec4 get() = MutableByteVec4(x, x, z, z) val xyxx: MutableByteVec4 get() = MutableByteVec4(x, y, x, x) val xyxy: MutableByteVec4 get() = MutableByteVec4(x, y, x, y) val xyxz: MutableByteVec4 get() = MutableByteVec4(x, y, x, z) val xyyx: MutableByteVec4 get() = MutableByteVec4(x, y, y, x) val xyyy: MutableByteVec4 get() = MutableByteVec4(x, y, y, y) val xyyz: MutableByteVec4 get() = MutableByteVec4(x, y, y, z) val xyzx: MutableByteVec4 get() = MutableByteVec4(x, y, z, x) val xyzy: MutableByteVec4 get() = MutableByteVec4(x, y, z, y) val xyzz: MutableByteVec4 get() = MutableByteVec4(x, y, z, z) val xzxx: MutableByteVec4 get() = MutableByteVec4(x, z, x, x) val xzxy: MutableByteVec4 get() = MutableByteVec4(x, z, x, y) val xzxz: MutableByteVec4 get() = MutableByteVec4(x, z, x, z) val xzyx: MutableByteVec4 get() = MutableByteVec4(x, z, y, x) val xzyy: MutableByteVec4 get() = MutableByteVec4(x, z, y, y) val xzyz: MutableByteVec4 get() = MutableByteVec4(x, z, y, z) val xzzx: MutableByteVec4 get() = MutableByteVec4(x, z, z, x) val xzzy: MutableByteVec4 get() = MutableByteVec4(x, z, z, y) val xzzz: MutableByteVec4 get() = MutableByteVec4(x, z, z, z) val yxxx: MutableByteVec4 get() = MutableByteVec4(y, x, x, x) val yxxy: MutableByteVec4 get() = MutableByteVec4(y, x, x, y) val yxxz: MutableByteVec4 get() = MutableByteVec4(y, x, x, z) val yxyx: MutableByteVec4 get() = MutableByteVec4(y, x, y, x) val yxyy: MutableByteVec4 get() = MutableByteVec4(y, x, y, y) val yxyz: MutableByteVec4 get() = MutableByteVec4(y, x, y, z) val yxzx: MutableByteVec4 get() = MutableByteVec4(y, x, z, x) val yxzy: MutableByteVec4 get() = MutableByteVec4(y, x, z, y) val yxzz: MutableByteVec4 get() = MutableByteVec4(y, x, z, z) val yyxx: MutableByteVec4 get() = MutableByteVec4(y, y, x, x) val yyxy: MutableByteVec4 get() = MutableByteVec4(y, y, x, y) val yyxz: MutableByteVec4 get() = MutableByteVec4(y, y, x, z) val yyyx: MutableByteVec4 get() = MutableByteVec4(y, y, y, x) val yyyy: MutableByteVec4 get() = MutableByteVec4(y, y, y, y) val yyyz: MutableByteVec4 get() = MutableByteVec4(y, y, y, z) val yyzx: MutableByteVec4 get() = MutableByteVec4(y, y, z, x) val yyzy: MutableByteVec4 get() = MutableByteVec4(y, y, z, y) val yyzz: MutableByteVec4 get() = MutableByteVec4(y, y, z, z) val yzxx: MutableByteVec4 get() = MutableByteVec4(y, z, x, x) val yzxy: MutableByteVec4 get() = MutableByteVec4(y, z, x, y) val yzxz: MutableByteVec4 get() = MutableByteVec4(y, z, x, z) val yzyx: MutableByteVec4 get() = MutableByteVec4(y, z, y, x) val yzyy: MutableByteVec4 get() = MutableByteVec4(y, z, y, y) val yzyz: MutableByteVec4 get() = MutableByteVec4(y, z, y, z) val yzzx: MutableByteVec4 get() = MutableByteVec4(y, z, z, x) val yzzy: MutableByteVec4 get() = MutableByteVec4(y, z, z, y) val yzzz: MutableByteVec4 get() = MutableByteVec4(y, z, z, z) val zxxx: MutableByteVec4 get() = MutableByteVec4(z, x, x, x) val zxxy: MutableByteVec4 get() = MutableByteVec4(z, x, x, y) val zxxz: MutableByteVec4 get() = MutableByteVec4(z, x, x, z) val zxyx: MutableByteVec4 get() = MutableByteVec4(z, x, y, x) val zxyy: MutableByteVec4 get() = MutableByteVec4(z, x, y, y) val zxyz: MutableByteVec4 get() = MutableByteVec4(z, x, y, z) val zxzx: MutableByteVec4 get() = MutableByteVec4(z, x, z, x) val zxzy: MutableByteVec4 get() = MutableByteVec4(z, x, z, y) val zxzz: MutableByteVec4 get() = MutableByteVec4(z, x, z, z) val zyxx: MutableByteVec4 get() = MutableByteVec4(z, y, x, x) val zyxy: MutableByteVec4 get() = MutableByteVec4(z, y, x, y) val zyxz: MutableByteVec4 get() = MutableByteVec4(z, y, x, z) val zyyx: MutableByteVec4 get() = MutableByteVec4(z, y, y, x) val zyyy: MutableByteVec4 get() = MutableByteVec4(z, y, y, y) val zyyz: MutableByteVec4 get() = MutableByteVec4(z, y, y, z) val zyzx: MutableByteVec4 get() = MutableByteVec4(z, y, z, x) val zyzy: MutableByteVec4 get() = MutableByteVec4(z, y, z, y) val zyzz: MutableByteVec4 get() = MutableByteVec4(z, y, z, z) val zzxx: MutableByteVec4 get() = MutableByteVec4(z, z, x, x) val zzxy: MutableByteVec4 get() = MutableByteVec4(z, z, x, y) val zzxz: MutableByteVec4 get() = MutableByteVec4(z, z, x, z) val zzyx: MutableByteVec4 get() = MutableByteVec4(z, z, y, x) val zzyy: MutableByteVec4 get() = MutableByteVec4(z, z, y, y) val zzyz: MutableByteVec4 get() = MutableByteVec4(z, z, y, z) val zzzx: MutableByteVec4 get() = MutableByteVec4(z, z, z, x) val zzzy: MutableByteVec4 get() = MutableByteVec4(z, z, z, y) val zzzz: MutableByteVec4 get() = MutableByteVec4(z, z, z, z) } val swizzle: Swizzle get() = Swizzle() } fun mutableVecOf(x: Byte, y: Byte, z: Byte): MutableByteVec3 = MutableByteVec3(x, y, z) operator fun Byte.plus(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(this + rhs.x, this + rhs.y, this + rhs.z) operator fun Byte.minus(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(this - rhs.x, this - rhs.y, this - rhs.z) operator fun Byte.times(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(this * rhs.x, this * rhs.y, this * rhs.z) operator fun Byte.div(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(this / rhs.x, this / rhs.y, this / rhs.z) operator fun Byte.rem(rhs: MutableByteVec3): MutableIntVec3 = MutableIntVec3(this % rhs.x, this % rhs.y, this % rhs.z)
mit
5015a5ea8722f56c3e1c00b053d8bd73
64.343891
147
0.633509
3.578934
false
false
false
false
oldergod/android-architecture
app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksScreenTest.kt
1
17305
/* * Copyright 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 com.example.android.architecture.blueprints.todoapp.tasks import android.support.test.InstrumentationRegistry import android.support.test.InstrumentationRegistry.getTargetContext import android.support.test.espresso.Espresso.onView import android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.action.ViewActions.closeSoftKeyboard import android.support.test.espresso.action.ViewActions.replaceText import android.support.test.espresso.action.ViewActions.typeText import android.support.test.espresso.assertion.ViewAssertions.doesNotExist import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.matcher.ViewMatchers.hasSibling import android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom import android.support.test.espresso.matcher.ViewMatchers.isChecked import android.support.test.espresso.matcher.ViewMatchers.isDescendantOfA import android.support.test.espresso.matcher.ViewMatchers.isDisplayed import android.support.test.espresso.matcher.ViewMatchers.withContentDescription import android.support.test.espresso.matcher.ViewMatchers.withId import android.support.test.espresso.matcher.ViewMatchers.withText import android.support.test.filters.LargeTest import android.support.test.filters.SdkSuppress import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.view.View import android.widget.ListView import com.example.android.architecture.blueprints.todoapp.Injection import com.example.android.architecture.blueprints.todoapp.R import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource import com.example.android.architecture.blueprints.todoapp.getCurrentActivity import com.example.android.architecture.blueprints.todoapp.getToolbarNavigationContentDescription import com.example.android.architecture.blueprints.todoapp.rotateOrientation import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.Matchers.allOf import org.hamcrest.TypeSafeMatcher import org.hamcrest.core.IsNot.not import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Tests for the tasks screen, the main screen which contains a list of all tasks. */ @RunWith(AndroidJUnit4::class) @LargeTest class TasksScreenTest { /** * [ActivityTestRule] is a JUnit [Rule] to launch your activity under test. * * * Rules are interceptors which are executed for each test method and are important building * blocks of Junit tests. */ @Suppress("MemberVisibilityCanPrivate") @get:Rule var tasksActivityTestRule: ActivityTestRule<TasksActivity> = object : ActivityTestRule<TasksActivity>(TasksActivity::class.java) { /** * To avoid a long list of tasks and the need to scroll through the list to find a * task, we call [TasksDataSource.deleteAllTasks] before each test. */ override fun beforeActivityLaunched() { super.beforeActivityLaunched() // Doing this in @Before generates a race condition. Injection .provideTasksRepository(InstrumentationRegistry.getTargetContext()) .deleteAllTasks() } } private val toolbarNavigationContentDescription: String get() = getToolbarNavigationContentDescription(tasksActivityTestRule.activity, R.id.toolbar) /** * A custom [Matcher] which matches an item in a [ListView] by its text. * * * View constraints: * * * View must be a child of a [ListView] * * * @param itemText the text to match * @return Matcher that matches text in the given view */ private fun withItemText(itemText: String): Matcher<View> { check(itemText.isNotEmpty()) { "itemText cannot be null or empty" } return object : TypeSafeMatcher<View>() { public override fun matchesSafely(item: View): Boolean { return allOf(isDescendantOfA(isAssignableFrom(ListView::class.java)), withText(itemText)) .matches(item) } override fun describeTo(description: Description) { description.appendText("is isDescendantOfA LV with text " + itemText) } } } @Test fun clickAddTaskButton_opensAddTaskUi() { // Click on the add task button onView(withId(R.id.fab_add_task)).perform(click()) // Check if the add task screen is displayed onView(withId(R.id.add_task_title)).check(matches(isDisplayed())) } @Test @Throws(Exception::class) fun editTask() { // First add a task createTask(TITLE1, DESCRIPTION) // Click on the task on the list onView(withText(TITLE1)).perform(click()) // Click on the edit task button onView(withId(R.id.fab_edit_task)).perform(click()) val editTaskTitle = TITLE2 val editTaskDescription = "New Description" // Edit task title and description onView(withId(R.id.add_task_title)) // Type new task title .perform(replaceText(editTaskTitle), closeSoftKeyboard()) onView(withId(R.id.add_task_description)) // Type new task description and close the keyboard .perform(replaceText(editTaskDescription), closeSoftKeyboard()) // Save the task onView(withId(R.id.fab_edit_task_done)).perform(click()) // Verify task is displayed on screen in the task list. onView(withItemText(editTaskTitle)).check(matches(isDisplayed())) // Verify previous task is not displayed onView(withItemText(TITLE1)).check(doesNotExist()) } @Test @Throws(Exception::class) fun addTaskToTasksList() { createTask(TITLE1, DESCRIPTION) // Verify task is displayed on screen onView(withItemText(TITLE1)).check(matches(isDisplayed())) } @Test fun markTaskAsComplete() { viewAllTasks() // Add active task createTask(TITLE1, DESCRIPTION) // Mark the task as complete clickCheckBoxForTask(TITLE1) // Verify task is shown as complete viewAllTasks() onView(withItemText(TITLE1)).check(matches(isDisplayed())) viewActiveTasks() onView(withItemText(TITLE1)).check(matches(not(isDisplayed()))) viewCompletedTasks() onView(withItemText(TITLE1)).check(matches(isDisplayed())) } @Test fun markTaskAsActive() { viewAllTasks() // Add completed task createTask(TITLE1, DESCRIPTION) clickCheckBoxForTask(TITLE1) // Mark the task as active clickCheckBoxForTask(TITLE1) // Verify task is shown as active viewAllTasks() onView(withItemText(TITLE1)).check(matches(isDisplayed())) viewActiveTasks() onView(withItemText(TITLE1)).check(matches(isDisplayed())) viewCompletedTasks() onView(withItemText(TITLE1)).check(matches(not(isDisplayed()))) } @Test fun showAllTasks() { // Add 2 active tasks createTask(TITLE1, DESCRIPTION) createTask(TITLE2, DESCRIPTION) //Verify that all our tasks are shown viewAllTasks() onView(withItemText(TITLE1)).check(matches(isDisplayed())) onView(withItemText(TITLE2)).check(matches(isDisplayed())) } @Test fun showActiveTasks() { // Add 2 active tasks createTask(TITLE1, DESCRIPTION) createTask(TITLE2, DESCRIPTION) //Verify that all our tasks are shown viewActiveTasks() onView(withItemText(TITLE1)).check(matches(isDisplayed())) onView(withItemText(TITLE2)).check(matches(isDisplayed())) } @Test fun showCompletedTasks() { // Add 2 completed tasks createTask(TITLE1, DESCRIPTION) clickCheckBoxForTask(TITLE1) createTask(TITLE2, DESCRIPTION) clickCheckBoxForTask(TITLE2) // Verify that all our tasks are shown viewCompletedTasks() onView(withItemText(TITLE1)).check(matches(isDisplayed())) onView(withItemText(TITLE2)).check(matches(isDisplayed())) } @Test fun clearCompletedTasks() { viewAllTasks() // Add 2 complete tasks createTask(TITLE1, DESCRIPTION) clickCheckBoxForTask(TITLE1) createTask(TITLE2, DESCRIPTION) clickCheckBoxForTask(TITLE2) // Click clear completed in menu openActionBarOverflowOrOptionsMenu(getTargetContext()) onView(withText(R.string.menu_clear)).perform(click()) //Verify that completed tasks are not shown onView(withItemText(TITLE1)).check(matches(not(isDisplayed()))) onView(withItemText(TITLE2)).check(matches(not(isDisplayed()))) } @Test fun createOneTask_deleteTask() { viewAllTasks() // Add active task createTask(TITLE1, DESCRIPTION) // Open it in details view onView(withText(TITLE1)).perform(click()) // Click delete task in menu onView(withId(R.id.menu_delete)).perform(click()) // Verify it was deleted viewAllTasks() onView(withText(TITLE1)).check(matches(not(isDisplayed()))) } @Test fun createTwoTasks_deleteOneTask() { // Add 2 active tasks createTask(TITLE1, DESCRIPTION) createTask(TITLE2, DESCRIPTION) // Open the second task in details view onView(withText(TITLE2)).perform(click()) // Click delete task in menu onView(withId(R.id.menu_delete)).perform(click()) // Verify only one task was deleted viewAllTasks() onView(withText(TITLE1)).check(matches(isDisplayed())) onView(withText(TITLE2)).check(doesNotExist()) } @Test fun markTaskAsCompleteOnDetailScreen_taskIsCompleteInList() { viewAllTasks() // Add 1 active task createTask(TITLE1, DESCRIPTION) // Click on the task on the list onView(withText(TITLE1)).perform(click()) // Click on the checkbox in task details screen onView(withId(R.id.task_detail_complete)).perform(click()) // Click on the navigation up button to go back to the list onView(withContentDescription(toolbarNavigationContentDescription)).perform(click()) // Check that the task is marked as completed onView(allOf(withId(R.id.complete), hasSibling(withText(TITLE1)))).check(matches(isChecked())) } @Test fun markTaskAsActiveOnDetailScreen_taskIsActiveInList() { viewAllTasks() // Add 1 completed task createTask(TITLE1, DESCRIPTION) clickCheckBoxForTask(TITLE1) // Click on the task on the list onView(withText(TITLE1)).perform(click()) // Click on the checkbox in task details screen onView(withId(R.id.task_detail_complete)).perform(click()) // Click on the navigation up button to go back to the list onView(withContentDescription(toolbarNavigationContentDescription)).perform(click()) // Check that the task is marked as active onView(allOf(withId(R.id.complete), hasSibling(withText(TITLE1)))) .check(matches(not(isChecked()))) } @Test fun markTaskAsAcompleteAndActiveOnDetailScreen_taskIsActiveInList() { viewAllTasks() // Add 1 active task createTask(TITLE1, DESCRIPTION) // Click on the task on the list onView(withText(TITLE1)).perform(click()) // Click on the checkbox in task details screen onView(withId(R.id.task_detail_complete)).perform(click()) // Click again to restore it to original state onView(withId(R.id.task_detail_complete)).perform(click()) // Click on the navigation up button to go back to the list onView(withContentDescription(toolbarNavigationContentDescription)).perform(click()) // Check that the task is marked as active onView(allOf(withId(R.id.complete), hasSibling(withText(TITLE1)))) .check(matches(not(isChecked()))) } @Test fun markTaskAsActiveAndCompleteOnDetailScreen_taskIsCompleteInList() { viewAllTasks() // Add 1 completed task createTask(TITLE1, DESCRIPTION) clickCheckBoxForTask(TITLE1) // Click on the task on the list onView(withText(TITLE1)).perform(click()) // Click on the checkbox in task details screen onView(withId(R.id.task_detail_complete)).perform(click()) // Click again to restore it to original state onView(withId(R.id.task_detail_complete)).perform(click()) // Click on the navigation up button to go back to the list onView(withContentDescription(toolbarNavigationContentDescription)).perform(click()) // Check that the task is marked as active onView(allOf(withId(R.id.complete), hasSibling(withText(TITLE1)))).check(matches(isChecked())) } @Test fun orientationChange_FilterActivePersists() { // Add a completed task createTask(TITLE1, DESCRIPTION) clickCheckBoxForTask(TITLE1) // when switching to active tasks viewActiveTasks() // then no tasks should appear onView(withText(TITLE1)).check(matches(not(isDisplayed()))) // when rotating the screen rotateOrientation(tasksActivityTestRule.activity) // then nothing changes onView(withText(TITLE1)).check(doesNotExist()) } @Test fun orientationChange_FilterCompletedPersists() { // Add a completed task createTask(TITLE1, DESCRIPTION) clickCheckBoxForTask(TITLE1) // when switching to completed tasks viewCompletedTasks() // the completed task should be displayed onView(withText(TITLE1)).check(matches(isDisplayed())) // when rotating the screen rotateOrientation(tasksActivityTestRule.activity) // then nothing changes onView(withText(TITLE1)).check(matches(isDisplayed())) onView(withText(R.string.label_completed)).check(matches(isDisplayed())) } @Test @SdkSuppress(minSdkVersion = 21) // Blinking cursor after rotation breaks this in API 19 @Throws(Throwable::class) fun orientationChange_DuringEdit_ChangePersists() { // Add a completed task createTask(TITLE1, DESCRIPTION) // Open the task in details view onView(withText(TITLE1)).perform(click()) // Click on the edit task button onView(withId(R.id.fab_edit_task)).perform(click()) // Change task title (but don't save) onView(withId(R.id.add_task_title)) // Type new task title .perform(replaceText(TITLE2), closeSoftKeyboard()) // Rotate the screen rotateOrientation(getCurrentActivity()) // Verify task title is restored onView(withId(R.id.add_task_title)).check(matches(withText(TITLE2))) } @Test @SdkSuppress(minSdkVersion = 21) // Blinking cursor after rotation breaks this in API 19 @Throws(IllegalStateException::class) fun orientationChange_DuringEdit_NoDuplicate() { // Add a completed task createTask(TITLE1, DESCRIPTION) // Open the task in details view onView(withText(TITLE1)).perform(click()) // Click on the edit task button onView(withId(R.id.fab_edit_task)).perform(click()) // Rotate the screen rotateOrientation(getCurrentActivity()) // Edit task title and description onView(withId(R.id.add_task_title)) // Type new task title .perform(replaceText(TITLE2), closeSoftKeyboard()) onView(withId(R.id.add_task_description)) // Type new task description and close the keyboard .perform(replaceText(DESCRIPTION), closeSoftKeyboard()) // Save the task onView(withId(R.id.fab_edit_task_done)).perform(click()) // Verify task is displayed on screen in the task list. onView(withItemText(TITLE2)).check(matches(isDisplayed())) // Verify previous task is not displayed onView(withItemText(TITLE1)).check(doesNotExist()) } private fun viewAllTasks() { onView(withId(R.id.menu_filter)).perform(click()) onView(withText(R.string.nav_all)).perform(click()) } private fun viewActiveTasks() { onView(withId(R.id.menu_filter)).perform(click()) onView(withText(R.string.nav_active)).perform(click()) } private fun viewCompletedTasks() { onView(withId(R.id.menu_filter)).perform(click()) onView(withText(R.string.nav_completed)).perform(click()) } private fun createTask(title: String, description: String) { // Click on the add task button onView(withId(R.id.fab_add_task)).perform(click()) // Add task title and description onView(withId(R.id.add_task_title)) // Type new task title .perform(typeText(title), closeSoftKeyboard()) onView(withId(R.id.add_task_description)) // Type new task description and close the keyboard .perform(typeText(description), closeSoftKeyboard()) // Save the task onView(withId(R.id.fab_edit_task_done)).perform(click()) } private fun clickCheckBoxForTask(title: String) { onView(allOf(withId(R.id.complete), hasSibling(withText(title)))).perform(click()) } companion object { private const val TITLE1 = "TITLE1" private const val DESCRIPTION = "DESCR" private const val TITLE2 = "TITLE2" } }
apache-2.0
90b28e870ba0e40eb9594c94ae7f3c43
31.528195
98
0.722161
4.303656
false
true
false
false
C6H2Cl2/YukariLib
src/main/java/c6h2cl2/YukariLib/ASM/YukariLibTransformer.kt
1
4042
package c6h2cl2.YukariLib.ASM import net.minecraft.launchwrapper.IClassTransformer import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper import net.minecraftforge.fml.relauncher.FMLLaunchHandler import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassVisitor import org.objectweb.asm.ClassWriter import org.objectweb.asm.MethodVisitor import org.objectweb.asm.Type import org.objectweb.asm.Opcodes.* /** * @author C6H2Cl2 */ class YukariLibTransformer : IClassTransformer { private val TARGETS = listOfNotNull("net.minecraft.client.renderer.block.model.ModelBakery") override fun transform(name: String, transformedName: String, basicClass: ByteArray): ByteArray { if (FMLLaunchHandler.side().isServer || !accept(name)) return basicClass val cr = ClassReader(basicClass) val cw = ClassWriter(cr, ClassWriter.COMPUTE_FRAMES) val cv = ModelBakeryClassVisitor(transformedName, cw) try { cr.accept(cv, 0) return cw.toByteArray() } catch (e: Exception) { println("\n\n\nERROR\n\n\n") return basicClass } } private class ModelBakeryClassVisitor(private val transformedName: String, private val cv: ClassVisitor? = null) : ClassVisitor(ASM5, cv) { init { visitMethod(ACC_PUBLIC or ACC_FINAL or ACC_STATIC, "putBuiltinModel", "(Ljava/lang/String;Ljava/lang/String;)V", null, null) } override fun visitMethod(access: Int, name: String?, desc: String?, signature: String?, exceptions: Array<out String>?): MethodVisitor { val mv = super.visitMethod(access, name, desc, signature, exceptions) return if (access != (ACC_PUBLIC or ACC_FINAL or ACC_STATIC) || name != "putBuiltinModel" || desc != "(Ljava/lang/String;Ljava/lang/String;)V" || signature != null || exceptions != null) { mv } else { ModelBakeryMethodVisitor(transformedName, mv) } } } private class ModelBakeryMethodVisitor(private val className: String, mv: MethodVisitor?) : MethodVisitor(ASM5, mv) { override fun visitCode() { visitFieldInsn(GETSTATIC, className, "BUILT_IN_MODELS", "Ljava/util/HashMap") visitVarInsn(ALOAD, 0) visitVarInsn(ALOAD, 1) visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(java.util.HashMap::class.java), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava.lang.Object;", false) visitMaxs(0, 0) super.visitCode() } } private fun accept(className: String): Boolean = TARGETS.contains(className) private fun unmapClassName(name: String): String { return FMLDeobfuscatingRemapper.INSTANCE.unmap(name.replace('.', '/')).replace('/', '.') } private fun mapClassName(name: String): String { return FMLDeobfuscatingRemapper.INSTANCE.map(name.replace('.', '/')).replace('/', '.') } private fun mapMethodName(owner: String, methodName: String, desc: String): String { return FMLDeobfuscatingRemapper.INSTANCE.mapMethodName(owner, methodName, desc) } private fun mapFieldName(owner: String, fieldName: String, desc: String): String { return FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(owner, fieldName, desc) } private fun toDesc(returnType: Any, vararg rawDesc: Any): String { val sb = StringBuilder("(") rawDesc.forEach { sb.append(toDesc(it)) } sb.append(')') sb.append(toDesc(returnType)) return sb.toString() } private fun toDesc(raw: Any): String { if (raw is Class<*>) { return Type.getDescriptor(raw) } else if (raw is String) { val desc = raw.replace('.', '/') return if (desc.matches(Regex("L.+;"))) { desc } else { "L$desc;" } } else { throw IllegalArgumentException() } } }
mpl-2.0
99f941a90288e9ee9f3636cf7e73b295
39.029703
200
0.642009
4.188601
false
false
false
false
mdanielwork/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/BaseCommitExecutorAction.kt
6
1667
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.changes.CommitExecutorBase import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog import com.intellij.openapi.vcs.ui.Refreshable abstract class BaseCommitExecutorAction : DumbAwareAction() { init { isEnabledInModalContext = true } override fun update(e: AnActionEvent) { val dialog = getCommitDialog(e) val executor = getCommitExecutor(dialog) e.presentation.isVisible = dialog != null && executor != null e.presentation.isEnabled = dialog != null && executor != null && isEnabled(dialog, executor) } override fun actionPerformed(e: AnActionEvent) { val dialog = getCommitDialog(e)!! val executor = getCommitExecutor(dialog)!! dialog.execute(executor) } protected abstract val executorId: String protected fun getCommitDialog(e: AnActionEvent): CommitChangeListDialog? = Refreshable.PANEL_KEY.getData(e.dataContext) as? CommitChangeListDialog protected fun getCommitExecutor(dialog: CommitChangeListDialog?): CommitExecutor? = dialog?.executors?.find { it.id == executorId } protected fun isEnabled(dialog: CheckinProjectPanel, executor: CommitExecutor): Boolean = dialog.hasDiffs() || (executor is CommitExecutorBase && !executor.areChangesRequired()) }
apache-2.0
e2937deebf8c73576011d9ad2b1d98b6
40.7
148
0.780444
4.656425
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/settings/internal/DataSetSettingCallShould.kt
1
3256
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.settings.internal import com.nhaarman.mockitokotlin2.* import io.reactivex.Single import org.hisp.dhis.android.core.arch.api.executors.internal.RxAPICallExecutor import org.hisp.dhis.android.core.arch.handlers.internal.Handler import org.hisp.dhis.android.core.maintenance.D2ErrorSamples import org.hisp.dhis.android.core.settings.DataSetSetting import org.hisp.dhis.android.core.settings.DataSetSettings import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class DataSetSettingCallShould { private val handler: Handler<DataSetSetting> = mock() private val service: SettingAppService = mock() private val dataSetSettingSingle: Single<DataSetSettings> = mock() private val apiCallExecutor: RxAPICallExecutor = mock() private val appVersionManager: SettingsAppInfoManager = mock() private lateinit var dataSetSettingCall: DataSetSettingCall @Before fun setUp() { whenever(appVersionManager.getDataStoreVersion()) doReturn Single.just(SettingsAppDataStoreVersion.V1_1) whenever(service.dataSetSettings(any())) doReturn dataSetSettingSingle dataSetSettingCall = DataSetSettingCall(handler, service, apiCallExecutor, appVersionManager) } @Test fun default_to_empty_collection_if_not_found() { whenever(apiCallExecutor.wrapSingle(dataSetSettingSingle, false)) doReturn Single.error(D2ErrorSamples.notFound()) dataSetSettingCall.getCompletable(false).blockingAwait() verify(handler).handleMany(emptyList()) verifyNoMoreInteractions(handler) } }
bsd-3-clause
fd982b829815cdde80b2937aee61c348
46.188406
112
0.773649
4.429932
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/page/ExtendedBottomSheetDialogFragment.kt
1
1130
package org.wikipedia.page import android.os.Build import android.view.View import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.google.android.material.bottomsheet.BottomSheetDialogFragment import org.wikipedia.WikipediaApp open class ExtendedBottomSheetDialogFragment : BottomSheetDialogFragment() { protected fun disableBackgroundDim() { requireDialog().window?.setDimAmount(0f) } protected fun setNavigationBarColor(@ColorInt color: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val isDarkThemeOrDarkBackground = (WikipediaApp.getInstance().currentTheme.isDark || color == ContextCompat.getColor(requireContext(), android.R.color.black)) requireDialog().window?.run { navigationBarColor = color decorView.systemUiVisibility = if (isDarkThemeOrDarkBackground) decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() else View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR or decorView.systemUiVisibility } } } }
apache-2.0
2c9c405c72751a3a1c52e45cb59580b5
39.357143
159
0.719469
5
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/compareToComparableSameType.kt
9
239
// WITH_STDLIB class A(val _value: Int): Comparable<A> { override operator fun compareTo(other: A) = _value.compareTo(other._value) } val low = A(0) val high = A(100) fun test(a: A): Boolean { return low <= a && a <= high<caret> }
apache-2.0
caed8d966611474801e42e0aed596926
23
78
0.631799
2.914634
false
true
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/WorkspaceModelDumper.kt
7
1037
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.workspaceModel.storage.EntityStorage @Suppress("unused") object WorkspaceModelDumper { fun simpleEntities(store: EntityStorage): String { return buildString { store as AbstractEntityStorage val classToEntities = HashMap<String, String>() store.entitiesByType.entityFamilies.forEachIndexed { i, entities -> if (entities == null) return@forEachIndexed val entityClass = i.findWorkspaceEntity() val ent = buildString { entities.entities.filterNotNull().forEach { this.append(" - ${it.javaClass.simpleName}:${it.id}\n") } } classToEntities[entityClass.simpleName] = ent } classToEntities.keys.sorted().forEach { key -> this.append("$key:\n") this.append("${classToEntities[key]}\n") } } } }
apache-2.0
c85031415001fe6d1a5def57d237259a
33.6
140
0.670203
4.608889
false
false
false
false
dahlstrom-g/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/injection/MarkdownCodeFenceErrorHighlightingIntention.kt
8
3352
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.injection import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.codeInsight.intention.IntentionAction import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.MarkdownFileType import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFence import org.intellij.plugins.markdown.settings.MarkdownSettings import org.intellij.plugins.markdown.ui.MarkdownNotifications internal class MarkdownCodeFenceErrorHighlightingIntention : IntentionAction { class CodeAnalyzerRestartListener: MarkdownSettings.ChangeListener { override fun settingsChanged(settings: MarkdownSettings) { val project = settings.project val editorManager = FileEditorManager.getInstance(project) ?: return val codeAnalyzer = DaemonCodeAnalyzerImpl.getInstance(project) ?: return val psiManager = PsiManager.getInstance(project) editorManager.openFiles .asSequence() .filter { FileTypeRegistry.getInstance().isFileOfType(it, MarkdownFileType.INSTANCE) } .mapNotNull(psiManager::findFile) .forEach(codeAnalyzer::restart) } } override fun getText(): String = MarkdownBundle.message("markdown.hide.problems.intention.text") override fun getFamilyName(): String = text override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean { if (file?.fileType != MarkdownFileType.INSTANCE || !MarkdownSettings.getInstance(project).showProblemsInCodeBlocks) { return false } val element = file?.findElementAt(editor?.caretModel?.offset ?: return false) ?: return false return PsiTreeUtil.getParentOfType(element, MarkdownCodeFence::class.java) != null } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { setHideErrors(project, true) val notification = MarkdownNotifications.group.createNotification( MarkdownBundle.message("markdown.hide.problems.notification.title"), MarkdownBundle.message("markdown.hide.problems.notification.content"), NotificationType.INFORMATION ) notification.addAction(object: NotificationAction(MarkdownBundle.message("markdown.hide.problems.notification.rollback.action.text")) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { setHideErrors(project, false) notification.expire() } }) notification.notify(project) } private fun setHideErrors(project: Project, hideErrors: Boolean) { MarkdownSettings.getInstance(project).update { it.showProblemsInCodeBlocks = !hideErrors } } override fun startInWriteAction(): Boolean = false }
apache-2.0
acfe57a9bc8039bc7248ebbed0407b0f
44.917808
140
0.784308
4.893431
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/util/ViewUtils.kt
1
9373
package jp.juggler.util import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.res.ColorStateList import android.graphics.Color import android.os.Build import android.view.View import android.view.ViewGroup import android.view.WindowInsetsController import android.view.WindowManager import android.view.inputmethod.InputMethodManager import android.widget.CompoundButton import android.widget.TextView import androidx.annotation.ColorInt import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SwitchCompat import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.pref.PrefI import org.xmlpull.v1.XmlPullParser import kotlin.math.pow private val log = LogCategory("ViewUtils") fun View?.scan(callback: (view: View) -> Unit) { this ?: return callback(this) if (this is ViewGroup) { for (i in 0 until this.childCount) { this.getChildAt(i)?.scan(callback) } } } val View?.activity: Activity? get() { var context = this?.context while (context is ContextWrapper) { if (context is Activity) return context context = context.baseContext } return null } fun View.hideKeyboard() { try { val imm = this.context?.getSystemService(Context.INPUT_METHOD_SERVICE) if (imm is InputMethodManager) { imm.hideSoftInputFromWindow(this.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } else { log.e("hideKeyboard: can't get InputMethodManager") } } catch (ex: Throwable) { log.trace(ex) } } fun View.showKeyboard() { try { val imm = this.context?.getSystemService(Context.INPUT_METHOD_SERVICE) if (imm is InputMethodManager) { imm.showSoftInput(this, InputMethodManager.HIDE_NOT_ALWAYS) } else { log.e("showKeyboard: can't get InputMethodManager") } } catch (ex: Throwable) { log.trace(ex) } } // set visibility VISIBLE or GONE // return this or null // レシーバがnullableなのはplatform typeによるnull例外を避ける目的 fun <T : View> T?.vg(visible: Boolean): T? { this?.visibility = if (visible) View.VISIBLE else View.GONE return if (visible) this else null } // set visibility VISIBLE or INVISIBLE // return this or null // レシーバがnullableなのはplatform typeによるnull例外を避ける目的 fun <T : View> T?.visibleOrInvisible(visible: Boolean): T? { this?.visibility = if (visible) View.VISIBLE else View.INVISIBLE return if (visible) this else null } fun <T : View> T.visible(): T = apply { visibility = View.VISIBLE } fun <T : View> T.invisible(): T = apply { visibility = View.INVISIBLE } fun <T : View> T.gone(): T = apply { visibility = View.GONE } fun ViewGroup.generateLayoutParamsEx(): ViewGroup.LayoutParams? = try { val parser = resources.getLayout(R.layout.generate_params) // Skip everything until the view tag. while (true) { val token = parser.nextToken() if (token == XmlPullParser.START_TAG) break } generateLayoutParams(parser) } catch (ex: Throwable) { log.e(ex, "generateLayoutParamsEx failed") null } // isChecked with skipping animation var CompoundButton.isCheckedNoAnime: Boolean get() = isChecked set(value) { isChecked = value jumpDrawablesToCurrentState() } private fun mixColor(col1: Int, col2: Int): Int = Color.rgb( (Color.red(col1) + Color.red(col2)) ushr 1, (Color.green(col1) + Color.green(col2)) ushr 1, (Color.blue(col1) + Color.blue(col2)) ushr 1 ) fun Context.setSwitchColor(root: View?) { val colorBg = attrColor(R.attr.colorWindowBackground) val colorOn = PrefI.ipSwitchOnColor() val colorOff = /* PrefI.ipSwitchOffColor().notZero() ?: */ attrColor(android.R.attr.colorPrimary) val colorDisabled = mixColor(colorBg, colorOff) val colorTrackDisabled = mixColor(colorBg, colorDisabled) val colorTrackOn = mixColor(colorBg, colorOn) val colorTrackOff = mixColor(colorBg, colorOff) // https://stackoverflow.com/a/25635526/9134243 val thumbStates = ColorStateList( arrayOf( intArrayOf(-android.R.attr.state_enabled), intArrayOf(android.R.attr.state_checked), intArrayOf() ), intArrayOf( colorDisabled, colorOn, colorOff ) ) val trackStates = ColorStateList( arrayOf( intArrayOf(-android.R.attr.state_enabled), intArrayOf(android.R.attr.state_checked), intArrayOf() ), intArrayOf( colorTrackDisabled, colorTrackOn, colorTrackOff ) ) root?.scan { (it as? SwitchCompat)?.apply { thumbTintList = thumbStates trackTintList = trackStates } } } private fun rgbToLab(rgb: Int): Triple<Float, Float, Float> { fun Int.revGamma(): Float { val v = toFloat() / 255f return when { v > 0.04045f -> ((v + 0.055f) / 1.055f).pow(2.4f) else -> v / 12.92f } } val r = Color.red(rgb).revGamma() val g = Color.green(rgb).revGamma() val b = Color.blue(rgb).revGamma() //https://en.wikipedia.org/wiki/Lab_color_space#CIELAB-CIEXYZ_conversions fun f(src: Float, k: Float): Float { val v = src * k return when { v > 0.008856f -> v.pow(1f / 3f) else -> (7.787f * v) + (4f / 29f) } } val x = f(r * 0.4124f + g * 0.3576f + b * 0.1805f, 100f / 95.047f) val y = f(r * 0.2126f + g * 0.7152f + b * 0.0722f, 100f / 100f) val z = f(r * 0.0193f + g * 0.1192f + b * 0.9505f, 100f / 108.883f) return Triple( (116 * y) - 16, // L 500 * (x - y), // a 200 * (y - z) //b ) } fun AppCompatActivity.setStatusBarColor(forceDark: Boolean = false) { window?.apply { if (Build.VERSION.SDK_INT < 30) { @Suppress("DEPRECATION") clearFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION ) } addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) var c = when { forceDark -> Color.BLACK else -> PrefI.ipStatusBarColor().notZero() ?: attrColor(R.attr.colorPrimaryDark) } setStatusBarColorCompat(c) c = when { forceDark -> Color.BLACK else -> PrefI.ipNavigationBarColor() } setNavigationBarColorCompat(c) } } private fun AppCompatActivity.setStatusBarColorCompat(@ColorInt c: Int) { window?.apply { statusBarColor = Color.BLACK or c if (Build.VERSION.SDK_INT >= 30) { decorView.windowInsetsController?.run { val bit = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS setSystemBarsAppearance(if (rgbToLab(c).first >= 50f) bit else 0, bit) } } else { @Suppress("DEPRECATION") val bit = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR @Suppress("DEPRECATION") decorView.systemUiVisibility = when { rgbToLab(c).first >= 50f -> { //Dark Text to show up on your light status bar decorView.systemUiVisibility or bit } else -> { //Light Text to show up on your dark status bar decorView.systemUiVisibility and bit.inv() } } } } } private fun AppCompatActivity.setNavigationBarColorCompat(@ColorInt c: Int) { if (c == 0) { // no way to restore to system default, need restart app. return } window?.apply { navigationBarColor = c or Color.BLACK if (Build.VERSION.SDK_INT >= 30) { decorView.windowInsetsController?.run { val bit = WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS setSystemBarsAppearance(if (rgbToLab(c).first >= 50f) bit else 0, bit) } } else { @Suppress("DEPRECATION") val bit = View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR @Suppress("DEPRECATION") decorView.systemUiVisibility = when { //Dark Text to show up on your light status bar rgbToLab(c).first >= 50f -> decorView.systemUiVisibility or bit //Light Text to show up on your dark status bar else -> decorView.systemUiVisibility and bit.inv() } } } } var TextView.textOrGone: CharSequence? get() = text set(value) { vg(value?.isNotEmpty() == true)?.text = value }
apache-2.0
efe554b80118898c22bb999cb166256a
30.058621
93
0.581478
4.11008
false
false
false
false
JuliaSoboleva/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/model/Distance.kt
2
4729
package co.smartreceipts.android.model import android.os.Parcelable import co.smartreceipts.android.date.DisplayableDate import co.smartreceipts.android.model.utils.ModelUtils import co.smartreceipts.core.sync.model.SyncState import co.smartreceipts.core.sync.model.Syncable import kotlinx.android.parcel.Parcelize import java.math.BigDecimal import java.sql.Date import java.util.* /** * An immutable [Distance] implementation to track distance. */ @Parcelize class Distance( override val id: Int, override val uuid: UUID, override val price: Price, override val syncState: SyncState, /** * The parent [Trip] for this distance */ val trip: Trip, /** * The [String] location to which this distance occurred (e.g. drove to Atlanta) */ val location: String, /** * The [BigDecimal] representation of the distance travelled */ val distance: BigDecimal, /** * The [BigDecimal] rate for which this distance may be reimbursed */ val rate: BigDecimal, /** * The [DisplayableDate] on which this distance occurred */ val displayableDate: DisplayableDate, /** * The user defined comment [String] for this receipt */ val comment: String, /** * The payment method associated with this receipt item. */ val paymentMethod: PaymentMethod, val autoCompleteMetadata: AutoCompleteMetadata ) : Keyed, Parcelable, Priceable, Comparable<Distance>, Syncable { /** * The [Date] in which the [displayableDate] was set */ val date: Date get() = displayableDate.date /** * The [TimeZone] in which the [displayableDate] was set */ val timeZone: TimeZone get() = displayableDate.timeZone /** * A "decimal-formatted" distance [String], which would appear to the end user as "25.20" or "25,20" instead of * showing naively as "25.2" or "25.2123144444" */ val decimalFormattedDistance: String get() = ModelUtils.getDecimalFormattedValue(distance, DISTANCE_PRECISION) /** * A "decimal-formatted" rate [String], which would appear to the end user as "25.20" or "25,20" instead of * showing naively as "25.2" */ val decimalFormattedRate: String get() = ModelUtils.getDecimalFormattedValue(rate, RATE_PRECISION) /** * The "currency-formatted" rate [String], which would appear as "$25.20" or "$25,20" as determined by the user's locale */ val currencyFormattedRate: String get() { val precision = if (decimalFormattedRate.endsWith("0")) Price.TOTAL_DECIMAL_PRECISION else RATE_PRECISION return ModelUtils.getCurrencyFormattedValue(rate, price.currency, precision) } override fun toString(): String { return "Distance [uuid=$uuid, location=$location, distance=$distance, displayableDate=$displayableDate, rate=$rate, price= $price, " + "comment=$comment, paymentMethod=$paymentMethod, autoCompleteMetadata=$autoCompleteMetadata]" } override fun compareTo(other: Distance): Int { return other.displayableDate.date.compareTo(displayableDate.date) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Distance if (id != other.id) return false if (uuid != other.uuid) return false if (trip != other.trip) return false if (location != other.location) return false if (distance != other.distance) return false if (rate != other.rate) return false if (price != other.price) return false if (displayableDate != other.displayableDate) return false if (comment != other.comment) return false if (paymentMethod != other.paymentMethod) return false if (autoCompleteMetadata != other.autoCompleteMetadata) return false return true } override fun hashCode(): Int { var result = id result = 31 * result + uuid.hashCode() result = 31 * result + trip.hashCode() result = 31 * result + location.hashCode() result = 31 * result + distance.hashCode() result = 31 * result + rate.hashCode() result = 31 * result + price.hashCode() result = 31 * result + displayableDate.hashCode() result = 31 * result + comment.hashCode() result = 31 * result + paymentMethod.hashCode() result = 31 * result + autoCompleteMetadata.hashCode() return result } companion object { @JvmField val PARCEL_KEY: String = Distance::class.java.name const val RATE_PRECISION = 3 const val DISTANCE_PRECISION = 2 } }
agpl-3.0
6cfd49c63309d7e6d590abcc5ed4be37
33.772059
142
0.658279
4.366574
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/bungeecord/BungeeCordModuleType.kt
1
1499
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bungeecord import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.bungeecord.generation.BungeeCordEventGenerationPanel import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants import com.demonwav.mcdev.util.CommonColors import com.intellij.psi.PsiClass object BungeeCordModuleType : AbstractModuleType<BungeeCordModule<BungeeCordModuleType>>("net.md-5", "bungeecord-api") { private const val ID = "BUNGEECORD_MODULE_TYPE" val IGNORED_ANNOTATIONS = listOf(BungeeCordConstants.HANDLER_ANNOTATION) val LISTENER_ANNOTATIONS = listOf(BungeeCordConstants.HANDLER_ANNOTATION) init { CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS) } override val platformType = PlatformType.BUNGEECORD override val icon = PlatformAssets.BUNGEECORD_ICON override val id = ID override val ignoredAnnotations = IGNORED_ANNOTATIONS override val listenerAnnotations = LISTENER_ANNOTATIONS override fun generateModule(facet: MinecraftFacet) = BungeeCordModule(facet, this) override fun getEventGenerationPanel(chosenClass: PsiClass) = BungeeCordEventGenerationPanel(chosenClass) }
mit
4f1fc7bce78436cc44e72452088008f3
35.560976
120
0.801868
4.584098
false
false
false
false
paplorinc/intellij-community
plugins/stats-collector/log-events/src/com/intellij/stats/completion/LogEventSerializer.kt
3
5170
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.stats.completion import com.google.gson.GsonBuilder import com.google.gson.internal.LinkedTreeMap import com.intellij.stats.completion.events.* import java.lang.reflect.Field import java.lang.reflect.Modifier object JsonSerializer { private val gson = GsonBuilder().serializeNulls().create() private val ignoredFields = setOf( "recorderId", "timestamp", "sessionUid", "actionType", "userUid", "bucket", "recorderVersion" ) fun toJson(obj: Any): String = gson.toJson(obj) fun <T> fromJson(json: String, clazz: Class<T>): DeserializationResult<T> { val declaredFields = allFields(clazz).map { it.name }.filter { it !in ignoredFields } val jsonFields = gson.fromJson(json, LinkedTreeMap::class.java).keys.map { it.toString() }.toSet() val value = gson.fromJson(json, clazz) val unknownFields = jsonFields.subtract(declaredFields) val absentFields = declaredFields.subtract(jsonFields) return DeserializationResult(value, unknownFields, absentFields) } private fun <T> allFields(clazz: Class<T>): List<Field> { val fields: List<Field> = clazz.declaredFields.asSequence() .filter { !Modifier.isStatic(it.modifiers) } .toList() if (clazz.superclass != null) { return fields + allFields(clazz.superclass) } return fields } } class DeserializationResult<out T>(val value: T, val unknownFields: Set<String>, val absentFields: Set<String>) object LogEventSerializer { private val actionClassMap: Map<Action, Class<out LogEvent>> = mapOf( Action.COMPLETION_STARTED to CompletionStartedEvent::class.java, Action.TYPE to TypeEvent::class.java, Action.DOWN to DownPressedEvent::class.java, Action.UP to UpPressedEvent::class.java, Action.BACKSPACE to BackspaceEvent::class.java, Action.COMPLETION_CANCELED to CompletionCancelledEvent::class.java, Action.EXPLICIT_SELECT to ExplicitSelectEvent::class.java, Action.TYPED_SELECT to TypedSelectEvent::class.java, Action.CUSTOM to CustomMessageEvent::class.java, Action.PERFORMANCE to PerformanceEvent::class.java ) fun toString(event: LogEvent): String { return "${event.timestamp}\t" + "${event.recorderId}\t" + "${event.recorderVersion}\t" + "${event.userUid}\t" + "${event.sessionUid}\t" + "${event.bucket}\t" + "${event.actionType}\t" + JsonSerializer.toJson(event) } fun fromString(line: String): DeserializedLogEvent { val parseResult = parseTabSeparatedLine(line, 7) ?: return DeserializedLogEvent(null, emptySet(), emptySet()) val elements = parseResult.elements val endOffset = parseResult.endOffset val timestamp = elements[0].toLong() val recorderId = elements[1] val recorderVersion = elements[2] val userUid = elements[3] val sessionUid = elements[4] val bucket = elements[5] val actionType = Action.valueOf(elements[6]) val clazz = actionClassMap[actionType] ?: return DeserializedLogEvent(null, emptySet(), emptySet()) val json = line.substring(endOffset + 1) val result = JsonSerializer.fromJson(json, clazz) val event = result.value event.userUid = userUid event.timestamp = timestamp event.recorderId = recorderId event.recorderVersion = recorderVersion event.sessionUid = sessionUid event.bucket = bucket event.actionType = actionType return DeserializedLogEvent(event, result.unknownFields, result.absentFields) } private fun parseTabSeparatedLine(line: String, elementsCount: Int): TabSeparatedParseResult? { val items = mutableListOf<String>() var start = -1 return try { for (i in 0 until elementsCount) { val nextSpace = line.indexOf('\t', start + 1) val newItem = line.substring(start + 1, nextSpace) items.add(newItem) start = nextSpace } TabSeparatedParseResult(items, start) } catch (e: Exception) { null } } } class TabSeparatedParseResult(val elements: List<String>, val endOffset: Int) class DeserializedLogEvent( val event: LogEvent?, val unknownEventFields: Set<String>, val absentEventFields: Set<String> )
apache-2.0
ab3d422a7228f8c4297b75f54cbf8af7
34.417808
117
0.65764
4.527145
false
false
false
false
paplorinc/intellij-community
platform/built-in-server/src/org/jetbrains/ide/StartUpMeasurementService.kt
1
2194
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.ide import com.intellij.ide.StartUpPerformanceReporter import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.startup.StartupActivity import com.intellij.util.io.hostName import com.intellij.util.net.NetUtils import io.netty.buffer.Unpooled import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpRequest import io.netty.handler.codec.http.QueryStringDecoder import org.jetbrains.io.response internal class StartUpMeasurementService : RestService() { override fun getServiceName() = "startUpMeasurement" override fun isAccessible(request: HttpRequest): Boolean { if (super.isAccessible(request)) { return true } // expose externally to use visualizer front-end // personal data is not exposed (but someone can say that 3rd plugin class names should be not exposed), // so, limit to dev builds only (EAP builds are not allowed too) or app in an internal mode (and still only for known hosts) return isTrustedHostName(request) && (ApplicationInfoEx.getInstanceEx().build.isSnapshot || ApplicationManager.getApplication().isInternal) } override fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean { return isTrustedHostName(request) || super.isHostTrusted(request, urlDecoder) } override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? { val lastReport = StartupActivity.POST_STARTUP_ACTIVITY.findExtensionOrFail(StartUpPerformanceReporter::class.java).lastReport!! val response = response("application/json", Unpooled.wrappedBuffer(lastReport)) sendResponse(request, context, response) return null } } private fun isTrustedHostName(request: HttpRequest): Boolean { val hostName = request.hostName ?: return false return hostName == "ij-perf.develar.org" || NetUtils.isLocalhost(hostName) }
apache-2.0
a9e0b7db5ca99b7f078cbf60578e62e3
46.717391
143
0.792616
4.551867
false
false
false
false
androidessence/RichTextView
app/src/main/java/com/androidessence/richtextview/MainActivity.kt
1
2636
package com.androidessence.richtextview import android.graphics.BitmapFactory import android.graphics.Color import android.os.Bundle import androidx.appcompat.app.AppCompatActivity //import com.androidessence.lib.CustomSpannableStringBuilder; import com.androidessence.lib.RichTextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val richTextView = findViewById(R.id.text_view) as RichTextView //richTextView.setSpannableString(new SpannableString(SAMPLE_STRING)); //richTextView.formatNumberSpan(); richTextView.text = SAMPLE_STRING richTextView.formatSpan(13, 18, RichTextView.FormatType.BOLD) richTextView.formatSpan(32, 39, RichTextView.FormatType.ITALIC) richTextView.formatSpan(53, 64, RichTextView.FormatType.UNDERLINE) richTextView.formatSpan(78, 92, RichTextView.FormatType.STRIKETHROUGH) richTextView.formatNumberSpan(1, 5) richTextView.formatBulletSpan(1, 5, 40, Color.GREEN) richTextView.formatSpan(106, 118, RichTextView.FormatType.SUPERSCRIPT) richTextView.formatSpan(132, 142, RichTextView.FormatType.SUBSCRIPT) richTextView.colorSpan(156, 161, RichTextView.ColorFormatType.FOREGROUND, Color.BLUE) // Test formatting to end of string. richTextView.colorSpan(180, 184, RichTextView.ColorFormatType.HIGHLIGHT, Color.RED) richTextView.formatImageSpan(206, 207, BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)) richTextView.addHyperlinkToSpan(224, 233, "http://google.com") richTextView.formatScaleXSpan(2f,248, 254) } companion object { private val SAMPLE_STRING = "This text is bold.\n" + // Bold = 13 - 18 "This text is italic.\n" + // Italic = 32 - 39 "This text is underlined.\n" + // Underlined = 53 - 64 "This text is strikethrough.\n" + // strikethrough = 78 - 92 "This text is superscript.\n" + // Superscript = 106 - 118 "This text is subscript.\n" + // Subscript = 132 - 142 "This text is blue.\n" + // Blue = 156 - 161 "This highlight is red.\n" + // Red = 180 - 184 "This line has a Image.\n" + // 207 "This line has a hyperlink.\n" +// Hyperlink = 223 - 233 "This text is scaled." // scaled = 248 - 258 } }
mit
0df30c965dc555e832b04c15eee26ac1
47.814815
93
0.64302
4.482993
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesStatisticsCollector.kt
3
3318
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.find.findUsages import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.eventLog.events.ObjectEventData import com.intellij.internal.statistic.eventLog.events.PrimitiveEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project import com.intellij.psi.search.PredefinedSearchScopeProvider import com.intellij.psi.search.SearchScope class FindUsagesStatisticsCollector : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { @JvmField val GROUP = EventLogGroup("find.usages", 1) @JvmField val SEARCHABLE_SCOPE_EVENT_FIELD = SearchableScopeField() @JvmField val SEARCH_FOR_TEXT_OCCURRENCES_FIELD = EventFields.Boolean("isSearchForTextOccurrences") @JvmField val IS_USAGES_FIELD = EventFields.Boolean("isUsages") const val OPTIONS_EVENT_ID = "options" @JvmField val ADDITIONAL = EventFields.createAdditionalDataField(GROUP.id, OPTIONS_EVENT_ID) @JvmField val FIND_USAGES_OPTIONS = GROUP.registerVarargEvent(OPTIONS_EVENT_ID, SEARCH_FOR_TEXT_OCCURRENCES_FIELD, IS_USAGES_FIELD, SEARCHABLE_SCOPE_EVENT_FIELD, ADDITIONAL) @JvmStatic fun logOptions(project: Project, options: FindUsagesOptions) { val data: MutableList<EventPair<*>> = mutableListOf(SEARCH_FOR_TEXT_OCCURRENCES_FIELD.with(options.isSearchForTextOccurrences), IS_USAGES_FIELD.with(options.isUsages) ) if (SearchableScopeField.isPredefinedScope(project, options.searchScope)) { data.add(SEARCHABLE_SCOPE_EVENT_FIELD.with(options.searchScope)) } if (options is FusAwareFindUsagesOptions) { data.add(ADDITIONAL.with(ObjectEventData(options.additionalUsageData))) } FIND_USAGES_OPTIONS.log(project, *data.toTypedArray()) } } class SearchableScopeField : PrimitiveEventField<SearchScope>() { override val name: String get() = "searchScope" override fun addData(fuData: FeatureUsageData, value: SearchScope) { fuData.addData(name, value.displayName) } override val validationRule: List<String> get() = listOf("{enum:All_Places|Project_Files|Project_and_Libraries|Project_Production_Files|Project_Test_Files|" + "Scratches_and_Consoles|Recently_Viewed_Files|Recently_Changed_Files|Open_Files|Current_File]}") companion object { @JvmStatic fun isPredefinedScope(project: Project, scope: SearchScope): Boolean { val predefinedScopes = PredefinedSearchScopeProvider.getInstance().getPredefinedScopes(project, null, true, true, false, false, true) return predefinedScopes.contains(scope) } } } }
apache-2.0
3120c879e80e4889974bcdbb341a3d20
42.103896
140
0.711573
4.713068
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GithubAccountManager.kt
2
4101
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.accounts import com.intellij.credentialStore.CredentialAttributes import com.intellij.credentialStore.Credentials import com.intellij.credentialStore.PasswordSafeSettingsListener import com.intellij.credentialStore.generateServiceName import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.util.messages.Topic import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.util.GithubUtil import kotlin.properties.Delegates.observable internal val GithubAccount.isGHAccount: Boolean get() = server.isGithubDotCom /** * Handles application-level Github accounts */ @State(name = "GithubAccounts", storages = [ Storage(value = "github.xml"), Storage(value = "github_settings.xml", deprecated = true) ], reportStatistic = false) internal class GithubAccountManager : PersistentStateComponent<Array<GithubAccount>> { var accounts: Set<GithubAccount> by observable(setOf()) { _, oldValue, newValue -> oldValue.filter { it !in newValue }.forEach(this::accountRemoved) LOG.debug("Account list changed to: $newValue") } private fun accountRemoved(account: GithubAccount) { updateAccountToken(account, null) getApplication().messageBus.syncPublisher(ACCOUNT_REMOVED_TOPIC).accountRemoved(account) } /** * Add/update/remove Github OAuth token from application */ fun updateAccountToken(account: GithubAccount, token: String?) { PasswordSafe.instance.set(createCredentialAttributes(account.id), token?.let { createCredentials(account.id, it) }) LOG.debug((if (token == null) "Cleared" else "Updated") + " OAuth token for account: $account") fireTokenChanged(account) } private fun fireTokenChanged(account: GithubAccount) { GithubApiRequestExecutorManager.getInstance().tokenChanged(account) // update cached executor tokens before calling listeners getApplication().messageBus.syncPublisher(ACCOUNT_TOKEN_CHANGED_TOPIC).tokenChanged(account) } /** * Retrieve OAuth token for account from password safe */ fun getTokenForAccount(account: GithubAccount): String? = PasswordSafe.instance.get(createCredentialAttributes(account.id))?.getPasswordAsString() override fun getState() = accounts.toTypedArray() override fun loadState(state: Array<GithubAccount>) { accounts = state.toHashSet() } companion object { private val LOG = logger<GithubAccountManager>() @JvmStatic val ACCOUNT_REMOVED_TOPIC = Topic("GITHUB_ACCOUNT_REMOVED", AccountRemovedListener::class.java) @JvmStatic val ACCOUNT_TOKEN_CHANGED_TOPIC = Topic("GITHUB_ACCOUNT_TOKEN_CHANGED", AccountTokenChangedListener::class.java) fun createAccount(name: String, server: GithubServerPath) = GithubAccount(name, server) } class PasswordStorageClearedListener : PasswordSafeSettingsListener { override fun credentialStoreCleared() { val accountManager = service<GithubAccountManager>() accountManager.accounts.forEach { accountManager.fireTokenChanged(it) } } } } private fun createCredentialAttributes(accountId: String) = CredentialAttributes(createServiceName(accountId)) private fun createCredentials(accountId: String, token: String) = Credentials(accountId, token) private fun createServiceName(accountId: String): String = generateServiceName(GithubUtil.SERVICE_DISPLAY_NAME, accountId) interface AccountRemovedListener { fun accountRemoved(removedAccount: GithubAccount) } interface AccountTokenChangedListener { fun tokenChanged(account: GithubAccount) }
apache-2.0
3cafec43ca3484a5173c9d26fbbf6954
40.434343
148
0.792002
4.757541
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/repository/AlertRepository.kt
1
1784
package jp.cordea.mackerelclient.repository import io.reactivex.Observable import io.reactivex.Single import io.reactivex.rxkotlin.Singles import jp.cordea.mackerelclient.api.response.AlertDataResponse import jp.cordea.mackerelclient.model.DisplayableAlert import javax.inject.Inject import javax.inject.Singleton @Singleton class AlertRepository @Inject constructor( private val remoteDataSource: AlertRemoteDataSource ) { fun getAlerts(filter: (AlertDataResponse) -> Boolean): Single<List<DisplayableAlert>> = remoteDataSource.getAlerts() .flatMap { alerts -> Observable .fromIterable(alerts.alerts) .filter(filter) .toList() .flatMap { getDisplayableAlerts(it) } } private fun getDisplayableAlerts(alerts: List<AlertDataResponse>): Single<List<DisplayableAlert>> { val hostIds = alerts.asSequence().map { it.hostId }.distinct().toList() val monitorIds = alerts.asSequence().map { it.monitorId }.distinct().toList() return Singles .zip( Observable.fromIterable(hostIds).flatMapSingle { remoteDataSource.getHost(it) }.map { it.host }.toList(), Observable.fromIterable(monitorIds).flatMapSingle { remoteDataSource.getMonitor(it) }.map { it.monitor }.toList() ) { host, monitor -> alerts.map { alert -> DisplayableAlert.from( alert, host.firstOrNull { alert.hostId == it.id }, monitor.first { alert.monitorId == it.id } ) } } } }
apache-2.0
1337330b5caa80cf92ad8657a95cbe30
37.782609
103
0.585762
5.171014
false
false
false
false
agoda-com/Kakao
kakao/src/main/kotlin/com/agoda/kakao/spinner/KSpinner.kt
1
9066
package com.agoda.kakao.spinner import android.view.View import android.widget.AdapterView import androidx.test.espresso.DataInteraction import androidx.test.espresso.Espresso import androidx.test.espresso.Espresso.onView import androidx.test.espresso.Root import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.matcher.RootMatchers import androidx.test.espresso.matcher.ViewMatchers import com.agoda.kakao.common.KakaoDslMarker import com.agoda.kakao.common.assertions.BaseAssertions import com.agoda.kakao.common.builders.ViewBuilder import com.agoda.kakao.common.matchers.SpinnerPopupMatcher import com.agoda.kakao.delegate.ViewInteractionDelegate import com.agoda.kakao.list.DataBuilder import com.agoda.kakao.list.KAdapterItem import com.agoda.kakao.list.KAdapterItemType import com.agoda.kakao.list.KAdapterItemTypeBuilder import org.hamcrest.CoreMatchers.allOf import org.hamcrest.Matcher import org.hamcrest.Matchers import kotlin.reflect.KClass @KakaoDslMarker class KSpinner : SpinnerAdapterActions, SpinnerAdapterAssertions, BaseAssertions { val matcher: Matcher<View> val itemTypes: Map<KClass<out KAdapterItem<*>>, KAdapterItemType<KAdapterItem<*>>> override val view: ViewInteractionDelegate override var popupView: ViewInteractionDelegate? = null override var root: Matcher<Root> = RootMatchers.DEFAULT /** * Constructs view class with view interaction from given ViewBuilder * * @param builder ViewBuilder which will result in view's interaction * @param itemTypeBuilder Lambda with receiver where you pass your item providers * * @see ViewBuilder */ constructor(builder: ViewBuilder.() -> Unit, itemTypeBuilder: KAdapterItemTypeBuilder.() -> Unit) { val vb = ViewBuilder().apply(builder) matcher = vb.getViewMatcher() view = vb.getViewInteractionDelegate() itemTypes = KAdapterItemTypeBuilder().apply(itemTypeBuilder).itemTypes } /** * Constructs view class with parent and view interaction from given ViewBuilder * * @param parent Matcher that will be used as parent in isDescendantOfA() matcher * @param builder ViewBuilder which will result in view's interaction * @param itemTypeBuilder Lambda with receiver where you pass your item providers * * @see ViewBuilder */ constructor( parent: Matcher<View>, builder: ViewBuilder.() -> Unit, itemTypeBuilder: KAdapterItemTypeBuilder.() -> Unit ) : this({ isDescendantOfA { withMatcher(parent) } builder(this) }, itemTypeBuilder) /** * Constructs view class with parent and view interaction from given ViewBuilder * * @param parent DataInteraction that will be used as parent to ViewBuilder * @param builder ViewBuilder which will result in view's interaction * @param itemTypeBuilder Lambda with receiver where you pass your item providers * * @see ViewBuilder */ @Suppress("UNCHECKED_CAST") constructor( parent: DataInteraction, builder: ViewBuilder.() -> Unit, itemTypeBuilder: KAdapterItemTypeBuilder.() -> Unit ) { val makeTargetMatcher = DataInteraction::class.java.getDeclaredMethod("makeTargetMatcher") val parentMatcher = makeTargetMatcher.invoke(parent) val vb = ViewBuilder().apply { isDescendantOfA { withMatcher(parentMatcher as Matcher<View>) } builder(this) } matcher = vb.getViewMatcher() view = vb.getViewInteractionDelegate() itemTypes = KAdapterItemTypeBuilder().apply(itemTypeBuilder).itemTypes } /** * Performs given actions/assertion on child at given position * * @param T Type of item at given position. Must be registered via constructor. * @param position Position of item in adapter * @param function Tail lambda which receiver will be matched item with given type T */ inline fun <reified T : KAdapterItem<*>> childAt(position: Int, function: T.() -> Unit) { val provideItem = itemTypes.getOrElse(T::class) { throw IllegalStateException("${T::class.java.simpleName} did not register to Spinner") }.provideItem val interaction = Espresso.onData(Matchers.anything()) .inRoot(SpinnerPopupMatcher()) .atPosition(position) function(provideItem(interaction) as T) } /** * Performs given actions/assertion on first child in adapter * * @param T Type of item at first position. Must be registered via constructor. * @param function Tail lambda which receiver will be matched item with given type T */ inline fun <reified T : KAdapterItem<*>> firstChild(function: T.() -> Unit) { childAt(0, function) } /** * Performs given actions/assertion on last child in adapter * * @param T Type of item at last position. Must be registered via constructor. * @param function Tail lambda which receiver will be matched item with given type T */ inline fun <reified T : KAdapterItem<*>> lastChild(function: T.() -> Unit) { childAt(getSize() - 1, function) } /** * Performs given actions/assertion on all children in adapter * * @param T Type of all items. Must be registered via constructor. * @param function Tail lambda which receiver will be matched item with given type T */ inline fun <reified T : KAdapterItem<*>> children(function: T.() -> Unit) { for (i in 0 until getSize()) { childAt(i, function) } } /** * Performs given actions/assertion on child that matches given matcher * * @param T Type of item at given position. Must be registered via constructor. * @param childMatcher Matcher for item in adapter * @return Item with type T. To make actions/assertions on it immediately, use perform() infix function. */ inline fun <reified T : KAdapterItem<*>> childWith(childMatcher: DataBuilder.() -> Unit): T { val provideItem = itemTypes.getOrElse(T::class) { throw IllegalStateException("${T::class.java.simpleName} did not register to Spinner") }.provideItem val interaction = Espresso.onData(DataBuilder().apply(childMatcher).getDataMatcher()) .inRoot(root) // .inAdapterView(withClassName(containsString("PopupDecorView"))) return provideItem(interaction) as T } /** * Operator that allows usage of DSL style * * @param function Tail lambda with receiver which is your view */ operator fun invoke(function: KSpinner.() -> Unit) { function(this) } /** * Infix function for invoking lambda on your view * * Sometimes instance of view is a result of a function or constructor. * In this specific case you can't call invoke() since it will be considered as * tail lambda of your fun/constructor. In such cases please use this function. * * @param function Tail lambda with receiver which is your view * @return This object */ infix fun perform(function: KSpinner.() -> Unit): KSpinner { function.invoke(this) return this } /** * Calls childAt() on your view with base child * * Calls childAt() on your Spinner and casts received item to KSpinnerItem * * @param position Position of child in adapter * @param tail Lambda with KSpinnerItem receiver * @see KSpinnerItem */ fun emptyChildAt(position: Int, tail: KSpinnerItem.() -> Unit) { childAt(position, tail) } /** * Calls firstChild() on your view with base child * * Calls firstChild() on your Spinner and casts received item to KSpinnerItem * * @param tail Lambda with KSpinnerItem receiver * @see KSpinnerItem */ fun emptyFirstChild(tail: KSpinnerItem.() -> Unit) { firstChild(tail) } /** * Calls lastChild() on your view with base child * * Calls lastChild() on your Spinner and casts received item to KSpinnerItem * * @param tail Lambda with KSpinnerItem receiver * @see KSpinnerItem */ fun emptyLastChild(tail: KSpinnerItem.() -> Unit) { lastChild(tail) } /** * Calls childWith() on your view with base child * * Calls childWith() on your Spinner and casts received item to KSpinnerItem * * @param builder Data builder that will match the child view * @return Matched KSpinnerItem * @see KSpinnerItem */ fun emptyChildWith(builder: DataBuilder.() -> Unit) = childWith<KSpinnerItem>(builder) override fun open() { view.perform(click()) popupView = ViewInteractionDelegate(onView(allOf(ViewMatchers.isAssignableFrom(AdapterView::class.java))).inRoot(SpinnerPopupMatcher())) } override fun close() { view.perform(click()) popupView = null } }
apache-2.0
004edf700c8059cd502f144acf7a1051
35.853659
136
0.677256
4.751572
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/values/Gets.kt
1
4728
package slatekit.common.values import org.threeten.bp.* import slatekit.common.DateTime import slatekit.common.ids.UPID import slatekit.common.ids.UPIDs import java.util.* interface Gets { fun getString(key: String): String fun getBool(key: String): Boolean fun getShort(key: String): Short fun getInt(key: String): Int fun getLong(key: String): Long fun getFloat(key: String): Float fun getDouble(key: String): Double fun getInstant(key:String): Instant fun getDateTime(key: String): DateTime fun getLocalDate(key: String): LocalDate fun getLocalTime(key: String): LocalTime fun getLocalDateTime(key: String): LocalDateTime fun getZonedDateTime(key: String): ZonedDateTime fun getZonedDateTimeUtc(key: String): ZonedDateTime fun getUUID(key: String): java.util.UUID = UUID.fromString(getString(key)) fun getUPID(key: String): UPID = UPIDs.parse(getString(key)) // Get values as Option[T] fun getStringOrNull(key: String): String? = getOrNull(key) { k: String -> getString(k) } fun getBoolOrNull(key: String): Boolean? = getOrNull(key) { k: String -> getBool(k) } fun getShortOrNull(key: String): Short? = getOrNull(key) { k: String -> getShort(k) } fun getIntOrNull(key: String): Int? = getOrNull(key) { k: String -> getInt(k) } fun getLongOrNull(key: String): Long? = getOrNull(key) { k: String -> getLong(k) } fun getFloatOrNull(key: String): Float? = getOrNull(key) { k: String -> getFloat(k) } fun getDoubleOrNull(key: String): Double? = getOrNull(key) { k: String -> getDouble(k) } fun getInstantOrNull(key: String): Instant? = getOrNull(key) { k: String -> getInstant(k) } fun getDateTimeOrNull(key: String): DateTime? = getOrNull(key) { k: String -> getDateTime(k) } fun getLocalDateOrNull(key: String): LocalDate? = getOrNull(key) { k: String -> getLocalDate(k) } fun getLocalTimeOrNull(key: String): LocalTime? = getOrNull(key) { k: String -> getLocalTime(k) } fun getLocalDateTimeOrNull(key: String): LocalDateTime? = getOrNull(key) { k: String -> getLocalDateTime(k) } fun getZonedDateTimeOrNull(key: String): ZonedDateTime? = getOrNull(key) { k: String -> getZonedDateTime(k) } fun getZonedDateTimeUtcOrNull(key: String): ZonedDateTime? = getOrNull(key) { k: String -> getZonedDateTimeUtc(k) } fun getUUIDOrNull(key: String): UUID? = getOrNull(key) { k: String -> UUID.fromString(getString(k)) } fun getUPIDOrNull(key: String): UPID? = getOrNull(key) { k: String -> UPIDs.parse(getString(k)) } // Get value or default fun getStringOrElse(key: String, default: String): String = getOrElse(key, { k: String -> getString(k) }, default) fun getBoolOrElse(key: String, default: Boolean): Boolean = getOrElse(key, { k: String -> getBool(k) }, default) fun getShortOrElse(key: String, default: Short): Short = getOrElse(key, { k: String -> getShort(k) }, default) fun getIntOrElse(key: String, default: Int): Int = getOrElse(key, { k: String -> getInt(k) }, default) fun getLongOrElse(key: String, default: Long): Long = getOrElse(key, { k: String -> getLong(k) }, default) fun getFloatOrElse(key: String, default: Float): Float = getOrElse(key, { k: String -> getFloat(k) }, default) fun getDoubleOrElse(key: String, default: Double): Double = getOrElse(key, { k: String -> getDouble(k) }, default) fun getInstantOrElse(key: String, default: Instant): Instant = getOrElse(key, { k: String -> getInstant(k) }, default) fun getDateTimeOrElse(key: String, default: DateTime): DateTime = getOrElse(key, { k: String -> getDateTime(k) }, default) fun getLocalDateOrElse(key: String, default: LocalDate): LocalDate = getOrElse(key, { k: String -> getLocalDate(k) }, default) fun getLocalTimeOrElse(key: String, default: LocalTime): LocalTime = getOrElse(key, { k: String -> getLocalTime(k) }, default) fun getLocalDateTimeOrElse(key: String, default: LocalDateTime): LocalDateTime = getOrElse(key, { k: String -> getLocalDateTime(k) }, default) fun getZonedDateTimeOrElse(key: String, default: ZonedDateTime): ZonedDateTime = getOrElse(key, { k: String -> getZonedDateTime(k) }, default) fun getZonedDateTimeUtcOrElse(key: String, default: ZonedDateTime): ZonedDateTime = getOrElse(key, { k: String -> getZonedDateTimeUtc(k) }, default) fun getUUIDOrElse(key: String, default:UUID): UUID = getOrElse(key, { k: String -> UUID.fromString(getString(k)) }, default) fun getUPIDOrElse(key: String, default:UPID): UPID = getOrElse(key, { k: String -> UPIDs.parse(getString(k)) }, default) fun <T> getOrNull(key: String, fetcher: (String) -> T): T? fun <T> getOrElse(key: String, fetcher: (String) -> T, default: T): T }
apache-2.0
71a7e8a60249a91f8b498a524670c262
69.58209
152
0.698181
3.752381
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/platformTypes/primitives/compareTo.kt
2
208
fun box(): String { val l = ArrayList<Int>() l.add(1) val x = l[0] < 2 if (x != true) return "Fail: $x}" val y = l[0].compareTo(2) if (y != -1) return "Fail (y): $y}" return "OK" }
apache-2.0
e77bc021b0fe3ce75dea08b6c1577585
22.222222
39
0.471154
2.6
false
false
false
false
Eifelschaf/svbrockscheid
app/src/main/java/de/kleinelamas/svbrockscheid/fragments/GamesFragment.kt
1
1751
package de.kleinelamas.svbrockscheid.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import de.kleinelamas.svbrockscheid.LeagueAdapter import de.kleinelamas.svbrockscheid.R import de.kleinelamas.svbrockscheid.SVBApp import de.kleinelamas.svbrockscheid.model.GameLiveData import kotlinx.android.synthetic.main.fragment_games.* import kotlinx.android.synthetic.main.fragment_games.view.* import javax.inject.Inject /** * @author Matthias Kutscheid */ class GamesFragment : Fragment() { @Inject lateinit var gameData : GameLiveData private val adapter: LeagueAdapter = LeagueAdapter() override fun onCreate(savedInstanceState: Bundle?) { SVBApp.component.inject(this) super.onCreate(savedInstanceState) gameData.observe(this, Observer { games -> games?.let { adapter.leagueHolder = games swipeLayout.isRefreshing = false } }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_games, container, false) view?.swipeLayout?.setOnRefreshListener { // get the data gameData.refresh() } view?.recyclerView?.layoutManager = LinearLayoutManager(view?.recyclerView?.context, RecyclerView.VERTICAL, false) view?.recyclerView?.adapter = adapter return view } }
apache-2.0
55f40813d15c2b22d776c9c46c6252a5
34.04
122
0.729869
4.823691
false
false
false
false
Madzi/owide
src/main/kotlin/owide/loader/qsp/Location.kt
1
560
package owide.loader.qsp class Location() : Storable { var name = "noname" var description = "" var code = "" val actions = mutableListOf<Action>() fun addAction(action: Action) = actions.add(action) override fun toSave(): String { return "" } override fun toText(): String { return "@location($name)" + (if (description.isEmpty()) "\n" else "[\n$description\n]\n") + "$code\n" + actions.map { it.toText() }.joinToString { "" } + "\n" } }
apache-2.0
ff2f8aeb192410e7006915d799064cec
23.347826
79
0.517857
4
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/changePackage/KotlinChangePackageRefactoring.kt
3
2556
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.changePackage import com.intellij.refactoring.RefactoringBundle import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.quoteIfNeeded import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.move.ContainerChangeInfo import org.jetbrains.kotlin.idea.refactoring.move.ContainerInfo import org.jetbrains.kotlin.idea.refactoring.move.getInternalReferencesToUpdateOnPackageNameChange import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.* import org.jetbrains.kotlin.idea.refactoring.move.postProcessMoveUsages import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile class KotlinChangePackageRefactoring(val file: KtFile) { private val project = file.project fun run(newFqName: FqName) { val packageDirective = file.packageDirective ?: return val currentFqName = packageDirective.fqName val declarationProcessor = MoveKotlinDeclarationsProcessor( MoveDeclarationsDescriptor( project = project, moveSource = MoveSource(file), moveTarget = KotlinDirectoryMoveTarget(newFqName, file.containingDirectory!!.virtualFile), delegate = MoveDeclarationsDelegate.TopLevel ) ) val declarationUsages = project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) { runReadAction { declarationProcessor.findUsages().toList() } } ?: return val changeInfo = ContainerChangeInfo(ContainerInfo.Package(currentFqName), ContainerInfo.Package(newFqName)) val internalUsages = file.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) project.executeWriteCommand(KotlinBundle.message("text.change.file.package.to.0", newFqName)) { packageDirective.fqName = newFqName.quoteIfNeeded() postProcessMoveUsages(internalUsages) performDelayedRefactoringRequests(project) declarationProcessor.execute(declarationUsages) } } }
apache-2.0
1c58537192e238fe44e2da73fb70e7c9
49.117647
158
0.762911
5.381053
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/models/Category.kt
1
4174
package com.kickstarter.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize class Category internal constructor( private val analyticsName: String, private val color: Int?, private val id: Long, private val name: String, private val parent: Category?, private val parentId: Long, private val parentName: String?, private val position: Int, private val projectsCount: Int, private val slug: String ) : Parcelable, Comparable<Category>, Relay { fun analyticsName() = this.analyticsName fun color() = this.color override fun id() = this.id fun name() = this.name fun parent() = this.parent fun parentId() = this.parentId fun parentName() = this.parentName fun position() = this.position fun projectsCount() = this.projectsCount fun slug() = this.slug @Parcelize data class Builder( private var analyticsName: String = "", private var color: Int? = 0, private var id: Long = 0L, private var name: String = "", private var parent: Category? = null, private var parentId: Long = 0L, private var parentName: String? = "", private var position: Int = 0, private var projectsCount: Int = 0, private var slug: String = "" ) : Parcelable { fun analyticsName(analyticsName: String?) = apply { analyticsName?.let { this.analyticsName = it } } fun color(color: Int?) = apply { this.color = color } fun id(id: Long?) = apply { this.id = id ?: 0L } fun name(name: String?) = apply { this.name = name ?: "" } fun parent(parent: Category?) = apply { this.parent = parent } fun parentId(parentId: Long?) = apply { this.parentId = parentId ?: 0L } fun parentName(parentName: String?) = apply { this.parentName = parentName } fun position(position: Int?) = apply { this.position = position ?: 0 } fun projectsCount(projectsCount: Int?) = apply { this.projectsCount = projectsCount ?: 0 } fun slug(slug: String?) = apply { this.slug = slug ?: "" } fun build() = Category( analyticsName = analyticsName, color = color, id = id, name = name, parent = parent, parentId = parentId, parentName = parentName, position = position, projectsCount = projectsCount, slug = slug ) } companion object { @JvmStatic fun builder() = Builder() } fun toBuilder() = Builder( analyticsName = analyticsName, color = color, id = id, name = name, parent = parent, parentId = parentId, parentName = parentName, position = position, projectsCount = projectsCount, slug = slug ) override fun compareTo(other: Category): Int { if (id() == other.id()) { return 0 } if (isRoot && id() == other.rootId()) { return -1 } else if (!isRoot && rootId() == other.id()) { return 1 } return other.root()?.let { root()?.name()?.compareTo(it.name()) } ?: 0 } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is Category) { equals = id() == other.id() && analyticsName() == other.analyticsName() && color() == other.color() && parentName() == other.parentName() && parent() == other.parent() && name() == other.name() && projectsCount() == other.projectsCount() && position() == other.position() && parentId() == other.parentId() && slug() == other.slug() } return equals } val isRoot: Boolean get() = parentId() == 0L fun root(): Category? { return if (isRoot) this else parent() } fun rootId(): Long { return if (isRoot) id() else parentId() } override fun hashCode(): Int { return super.hashCode() } }
apache-2.0
91cf990510633403f8ff724006e09fae
31.356589
108
0.553186
4.478541
false
false
false
false
lz1asl/CaveSurvey
src/main/java/com/astoev/cave/survey/service/export/vtopo/VisualTopoExport.kt
1
7270
package com.astoev.cave.survey.service.export.vtopo import android.content.res.Resources import android.util.Log import com.astoev.cave.survey.Constants import com.astoev.cave.survey.activity.map.MapUtilities import com.astoev.cave.survey.model.Location import com.astoev.cave.survey.model.Option.* import com.astoev.cave.survey.model.Photo import com.astoev.cave.survey.model.Project import com.astoev.cave.survey.model.Sketch import com.astoev.cave.survey.service.Options.getOptionValue import com.astoev.cave.survey.service.export.AbstractDataExport import com.astoev.cave.survey.service.export.AbstractDataExport.Entities.* import com.astoev.cave.survey.service.export.ExportEntityType import com.astoev.cave.survey.service.export.ExportEntityType.* import com.astoev.cave.survey.service.gps.UtmCoordinate import com.astoev.cave.survey.util.AndroidUtil import com.astoev.cave.survey.util.StreamUtil import java.io.OutputStream import java.text.SimpleDateFormat import java.util.* class VisualTopoExport(aResources: Resources?) : AbstractDataExport(aResources) { private val SEPARATOR = "," private val COORDINATE_PLACEHOLDER = ",,,,LT93" private val ENTRANCE = "Entree A0" private val PLACEHOLDER = "*" private var body = StringBuilder() private var rowType: ExportEntityType? = null private var location: String = COORDINATE_PLACEHOLDER private var legFrom: String = "A0" private var entrance: String = ENTRANCE private var distanceInMeters = UNIT_METERS == getOptionValue(CODE_DISTANCE_UNITS) init { body.clear() } override fun setValue(entityType: Entities, value: String) { val entry = when (entityType) { FROM -> { legFrom = value if (VECTOR == rowType) { rightPad(PLACEHOLDER, 12) + rightPad(PLACEHOLDER, 22) } else rightPad(ensureNotEmpty(value), 12) } TO -> rightPad(ensureNotEmpty(value), 22) else -> "" } body.append(entry) } override fun setValue(entityType: Entities?, aValue: Float?) { val entry = when (entityType) { DISTANCE -> leftPad(ensureNotEmpty(distanceInMeters(aValue), "0.00"), 8) COMPASS, INCLINATION -> leftPad(ensureNotEmpty(aValue, "0.00"), 8) LEFT, RIGHT, UP, DOWN -> leftPad(ensureNotEmpty(distanceInMeters(aValue)), 7) else -> "" } body.append(entry) } override fun setPhoto(aPhoto: Photo?) { // TODO } override fun setLocation(aLocation: Location) { // use the first location if (COORDINATE_PLACEHOLDER == location) { val utmCoordinate = UtmCoordinate(aLocation.latitude, aLocation.longitude) location = SEPARATOR + utmCoordinate.easting / 1000 + SEPARATOR + utmCoordinate.northing / 1000 + SEPARATOR + aLocation.altitude + ".00" + SEPARATOR + "UTM" + utmCoordinate.zone entrance = "Entree " + legFrom } } override fun writeTo(aProject: Project, aStream: OutputStream) { // apply the location val troContents = body.toString() .replace(COORDINATE_PLACEHOLDER, location) .replace(ENTRANCE, entrance) // result StreamUtil.write(troContents.toByteArray(), aStream) } override fun getExtension(): String { return VISUAL_TOPO_FILE_EXTENSION } override fun getMimeType(): String { return "application/visualtopo" } override fun prepare(aProject: Project) { Log.i(Constants.LOG_TAG_SERVICE, "Start Visual Topo export ") body.clear() // headers body.appendLine("Version 5.11") body.appendLine("Verification 1") body.appendLine() body.append("Trou ") .append(aProject.name) .appendLine(COORDINATE_PLACEHOLDER) body.appendLine("Entree A0") body.appendLine("Couleur 0,0,0") body.appendLine() body.append("Param Deca ") .append(if (UNIT_GRADS == getOptionValue(CODE_AZIMUTH_UNITS)) "Gra" else "Degd") .append(" Clino ") .append(if (UNIT_GRADS == getOptionValue(CODE_SLOPE_UNITS)) "Gra" else "Degd") .append(" 0.0000 Dir,Dir,Dir Inc Std ") .append(formatDate(aProject.creationDate)) .append(" A ;Generated by CaveSurvey ") .append(AndroidUtil.getAppVersion()) body.appendLine(";") body.appendLine() body.appendLine("A0 A0 0.00 0.00 0.00 * * * * N I * *") Log.i(Constants.LOG_TAG_SERVICE, "Generated body: $body") } override fun prepareEntity(rowCounter: Int, type: ExportEntityType) { rowType = type } override fun endEntity(rowCounter: Int) { if (VECTOR == rowType) { // l/r/u/d not sent for vectors body.append(leftPad(PLACEHOLDER, 7)) body.append(leftPad(PLACEHOLDER, 7)) body.append(leftPad(PLACEHOLDER, 7)) body.append(leftPad(PLACEHOLDER, 7)) } //First flag : orientation of the shot and the followings shots in extended elevation, N for normal, I for reverse //Second flag : Exclusion of this shot from development, I for include, E for exclude. Splay shots must always be excluded. //Third flag : D if a splay is a detail, not the wall, M for the wall. //Fourth flag : S if you want a vertical section (only if there are enough splay shots to compute it), * otherwise body.append(" N ") .append(if (LEG == rowType || MIDDLE == rowType) "I" else "E") .append(if (LEG == rowType || MIDDLE == rowType) " *" else " M") .appendLine(" *") } override fun setDrawing(aSketch: Sketch?) { // TODO } private fun format(value: Float): String { return "%.2f".format(Locale.ENGLISH, value) } private fun leftPad(value: String, length: Int): String { return value.padStart(length, ' ') } private fun rightPad(value: String, length: Int): String { return value.padEnd(length, ' ') } private fun ensureNotEmpty(value: String?): String { return ensureNotEmpty(value, PLACEHOLDER) } private fun ensureNotEmpty(value: String?, placeholder: String): String { return value ?: placeholder } private fun ensureNotEmpty(value: Float?): String { return ensureNotEmpty(value, PLACEHOLDER) } private fun distanceInMeters(value: Float?): Float? { // Visual Topo supports only meters return if (distanceInMeters) value else MapUtilities.getFeetsInMeters(value) } private fun ensureNotEmpty(value: Float?, placeholder: String): String { if (value == null) { return placeholder } return format(value) } companion object { const val VISUAL_TOPO_FILE_EXTENSION = ".tro" private const val HEADER_DATE_FORMAT = "dd/MM/yyyy" fun formatDate(date: Date): String { return SimpleDateFormat(HEADER_DATE_FORMAT).format(date) } } }
mit
06d512a391d2219fe1b413fdeaea5f95
35.355
131
0.628611
4.086565
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/MainToolbar.kt
1
6169
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.headertoolbar import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.customization.CustomActionsSchema import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.impl.IdeFrameDecorator import com.intellij.openapi.wm.impl.IdeRootPane import com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar.MainMenuButton import com.intellij.openapi.wm.impl.headertoolbar.MainToolbarWidgetFactory.Position import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.util.ui.JBUI import java.awt.Dimension import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.util.* import javax.swing.JComponent import javax.swing.JPanel private val EP_NAME = ExtensionPointName<MainToolbarProjectWidgetFactory>("com.intellij.projectToolbarWidget") internal class MainToolbar: JPanel(HorizontalLayout(10)) { private val layoutMap = EnumMap(mapOf( Position.Left to HorizontalLayout.LEFT, Position.Right to HorizontalLayout.RIGHT, Position.Center to HorizontalLayout.CENTER )) private val visibleComponentsPool = VisibleComponentsPool() private val disposable = Disposer.newDisposable() private val mainMenuButton: MainMenuButton? init { background = JBUI.CurrentTheme.CustomFrameDecorations.mainToolbarBackground(true) isOpaque = true if (IdeRootPane.isMenuButtonInToolbar()) { mainMenuButton = MainMenuButton() Disposer.register(disposable, mainMenuButton.menuShortcutHandler) } else { mainMenuButton = null } } // Separate init because first, as part of IdeRootPane creation, we add bare component to allocate space and then, // as part of EDT task scheduled in a start-up activity, do fill it. That's to avoid flickering due to resizing. fun init(project: Project?) { mainMenuButton?.let { addWidget(it.button, Position.Left) } for (factory in MainToolbarAppWidgetFactory.EP_NAME.extensionList) { addWidget(factory.createWidget(), factory.getPosition()) } project?.let { for (factory in EP_NAME.extensionList) { addWidget(factory.createWidget(project), factory.getPosition()) } } createActionBar()?.let { addWidget(it, Position.Right) } addComponentListener(ResizeListener()) } override fun removeNotify() { super.removeNotify() Disposer.dispose(disposable) } private fun addWidget(widget: JComponent, position: Position) { add(layoutMap[position], widget) visibleComponentsPool.addElement(widget, position) (widget as? Disposable)?.let { Disposer.register(disposable, it) } } private fun createActionBar(): JComponent? { val group = CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_EXPERIMENTAL_TOOLBAR_ACTIONS) as ActionGroup? return group?.let { val toolbar = TitleActionToolbar(ActionPlaces.MAIN_TOOLBAR, it, true) toolbar.setMinimumButtonSize(Dimension(40, 40)) toolbar.targetComponent = null toolbar.layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY val comp = toolbar.component comp.border = JBUI.Borders.empty() comp.isOpaque = false comp } } private inner class ResizeListener : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { val visibleElementsWidth = components.asSequence().filter { it.isVisible }.sumOf { it.preferredSize.width } val componentWidth = size.width if (visibleElementsWidth > componentWidth) { decreaseVisibleSizeBy(visibleElementsWidth - componentWidth) } else { increaseVisibleSizeBy(componentWidth - visibleElementsWidth) } } private fun increaseVisibleSizeBy(delta: Int) { var restDelta = delta var comp = visibleComponentsPool.nextToShow() while (comp != null && restDelta > 0) { val width = comp.preferredSize.width if (width > restDelta) return comp.isVisible = true restDelta -= width comp = visibleComponentsPool.nextToShow() } } private fun decreaseVisibleSizeBy(delta: Int) { var restDelta = delta var comp = visibleComponentsPool.nextToHide() while (comp != null && restDelta > 0) { comp.isVisible = false restDelta -= comp.preferredSize.width comp = visibleComponentsPool.nextToShow() } } } } private class VisibleComponentsPool { val elements = EnumMap(mapOf<Position, MutableList<JComponent>>( Position.Left to mutableListOf(), Position.Right to mutableListOf(), Position.Center to mutableListOf() )) fun addElement(comp: JComponent, position: Position) = elements[position]!!.add(comp) fun nextToShow(): JComponent? { return elements[Position.Center]!!.firstOrNull { !it.isVisible } ?: elements[Position.Right]!!.firstOrNull { !it.isVisible } ?: elements[Position.Left]!!.firstOrNull { !it.isVisible } } fun nextToHide(): JComponent? { return elements[Position.Left]!!.lastOrNull { it.isVisible } ?: elements[Position.Right]!!.lastOrNull { it.isVisible } ?: elements[Position.Center]!!.lastOrNull { it.isVisible } } } @JvmOverloads internal fun isToolbarInHeader(settings: UISettings = UISettings.shadowInstance) : Boolean { return ((SystemInfoRt.isMac && Registry.`is`("ide.experimental.ui.title.toolbar.in.macos", true)) || (SystemInfoRt.isWindows && !settings.separateMainMenu && settings.mergeMainMenuWithWindowTitle)) && IdeFrameDecorator.isCustomDecorationAvailable() }
apache-2.0
510854ac6a7f0c629764ee3287a9a4d0
37.5625
160
0.737397
4.536029
false
false
false
false
romannurik/muzei
wearable/src/main/java/com/google/android/apps/muzei/MuzeiWatchFace.kt
1
28053
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.android.apps.muzei import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface import android.graphics.drawable.Drawable import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Message import android.support.wearable.complications.ComplicationData import android.support.wearable.complications.SystemProviders import android.support.wearable.complications.rendering.ComplicationDrawable import android.support.wearable.watchface.CanvasWatchFaceService import android.support.wearable.watchface.WatchFaceService import android.support.wearable.watchface.WatchFaceStyle import android.text.format.DateFormat import android.util.Log import android.view.Gravity import android.view.SurfaceHolder import androidx.core.content.edit import androidx.core.content.res.ResourcesCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.lifecycleScope import androidx.preference.PreferenceManager import com.google.android.apps.muzei.complications.ArtworkComplicationProviderService import com.google.android.apps.muzei.datalayer.ActivateMuzeiReceiver import com.google.android.apps.muzei.featuredart.BuildConfig.FEATURED_ART_AUTHORITY import com.google.android.apps.muzei.render.ImageLoader import com.google.android.apps.muzei.room.Artwork import com.google.android.apps.muzei.room.MuzeiDatabase import com.google.android.apps.muzei.room.contentUri import com.google.android.apps.muzei.sync.ProviderManager import com.google.android.apps.muzei.util.ImageBlurrer import com.google.android.apps.muzei.util.blur import com.google.android.apps.muzei.util.collectIn import com.google.firebase.analytics.ktx.analytics import com.google.firebase.ktx.Firebase import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch import net.nurik.roman.muzei.BuildConfig import net.nurik.roman.muzei.R import java.io.FileNotFoundException import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import java.util.TimeZone import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.math.min /** * Default watch face for Muzei, showing the current time atop the current artwork. In ambient * mode, the artwork is invisible. On devices with low-bit ambient mode, the text is drawn without * anti-aliasing in ambient mode. On devices which require burn-in protection, the hours are drawn * with a thinner font. */ class MuzeiWatchFace : CanvasWatchFaceService(), LifecycleOwner { companion object { private const val TAG = "MuzeiWatchFace" internal const val TOP_COMPLICATION_ID = 0 internal const val BOTTOM_COMPLICATION_ID = 1 /** * Preference key for saving whether the watch face is blurred */ private const val BLURRED_PREF_KEY = "BLURRED" /** * Update rate in milliseconds. */ private val UPDATE_RATE_MS = TimeUnit.MINUTES.toMillis(1) internal const val MSG_UPDATE_TIME = 0 } private val lifecycleRegistry = LifecycleRegistry(this) override fun getLifecycle(): Lifecycle { return lifecycleRegistry } override fun onCreate() { super.onCreate() lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) Firebase.analytics.setUserProperty("device_type", BuildConfig.DEVICE_TYPE) ProviderManager.getInstance(this).observe(this) { provider -> if (provider == null) { val context = this@MuzeiWatchFace lifecycleScope.launch(NonCancellable) { ProviderManager.select(context, FEATURED_ART_AUTHORITY) ActivateMuzeiReceiver.checkForPhoneApp(context) } } } ProviderChangedReceiver.observeForVisibility(this, this) } override fun onCreateEngine(): CanvasWatchFaceService.Engine { return Engine() } override fun onDestroy() { super.onDestroy() lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) } private inner class Engine : CanvasWatchFaceService.Engine() { val timeZoneReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { calendar.timeZone = TimeZone.getDefault() invalidate() } } val localeChangedReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { recomputeDateFormat() invalidate() } } var registeredTimeZoneReceiver = false var registeredLocaleChangedReceiver = false val backgroundPaint: Paint = Paint().apply { color = Color.BLACK } val heavyTypeface: Typeface? by lazy { ResourcesCompat.getFont(this@MuzeiWatchFace, R.font.nunito_clock_bold) } val lightTypeface: Typeface? by lazy { ResourcesCompat.getFont(this@MuzeiWatchFace, R.font.nunito_clock_regular) } val densityMultiplier = resources.displayMetrics.density lateinit var clockPaint: Paint lateinit var clockAmbientShadowPaint: Paint var clockTextHeight: Float = 0f lateinit var datePaint: Paint lateinit var dateAmbientShadowPaint: Paint var dateTextHeight: Float = 0f lateinit var timeFormat12h: SimpleDateFormat lateinit var timeFormat24h: SimpleDateFormat lateinit var dateFormat: SimpleDateFormat var topComplication: ComplicationDrawable? = null var bottomComplication: ComplicationDrawable? = null private val drawableCallback = object : Drawable.Callback { override fun invalidateDrawable(who: Drawable) { invalidate() } override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) { } override fun unscheduleDrawable(who: Drawable, what: Runnable) { } } /** * Handler to update the time periodically in interactive mode. */ val updateTimeHandler: Handler = @SuppressLint("HandlerLeak") object : Handler(Looper.getMainLooper()) { override fun handleMessage(message: Message) { when (message.what) { MSG_UPDATE_TIME -> { invalidate() if (isVisible) { val timeMs = System.currentTimeMillis() val delayMs = UPDATE_RATE_MS - timeMs % UPDATE_RATE_MS this.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs) } } } } } var backgroundScaledBlurredBitmap: Bitmap? = null var backgroundScaledBitmap: Bitmap? = null var backgroundBitmap: Bitmap? = null val clockMargin: Float by lazy { resources.getDimension(R.dimen.clock_margin) } val dateMinAvailableMargin: Float by lazy { resources.getDimension(R.dimen.date_min_available_margin) } val complicationMaxHeight: Float by lazy { resources.getDimension(R.dimen.complication_max_height) } var ambient: Boolean = false val calendar: Calendar = Calendar.getInstance() var cardBounds = Rect() var currentWidth = 0 var currentHeight = 0 /** * Whether the display supports fewer bits for each color in ambient mode. When true, we * disable anti-aliasing in ambient mode. */ var lowBitAmbient: Boolean = false lateinit var tapAction: String var blurred: Boolean = false private suspend fun loadImage(artwork: Artwork?) { if (BuildConfig.DEBUG) { Log.d(TAG, "Artwork = ${artwork?.contentUri}") } val bitmap: Bitmap? = try { artwork?.run { ImageLoader.decode(contentResolver, contentUri) } } catch (e: FileNotFoundException) { Log.w(TAG, "Could not find current artwork image", e) null } if (bitmap != null && !bitmap.sameAs(backgroundBitmap)) { backgroundBitmap = bitmap createScaledBitmap() postInvalidate() } } override fun onCreate(holder: SurfaceHolder) { super.onCreate(holder) Firebase.analytics.logEvent("watchface_created", null) val database = MuzeiDatabase.getInstance(this@MuzeiWatchFace) database.artworkDao().currentArtwork.collectIn(this@MuzeiWatchFace) { artwork -> loadImage(artwork) } clockPaint = Paint().apply { color = Color.WHITE setShadowLayer(1f * densityMultiplier, 0f, 0.5f * densityMultiplier, -0x34000000) isAntiAlias = true typeface = heavyTypeface textAlign = Paint.Align.CENTER textSize = resources.getDimension(R.dimen.clock_text_size) } recomputeClockTextHeight() clockAmbientShadowPaint = Paint(clockPaint).apply { color = Color.TRANSPARENT setShadowLayer(6f * densityMultiplier, 0f, 2f * densityMultiplier, 0x66000000) } datePaint = Paint().apply { color = Color.WHITE setShadowLayer(1f * densityMultiplier, 0f, 0.5f * densityMultiplier, -0x34000000) isAntiAlias = true typeface = lightTypeface textAlign = Paint.Align.CENTER textSize = resources.getDimension(R.dimen.date_text_size) } val fm = datePaint.fontMetrics dateTextHeight = -fm.top dateAmbientShadowPaint = Paint(datePaint).apply { color = Color.TRANSPARENT setShadowLayer(4f * densityMultiplier, 0f, 2f * densityMultiplier, 0x66000000) } recomputeDateFormat() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences( this@MuzeiWatchFace) val showDate = sharedPreferences.getBoolean( ConfigActivity.SHOW_DATE_PREFERENCE_KEY, true) if (showDate) { setDefaultSystemComplicationProvider(TOP_COMPLICATION_ID, SystemProviders.DATE, ComplicationData.TYPE_SHORT_TEXT) } setDefaultComplicationProvider(BOTTOM_COMPLICATION_ID, ComponentName(this@MuzeiWatchFace, ArtworkComplicationProviderService::class.java), ComplicationData.TYPE_LONG_TEXT) setActiveComplications(TOP_COMPLICATION_ID, BOTTOM_COMPLICATION_ID) topComplication = (getDrawable(R.drawable.complication) as ComplicationDrawable).apply { setContext(this@MuzeiWatchFace) } bottomComplication = (getDrawable(R.drawable.complication) as ComplicationDrawable).apply { setContext(this@MuzeiWatchFace) } listOfNotNull(topComplication, bottomComplication).forEach { it.callback = drawableCallback } } updateBlurredStatus() } private fun updateBlurredStatus() { val preferences = PreferenceManager.getDefaultSharedPreferences(this@MuzeiWatchFace) tapAction = preferences.getString(ConfigActivity.TAP_PREFERENCE_KEY, null) ?: getString(R.string.config_tap_default) blurred = when(tapAction) { "always" -> true "never" -> false else -> preferences.getBoolean(BLURRED_PREF_KEY, false) } updateWatchFaceStyle() } private fun recomputeClockTextHeight() { val fm = clockPaint.fontMetrics clockTextHeight = -fm.top } private fun recomputeDateFormat() { timeFormat12h = SimpleDateFormat("h:mm", Locale.getDefault()) timeFormat24h = SimpleDateFormat("H:mm", Locale.getDefault()) val bestPattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "Md") dateFormat = SimpleDateFormat(bestPattern, Locale.getDefault()) } @Suppress("DEPRECATION") private fun updateWatchFaceStyle() { setWatchFaceStyle(WatchFaceStyle.Builder(this@MuzeiWatchFace) .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE) .setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE) .setPeekOpacityMode(if (blurred) WatchFaceStyle.PEEK_OPACITY_MODE_TRANSLUCENT else WatchFaceStyle.PEEK_OPACITY_MODE_OPAQUE) .setStatusBarGravity(Gravity.TOP or Gravity.START) .setHotwordIndicatorGravity(Gravity.TOP or Gravity.START) .setViewProtectionMode(if (blurred) 0 else WatchFaceStyle.PROTECT_HOTWORD_INDICATOR or WatchFaceStyle.PROTECT_STATUS_BAR) .setAcceptsTapEvents(true) .build()) listOfNotNull(topComplication, bottomComplication).forEach { it.setBackgroundColorActive(if (blurred) Color.TRANSPARENT else 0x66000000) } invalidate() } override fun onDestroy() { Firebase.analytics.logEvent("watchface_destroyed", null) updateTimeHandler.removeMessages(MSG_UPDATE_TIME) super.onDestroy() } override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { super.onSurfaceChanged(holder, format, width, height) currentWidth = width currentHeight = height createScaledBitmap() } private fun createScaledBitmap() { if (currentWidth == 0 || currentHeight == 0) { // Wait for the surface to be created return } val background = backgroundBitmap ?: return val scaleHeightFactor = currentHeight * 1f / background.height val scaleWidthFactor = currentWidth * 1f / background.width // Use the larger scale factor to ensure that we center crop and don't show any // black bars (rather than use the minimum and scale down to see the whole image) val scalingFactor = max(scaleHeightFactor, scaleWidthFactor) backgroundScaledBitmap = Bitmap.createScaledBitmap( background, (scalingFactor * background.width).toInt(), (scalingFactor * background.height).toInt(), true /* filter */) backgroundScaledBlurredBitmap = backgroundScaledBitmap.blur(this@MuzeiWatchFace, (ImageBlurrer.MAX_SUPPORTED_BLUR_PIXELS / 2).toFloat()) } override fun onVisibilityChanged(visible: Boolean) { super.onVisibilityChanged(visible) if (BuildConfig.DEBUG) { Log.d(TAG, "onVisibilityChanged: visible = $visible") } if (visible) { lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START) registerReceiver() // Update time zone in case it changed while we weren't visible. calendar.timeZone = TimeZone.getDefault() // Update the blurred status in case the preference has changed updateBlurredStatus() updateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME) } else { lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP) updateTimeHandler.removeMessages(MSG_UPDATE_TIME) unregisterReceiver() } } private fun registerReceiver() { if (registeredTimeZoneReceiver) { return } registeredTimeZoneReceiver = true val filter = IntentFilter(Intent.ACTION_TIMEZONE_CHANGED) [email protected](timeZoneReceiver, filter) registeredLocaleChangedReceiver = true val localeFilter = IntentFilter(Intent.ACTION_LOCALE_CHANGED) [email protected](localeChangedReceiver, localeFilter) } private fun unregisterReceiver() { if (registeredTimeZoneReceiver) { registeredTimeZoneReceiver = false [email protected](timeZoneReceiver) } if (registeredLocaleChangedReceiver) { registeredLocaleChangedReceiver = false [email protected](localeChangedReceiver) } } override fun onPropertiesChanged(properties: Bundle) { super.onPropertiesChanged(properties) val burnInProtection = properties.getBoolean(WatchFaceService.PROPERTY_BURN_IN_PROTECTION, false) val textTypeface = if (burnInProtection) lightTypeface else heavyTypeface clockPaint.typeface = textTypeface clockAmbientShadowPaint.typeface = textTypeface recomputeClockTextHeight() lowBitAmbient = properties.getBoolean(WatchFaceService.PROPERTY_LOW_BIT_AMBIENT, false) listOfNotNull(topComplication, bottomComplication).forEach { it.setBurnInProtection(burnInProtection) it.setLowBitAmbient(lowBitAmbient) } invalidate() if (BuildConfig.DEBUG) { Log.d(TAG, "onPropertiesChanged: burn-in protection = $burnInProtection, " + "low-bit ambient = $lowBitAmbient") } } @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun onPeekCardPositionUpdate(bounds: Rect) { super.onPeekCardPositionUpdate(bounds) if (bounds != cardBounds) { cardBounds.set(bounds) if (BuildConfig.DEBUG) { Log.d(TAG, "onPeekCardPositionUpdate: $cardBounds") } invalidate() } } override fun onTimeTick() { super.onTimeTick() invalidate() } override fun onComplicationDataUpdate(watchFaceComplicationId: Int, data: ComplicationData?) { when (watchFaceComplicationId) { TOP_COMPLICATION_ID -> { topComplication?.setComplicationData(data) } BOTTOM_COMPLICATION_ID -> { bottomComplication?.setComplicationData(data) } } invalidate() } override fun onTapCommand(@TapType tapType: Int, x: Int, y: Int, eventTime: Long) { when (tapType) { WatchFaceService.TAP_TYPE_TAP -> { when { topComplication?.onTap(x, y) == true -> { invalidate() } bottomComplication?.onTap(x, y) == true -> { invalidate() } tapAction == "toggle" -> { blurred = !blurred val preferences = PreferenceManager.getDefaultSharedPreferences(this@MuzeiWatchFace) preferences.edit { putBoolean(BLURRED_PREF_KEY, blurred) } updateWatchFaceStyle() invalidate() } } } else -> super.onTapCommand(tapType, x, y, eventTime) } } override fun onAmbientModeChanged(inAmbientMode: Boolean) { if (BuildConfig.DEBUG) { Log.d(TAG, "onAmbientModeChanged: $inAmbientMode") } super.onAmbientModeChanged(inAmbientMode) if (ambient != inAmbientMode) { ambient = inAmbientMode if (lowBitAmbient) { val antiAlias = !inAmbientMode clockPaint.isAntiAlias = antiAlias clockAmbientShadowPaint.isAntiAlias = antiAlias datePaint.isAntiAlias = antiAlias dateAmbientShadowPaint.isAntiAlias = antiAlias } listOfNotNull(topComplication, bottomComplication).forEach { it.setInAmbientMode(ambient) } invalidate() } } override fun onDraw(canvas: Canvas, bounds: Rect) { calendar.timeInMillis = System.currentTimeMillis() val width = canvas.width val height = canvas.height // Draw the background val background = if (blurred) backgroundScaledBlurredBitmap else backgroundScaledBitmap if (ambient || background == null) { canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), backgroundPaint) } else { // Draw the scaled background canvas.drawBitmap(background, ((width - background.width) / 2).toFloat(), ((height - background.height) / 2).toFloat(), null) if (blurred) { canvas.drawColor(Color.argb(68, 0, 0, 0)) } } // Draw the time val formattedTime = if (DateFormat.is24HourFormat(this@MuzeiWatchFace)) timeFormat24h.format(calendar.time) else timeFormat12h.format(calendar.time) val xOffset = width / 2f val yOffset = min((height + clockTextHeight) / 2, (if (cardBounds.top == 0) height else cardBounds.top) - clockMargin) if (!blurred) { canvas.drawText(formattedTime, xOffset, yOffset, clockAmbientShadowPaint) } canvas.drawText(formattedTime, xOffset, yOffset, clockPaint) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { topComplication?.run { val (top, bottom) = run { var top = clockMargin.toInt() var bottom = ((height - clockTextHeight - clockMargin) / 2).toInt() val maxHeight = bottom - top if (maxHeight > complicationMaxHeight.toInt()) { val difference = maxHeight - complicationMaxHeight.toInt() top += difference / 2 bottom -= difference / 2 } Pair(top, bottom) } val complicationHeight = bottom - top setBounds((canvas.width - complicationHeight) / 2, top, (canvas.width + complicationHeight) / 2, bottom) draw(canvas, calendar.timeInMillis) } } else { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences( this@MuzeiWatchFace) val showDate = sharedPreferences.getBoolean( ConfigActivity.SHOW_DATE_PREFERENCE_KEY, true) // If no card is visible, we have the entire screen. // Otherwise, only the space above the card is available val spaceAvailable = (if (cardBounds.top == 0) height else cardBounds.top).toFloat() // Compute the height of the clock and date val clockHeight = clockTextHeight + clockMargin val dateHeight = dateTextHeight + clockMargin // Only show the date if the height of the clock + date + margin fits in the // available space Otherwise it may be obstructed by an app icon (square) // or unread notification / charging indicator (round) if (showDate && clockHeight + dateHeight + dateMinAvailableMargin < spaceAvailable) { // Draw the date val formattedDate = dateFormat.format(calendar.time) val yDateOffset = yOffset - clockTextHeight - clockMargin // date above centered time if (!blurred) { canvas.drawText(formattedDate, xOffset, yDateOffset, dateAmbientShadowPaint) } canvas.drawText(formattedDate, xOffset, yDateOffset, datePaint) } } // Draw the bottom complication if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { bottomComplication?.run { val (top, bottom) = run { var top = ((height + clockTextHeight + clockMargin) / 2).toInt() var bottom = height - clockMargin.toInt() val maxHeight = bottom - top if (maxHeight > complicationMaxHeight.toInt()) { val difference = maxHeight - complicationMaxHeight.toInt() top += difference / 2 bottom -= difference / 2 } Pair(top, bottom) } val complicationHeight = bottom - top val complicationWidth = (2.75f * complicationHeight).toInt() setBounds((canvas.width - complicationWidth) / 2, top, (canvas.width + complicationWidth) / 2, bottom) draw(canvas, calendar.timeInMillis) } } } } }
apache-2.0
da50db7ba0a4329d8b04aba095208f61
41.440242
130
0.58336
5.448242
false
false
false
false
idea4bsd/idea4bsd
plugins/settings-repository/testSrc/GitTestCase.kt
4
4167
package org.jetbrains.settingsRepository.test import com.intellij.openapi.vcs.merge.MergeSession import com.intellij.testFramework.ProjectRule import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Repository import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode import org.jetbrains.settingsRepository.SyncType import org.jetbrains.settingsRepository.conflictResolver import org.jetbrains.settingsRepository.git.GitRepositoryManager import org.jetbrains.settingsRepository.git.commit import org.jetbrains.settingsRepository.git.resetHard import org.junit.ClassRule import java.nio.file.FileSystem import java.util.* import kotlin.properties.Delegates internal abstract class GitTestCase : IcsTestCase() { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } protected val repositoryManager: GitRepositoryManager get() = icsManager.repositoryManager as GitRepositoryManager protected val repository: Repository get() = repositoryManager.repository protected var remoteRepository: Repository by Delegates.notNull() init { conflictResolver = { files, mergeProvider -> val mergeSession = mergeProvider.createMergeSession(files) for (file in files) { val mergeData = mergeProvider.loadRevisions(file) if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_THEIRS)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours) } else if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_THEIRS) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs) } else if (Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) { file.setBinaryContent(mergeData.LAST) mergeProvider.conflictResolvedForFile(file) } else { throw CannotResolveConflictInTestMode() } } } } class FileInfo(val name: String, val data: ByteArray) protected fun addAndCommit(path: String): FileInfo { val data = """<file path="$path" />""".toByteArray() provider.write(path, data) repositoryManager.commit() return FileInfo(path, data) } protected fun createRemoteRepository(branchName: String? = null, initialCommit: Boolean = false) { val repository = tempDirManager.createRepository("upstream") if (initialCommit) { repository .add(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .commit("") } if (branchName != null) { if (!initialCommit) { // jgit cannot checkout&create branch if no HEAD (no commits in our empty repository), so we create initial empty commit repository.commit("") } Git(repository).checkout().setCreateBranch(true).setName(branchName).call() } remoteRepository = repository } protected fun restoreRemoteAfterPush() { /** we must not push to non-bare repository - but we do it in test (our sync merge equals to "pull&push"), " By default, updating the current branch in a non-bare repository is denied, because it will make the index and work tree inconsistent with what you pushed, and will require 'git reset --hard' to match the work tree to HEAD. " so, we do "git reset --hard" */ remoteRepository.resetHard() } protected fun sync(syncType: SyncType) { icsManager.sync(syncType) } protected fun createLocalAndRemoteRepositories(remoteBranchName: String? = null, initialCommit: Boolean = false) { createRemoteRepository(remoteBranchName, true) configureLocalRepository(remoteBranchName) if (initialCommit) { addAndCommit("local.xml") } } protected fun configureLocalRepository(remoteBranchName: String? = null) { repositoryManager.setUpstream(remoteRepository.workTree.absolutePath, remoteBranchName) } protected fun FileSystem.compare(): FileSystem { val root = getPath("/")!! compareFiles(root, repository.workTreePath) compareFiles(root, remoteRepository.workTreePath) return this } }
apache-2.0
fe210c7031dda8853da1a80d4b6d7cf8
35.243478
131
0.729302
4.806228
false
true
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/declaration/PropertyTranslator.kt
1
12934
/* * Copyright 2010-2015 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.js.translate.declaration import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.LocalVariableAccessorDescriptor import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.translate.callTranslator.CallTranslator import org.jetbrains.kotlin.js.translate.context.Namer import org.jetbrains.kotlin.js.translate.context.Namer.getDelegateNameRef import org.jetbrains.kotlin.js.translate.context.Namer.getReceiverParameterName import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.expression.translateAndAliasParameters import org.jetbrains.kotlin.js.translate.expression.translateFunction import org.jetbrains.kotlin.js.translate.general.AbstractTranslator import org.jetbrains.kotlin.js.translate.general.Translation import org.jetbrains.kotlin.js.translate.utils.BindingUtils import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.pureFqn import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils import org.jetbrains.kotlin.js.translate.utils.TranslationUtils.* import org.jetbrains.kotlin.js.translate.utils.jsAstUtils.addParameter import org.jetbrains.kotlin.js.translate.utils.jsAstUtils.addStatement import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension /** * Translates single property /w accessors. */ fun translateAccessors( descriptor: VariableDescriptorWithAccessors, declaration: KtProperty?, result: MutableList<JsPropertyInitializer>, context: TranslationContext ) { if (descriptor is PropertyDescriptor && (descriptor.modality == Modality.ABSTRACT || JsDescriptorUtils.isSimpleFinalProperty(descriptor))) return PropertyTranslator(descriptor, declaration, context).translate(result) } fun translateAccessors( descriptor: VariableDescriptorWithAccessors, result: MutableList<JsPropertyInitializer>, context: TranslationContext ) { translateAccessors(descriptor, null, result, context) } fun MutableList<JsPropertyInitializer>.addGetterAndSetter( descriptor: VariableDescriptorWithAccessors, generateGetter: () -> JsPropertyInitializer, generateSetter: () -> JsPropertyInitializer ) { add(generateGetter()) if (descriptor.isVar) { add(generateSetter()) } } class DefaultPropertyTranslator( val descriptor: VariableDescriptorWithAccessors, context: TranslationContext, val delegateReference: JsExpression ) : AbstractTranslator(context) { fun generateDefaultGetterFunction(getterDescriptor: VariableAccessorDescriptor, function: JsFunction) { val delegatedCall = bindingContext()[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getterDescriptor] if (delegatedCall != null) { return generateDelegatedGetterFunction(getterDescriptor, delegatedCall, function) } assert(!descriptor.isExtension) { "Unexpected extension property $descriptor}" } assert(descriptor is PropertyDescriptor) { "Property descriptor expected: $descriptor" } val result = backingFieldReference(context(), descriptor as PropertyDescriptor) function.body.statements += JsReturn(result) } private fun generateDelegatedGetterFunction( getterDescriptor: VariableAccessorDescriptor, delegatedCall: ResolvedCall<FunctionDescriptor>, function: JsFunction ) { val host = translateHost(getterDescriptor, function) val delegateContext = context() .newDeclarationIfNecessary(getterDescriptor, function) .contextWithPropertyMetadataCreationIntrinsified(delegatedCall, descriptor, host) val delegatedJsCall = CallTranslator.translate(delegateContext, delegatedCall, delegateReference) val returnResult = JsReturn(delegatedJsCall) function.addStatement(returnResult) } fun generateDefaultSetterFunction(setterDescriptor: VariableAccessorDescriptor, function: JsFunction) { assert(setterDescriptor.valueParameters.size == 1) { "Setter must have 1 parameter" } val correspondingPropertyName = setterDescriptor.correspondingVariable.name.asString() val valueParameter = function.addParameter(correspondingPropertyName).name val withAliased = context().innerContextWithAliased(setterDescriptor.valueParameters[0], valueParameter.makeRef()) val delegatedCall = bindingContext()[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, setterDescriptor] if (delegatedCall != null) { val host = translateHost(setterDescriptor, function) val delegateContext = withAliased .newDeclarationIfNecessary(setterDescriptor, function) .contextWithPropertyMetadataCreationIntrinsified(delegatedCall, descriptor, host) val delegatedJsCall = CallTranslator.translate(delegateContext, delegatedCall, delegateReference) function.addStatement(delegatedJsCall.makeStmt()) } else { assert(!descriptor.isExtension) { "Unexpected extension property $descriptor}" } assert(descriptor is PropertyDescriptor) { "Property descriptor expected: $descriptor" } val assignment = assignmentToBackingField(withAliased, descriptor as PropertyDescriptor, valueParameter.makeRef()) function.addStatement(assignment.makeStmt()) } } private fun TranslationContext.newDeclarationIfNecessary( descriptor: VariableAccessorDescriptor, function: JsFunction ): TranslationContext { return if (descriptor.correspondingVariable !is LocalVariableDescriptor) { newDeclaration(descriptor) } else { innerBlock(function.body) } } private fun translateHost(accessorDescriptor: VariableAccessorDescriptor, function: JsFunction): JsExpression { return if (accessorDescriptor.isExtension) { function.addParameter(getReceiverParameterName(), 0).name.makeRef() } else { JsLiteral.THIS } } } fun TranslationContext.translateDelegateOrInitializerExpression(expression: KtProperty): JsExpression? { val propertyDescriptor = BindingUtils.getDescriptorForElement(bindingContext(), expression) as VariableDescriptorWithAccessors val expressionPsi = expression.delegateExpressionOrInitializer ?: return null val initializer = Translation.translateAsExpression(expressionPsi, this) val provideDelegateCall = bindingContext()[BindingContext.PROVIDE_DELEGATE_RESOLVED_CALL, propertyDescriptor] return if (provideDelegateCall != null) { val innerContext = this.contextWithPropertyMetadataCreationIntrinsified(provideDelegateCall, propertyDescriptor, JsLiteral.THIS) CallTranslator.translate(innerContext, provideDelegateCall, initializer) } else { initializer } } fun TranslationContext.contextWithPropertyMetadataCreationIntrinsified( delegatedCall: ResolvedCall<FunctionDescriptor>, property: VariableDescriptorWithAccessors, host: JsExpression ): TranslationContext { val propertyNameLiteral = program().getStringLiteral(property.name.asString()) // 0th argument is instance, 1st is KProperty, 2nd (for setter) is value val hostExpression = (delegatedCall.valueArgumentsByIndex!![0] as ExpressionValueArgument).valueArgument!!.getArgumentExpression() val fakeArgumentExpression = (delegatedCall.valueArgumentsByIndex!![1] as ExpressionValueArgument).valueArgument!!.getArgumentExpression() return innerContextWithAliasesForExpressions(mapOf( hostExpression to host, fakeArgumentExpression to JsNew(pureFqn("PropertyMetadata", Namer.kotlinObject()), listOf(propertyNameLiteral)) )) } fun KtProperty.hasCustomGetter() = getter?.hasBody() ?: false fun KtProperty.hasCustomSetter() = setter?.hasBody() ?: false private class PropertyTranslator( val descriptor: VariableDescriptorWithAccessors, val declaration: KtProperty?, context: TranslationContext ) : AbstractTranslator(context) { fun translate(result: MutableList<JsPropertyInitializer>) { result.addGetterAndSetter(descriptor, { generateGetter() }, { generateSetter() }) } private fun generateGetter(): JsPropertyInitializer = if (declaration?.hasCustomGetter() ?: false) translateCustomAccessor(getCustomGetterDeclaration()) else generateDefaultGetter() private fun generateSetter(): JsPropertyInitializer = if (declaration?.hasCustomSetter() ?: false) translateCustomAccessor(getCustomSetterDeclaration()) else generateDefaultSetter() private fun getCustomGetterDeclaration(): KtPropertyAccessor = declaration?.getter ?: throw IllegalStateException("declaration and getter should not be null descriptor=$descriptor declaration=$declaration") private fun getCustomSetterDeclaration(): KtPropertyAccessor = declaration?.setter ?: throw IllegalStateException("declaration and setter should not be null descriptor=$descriptor declaration=$declaration") private fun generateDefaultGetter(): JsPropertyInitializer { val getterDescriptor = descriptor.getter ?: throw IllegalStateException("Getter descriptor should not be null") val defaultFunction = createFunction(getterDescriptor).apply { val delegateRef = getDelegateNameRef(descriptor.name.asString()) DefaultPropertyTranslator(descriptor, context(), delegateRef).generateDefaultGetterFunction(getterDescriptor, this) } return generateDefaultAccessor(getterDescriptor, defaultFunction) } private fun generateDefaultSetter(): JsPropertyInitializer { val setterDescriptor = descriptor.setter ?: throw IllegalStateException("Setter descriptor should not be null") val defaultFunction = createFunction(setterDescriptor).apply { val delegateRef = getDelegateNameRef(descriptor.name.asString()) DefaultPropertyTranslator(descriptor, context(), delegateRef).generateDefaultSetterFunction(setterDescriptor, this) } return generateDefaultAccessor(setterDescriptor, defaultFunction) } private fun generateDefaultAccessor(accessorDescriptor: VariableAccessorDescriptor, function: JsFunction): JsPropertyInitializer = translateFunctionAsEcma5PropertyDescriptor(function, accessorDescriptor, context()) private fun translateCustomAccessor(expression: KtPropertyAccessor): JsPropertyInitializer { val descriptor = BindingUtils.getFunctionDescriptor(bindingContext(), expression) val function = JsFunction(context().getScopeForDescriptor(descriptor), JsBlock(), descriptor.toString()) context().translateAndAliasParameters(descriptor, function.parameters).translateFunction(expression, function) return translateFunctionAsEcma5PropertyDescriptor(function, descriptor, context()) } private fun createFunction(descriptor: VariableAccessorDescriptor) = JsFunction(context().getScopeForDescriptor(descriptor), JsBlock(), accessorDescription(descriptor)) private fun accessorDescription(accessorDescriptor: VariableAccessorDescriptor): String { val accessorType = when (accessorDescriptor) { is PropertyGetterDescriptor, is LocalVariableAccessorDescriptor.Getter -> "getter" is PropertySetterDescriptor, is LocalVariableAccessorDescriptor.Setter -> "setter" else -> throw IllegalArgumentException("Unknown accessor type ${accessorDescriptor.javaClass}") } val name = accessorDescriptor.name.asString() return "$accessorType for $name" } }
apache-2.0
8524fec096020302e8859bae8c2c0b3c
47.992424
139
0.74826
5.510865
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsPassFactory.kt
3
2887
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.cutPaste import com.intellij.codeHighlighting.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.HighlightInfoType import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiModificationTracker import org.jetbrains.kotlin.idea.core.util.range class MoveDeclarationsPassFactory : TextEditorHighlightingPassFactory { class Registrar : TextEditorHighlightingPassFactoryRegistrar { override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) { registrar.registerTextEditorHighlightingPass( MoveDeclarationsPassFactory(), TextEditorHighlightingPassRegistrar.Anchor.BEFORE, Pass.POPUP_HINTS, true, true ) } } override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { return MyPass(file.project, file, editor) } private class MyPass( private val project: Project, private val file: PsiFile, private val editor: Editor ) : TextEditorHighlightingPass(project, editor.document, true) { override fun doCollectInformation(progress: ProgressIndicator) {} override fun doApplyInformationToEditor() { val info = buildHighlightingInfo() UpdateHighlightersUtil.setHighlightersToEditor(project, myDocument!!, 0, file.textLength, listOfNotNull(info), colorsScheme, id) } private fun buildHighlightingInfo(): HighlightInfo? { val cookie = editor.getUserData(MoveDeclarationsEditorCookie.KEY) ?: return null if (cookie.modificationCount != PsiModificationTracker.SERVICE.getInstance(project).modificationCount) return null val processor = MoveDeclarationsProcessor.build(editor, cookie) if (processor == null) { editor.putUserData(MoveDeclarationsEditorCookie.KEY, null) return null } val info = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION) .range(cookie.bounds.range!!) .createUnconditionally() QuickFixAction.registerQuickFixAction(info, MoveDeclarationsIntentionAction(processor, cookie.bounds, cookie.modificationCount)) return info } } }
apache-2.0
162653407de657c2ca7d6a2b3102d923
41.455882
158
0.720471
5.356215
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/application/options/editor/fonts/AppFontOptionsPanel.kt
2
7556
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.application.options.editor.fonts import com.intellij.application.options.colors.AbstractFontOptionsPanel import com.intellij.application.options.colors.ColorAndFontSettingsListener import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.colors.FontPreferences import com.intellij.openapi.editor.colors.ModifiableFontPreferences import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl import com.intellij.openapi.editor.impl.FontFamilyService import com.intellij.ui.AbstractFontCombo import com.intellij.ui.components.Label import com.intellij.ui.dsl.builder.* import com.intellij.util.ObjectUtils import com.intellij.util.ui.JBUI import org.jetbrains.annotations.Nls import java.awt.BorderLayout import java.awt.Dimension import java.util.function.Consumer import javax.swing.JComponent open class AppFontOptionsPanel(private val scheme: EditorColorsScheme) : AbstractFontOptionsPanel() { protected val defaultPreferences = FontPreferencesImpl() private var regularWeightCombo: FontWeightCombo? = null private var boldWeightCombo: FontWeightCombo? = null init { addListener(object : ColorAndFontSettingsListener.Abstract() { override fun fontChanged() { updateFontPreferences() } }) AppEditorFontOptions.initDefaults(defaultPreferences) updateOptionsList() } override fun isReadOnly(): Boolean { return false } override fun isDelegating(): Boolean { return false } override fun getFontPreferences(): FontPreferences { return scheme.fontPreferences } override fun setFontSize(fontSize: Int) { setFontSize(fontSize.toFloat()) } override fun setFontSize(fontSize: Float) { scheme.setEditorFontSize(fontSize) } override fun getLineSpacing(): Float { return scheme.lineSpacing } override fun setCurrentLineSpacing(lineSpacing: Float) { scheme.lineSpacing = lineSpacing } override fun createPrimaryFontCombo(): AbstractFontCombo<*>? { return if (isAdvancedFontFamiliesUI()) { FontFamilyCombo(true) } else { super.createPrimaryFontCombo() } } override fun createSecondaryFontCombo(): AbstractFontCombo<*>? { return if (isAdvancedFontFamiliesUI()) { FontFamilyCombo(false) } else { super.createSecondaryFontCombo() } } override fun addControls() { layout = BorderLayout() add(createControls(), BorderLayout.CENTER) } fun updateOnChangedFont() { updateOptionsList() fireFontChanged() } override fun createControls(): JComponent { return panel { row(primaryLabel) { cell(primaryCombo) } row(sizeLabel) { cell(editorFontSizeField) cell(lineSpacingField) .label(lineSpacingLabel) }.bottomGap(BottomGap.SMALL) row { cell(enableLigaturesCheckbox) .gap(RightGap.SMALL) cell(enableLigaturesHintLabel) }.layout(RowLayout.INDEPENDENT) .bottomGap(BottomGap.SMALL) val customComponent = createCustomComponent() if (customComponent != null) { row { cell(customComponent) } } createTypographySettings() }.withBorder(JBUI.Borders.empty(BASE_INSET)) } open fun updateFontPreferences() { regularWeightCombo?.apply { update(fontPreferences) } boldWeightCombo?.apply { update(fontPreferences) } } protected open fun createCustomComponent() : JComponent? = null private fun Panel.createTypographySettings() { collapsibleGroup(ApplicationBundle.message("settings.editor.font.typography.settings"), indent = false) { if (isAdvancedFontFamiliesUI()) { row(ApplicationBundle.message("settings.editor.font.main.weight")) { val component = createRegularWeightCombo() regularWeightCombo = component cell(component) } row(ApplicationBundle.message("settings.editor.font.bold.weight")) { val component = createBoldWeightCombo() boldWeightCombo = component val boldFontHint = createBoldFontHint() cell(component) .comment(boldFontHint.first, DEFAULT_COMMENT_WIDTH, boldFontHint.second) }.bottomGap(BottomGap.SMALL) } val secondaryFont = Label(ApplicationBundle.message("secondary.font")) setSecondaryFontLabel(secondaryFont) row(secondaryFont) { cell(secondaryCombo) .comment(ApplicationBundle.message("label.fallback.fonts.list.description")) } } } protected open fun createBoldFontHint(): Pair<@Nls String?, HyperlinkEventAction> = Pair(null, HyperlinkEventAction.HTML_HYPERLINK_INSTANCE) private fun createRegularWeightCombo(): FontWeightCombo { val result = RegularFontWeightCombo() fixComboWidth(result) result.addActionListener { changeFontPreferences { preferences: FontPreferences -> if (preferences is ModifiableFontPreferences) { val newSubFamily = result.selectedSubFamily if (preferences.regularSubFamily != newSubFamily) { preferences.boldSubFamily = null // Reset bold subfamily for a different regular } preferences.regularSubFamily = newSubFamily } } } return result } private fun createBoldWeightCombo(): FontWeightCombo { val result = BoldFontWeightCombo() fixComboWidth(result) result.addActionListener { changeFontPreferences { preferences: FontPreferences -> if (preferences is ModifiableFontPreferences) { preferences.boldSubFamily = result.selectedSubFamily } } } return result } private fun changeFontPreferences(consumer: Consumer<FontPreferences>) { val preferences = fontPreferences consumer.accept(preferences) fireFontChanged() } private class RegularFontWeightCombo : FontWeightCombo(false) { public override fun getSubFamily(preferences: FontPreferences): String? { return preferences.regularSubFamily } public override fun getRecommendedSubFamily(family: String): String { return FontFamilyService.getRecommendedSubFamily(family) } } private inner class BoldFontWeightCombo : FontWeightCombo(true) { public override fun getSubFamily(preferences: FontPreferences): String? { return preferences.boldSubFamily } public override fun getRecommendedSubFamily(family: String): String { return FontFamilyService.getRecommendedBoldSubFamily( family, ObjectUtils.notNull(regularWeightCombo?.selectedSubFamily, FontFamilyService.getRecommendedSubFamily(family))) } } override fun updateOptionsList() { super.updateOptionsList() regularWeightCombo?.isEnabled = !isReadOnly boldWeightCombo?.isEnabled = !isReadOnly } } private fun isAdvancedFontFamiliesUI(): Boolean { return AppEditorFontOptions.NEW_FONT_SELECTOR } private const val FONT_WEIGHT_COMBO_WIDTH = 250 private fun fixComboWidth(combo: FontWeightCombo) { val width = JBUI.scale(FONT_WEIGHT_COMBO_WIDTH) with(combo) { minimumSize = Dimension(width, 0) maximumSize = Dimension(width, Int.MAX_VALUE) preferredSize = Dimension(width, preferredSize.height) } }
apache-2.0
cec92cae3440b7d381a979ddd1f12b8e
29.10757
158
0.723796
4.693168
false
false
false
false
NineWorlds/serenity-android
serenity-app/src/test/kotlin/us/nineworlds/serenity/ui/leanback/search/CardPresenterTest.kt
2
3302
package us.nineworlds.serenity.ui.leanback.search import android.app.Activity import androidx.leanback.widget.ImageCardView import androidx.core.content.ContextCompat import android.widget.LinearLayout import androidx.test.core.app.ApplicationProvider.getApplicationContext import com.nhaarman.mockitokotlin2.anyOrNull import com.nhaarman.mockitokotlin2.atLeast import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.spy import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mock import org.mockito.junit.MockitoJUnit import org.mockito.quality.Strictness import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import us.nineworlds.serenity.R import us.nineworlds.serenity.core.model.VideoContentInfo @RunWith(RobolectricTestRunner::class) class CardPresenterTest { @Rule @JvmField public val rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS) @Mock lateinit var mockImageCardView: ImageCardView @Mock lateinit var mockVideoContentInfo: VideoContentInfo @Mock lateinit var mockViewHolder: CardPresenter.CardPresenterViewHolder lateinit var presenter: CardPresenter @Before fun setUp() { presenter = CardPresenter(getApplicationContext()) } @Test fun onCreateViewHolderReturnsExpectedViewHolderInstance() { val linearLayout = LinearLayout(getApplicationContext()) val spy = spy(presenter) doReturn(mockImageCardView).whenever(spy).createImageView() val result = spy.onCreateViewHolder(linearLayout) assertThat(result).isInstanceOf(CardPresenter.CardPresenterViewHolder::class.java) } @Test fun imageCardViewHasExpectedValuesSetWhenViewHolderIsCreated() { val linearLayout = LinearLayout(getApplicationContext()) val spy = spy(presenter) doReturn(mockImageCardView).whenever(spy).createImageView() spy.onCreateViewHolder(linearLayout) verify(mockImageCardView).isFocusable = true verify(mockImageCardView).isFocusableInTouchMode = true verify(mockImageCardView).setBackgroundColor(ContextCompat.getColor(linearLayout.context, R.color.holo_color)) } @Test fun onBindViewHolderSetsExpectedImageDimensions() { val activity = Robolectric.buildActivity(Activity::class.java).create().get() val spy = spy(presenter) doReturn(mockImageCardView).whenever(mockViewHolder).cardView doReturn("").whenever(mockVideoContentInfo).imageURL doReturn(activity).whenever(spy).getActivity(anyOrNull()) spy.onBindViewHolder(mockViewHolder, mockVideoContentInfo) verify(mockViewHolder).movie = mockVideoContentInfo verify(mockVideoContentInfo, atLeast(2)).imageURL verify(mockImageCardView).titleText = null verify(mockImageCardView).contentText = null verify(spy).getActivity(anyOrNull()) verify(mockImageCardView).setMainImageDimensions(anyInt(), anyInt()) verify(mockViewHolder).updateCardViewImage(anyOrNull()) } @Test fun unBindViewHolderResetsViews() { presenter.onUnbindViewHolder(mockViewHolder) verify(mockViewHolder).reset() } }
mit
c1f6a178e5b80b04d764e33051d90f86
32.02
114
0.804361
4.771676
false
true
false
false
androidx/androidx
compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/PainterResourcesDemo.kt
3
1974
/* * 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.compose.ui.demos import android.os.Bundle import android.view.ViewGroup import androidx.activity.ComponentActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.vectorResource internal class PainterResourcesDemoActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val composeView = ComposeView(this) setContentView( composeView, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) composeView.setContent { PainterResourcesDemo() } } } @Composable fun PainterResourcesDemo() { // A resource that switches between day and night mode val painter = painterResource(id = R.drawable.ic_painterresource) val vector = ImageVector.Companion.vectorResource(id = R.drawable.ic_painterresource) Column { Image(painter, contentDescription = null) Image(vector, contentDescription = null) } }
apache-2.0
62d9b773f132a1e2e4464f46006e8a2e
33.051724
89
0.73151
4.688836
false
false
false
false