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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/internal/impl/SubscribeDelegate.kt | 1 | 6792 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.impl
import net.mm2d.upnp.Http
import net.mm2d.upnp.HttpClient
import net.mm2d.upnp.HttpRequest
import net.mm2d.upnp.HttpResponse
import net.mm2d.upnp.internal.manager.SubscribeManager
import net.mm2d.upnp.log.Logger
import net.mm2d.upnp.util.toAddressString
import java.io.IOException
import java.net.MalformedURLException
import java.net.URL
import java.util.*
import java.util.concurrent.TimeUnit
internal class SubscribeDelegate(
private val service: ServiceImpl
) {
private val device: DeviceImpl = service.device
private val subscribeManager: SubscribeManager = device.controlPoint.subscribeManager
var subscriptionId: String? = null
private set
internal val callback: String
get() {
val address = device.ssdpMessage.localAddress ?: return ""
val port = subscribeManager.getEventPort()
return "<http://${address.toAddressString(port)}/>"
}
private fun createHttpClient(): HttpClient = HttpClient.create(false)
// VisibleForTesting
@Throws(MalformedURLException::class)
internal fun makeAbsoluteUrl(url: String): URL = Http.makeAbsoluteUrl(device.baseUrl, url, device.scopeId)
suspend fun subscribe(keepRenew: Boolean): Boolean {
try {
val sId = subscriptionId
if (!sId.isNullOrEmpty()) {
if (renewSubscribeActual(sId)) {
subscribeManager.setKeepRenew(service, keepRenew)
return true
}
return false
}
return subscribeActual(keepRenew)
} catch (e: IOException) {
Logger.e(e, "fail to subscribe")
}
return false
}
// VisibleForTesting
@Throws(IOException::class)
internal fun subscribeActual(keepRenew: Boolean): Boolean {
val request = makeSubscribeRequest()
val response = createHttpClient().post(request)
if (response.getStatus() != Http.Status.HTTP_OK) {
Logger.w { "error subscribe request:\n$request\nresponse:\n$response" }
return false
}
val sid = response.getHeader(Http.SID)
val timeout = parseTimeout(response)
if (sid.isNullOrEmpty() || timeout <= 0) {
Logger.w { "error subscribe response:\n$response" }
return false
}
Logger.v { "subscribe request:\n$request\nresponse:\n$response" }
subscriptionId = sid
subscribeManager.register(service, timeout, keepRenew)
return true
}
@Throws(IOException::class)
private fun makeSubscribeRequest(): HttpRequest =
HttpRequest.create().apply {
setMethod(Http.SUBSCRIBE)
setUrl(makeAbsoluteUrl(service.eventSubUrl), true)
setHeader(Http.NT, Http.UPNP_EVENT)
setHeader(Http.CALLBACK, callback)
setHeader(Http.TIMEOUT, "Second-300")
setHeader(Http.CONTENT_LENGTH, "0")
}
suspend fun renewSubscribe(): Boolean {
return try {
val sId = subscriptionId
if (sId.isNullOrEmpty()) subscribeActual(false)
else renewSubscribeActual(sId)
} catch (e: IOException) {
Logger.e(e, "fail to renewSubscribe")
false
}
}
// VisibleForTesting
@Throws(IOException::class)
internal fun renewSubscribeActual(subscriptionId: String): Boolean {
val request = makeRenewSubscribeRequest(subscriptionId)
val response = createHttpClient().post(request)
if (response.getStatus() != Http.Status.HTTP_OK) {
Logger.w { "renewSubscribe request:\n$request\nresponse:\n$response" }
return false
}
val sid = response.getHeader(Http.SID)
val timeout = parseTimeout(response)
if (sid != subscriptionId || timeout <= 0) {
Logger.w { "renewSubscribe response:\n$response" }
return false
}
Logger.v { "renew subscribe request:\n$request\nresponse:\n$response" }
subscribeManager.renew(service, timeout)
return true
}
@Throws(IOException::class)
private fun makeRenewSubscribeRequest(subscriptionId: String): HttpRequest =
HttpRequest.create().apply {
setMethod(Http.SUBSCRIBE)
setUrl(makeAbsoluteUrl(service.eventSubUrl), true)
setHeader(Http.SID, subscriptionId)
setHeader(Http.TIMEOUT, "Second-300")
setHeader(Http.CONTENT_LENGTH, "0")
}
suspend fun unsubscribe(): Boolean {
val sId = subscriptionId
if (sId.isNullOrEmpty()) {
return false
}
try {
val request = makeUnsubscribeRequest(sId)
val response = createHttpClient().post(request)
subscribeManager.unregister(service)
subscriptionId = null
if (response.getStatus() != Http.Status.HTTP_OK) {
Logger.w { "unsubscribe request:\n$request\nresponse:\n$response" }
return false
}
Logger.v { "unsubscribe request:\n$request\nresponse:\n$response" }
return true
} catch (e: IOException) {
Logger.w(e, "fail to unsubscribe")
}
return false
}
@Throws(IOException::class)
private fun makeUnsubscribeRequest(subscriptionId: String): HttpRequest =
HttpRequest.create().apply {
setMethod(Http.UNSUBSCRIBE)
setUrl(makeAbsoluteUrl(service.eventSubUrl), true)
setHeader(Http.SID, subscriptionId)
setHeader(Http.CONTENT_LENGTH, "0")
}
companion object {
private val DEFAULT_SUBSCRIPTION_TIMEOUT = TimeUnit.SECONDS.toMillis(300)
private const val SECOND_PREFIX = "second-"
// VisibleForTesting
internal fun parseTimeout(response: HttpResponse): Long {
val timeout = response.getHeader(Http.TIMEOUT)?.lowercase(Locale.ENGLISH)
if (timeout.isNullOrEmpty() || timeout.contains("infinite")) {
// infiniteはUPnP2.0でdeprecated扱い、有限な値にする。
return DEFAULT_SUBSCRIPTION_TIMEOUT
}
val pos = timeout.indexOf(SECOND_PREFIX)
if (pos < 0) {
return DEFAULT_SUBSCRIPTION_TIMEOUT
}
val secondSection = timeout.substring(pos + SECOND_PREFIX.length)
.toLongOrNull()
?: return DEFAULT_SUBSCRIPTION_TIMEOUT
return TimeUnit.SECONDS.toMillis(secondSection)
}
}
}
| mit | 687812dcb14739051e002bc1d3071566 | 35.333333 | 110 | 0.620746 | 4.63194 | false | false | false | false |
Pixelhash/SignColors | src/main/kotlin/de/codehat/signcolors/listener/BlockListener.kt | 1 | 1881 | package de.codehat.signcolors.listener
import de.codehat.signcolors.SignColors
import de.codehat.signcolors.permission.Permissions
import de.codehat.signcolors.util.hasPermission
import org.bukkit.GameMode
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.event.block.BlockPlaceEvent
import org.bukkit.inventory.ItemStack
class BlockListener: Listener {
@Suppress("unused")
@EventHandler
fun onPlacingOneSign(event: BlockPlaceEvent) {
val player = event.player
val itemInMainHand = player.inventory.itemInMainHand
if (itemInMainHand != null && SignColors.instance.coloredSignManager.signCrafting
&& !player.hasPermission(Permissions.BYPASS_SIGN_CRAFTING)) {
if (itemInMainHand.amount == 1 && itemInMainHand.type == Material.SIGN
&& itemInMainHand.itemMeta.hasLore()) {
SignColors.instance.fixSignPlayers.add(player)
}
}
}
@Suppress("unused")
@EventHandler
fun onBreakColoredSign(event: BlockBreakEvent) {
val player = event.player
val block = event.block
if (SignColors.instance.coloredSignManager.signCrafting
&& (block.type == Material.WALL_SIGN || block.type == Material.SIGN)
&& SignColors.instance.signLocationDao.exists(block)) {
block.type = Material.AIR
if (player.gameMode == GameMode.SURVIVAL) {
val droppedStack = ItemStack(SignColors.instance.coloredSignManager.coloredSignStack)
droppedStack.amount = 1
block.world.dropItemNaturally(block.location, droppedStack)
}
SignColors.instance.signLocationDao.delete(block)
event.isCancelled = true
}
}
}
| gpl-3.0 | 1503f06e49a2471b1da1cd35e6e43455 | 35.882353 | 101 | 0.680489 | 4.510791 | false | false | false | false |
andimage/PCBridge | src/main/kotlin/com/projectcitybuild/integrations/essentials/EssentialsIntegration.kt | 1 | 1642 | package com.projectcitybuild.integrations.essentials
import com.earth2me.essentials.Essentials
import com.projectcitybuild.core.SpigotListener
import com.projectcitybuild.core.contracts.SpigotIntegration
import com.projectcitybuild.modules.logger.PlatformLogger
import dagger.Reusable
import org.bukkit.entity.Player
import org.bukkit.plugin.Plugin
import javax.inject.Inject
@Reusable
class EssentialsIntegration @Inject constructor(
private val plugin: Plugin,
private val logger: PlatformLogger,
) : SpigotListener, SpigotIntegration {
class EssentialsAPINotFoundException : Exception("Essentials plugin not found")
private var essentials: Essentials? = null
override fun onEnable() {
val anyPlugin = plugin.server.pluginManager.getPlugin("Essentials")
if (anyPlugin == null) {
logger.fatal("Cannot find EssentialsX plugin. Disabling integration")
return
}
if (anyPlugin !is Essentials) {
logger.fatal("Found EssentialsX plugin but cannot access API")
throw EssentialsAPINotFoundException()
}
logger.info("Essentials integration enabled")
essentials = anyPlugin
}
override fun onDisable() {
if (essentials != null) {
essentials = null
}
}
/**
* Sets the player's current position as their last known location
* in Essentials
*/
fun updatePlayerLastLocation(player: Player) {
val essentials = essentials
?: return
val essentialsPlayer = essentials.getUser(player)
essentialsPlayer.setLastLocation()
}
}
| mit | dd01d9ed5878d6f5ed62aa5406112410 | 28.854545 | 83 | 0.696711 | 4.745665 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/actions/mover/RsItemUpDownMoverTest.kt | 2 | 6463 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions.mover
import org.intellij.lang.annotations.Language
import org.rust.CheckTestmarkHit
class RsItemUpDownMoverTest : RsStatementUpDownMoverTestBase() {
fun `test step nowhere`() = doTest("""
/*item*/
""", """
/*item*/
""")
fun `test step comment`() = doTest("""
/*item*/
//EOF
""", """
//EOF
/*item*/
""")
fun `test move struct out of function`() = moveDown("""
fn s() {
struct /*caret*/Foo {
pub f: u32,
}
}
""", """
fn s() {
}
struct /*caret*/Foo {
pub f: u32,
}
""")
fun `test move function out of mod`() = moveDown("""
mod s {
fn /*caret*/foo() {}
}
""", """
mod s {
}
fn /*caret*/foo() {}
""")
@CheckTestmarkHit(UpDownMoverTestMarks.MoveOutOfImpl::class)
fun `test impl prevent step out`() = moveDownAndBackUp("""
struct S;
impl S {
fn /*caret*/test() {
test!();
}
}
""")
@CheckTestmarkHit(UpDownMoverTestMarks.MoveOutOfImpl::class)
fun `test trait prevent step out`() = moveDownAndBackUp("""
trait T {
type /*caret*/Foo;
}
""")
fun `test can move items inside impl`() {
moveDownAndBackUp("""
impl s {
const /*caret*/FOO: i32 = 92;
fn foo() {
}
}
""", """
impl s {
fn foo() {
}
const /*caret*/FOO: i32 = 92;
}
""")
}
//TODO: all tests bellow are way to similar.
// Could we reduce test duplication here?
fun `test step over single line function 2`() = doTest("""
/*item*/
fn foo() { }
""", """
fn foo() { }
/*item*/
""")
fun `test step over multi line function`() = doTest("""
/*item*/
fn foo() {
}
""", """
fn foo() {
}
/*item*/
""")
fun `test step over single line struct`() = doTest("""
/*item*/
struct S;
""", """
struct S;
/*item*/
""")
fun `test step over multi line struct`() = doTest("""
/*item*/
struct S {
test: u32
}
""", """
struct S {
test: u32
}
/*item*/
""")
fun `test step over multi line struct with attr`() = doTest("""
/*item*/
#[derive(Debug)]
struct S {
test: u32
}
""", """
#[derive(Debug)]
struct S {
test: u32
}
/*item*/
""")
fun `test step over multiline impl`() = doTest("""
struct S;
/*item*/
impl S {
}
""", """
struct S;
impl S {
}
/*item*/
""")
fun `test step over multiline trait`() = doTest("""
/*item*/
#[test]
trait S {
}
""", """
#[test]
trait S {
}
/*item*/
""")
fun `test step over multiline macro`() = doTest("""
/*item*/
test! {
}
""", """
test! {
}
/*item*/
""")
fun `test step over single line macro`() = doTest("""
/*item*/
test!();
""", """
test!();
/*item*/
""")
fun `test step over single line macro rules`() = doTest("""
/*item*/
macro_rules! test {}
""", """
macro_rules! test {}
/*item*/
""")
fun `test step over multi line macro rules`() = doTest("""
/*item*/
macro_rules! test {
}
""", """
macro_rules! test {
}
/*item*/
""")
fun `test step over single line mod`() = doTest("""
/*item*/
mod test;
""", """
mod test;
/*item*/
""")
fun `test step over multi line mod`() = doTest("""
/*item*/
mod test {
}
""", """
mod test {
}
/*item*/
""")
fun `test step over use`() = doTest("""
/*item*/
use test::
test;
""", """
use test::
test;
/*item*/
""")
fun `test step over extern crate`() = doTest("""
/*item*/
extern crate test;
""", """
extern crate test;
/*item*/
""")
private val items = listOf(
"""
struct /*caret*/ A {
test: u32
}
""",
"""
struct /*caret*/ A;
""",
"""
#[derive(Debug)]
struct /*caret*/ A {
test: u32
}
""",
"""
fn /*caret*/test() {
}
""",
"""
fn <selection>test() {</selection>
}
""",
"""
#[test]
fn /*caret*/test() {
}
""",
"""
fn /*caret*/test() { }
""",
"""
impl /*caret*/Test {
}
""",
"""
trait /*caret*/Test {
}
""",
"""
mod /*caret*/test {
}
""",
"""
test! /*caret*/ {
}
""",
"""
test! /*caret*/ ();
""",
"""
macro_rules! test/*caret*/ {
}
""",
"""
use test::{
test
};
"""
).map { it.trimIndent() }
private fun doTest(@Language("Rust") _a: String, @Language("Rust") _b: String) {
val placeholder = "/*item*/"
fun replacePlaceholder(_text: String, replacement: String): String {
val text = _text.trimIndent()
val indent = text.lines().find { placeholder in it }!!.substringBefore(placeholder)
return text.replace("$indent$placeholder", replacement.trimIndent().lines().joinToString("\n") { "$indent$it" })
}
for (item in items) {
val a = replacePlaceholder(_a, item)
val b = replacePlaceholder(_b, item)
moveDownAndBackUp(a, b)
}
}
}
| mit | b97eb602f2549fe3ec901b1b698f8572 | 18.178042 | 124 | 0.377843 | 4.6 | false | true | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/navigator/VirtualFileFinder.kt | 1 | 2558 | package com.github.jk1.ytplugin.navigator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import java.io.File
object VirtualFileFinder {
// todo: rewrite towards more concise and readable style
fun findFile(relativePath: String, project: Project): VirtualFile? {
val fileIndex = ProjectRootManager.getInstance(project).fileIndex
val file = File(relativePath)
val candidates = FilenameIndex.getVirtualFilesByName(project, file.name, GlobalSearchScope.allScope(project))
var mostMatchedCandidate: VirtualFile? = null
var maxMatchedParentsCount = -1
val candidatesIterator = candidates.iterator()
while (true) {
var candidate: VirtualFile
var matchedParentsCount: Int
do {
do {
do {
do {
if (!candidatesIterator.hasNext()) {
return mostMatchedCandidate
}
candidate = candidatesIterator.next() as VirtualFile
} while (!candidate.exists())
} while (candidate.isDirectory)
} while (!fileIndex.isInContent(candidate) && !fileIndex.isInLibrarySource(candidate))
matchedParentsCount = matchParents(candidate, file)
} while (matchedParentsCount <= maxMatchedParentsCount && (matchedParentsCount != maxMatchedParentsCount || (!fileIndex.isInContent(candidate) || !fileIndex.isInLibrarySource(mostMatchedCandidate!!)) && countParents(candidate) >= countParents(mostMatchedCandidate!!)))
mostMatchedCandidate = candidate
maxMatchedParentsCount = matchedParentsCount
}
}
private fun matchParents(candidate: VirtualFile, relativeFile: File): Int {
val fileParent: File? = relativeFile.parentFile
val candidateParent: VirtualFile? = candidate.parent
if (fileParent != null && candidateParent != null && candidateParent.name == fileParent.name) {
return 1 + matchParents(candidateParent, fileParent)
} else {
return 0
}
}
private fun countParents(file: VirtualFile): Int =
when (file.parent) {
null -> 0
else -> 1 + countParents(file.parent)
}
} | apache-2.0 | 1e80c58e7bb7c2a5d394561c391c2488 | 40.274194 | 280 | 0.630962 | 5.318087 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/pastry/tests/PastryTestScroll.kt | 1 | 1941 | package com.teamwizardry.librarianlib.facade.test.screens.pastry.tests
import com.teamwizardry.librarianlib.facade.layers.SpriteLayer
import com.teamwizardry.librarianlib.facade.pastry.layers.PastryScrollPane
import com.teamwizardry.librarianlib.facade.pastry.layers.dropdown.DropdownTextItem
import com.teamwizardry.librarianlib.facade.pastry.layers.dropdown.PastryDropdown
import com.teamwizardry.librarianlib.facade.test.screens.pastry.PastryTestBase
import com.teamwizardry.librarianlib.math.Vec2d
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.mosaic.Mosaic
import net.minecraft.util.Identifier
class PastryTestScroll: PastryTestBase() {
init {
val size = vec(150, 150)
val scroll = PastryScrollPane(0, 0, size.xi + 2, size.yi + 2)
val contentBackground = SpriteLayer(Mosaic(Identifier("textures/block/dirt.png"), 16, 16).getSprite(""))
scroll.content.add(contentBackground)
scroll.showHorizontalScrollbar = null
scroll.showVerticalScrollbar = null
val sizeDropdown = PastryDropdown<Vec2d>(3, 0, 0) {
scroll.content.size = it
contentBackground.size = it
}
sizeDropdown.items.addAll(
listOf(
"Zero" to vec(0, 0),
"Small" to size * 0.75,
"Exact" to size,
"Wide" to size * vec(1.5, 1),
"Wide + Short" to size * vec(1.5, 0.75),
"Tall" to size * vec(1, 1.5),
"Tall + Narrow" to size * vec(0.75, 1.5),
"Big" to size * vec(1.5, 1.5),
"Huge" to size * vec(2.5, 2.5)
).map {
DropdownTextItem(it.second, "${it.first} (${it.second.x}, ${it.second.y})")
}
)
sizeDropdown.sizeToFit()
sizeDropdown.select(size)
this.stack.add(sizeDropdown)
this.stack.add(scroll)
}
} | lgpl-3.0 | d56777644b1718404aff3e65e742e02d | 41.217391 | 112 | 0.634724 | 3.882 | false | true | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/MotionTokens.kt | 3 | 2260 | /*
* 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.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.animation.core.CubicBezierEasing
internal object MotionTokens {
const val DurationExtraLong1 = 700.0
const val DurationExtraLong2 = 800.0
const val DurationExtraLong3 = 900.0
const val DurationExtraLong4 = 1000.0
const val DurationLong1 = 450.0
const val DurationLong2 = 500.0
const val DurationLong3 = 550.0
const val DurationLong4 = 600.0
const val DurationMedium1 = 250.0
const val DurationMedium2 = 300.0
const val DurationMedium3 = 350.0
const val DurationMedium4 = 400.0
const val DurationShort1 = 50.0
const val DurationShort2 = 100.0
const val DurationShort3 = 150.0
const val DurationShort4 = 200.0
val EasingEmphasizedCubicBezier = CubicBezierEasing(0.2f, 0.0f, 0.0f, 1.0f)
val EasingEmphasizedAccelerateCubicBezier = CubicBezierEasing(0.3f, 0.0f, 0.8f, 0.15f)
val EasingEmphasizedDecelerateCubicBezier = CubicBezierEasing(0.05f, 0.7f, 0.1f, 1.0f)
val EasingLegacyCubicBezier = CubicBezierEasing(0.4f, 0.0f, 0.2f, 1.0f)
val EasingLegacyAccelerateCubicBezier = CubicBezierEasing(0.4f, 0.0f, 1.0f, 1.0f)
val EasingLegacyDecelerateCubicBezier = CubicBezierEasing(0.0f, 0.0f, 0.2f, 1.0f)
val EasingLinearCubicBezier = CubicBezierEasing(0.0f, 0.0f, 1.0f, 1.0f)
val EasingStandardCubicBezier = CubicBezierEasing(0.2f, 0.0f, 0.0f, 1.0f)
val EasingStandardAccelerateCubicBezier = CubicBezierEasing(0.3f, 0.0f, 1.0f, 1.0f)
val EasingStandardDecelerateCubicBezier = CubicBezierEasing(0.0f, 0.0f, 0.0f, 1.0f)
}
| apache-2.0 | a5086a4689938290fb2e486178bc8a27 | 44.2 | 90 | 0.740708 | 3.294461 | false | false | false | false |
inorichi/tachiyomi-extensions | src/it/mangaeden/src/eu/kanade/tachiyomi/extension/it/mangaeden/Mangaeden.kt | 1 | 9329 | package eu.kanade.tachiyomi.extension.it.mangaeden
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
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 eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class Mangaeden : ParsedHttpSource() {
override val name = "Manga Eden"
override val baseUrl = "https://www2.mangaeden.com"
override val lang = "it"
override val supportsLatest = true
// so hcaptcha won't be triggered on images
override fun headersBuilder(): Headers.Builder {
return super.headersBuilder().add("Referer", baseUrl)
}
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/it/it-directory/?order=3&page=$page", headers)
override fun latestUpdatesSelector() = searchMangaSelector()
override fun latestUpdatesFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = searchMangaNextPageSelector()
override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/it/it-directory/?order=1&page=$page", headers)
override fun popularMangaSelector() = searchMangaSelector()
override fun popularMangaFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun popularMangaNextPageSelector() = searchMangaNextPageSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/it/it-directory/".toHttpUrlOrNull()?.newBuilder()!!.addQueryParameter("title", query)
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is StatusList ->
filter.state
.filter { it.state }
.map { it.id.toString() }
.forEach { url.addQueryParameter("status", it) }
is Types ->
filter.state
.filter { it.state }
.map { it.id.toString() }
.forEach { url.addQueryParameter("type", it) }
is GenreList ->
filter.state
.filter { !it.isIgnored() }
.forEach { genre -> url.addQueryParameter(if (genre.isIncluded()) "categoriesInc" else "categoriesExcl", genre.id) }
is TextField -> url.addQueryParameter(filter.key, filter.state)
is OrderBy -> filter.state?.let {
val sortId = it.index
url.addQueryParameter("order", if (it.ascending) "-$sortId" else "$sortId")
}
}
}
url.addQueryParameter("page", page.toString())
return GET(url.toString(), headers)
}
override fun searchMangaSelector() = "table#mangaList tbody tr td:first-child a"
override fun searchMangaFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.text()
}
override fun searchMangaNextPageSelector() = "a:has(span.next)"
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val infos = document.select("div.rightbox")
author = infos.select("a[href^=/it/it-directory/?author]").first()?.text()
artist = infos.select("a[href^=/it/it-directory/?artist]").first()?.text()
genre = infos.select("a[href^=/it/it-directory/?categoriesInc]").joinToString { it.text() }
description = document.select("h2#mangaDescription").text()
status = parseStatus(infos.select("h4:containsOwn(Stato)").first()?.nextSibling().toString())
thumbnail_url = document.select("div.mangaImage2 > img").attr("abs:src")
}
private fun parseStatus(status: String) = when {
status.contains("In Corso", true) -> SManga.ONGOING
status.contains("Completato", true) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div#leftContent > table > tbody > tr"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
val a = element.select("a[href^=/it/it-manga/]").first()
setUrlWithoutDomain(a.attr("href"))
name = a?.select("b")?.first()?.text().orEmpty()
date_upload = element.select("td.chapterDate").first()?.text()?.let { parseChapterDate(it.trim()) } ?: 0L
}
private fun parseChapterDate(date: String): Long =
when {
"Oggi" in date -> {
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
}
"Ieri" in date -> {
Calendar.getInstance().apply {
add(Calendar.DATE, -1)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
}
else ->
try {
SimpleDateFormat("d MMM yyyy", Locale.ITALIAN).parse(date)?.time ?: 0L
} catch (e: ParseException) {
0L
}
}
override fun pageListParse(document: Document): List<Page> {
return document.select("select#pageSelect option").mapIndexed { i, element ->
Page(i, element.attr("abs:value"))
}
}
override fun imageUrlParse(document: Document): String = document.select("a.next img").attr("abs:src")
private class NamedId(name: String, val id: Int) : Filter.CheckBox(name)
private class Genre(name: String, val id: String) : Filter.TriState(name)
private class TextField(name: String, val key: String) : Filter.Text(name)
private class OrderBy : Filter.Sort(
"Order by",
arrayOf("Titolo manga", "Visite", "Capitoli", "Ultimo capitolo"),
Selection(1, false)
)
private class StatusList(statuses: List<NamedId>) : Filter.Group<NamedId>("Stato", statuses)
private class Types(types: List<NamedId>) : Filter.Group<NamedId>("Tipo", types)
private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Generi", genres)
override fun getFilterList() = FilterList(
TextField("Autore", "author"),
TextField("Artista", "artist"),
OrderBy(),
Types(types()),
StatusList(statuses()),
GenreList(genres())
)
private fun types() = listOf(
NamedId("Japanese Manga", 0),
NamedId("Korean Manhwa", 1),
NamedId("Chinese Manhua", 2),
NamedId("Comic", 3),
NamedId("Doujinshi", 4)
)
private fun statuses() = listOf(
NamedId("In corso", 1),
NamedId("Completato", 2),
NamedId("Sospeso", 0)
)
private fun genres() = listOf(
Genre("Avventura", "4e70ea8cc092255ef70073d3"),
Genre("Azione", "4e70ea8cc092255ef70073c3"),
Genre("Bara", "4e70ea90c092255ef70074b7"),
Genre("Commedia", "4e70ea8cc092255ef70073d0"),
Genre("Demenziale", "4e70ea8fc092255ef7007475"),
Genre("Dounshinji", "4e70ea93c092255ef70074e4"),
Genre("Drama", "4e70ea8cc092255ef70073f9"),
Genre("Ecchi", "4e70ea8cc092255ef70073cd"),
Genre("Fantasy", "4e70ea8cc092255ef70073c4"),
Genre("Harem", "4e70ea8cc092255ef70073d1"),
Genre("Hentai", "4e70ea90c092255ef700749a"),
Genre("Horror", "4e70ea8cc092255ef70073ce"),
Genre("Josei", "4e70ea90c092255ef70074bd"),
Genre("Magico", "4e70ea93c092255ef700751b"),
Genre("Mecha", "4e70ea8cc092255ef70073ef"),
Genre("Misteri", "4e70ea8dc092255ef700740a"),
Genre("Musica", "4e70ea8fc092255ef7007456"),
Genre("Psicologico", "4e70ea8ec092255ef7007439"),
Genre("Raccolta", "4e70ea90c092255ef70074ae"),
Genre("Romantico", "4e70ea8cc092255ef70073c5"),
Genre("Sci-Fi", "4e70ea8cc092255ef70073e4"),
Genre("Scolastico", "4e70ea8cc092255ef70073e5"),
Genre("Seinen", "4e70ea8cc092255ef70073ea"),
Genre("Sentimentale", "4e70ea8dc092255ef7007432"),
Genre("Shota", "4e70ea90c092255ef70074b8"),
Genre("Shoujo", "4e70ea8dc092255ef7007421"),
Genre("Shounen", "4e70ea8cc092255ef70073c6"),
Genre("Sovrannaturale", "4e70ea8cc092255ef70073c7"),
Genre("Splatter", "4e70ea99c092255ef70075a3"),
Genre("Sportivo", "4e70ea8dc092255ef7007426"),
Genre("Storico", "4e70ea8cc092255ef70073f4"),
Genre("Vita Quotidiana", "4e70ea8ec092255ef700743f"),
Genre("Yaoi", "4e70ea8cc092255ef70073de"),
Genre("Yuri", "4e70ea9ac092255ef70075d1")
)
}
| apache-2.0 | dbd9202592e258dd00f03704dd276952 | 40.647321 | 140 | 0.623432 | 3.891948 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/mine/adapter/NoticeMenuAdapter.kt | 1 | 2573 | package com.intfocus.template.dashboard.mine.adapter
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.intfocus.template.R
import com.intfocus.template.dashboard.mine.bean.NoticeMenuBean
/**
* Created by CANC on 2017/7/24.
*/
class NoticeMenuAdapter(val context: Context,
private var noticeMenuDatas: List<NoticeMenuBean>?,
var listener: NoticeItemListener) : RecyclerView.Adapter<NoticeMenuAdapter.NoticeMenuHolder>() {
var inflater = LayoutInflater.from(context)
fun setData(data: List<NoticeMenuBean>?) {
this.noticeMenuDatas = data
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoticeMenuHolder {
val contentView = inflater.inflate(R.layout.item_notice_menu, parent, false)
return NoticeMenuHolder(contentView)
}
override fun onBindViewHolder(holder: NoticeMenuHolder, position: Int) {
if (noticeMenuDatas != null) {
holder.tvNoticeMenuName.text = getTypeStr(noticeMenuDatas!![position].code)
holder.tvNoticeMenuName.setOnClickListener { listener.menuClick(noticeMenuDatas!![position]) }
if (noticeMenuDatas!![position].isSelected) {
holder.tvNoticeMenuName.setBackgroundResource(R.drawable.background_light_blue_radius_border_dark_blue)
holder.tvNoticeMenuName.setTextColor(ContextCompat.getColor(context, R.color.color15))
} else {
holder.tvNoticeMenuName.setBackgroundResource(R.drawable.background_white_border_gray)
holder.tvNoticeMenuName.setTextColor(ContextCompat.getColor(context, R.color.color3))
}
}
}
override fun getItemCount(): Int = if (noticeMenuDatas == null) 0 else noticeMenuDatas!!.size
class NoticeMenuHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvNoticeMenuName = itemView.findViewById<TextView>(R.id.tv_notice_menu_name)
}
interface NoticeItemListener {
fun menuClick(noticeMenuBean: NoticeMenuBean)
}
private fun getTypeStr(type: Int): String {
when (type) {
0 -> return "系统公告"
1 -> return "业务公告"
2 -> return "预警体系"
3 -> return "报表评论"
}
return "未知公告"
}
}
| gpl-3.0 | 01e3df8892ec0b7eaf65983d1cdf21aa | 37.969231 | 120 | 0.688906 | 4.352234 | false | false | false | false |
ZieIony/Carbon | samples/src/main/java/tk/zielony/carbonsamples/dialog/ListDialogActivity.kt | 1 | 2214 | package tk.zielony.carbonsamples.dialog
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import carbon.component.DefaultImageTextSubtextDateItem
import carbon.component.ImageTextSubtextDateRow
import carbon.dialog.ListDialog
import carbon.widget.EditText
import com.annimon.stream.Stream
import tk.zielony.carbonsamples.R
import tk.zielony.carbonsamples.SampleAnnotation
import tk.zielony.carbonsamples.ThemedActivity
import tk.zielony.randomdata.RandomData
import tk.zielony.randomdata.Target
import tk.zielony.randomdata.common.DateGenerator
import tk.zielony.randomdata.common.DrawableImageGenerator
import tk.zielony.randomdata.common.TextGenerator
import tk.zielony.randomdata.person.StringNameGenerator
import tk.zielony.randomdata.transformer.DateToStringTransformer
@SampleAnnotation(layoutId = R.layout.activity_listdialog, titleId = R.string.listDialogActivity_title)
class ListDialogActivity : ThemedActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
val titleText = findViewById<EditText>(R.id.titleText)
val items = Stream.generate { DefaultImageTextSubtextDateItem() }.limit(9).toList()
val randomData = RandomData()
randomData.addGenerator(Drawable::class.java, DrawableImageGenerator(this))
randomData.addGenerator(String::class.java, StringNameGenerator().withMatcher {
f: Target -> f.name == "text" && f.declaringClass == DefaultImageTextSubtextDateItem::class.java
})
randomData.addGenerator(String::class.java, TextGenerator().withMatcher { f: Target -> f.name == "subtext" })
randomData.addGenerator(String::class.java, DateGenerator().withTransformer(DateToStringTransformer()))
randomData.fill(items)
findViewById<View>(R.id.button).setOnClickListener { view: View? ->
val dialog = ListDialog<DefaultImageTextSubtextDateItem>(this)
dialog.setItems(items, { ImageTextSubtextDateRow<DefaultImageTextSubtextDateItem>(it) })
if (titleText.length() > 0) dialog.setTitle(titleText.getText())
dialog.show()
}
}
} | apache-2.0 | 67c6a8e3464cda9c1416f716924c68c4 | 44.204082 | 117 | 0.763776 | 4.299029 | false | false | false | false |
kryptnostic/rhizome | src/main/kotlin/com/openlattice/tasks/pods/TaskSchedulerPod.kt | 1 | 4242 | /*
* Copyright (C) 2019. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.tasks.pods
import com.hazelcast.core.HazelcastInstance
import com.kryptnostic.rhizome.startup.Requirement
import com.openlattice.tasks.HazelcastFixedRateTask
import com.openlattice.tasks.HazelcastInitializationTask
import com.openlattice.tasks.HazelcastTaskDependencies
import com.openlattice.tasks.TaskService
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import javax.inject.Inject
const val STARTUP_LOCK = "_TSS_STARTUP_LOCK_"
const val LATCH = "_TSS_LATCH_"
private val logger = LoggerFactory.getLogger(TaskSchedulerBootstrapPod::class.java)
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
@Configuration
@Import(TaskSchedulerBootstrapPod::class)
class TaskSchedulerPod {
@Inject
private lateinit var context: ApplicationContext
@Inject
private lateinit var hazelcastInstance: HazelcastInstance
@Inject
private lateinit var tasks: MutableSet<HazelcastFixedRateTask<*>>
@Inject
private lateinit var initializers: MutableSet<HazelcastInitializationTask<*>>
@Inject
private lateinit var dependencies: MutableSet<HazelcastTaskDependencies>
@Bean
fun taskSchedulerService(): TaskService {
val dependenciesMap: Map<Class<*>, HazelcastTaskDependencies> = dependencies
.filter { it !is TaskSchedulerBootstrapPod.NoOpDependencies }
.groupBy { it.javaClass as Class<*> }
.mapValues {
if (it.value.size > 1) {
logger.error(
"Encountered {} dependencies of type {}. Please resolve ambiguity.",
it.value.size,
it.key.canonicalName
)
throw IllegalStateException(
"Encountered ${it.value.size} dependencies of type ${it.key.canonicalName}. Please resolve ambiguity."
)
} else {
it.value.first()
}
}
val validTasks = tasks.filter { it.name != NO_OP_TASK_NAME }
validTasks.forEach { task ->
if (!dependenciesMap.contains(task.getDependenciesClass())) {
logger.error("Dependencies missing for task {}", task.name)
throw IllegalStateException("Dependencies missing for task ${task.name}")
}
}
val validInitializers = initializers.filter { it.name != NO_OP_INITIALIZER_NAME }
validInitializers.forEach { initializer ->
if (!dependenciesMap.contains(initializer.getDependenciesClass())) {
logger.error("Dependencies missing for initializer {}", initializer.name)
throw IllegalStateException("Dependencies missing for initializer ${initializer.name}")
}
}
return TaskService(
context,
dependenciesMap,
validTasks.toSet(),
validInitializers.toSet(),
hazelcastInstance
)
}
@Bean
fun initializersCompletedRequirement(): Requirement {
return taskSchedulerService().getInitializersCompletedRequirements()
}
} | apache-2.0 | ddba859dae789e7667a574bbf74e4627 | 35.577586 | 134 | 0.658652 | 5.129383 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/browse/MovieBrowseFragment.kt | 1 | 5079 | package com.themovielist.browse
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.arlib.floatingsearchview.FloatingSearchView
import com.themovielist.R
import com.themovielist.base.BaseFragment
import com.themovielist.base.BasePresenter
import com.themovielist.injector.components.ApplicationComponent
import com.themovielist.injector.components.DaggerFragmentComponent
import com.themovielist.model.MovieModel
import com.themovielist.model.response.ConfigurationImageResponseModel
import com.themovielist.model.view.MovieCastViewModel
import com.themovielist.model.view.MovieImageGenreViewModel
import com.themovielist.model.view.SearchSuggestionModel
import com.themovielist.movielist.MovieListFragment
import com.themovielist.util.setDisplay
import kotlinx.android.synthetic.main.movie_browse_fragment.*
import javax.inject.Inject
class MovieBrowseFragment : BaseFragment<MovieBrowseContract.View>(), MovieBrowseContract.View {
override val presenterImplementation: BasePresenter<MovieBrowseContract.View>
get() = mPresenter
override val viewImplementation: MovieBrowseContract.View
get() = this
@Inject
lateinit var mPresenter: MovieBrowsePresenter
lateinit var mMovieListFragment: MovieListFragment
override fun onInjectDependencies(applicationComponent: ApplicationComponent) {
DaggerFragmentComponent.builder()
.applicationComponent(applicationComponent)
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.movie_browse_fragment, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
configureComponents()
val movieCastViewModel = buildMovieCastViewModel(savedInstanceState)
mPresenter.start(movieCastViewModel)
}
private fun configureComponents() {
fsvMovieBrowseSearch.setOnQueryChangeListener { _, newQuery ->
mPresenter.onQueryChanged(newQuery)
}
fsvMovieBrowseSearch.setOnBindSuggestionCallback { suggestionView, _, _, searchSuggestion, _ ->
suggestionView.setOnClickListener {
val movieSuggestionModel = searchSuggestion as SearchSuggestionModel
mPresenter.onSelectSuggestion(movieSuggestionModel)
}
}
fsvMovieBrowseSearch.setOnFocusChangeListener(object : FloatingSearchView.OnFocusChangeListener {
override fun onFocusCleared() {
fsvMovieBrowseSearch.setSearchHint(getString(R.string.search))
}
override fun onFocus() {
fsvMovieBrowseSearch.setSearchHint(getString(R.string.type_at_least_three_characters))
}
})
mMovieListFragment = fragmentManager.findFragmentById(R.id.fragmentBrowseMovieList) as? MovieListFragment ?:
childFragmentManager.findFragmentById(R.id.fragmentBrowseMovieList) as MovieListFragment
mMovieListFragment.onTryAgainListener = {
mPresenter.tryAgain()
}
mMovieListFragment.useListLayout()
}
override fun showLoadingQueryResultIndicator() {
fsvMovieBrowseSearch.showProgress()
}
override fun showSuggestion(suggestionList: List<MovieModel>) {
fsvMovieBrowseSearch.swapSuggestions(suggestionList.map { SearchSuggestionModel(it) })
}
override fun hideLoadingQueryResultIndicator() {
fsvMovieBrowseSearch.hideProgress()
}
private fun buildMovieCastViewModel(savedInstanceState: Bundle?): MovieCastViewModel {
return if (savedInstanceState == null) {
MovieCastViewModel()
} else {
savedInstanceState.getParcelable(MOVIE_CAST_VIEW_MODEL_BUNDLE_KEY)
}
}
override fun closeSuggestion() {
fsvMovieBrowseSearch.clearSuggestions()
fsvMovieBrowseSearch.clearSearchFocus()
}
override fun showMovieList(movieList: List<MovieImageGenreViewModel>, configurationImageResponseModel: ConfigurationImageResponseModel) {
blah.setDisplay(false)
flMovieListContainer.setDisplay(true)
mMovieListFragment.replaceMoviesToList(movieList, configurationImageResponseModel)
}
override fun showErrorLoadingQueryResult(error: Throwable) {
mMovieListFragment.showErrorLoadingMovies()
}
override fun hideLoadingIndicator() {
mMovieListFragment.hideLoadingIndicator()
}
override fun showLoadingIndicator() {
mMovieListFragment.showLoadingIndicator()
}
override fun onStop() {
super.onStop()
mPresenter.onStop()
}
companion object {
const val MOVIE_CAST_VIEW_MODEL_BUNDLE_KEY = "movie_cast_view_model"
fun getInstance(): MovieBrowseFragment {
return MovieBrowseFragment()
}
}
}
| apache-2.0 | 08bf11e28c251b33c7a5604fa71dc8ec | 35.539568 | 141 | 0.729868 | 5.323899 | false | false | false | false |
jeffgbutler/mybatis-dynamic-sql | src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/KotlinUpdateBuilder.kt | 1 | 3292 | /*
* Copyright 2016-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.dynamic.sql.util.kotlin
import org.mybatis.dynamic.sql.BasicColumn
import org.mybatis.dynamic.sql.SortSpecification
import org.mybatis.dynamic.sql.SqlColumn
import org.mybatis.dynamic.sql.update.UpdateDSL
import org.mybatis.dynamic.sql.update.UpdateModel
import org.mybatis.dynamic.sql.util.Buildable
typealias UpdateCompleter = KotlinUpdateBuilder.() -> Unit
class KotlinUpdateBuilder(private val dsl: UpdateDSL<UpdateModel>) :
KotlinBaseBuilder<UpdateDSL<UpdateModel>>(), Buildable<UpdateModel> {
fun <T> set(column: SqlColumn<T>): KotlinSetClauseFinisher<T> = KotlinSetClauseFinisher(column)
fun orderBy(vararg columns: SortSpecification) {
dsl.orderBy(columns.toList())
}
fun limit(limit: Long) {
dsl.limit(limit)
}
override fun build(): UpdateModel = dsl.build()
override fun getDsl(): UpdateDSL<UpdateModel> = dsl
@MyBatisDslMarker
@Suppress("TooManyFunctions")
inner class KotlinSetClauseFinisher<T>(private val column: SqlColumn<T>) {
fun equalToNull(): Unit =
applyToDsl {
set(column).equalToNull()
}
infix fun equalToConstant(constant: String): Unit =
applyToDsl {
set(column).equalToConstant(constant)
}
infix fun equalToStringConstant(constant: String): Unit =
applyToDsl {
set(column).equalToStringConstant(constant)
}
infix fun equalTo(value: T & Any): Unit = equalTo { value }
infix fun equalTo(value: () -> T & Any): Unit =
applyToDsl {
set(column).equalTo(value)
}
infix fun equalTo(rightColumn: BasicColumn): Unit =
applyToDsl {
set(column).equalTo(rightColumn)
}
infix fun equalToOrNull(value: T?): Unit = equalToOrNull { value }
infix fun equalToOrNull(value: () -> T?): Unit =
applyToDsl {
set(column).equalToOrNull(value)
}
infix fun equalToQueryResult(subQuery: KotlinSubQueryBuilder.() -> Unit): Unit =
applyToDsl {
set(column).equalTo(KotlinSubQueryBuilder().apply(subQuery))
}
infix fun equalToWhenPresent(value: () -> T?): Unit =
applyToDsl {
set(column).equalToWhenPresent(value)
}
infix fun equalToWhenPresent(value: T?): Unit = equalToWhenPresent { value }
private fun applyToDsl(block: UpdateDSL<UpdateModel>.() -> Unit) {
[email protected](block)
}
}
}
| apache-2.0 | 457abc08bfb018885b2cf86d76939bce | 32.938144 | 99 | 0.639429 | 4.491132 | false | false | false | false |
udacity/ud862-samples | GroupsDemo/app/src/main/java/com/udacity/groupsdemo/MainActivity.kt | 1 | 911 | package com.udacity.groupsdemo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.constraint.Group
import android.view.View
import android.widget.Button
class MainActivity : AppCompatActivity(), View.OnClickListener {
lateinit var button: Button
lateinit var group: Group
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button)
group = findViewById(R.id.group)
button.setOnClickListener(this)
}
override fun onClick(v: View?) {
if (group.visibility == View.GONE) {
group.visibility = View.VISIBLE
button.setText(R.string.hide_details)
} else {
group.visibility = View.GONE
button.setText(R.string.show_details)
}
}
}
| mit | ad41d1224ab8feecfa2ffe035999b591 | 26.606061 | 64 | 0.678375 | 4.379808 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/browse/BrowseSourcePresenter.kt | 1 | 16323 | package eu.kanade.tachiyomi.ui.browse.source.browse
import android.content.res.Configuration
import android.os.Bundle
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.map
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.core.prefs.CheckboxState
import eu.kanade.core.prefs.mapAsCheckboxState
import eu.kanade.domain.base.BasePreferences
import eu.kanade.domain.category.interactor.GetCategories
import eu.kanade.domain.category.interactor.SetMangaCategories
import eu.kanade.domain.chapter.interactor.GetChapterByMangaId
import eu.kanade.domain.chapter.interactor.SetMangaDefaultChapterFlags
import eu.kanade.domain.chapter.interactor.SyncChaptersWithTrackServiceTwoWay
import eu.kanade.domain.library.service.LibraryPreferences
import eu.kanade.domain.manga.interactor.GetDuplicateLibraryManga
import eu.kanade.domain.manga.interactor.GetManga
import eu.kanade.domain.manga.interactor.InsertManga
import eu.kanade.domain.manga.interactor.UpdateManga
import eu.kanade.domain.manga.model.toDbManga
import eu.kanade.domain.manga.model.toMangaUpdate
import eu.kanade.domain.source.interactor.GetRemoteManga
import eu.kanade.domain.source.service.SourcePreferences
import eu.kanade.domain.track.interactor.InsertTrack
import eu.kanade.domain.track.model.toDomainTrack
import eu.kanade.presentation.browse.BrowseSourceState
import eu.kanade.presentation.browse.BrowseSourceStateImpl
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.toDomainManga
import eu.kanade.tachiyomi.data.track.EnhancedTrackService
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.ui.browse.source.filter.CheckboxItem
import eu.kanade.tachiyomi.ui.browse.source.filter.CheckboxSectionItem
import eu.kanade.tachiyomi.ui.browse.source.filter.GroupItem
import eu.kanade.tachiyomi.ui.browse.source.filter.HeaderItem
import eu.kanade.tachiyomi.ui.browse.source.filter.SelectItem
import eu.kanade.tachiyomi.ui.browse.source.filter.SelectSectionItem
import eu.kanade.tachiyomi.ui.browse.source.filter.SeparatorItem
import eu.kanade.tachiyomi.ui.browse.source.filter.SortGroup
import eu.kanade.tachiyomi.ui.browse.source.filter.SortItem
import eu.kanade.tachiyomi.ui.browse.source.filter.TextItem
import eu.kanade.tachiyomi.ui.browse.source.filter.TextSectionItem
import eu.kanade.tachiyomi.ui.browse.source.filter.TriStateItem
import eu.kanade.tachiyomi.ui.browse.source.filter.TriStateSectionItem
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.withIOContext
import eu.kanade.tachiyomi.util.lang.withNonCancellableContext
import eu.kanade.tachiyomi.util.removeCovers
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import logcat.LogPriority
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.Date
import eu.kanade.domain.category.model.Category as DomainCategory
import eu.kanade.domain.manga.model.Manga as DomainManga
open class BrowseSourcePresenter(
private val sourceId: Long,
searchQuery: String? = null,
private val state: BrowseSourceStateImpl = BrowseSourceState(searchQuery) as BrowseSourceStateImpl,
private val sourceManager: SourceManager = Injekt.get(),
preferences: BasePreferences = Injekt.get(),
sourcePreferences: SourcePreferences = Injekt.get(),
private val libraryPreferences: LibraryPreferences = Injekt.get(),
private val coverCache: CoverCache = Injekt.get(),
private val getRemoteManga: GetRemoteManga = Injekt.get(),
private val getManga: GetManga = Injekt.get(),
private val getDuplicateLibraryManga: GetDuplicateLibraryManga = Injekt.get(),
private val getCategories: GetCategories = Injekt.get(),
private val getChapterByMangaId: GetChapterByMangaId = Injekt.get(),
private val setMangaCategories: SetMangaCategories = Injekt.get(),
private val setMangaDefaultChapterFlags: SetMangaDefaultChapterFlags = Injekt.get(),
private val insertManga: InsertManga = Injekt.get(),
private val updateManga: UpdateManga = Injekt.get(),
private val insertTrack: InsertTrack = Injekt.get(),
private val syncChaptersWithTrackServiceTwoWay: SyncChaptersWithTrackServiceTwoWay = Injekt.get(),
) : BasePresenter<BrowseSourceController>(), BrowseSourceState by state {
private val loggedServices by lazy { Injekt.get<TrackManager>().services.filter { it.isLogged } }
var displayMode by sourcePreferences.sourceDisplayMode().asState()
val isDownloadOnly: Boolean by preferences.downloadedOnly().asState()
val isIncognitoMode: Boolean by preferences.incognitoMode().asState()
@Composable
fun getColumnsPreferenceForCurrentOrientation(): State<GridCells> {
val isLandscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE
return produceState<GridCells>(initialValue = GridCells.Adaptive(128.dp), isLandscape) {
(if (isLandscape) libraryPreferences.landscapeColumns() else libraryPreferences.portraitColumns())
.changes()
.collectLatest { columns ->
value = if (columns == 0) GridCells.Adaptive(128.dp) else GridCells.Fixed(columns)
}
}
}
@Composable
fun getMangaList(): Flow<PagingData<DomainManga>> {
return remember(currentFilter) {
Pager(
PagingConfig(pageSize = 25),
) {
getRemoteManga.subscribe(sourceId, currentFilter.query, currentFilter.filters)
}.flow
.map {
it.map {
withIOContext {
networkToLocalManga(it, sourceId).toDomainManga()!!
}
}
}
.cachedIn(presenterScope)
}
}
@Composable
fun getManga(initialManga: DomainManga): State<DomainManga> {
return produceState(initialValue = initialManga) {
getManga.subscribe(initialManga.url, initialManga.source)
.collectLatest { manga ->
if (manga == null) return@collectLatest
withIOContext {
initializeManga(manga)
}
value = manga
}
}
}
fun reset() {
state.filters = source!!.getFilterList()
if (currentFilter !is Filter.UserInput) return
state.currentFilter = (currentFilter as Filter.UserInput).copy(filters = state.filters)
}
fun search(query: String? = null, filters: FilterList? = null) {
Filter.valueOf(query ?: "").let {
if (it !is Filter.UserInput) {
state.currentFilter = it
return
}
}
val input: Filter.UserInput = if (currentFilter is Filter.UserInput) currentFilter as Filter.UserInput else Filter.UserInput()
state.currentFilter = input.copy(
query = query ?: input.query,
filters = filters ?: input.filters,
)
}
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
state.source = sourceManager.get(sourceId) as? CatalogueSource ?: return
state.filters = source!!.getFilterList()
}
/**
* Returns a manga from the database for the given manga from network. It creates a new entry
* if the manga is not yet in the database.
*
* @param sManga the manga from the source.
* @return a manga from the database.
*/
private suspend fun networkToLocalManga(sManga: SManga, sourceId: Long): Manga {
var localManga = getManga.await(sManga.url, sourceId)
if (localManga == null) {
val newManga = Manga.create(sManga.url, sManga.title, sourceId)
newManga.copyFrom(sManga)
newManga.id = -1
val id = insertManga.await(newManga.toDomainManga()!!)
val result = getManga.await(id!!)
localManga = result
} else if (!localManga.favorite) {
// if the manga isn't a favorite, set its display title from source
// if it later becomes a favorite, updated title will go to db
localManga = localManga.copy(title = sManga.title)
}
return localManga?.toDbManga()!!
}
/**
* Initialize a manga.
*
* @param manga to initialize.
*/
private suspend fun initializeManga(manga: DomainManga) {
if (manga.thumbnailUrl != null || manga.initialized) return
withNonCancellableContext {
try {
val networkManga = source!!.getMangaDetails(manga.toSManga())
val updatedManga = manga.copyFrom(networkManga)
.copy(initialized = true)
updateManga.await(updatedManga.toMangaUpdate())
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
}
}
}
/**
* Adds or removes a manga from the library.
*
* @param manga the manga to update.
*/
fun changeMangaFavorite(manga: DomainManga) {
presenterScope.launch {
var new = manga.copy(
favorite = !manga.favorite,
dateAdded = when (manga.favorite) {
true -> 0
false -> Date().time
},
)
if (!new.favorite) {
new = new.removeCovers(coverCache)
} else {
setMangaDefaultChapterFlags.await(manga)
autoAddTrack(manga)
}
updateManga.await(new.toMangaUpdate())
}
}
fun getSourceOrStub(manga: DomainManga): Source {
return sourceManager.getOrStub(manga.source)
}
fun addFavorite(manga: DomainManga) {
presenterScope.launch {
val categories = getCategories()
val defaultCategoryId = libraryPreferences.defaultCategory().get()
val defaultCategory = categories.find { it.id == defaultCategoryId.toLong() }
when {
// Default category set
defaultCategory != null -> {
moveMangaToCategories(manga, defaultCategory)
changeMangaFavorite(manga)
}
// Automatic 'Default' or no categories
defaultCategoryId == 0 || categories.isEmpty() -> {
moveMangaToCategories(manga)
changeMangaFavorite(manga)
}
// Choose a category
else -> {
val preselectedIds = getCategories.await(manga.id).map { it.id }
state.dialog = Dialog.ChangeMangaCategory(manga, categories.mapAsCheckboxState { it.id in preselectedIds })
}
}
}
}
private suspend fun autoAddTrack(manga: DomainManga) {
loggedServices
.filterIsInstance<EnhancedTrackService>()
.filter { it.accept(source!!) }
.forEach { service ->
try {
service.match(manga.toDbManga())?.let { track ->
track.manga_id = manga.id
(service as TrackService).bind(track)
insertTrack.await(track.toDomainTrack()!!)
val chapters = getChapterByMangaId.await(manga.id)
syncChaptersWithTrackServiceTwoWay.await(chapters, track.toDomainTrack()!!, service)
}
} catch (e: Exception) {
logcat(LogPriority.WARN, e) { "Could not match manga: ${manga.title} with service $service" }
}
}
}
/**
* Get user categories.
*
* @return List of categories, not including the default category
*/
suspend fun getCategories(): List<DomainCategory> {
return getCategories.subscribe()
.firstOrNull()
?.filterNot { it.isSystemCategory }
?: emptyList()
}
suspend fun getDuplicateLibraryManga(manga: DomainManga): DomainManga? {
return getDuplicateLibraryManga.await(manga.title, manga.source)
}
fun moveMangaToCategories(manga: DomainManga, vararg categories: DomainCategory) {
moveMangaToCategories(manga, categories.filter { it.id != 0L }.map { it.id })
}
fun moveMangaToCategories(manga: DomainManga, categoryIds: List<Long>) {
presenterScope.launchIO {
setMangaCategories.await(
mangaId = manga.id,
categoryIds = categoryIds.toList(),
)
}
}
sealed class Filter(open val query: String, open val filters: FilterList) {
object Popular : Filter(query = GetRemoteManga.QUERY_POPULAR, filters = FilterList())
object Latest : Filter(query = GetRemoteManga.QUERY_LATEST, filters = FilterList())
data class UserInput(override val query: String = "", override val filters: FilterList = FilterList()) : Filter(query = query, filters = filters)
companion object {
fun valueOf(query: String): Filter {
return when (query) {
GetRemoteManga.QUERY_POPULAR -> Popular
GetRemoteManga.QUERY_LATEST -> Latest
else -> UserInput(query = query)
}
}
}
}
sealed class Dialog {
data class RemoveManga(val manga: DomainManga) : Dialog()
data class AddDuplicateManga(val manga: DomainManga, val duplicate: DomainManga) : Dialog()
data class ChangeMangaCategory(
val manga: DomainManga,
val initialSelection: List<CheckboxState.State<DomainCategory>>,
) : Dialog()
}
}
fun FilterList.toItems(): List<IFlexible<*>> {
return mapNotNull { filter ->
when (filter) {
is Filter.Header -> HeaderItem(filter)
is Filter.Separator -> SeparatorItem(filter)
is Filter.CheckBox -> CheckboxItem(filter)
is Filter.TriState -> TriStateItem(filter)
is Filter.Text -> TextItem(filter)
is Filter.Select<*> -> SelectItem(filter)
is Filter.Group<*> -> {
val group = GroupItem(filter)
val subItems = filter.state.mapNotNull {
when (it) {
is Filter.CheckBox -> CheckboxSectionItem(it)
is Filter.TriState -> TriStateSectionItem(it)
is Filter.Text -> TextSectionItem(it)
is Filter.Select<*> -> SelectSectionItem(it)
else -> null
}
}
subItems.forEach { it.header = group }
group.subItems = subItems
group
}
is Filter.Sort -> {
val group = SortGroup(filter)
val subItems = filter.values.map {
SortItem(it, group)
}
group.subItems = subItems
group
}
}
}
}
| apache-2.0 | 57a6c380a098e8dc15d5d8e5b323aa56 | 39.8075 | 153 | 0.649452 | 4.706747 | false | false | false | false |
trofimovilya/Alarmebble | Alarmebble-Android/app/src/main/kotlin/ru/ilyatrofimov/alarmebble/ui/AppsAdapter.kt | 1 | 2900 | package ru.ilyatrofimov.alarmebble.ui
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.ResolveInfo
import android.preference.PreferenceManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.list_item_app.view.*
import ru.ilyatrofimov.alarmebble.R
import java.util.*
class AppsAdapter(private val context: Context) : RecyclerView.Adapter<AppsAdapter.ViewHolder>() {
private var appsList: List<ResolveInfo>
private var checkedPosition: Int
private var selectedActivity: String
private val settings: SharedPreferences
init {
checkedPosition = -1
appsList = ArrayList()
settings = PreferenceManager.getDefaultSharedPreferences(context)
selectedActivity = settings.getString(context.getString(R.string.key_activity), "")
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(LayoutInflater
.from(parent.context).inflate(R.layout.list_item_app, parent, false))
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val app = appsList[position]
if (selectedActivity.equals(app.activityInfo.name)) {
checkedPosition = position
}
with (holder) {
radioButton.isChecked = position == checkedPosition
icon.setImageDrawable(app.loadIcon(context.packageManager))
appName.text = app.loadLabel(context.packageManager)
activityName.text = app.activityInfo.name
activityName.isSelected = radioButton.isChecked
itemView.setOnClickListener {
if (!radioButton.isChecked && checkedPosition != position) {
settings.edit()
.putString(context.getString(R.string.key_process)
, app.activityInfo.processName)
.putString(context.getString(R.string.key_activity)
, app.activityInfo.name)
.apply()
selectedActivity = app.activityInfo.name
radioButton.isChecked = true
activityName.isSelected = true
notifyItemChanged(checkedPosition)
checkedPosition = position
}
}
}
}
override fun getItemCount() = appsList.size
fun setAppsList(appsList: List<ResolveInfo>) {
this.appsList = appsList
notifyDataSetChanged()
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val icon = view.icon
val appName = view.text_app_name
val activityName = view.text_activity_name
val radioButton = view.radio_button
}
}
| mit | 90b4bc22c39a359b9129338bc7087c11 | 36.662338 | 98 | 0.646552 | 5.06993 | false | false | false | false |
java-opengl-labs/ogl-samples | src/main/kotlin/ogl_samples/tests/gl300/gl-300-fbo-multisample.kt | 1 | 5865 | package ogl_samples.tests.gl300
/**
* Created by elect on 08/04/17.
*/
import gli.Texture2d
import gli.gl
import glm_.glm
import glm_.mat4x4.Mat4
import glm_.vec2.Vec2
import glm_.vec2.Vec2i
import ogl_samples.framework.Compiler
import ogl_samples.framework.TestA
import org.lwjgl.opengl.ARBFramebufferObject.*
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL13.*
import uno.buffer.bufferOf
import uno.caps.Caps.Profile
import uno.glf.Vertex
import uno.glf.glf
import uno.glf.semantic
import uno.gln.*
fun main(args: Array<String>) {
gl_300_fbo_multisample().loop()
}
private class gl_300_fbo_multisample : TestA("gl-300-fbo-multisample", Profile.COMPATIBILITY, 3, 0) {
val SHADER_SOURCE = "gl-300/image-2d"
val TEXTURE_DIFFUSE = "kueken7_rgba8_srgb.dds"
val FRAMEBUFFER_SIZE = Vec2i(160, 120)
// With DDS textures, v texture coordinate are reversed, from top to bottom
override var vertexCount = 6
override var vertexData = bufferOf(
Vertex.pos2_tc2(Vec2(-2f, -1.5f), Vec2(0f, 0f)),
Vertex.pos2_tc2(Vec2(+2f, -1.5f), Vec2(1f, 0f)),
Vertex.pos2_tc2(Vec2(+2f, +1.5f), Vec2(1f, 1f)),
Vertex.pos2_tc2(Vec2(+2f, +1.5f), Vec2(1f, 1f)),
Vertex.pos2_tc2(Vec2(-2f, +1.5f), Vec2(0f, 1f)),
Vertex.pos2_tc2(Vec2(-2f, -1.5f), Vec2(0f, 0f)))
override fun initProgram(): Boolean {
var validated = true
val compiler = Compiler()
if (validated) {
val vertShaderName = compiler.create("$SHADER_SOURCE.vert")
val fragShaderName = compiler.create("$SHADER_SOURCE.frag")
initProgram(programName) {
attach(vertShaderName, fragShaderName)
"Position".attrib = semantic.attr.POSITION
"Texcoord".attrib = semantic.attr.TEX_COORD
link()
validated = validated && compiler.check()
validated = validated && compiler checkProgram name
}
}
if (validated) usingProgram(programName) {
Uniform.mvp = "MVP".uniform
Uniform.diffuse = "Diffuse".unit
}
return validated && checkError("initProgram")
}
override fun initBuffer() = initArrayBuffer(vertexData)
override fun initTexture(): Boolean {
val texture = Texture2d(gli.loadDDS("$dataDirectory/$TEXTURE_DIFFUSE"))
gli.gl.profile = gl.Profile.GL32
initTextures2d() {
at(Texture.DIFFUSE) {
levels(base = 0, max = texture.levels() - 1)
filter(min = linear_mmLinear, mag = linear)
val format = gl.translate(texture.format, texture.swizzles)
for (level in 0 until texture.levels())
glTexImage2D(level, format, texture)
}
at(Texture.COLOR) {
filter(min = nearest, mag = nearest)
image(GL_RGBA8, FRAMEBUFFER_SIZE, GL_RGBA, GL_UNSIGNED_BYTE)
}
}
texture.dispose() // TODO rename to destroy
return checkError("initTexture")
}
override fun initRenderbuffer(): Boolean {
initRenderbuffers {
at(Renderbuffer.COLOR) {
storageMultisample(8, GL_RGBA8, FRAMEBUFFER_SIZE) // The first parameter is the number of samples.
if (size != FRAMEBUFFER_SIZE || samples != 8 || format != GL_RGBA8)
return false
}
}
return checkError("initRenderbuffer")
}
override fun initFramebuffer(): Boolean {
initFramebuffers {
at(Framebuffer.RENDER) {
renderbuffer(GL_COLOR_ATTACHMENT0, Renderbuffer.COLOR)
if (!complete) return false
}
at(Framebuffer.RESOLVE) {
texture2D(GL_COLOR_ATTACHMENT0, Texture.COLOR)
if (!complete) return false
}
}
return checkError("initFramebuffer")
}
override fun initVertexArray() = initVertexArray(glf.pos2_tc2)
override fun render(): Boolean {
// Clear the framebuffer
glBindFramebuffer()
glClearColorBuffer(1f, 0.5f, 0f, 1f)
glUseProgram(programName)
// Pass 1
// Render the scene in a multisampled framebuffer
glEnable(GL_MULTISAMPLE)
renderFBO(Framebuffer.RENDER)
glDisable(GL_MULTISAMPLE)
// Resolved multisampling
glBindFramebuffer(GL_READ_FRAMEBUFFER, Framebuffer.RENDER)
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, Framebuffer.RESOLVE)
glBlitFramebuffer(FRAMEBUFFER_SIZE)
glBindFramebuffer()
// Pass 2
// Render the colorbuffer from the multisampled framebuffer
glViewport(windowSize)
renderFB(Texture.COLOR)
return true
}
fun renderFBO(framebuffer: Enum<*>): Boolean {
glBindFramebuffer(framebuffer)
glClearColor(0f, 0.5f, 1f, 1f)
glClear(GL_COLOR_BUFFER_BIT)
val perspective = glm.perspective(glm.PIf * 0.25f, FRAMEBUFFER_SIZE, 0.1f, 100f)
val model = Mat4()
val mvp = perspective * view * model
glUniform(Uniform.mvp, mvp)
glViewport(FRAMEBUFFER_SIZE)
withTexture2d(0, Texture.DIFFUSE) {
glBindVertexArray(vertexArrayName)
glDrawArrays(vertexCount)
}
return checkError("renderFBO")
}
fun renderFB(texture2DName: Enum<*>) {
val perspective = glm.perspective(glm.PIf * 0.25f, windowSize, 0.1f, 100f)
val model = Mat4()
val mvp = perspective * view * model
glUniform(Uniform.mvp, mvp)
withTexture2d(0, Texture.COLOR) {
glBindVertexArray(vertexArrayName)
glDrawArrays(vertexCount)
}
checkError("renderFB")
}
} | mit | 6c80dabf22f49444e73b9e84e518bc8a | 28.477387 | 116 | 0.602046 | 4.061634 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/reader/repository/FetchInterestTagsUseCaseTest.kt | 1 | 3777 | package org.wordpress.android.ui.reader.repository
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import org.assertj.core.api.Assertions
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.models.ReaderTag
import org.wordpress.android.models.ReaderTagList
import org.wordpress.android.test
import org.wordpress.android.ui.reader.ReaderEvents.InterestTagsFetchEnded
import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.Error.NetworkUnavailable
import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.Error.RemoteRequestFailure
import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.SuccessWithData
import org.wordpress.android.ui.reader.repository.usecases.tags.FetchInterestTagsUseCase
import org.wordpress.android.ui.reader.services.update.ReaderUpdateLogic.UpdateTask.INTEREST_TAGS
import org.wordpress.android.ui.reader.services.update.wrapper.ReaderUpdateServiceStarterWrapper
import org.wordpress.android.util.EventBusWrapper
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.viewmodel.ContextProvider
import java.util.EnumSet
@RunWith(MockitoJUnitRunner::class)
class FetchInterestTagsUseCaseTest {
@Rule
@JvmField val rule = InstantTaskExecutorRule()
@Mock lateinit var contextProvider: ContextProvider
@Mock lateinit var eventBusWrapper: EventBusWrapper
@Mock lateinit var networkUtilsWrapper: NetworkUtilsWrapper
@Mock lateinit var readerUpdateServiceStarterWrapper: ReaderUpdateServiceStarterWrapper
private lateinit var useCase: FetchInterestTagsUseCase
@Before
fun setUp() {
useCase = FetchInterestTagsUseCase(
contextProvider,
eventBusWrapper,
networkUtilsWrapper,
readerUpdateServiceStarterWrapper
)
whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true)
}
@Test
fun `NetworkUnavailable returned when no network found`() = test {
// Given
whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false)
// When
val result = useCase.fetch()
// Then
Assertions.assertThat(result).isEqualTo(NetworkUnavailable)
}
@Test
fun `SuccessWithData returned when InterestTagsFetchEnded event is posted with true`() = test {
// Given
val readerTag = mock<ReaderTag>()
val event = InterestTagsFetchEnded(ReaderTagList().apply { add(readerTag) }, true)
whenever(
readerUpdateServiceStarterWrapper.startService(
contextProvider.getContext(),
EnumSet.of(INTEREST_TAGS)
)
).then { useCase.onInterestTagsFetchEnded(event) }
// When
val result = useCase.fetch()
// Then
Assertions.assertThat(result).isEqualTo(SuccessWithData(event.interestTags))
}
@Test
fun `RemoteRequestFailure returned when InterestTagsFetchEnded event is posted with false`() = test {
// Given
val event = InterestTagsFetchEnded(ReaderTagList(), false)
whenever(
readerUpdateServiceStarterWrapper.startService(
contextProvider.getContext(),
EnumSet.of(INTEREST_TAGS)
)
).then { useCase.onInterestTagsFetchEnded(event) }
// When
val result = useCase.fetch()
// Then
Assertions.assertThat(result).isEqualTo(RemoteRequestFailure)
}
}
| gpl-2.0 | 7d7f96df3140691147ceac747ef47d38 | 37.151515 | 106 | 0.727297 | 5.097166 | false | true | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareDelegatingMoveDestination.kt | 1 | 4027 | // 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.moveClassesOrPackages
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPackage
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.MoveDestination
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.refactoring.move.createMoveUsageInfoIfPossible
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.analyzeConflictsInFile
import org.jetbrains.kotlin.idea.stubindex.KotlinExactPackagesIndex
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
class KotlinAwareDelegatingMoveDestination(
private val delegate: MoveDestination,
private val targetPackage: PsiPackage?,
private val targetDirectory: PsiDirectory?
) : MoveDestination by delegate {
override fun analyzeModuleConflicts(
elements: Collection<PsiElement>,
conflicts: MultiMap<PsiElement, String>,
usages: Array<out UsageInfo>
) {
delegate.analyzeModuleConflicts(elements, conflicts, usages)
if (targetPackage == null || targetDirectory == null) return
val project = targetDirectory.project
val moveTarget = KotlinDirectoryMoveTarget(FqName(targetPackage.qualifiedName), targetDirectory.virtualFile)
val directoriesToMove = elements.flatMapTo(LinkedHashSet<PsiDirectory>()) {
(it as? PsiPackage)?.directories?.toList() ?: emptyList()
}
val projectScope = project.projectScope()
val filesToProcess = elements.flatMapTo(LinkedHashSet<KtFile>()) {
if (it is PsiPackage) KotlinExactPackagesIndex.get(it.qualifiedName, project, projectScope) else emptyList()
}
val extraElementsForReferenceSearch = LinkedHashSet<PsiElement>()
val extraElementCollector = object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement) {
if (element is KtNamedDeclaration && element.hasModifier(KtTokens.INTERNAL_KEYWORD)) {
element.parentsWithSelf.lastOrNull { it is KtNamedDeclaration }?.let { extraElementsForReferenceSearch += it }
stopWalking()
}
super.visitElement(element)
}
}
filesToProcess.flatMap { it.declarations }.forEach { it.accept(extraElementCollector) }
val progressIndicator = ProgressManager.getInstance().progressIndicator!!
progressIndicator.pushState()
val extraUsages = ArrayList<UsageInfo>()
try {
progressIndicator.text = KotlinBundle.message("text.looking.for.usages")
for ((index, element) in extraElementsForReferenceSearch.withIndex()) {
progressIndicator.fraction = (index + 1) / extraElementsForReferenceSearch.size.toDouble()
ReferencesSearch.search(element, projectScope).mapNotNullTo(extraUsages) { ref ->
createMoveUsageInfoIfPossible(ref, element, addImportToOriginalFile = true, isInternal = false)
}
}
} finally {
progressIndicator.popState()
}
filesToProcess.forEach {
analyzeConflictsInFile(it, extraUsages, moveTarget, directoriesToMove, conflicts) {}
}
}
} | apache-2.0 | 457d43a28d795a86ba83a2f659452d43 | 48.121951 | 158 | 0.73181 | 5.169448 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/ui/connection_manager/ConnectionManagerActivity.kt | 1 | 5418 | package com.kelsos.mbrc.ui.connection_manager
import android.os.Bundle
import android.view.MenuItem
import androidx.core.view.isGone
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.snackbar.Snackbar
import com.kelsos.mbrc.R
import com.kelsos.mbrc.constants.UserInputEventType
import com.kelsos.mbrc.data.ConnectionSettings
import com.kelsos.mbrc.enums.DiscoveryStop
import com.kelsos.mbrc.events.DefaultSettingsChangedEvent
import com.kelsos.mbrc.events.MessageEvent
import com.kelsos.mbrc.events.bus.RxBus
import com.kelsos.mbrc.events.ui.ConnectionSettingsChanged
import com.kelsos.mbrc.events.ui.DiscoveryStopped
import com.kelsos.mbrc.events.ui.NotifyUser
import com.kelsos.mbrc.ui.activities.FontActivity
import com.kelsos.mbrc.ui.dialogs.SettingsDialogFragment
import toothpick.Scope
import toothpick.Toothpick
import toothpick.smoothie.module.SmoothieActivityModule
import javax.inject.Inject
class ConnectionManagerActivity : FontActivity(),
ConnectionManagerView,
SettingsDialogFragment.SettingsSaveListener,
ConnectionAdapter.ConnectionChangeListener {
@Inject
lateinit var bus: RxBus
@Inject
lateinit var presenter: ConnectionManagerPresenter
@BindView(R.id.connection_list)
lateinit var mRecyclerView: RecyclerView
@BindView(R.id.toolbar)
lateinit var mToolbar: MaterialToolbar
private var adapter: ConnectionAdapter? = null
private var scope: Scope? = null
@OnClick(R.id.connection_add)
internal fun onAddButtonClick() {
val settingsDialog = SettingsDialogFragment()
settingsDialog.show(supportFragmentManager, "settings_dialog")
}
@OnClick(R.id.connection_scan)
internal fun onScanButtonClick() {
findViewById<LinearProgressIndicator>(R.id.connection_manager__progress).isGone = false
bus.post(MessageEvent(UserInputEventType.StartDiscovery))
}
override fun onCreate(savedInstanceState: Bundle?) {
scope = Toothpick.openScopes(application, this)
scope!!.installModules(SmoothieActivityModule(this), ConnectionManagerModule.create())
super.onCreate(savedInstanceState)
Toothpick.inject(this, scope)
setContentView(R.layout.ui_activity_connection_manager)
ButterKnife.bind(this)
setSupportActionBar(mToolbar)
mRecyclerView.setHasFixedSize(true)
val mLayoutManager = LinearLayoutManager(this)
mRecyclerView.layoutManager = mLayoutManager
adapter = ConnectionAdapter()
adapter!!.setChangeListener(this)
mRecyclerView.adapter = adapter
presenter.attach(this)
presenter.load()
}
override fun onDestroy() {
Toothpick.closeScope(this)
super.onDestroy()
}
override fun onStart() {
super.onStart()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setTitle(R.string.connection_manager_title)
}
override fun onResume() {
super.onResume()
presenter.attach(this)
bus.register(
this,
ConnectionSettingsChanged::class.java,
{ this.onConnectionSettingsChange(it) },
true
)
bus.register(this, DiscoveryStopped::class.java, { this.onDiscoveryStopped(it) }, true)
bus.register(this, NotifyUser::class.java, { this.onUserNotification(it) }, true)
}
override fun onPause() {
super.onPause()
presenter.detach()
bus.unregister(this)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> onBackPressed()
else -> return false
}
return true
}
override fun onSave(settings: ConnectionSettings) {
presenter.save(settings)
}
private fun onConnectionSettingsChange(event: ConnectionSettingsChanged) {
adapter!!.setSelectionId(event.defaultId)
}
private fun onDiscoveryStopped(event: DiscoveryStopped) {
findViewById<LinearProgressIndicator>(R.id.connection_manager__progress).isGone = true
val message: String = when (event.reason) {
DiscoveryStop.NO_WIFI -> getString(R.string.con_man_no_wifi)
DiscoveryStop.NOT_FOUND -> getString(R.string.con_man_not_found)
DiscoveryStop.COMPLETE -> {
presenter.load()
getString(R.string.con_man_success)
}
}
Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show()
}
private fun onUserNotification(event: NotifyUser) {
val message = if (event.isFromResource) getString(event.resId) else event.message
Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show()
}
override fun onDelete(settings: ConnectionSettings) {
presenter.delete(settings)
}
override fun onEdit(settings: ConnectionSettings) {
val settingsDialog = SettingsDialogFragment.newInstance(settings)
val fragmentManager = supportFragmentManager
settingsDialog.show(fragmentManager, "settings_dialog")
}
override fun onDefault(settings: ConnectionSettings) {
presenter.setDefault(settings)
}
override fun updateModel(connectionModel: ConnectionModel) {
adapter!!.update(connectionModel)
}
override fun defaultChanged() {
bus.post(DefaultSettingsChangedEvent.create())
}
override fun dataUpdated() {
presenter.load()
}
}
| gpl-3.0 | 98905c9052155922fe3a666767891849 | 30.684211 | 91 | 0.764858 | 4.451931 | false | false | false | false |
androidstarters/androidstarters.com | templates/buffer-clean-architecture-components-kotlin/mobile-ui/src/main/java/org/buffer/android/boilerplate/ui/browse/BrowseActivity.kt | 1 | 3927 | package <%= appPackage %>.ui.browse
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_browse.*
import <%= appPackage %>.presentation.browse.BrowseBufferoosViewModel
import <%= appPackage %>.presentation.browse.BrowseBufferoosViewModelFactory
import <%= appPackage %>.presentation.data.ResourceState
import <%= appPackage %>.presentation.data.Resource
import <%= appPackage %>.presentation.model.BufferooView
import <%= appPackage %>.ui.R
import <%= appPackage %>.ui.mapper.BufferooMapper
import <%= appPackage %>.ui.widget.empty.EmptyListener
import <%= appPackage %>.ui.widget.error.ErrorListener
import javax.inject.Inject
class BrowseActivity: AppCompatActivity() {
@Inject lateinit var browseAdapter: BrowseAdapter
@Inject lateinit var mapper: BufferooMapper
@Inject lateinit var viewModelFactory: BrowseBufferoosViewModelFactory
private lateinit var browseBufferoosViewModel: BrowseBufferoosViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_browse)
AndroidInjection.inject(this)
browseBufferoosViewModel = ViewModelProviders.of(this, viewModelFactory)
.get(BrowseBufferoosViewModel::class.java)
setupBrowseRecycler()
setupViewListeners()
}
override fun onStart() {
super.onStart()
browseBufferoosViewModel.getBufferoos().observe(this,
Observer<Resource<List<BufferooView>>> {
if (it != null) this.handleDataState(it.status, it.data, it.message) })
}
private fun setupBrowseRecycler() {
recycler_browse.layoutManager = LinearLayoutManager(this)
recycler_browse.adapter = browseAdapter
}
private fun handleDataState(resourceState: ResourceState, data: List<BufferooView>?,
message: String?) {
when (resourceState) {
ResourceState.LOADING -> setupScreenForLoadingState()
ResourceState.SUCCESS -> setupScreenForSuccess(data)
ResourceState.ERROR -> setupScreenForError(message)
}
}
private fun setupScreenForLoadingState() {
progress.visibility = View.VISIBLE
recycler_browse.visibility = View.GONE
view_empty.visibility = View.GONE
view_error.visibility = View.GONE
}
private fun setupScreenForSuccess(data: List<BufferooView>?) {
view_error.visibility = View.GONE
progress.visibility = View.GONE
if (data!= null && data.isNotEmpty()) {
updateListView(data)
recycler_browse.visibility = View.VISIBLE
} else {
view_empty.visibility = View.VISIBLE
}
}
private fun updateListView(bufferoos: List<BufferooView>) {
browseAdapter.bufferoos = bufferoos.map { mapper.mapToViewModel(it) }
browseAdapter.notifyDataSetChanged()
}
private fun setupScreenForError(message: String?) {
progress.visibility = View.GONE
recycler_browse.visibility = View.GONE
view_empty.visibility = View.GONE
view_error.visibility = View.VISIBLE
}
private fun setupViewListeners() {
view_empty.emptyListener = emptyListener
view_error.errorListener = errorListener
}
private val emptyListener = object : EmptyListener {
override fun onCheckAgainClicked() {
browseBufferoosViewModel.fetchBufferoos()
}
}
private val errorListener = object : ErrorListener {
override fun onTryAgainClicked() {
browseBufferoosViewModel.fetchBufferoos()
}
}
} | mit | 42070d6622e8bcf901027235e523d94a | 35.036697 | 91 | 0.696715 | 5.047558 | false | false | false | false |
hellenxu/TipsProject | DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/fragment/WelcomeActivity.kt | 1 | 1460 | package six.ca.droiddailyproject.fragment
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.view.ViewGroup
import android.widget.TextView
import six.ca.droiddailyproject.R
import six.ca.droiddailyproject.SixApplication
/**
* @author hellenxu
* @date 2020-03-01
* Copyright 2020 Six. All rights reserved.
*/
class WelcomeActivity: AppCompatActivity() {
override fun onStart() {
super.onStart()
InfoManager.instance.sharedInt = 1
InfoManager.instance.sharedInfo = InfoManager.Info("123456")
StaticInfo.sharedInt = 2
StaticInfo.sharedInfo = InfoManager.Info("987654")
SixApplication.sharedInt = 4
SixApplication.sharedInfo = InfoManager.Info("plokju")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val tvWelcome = TextView(this)
tvWelcome.text = "Welcome"
tvWelcome.textSize = 22f
tvWelcome.setOnClickListener {
val intent = Intent(this, NestedSampleActivity::class.java)
.apply {
val bundle = Bundle()
bundle.putInt("intent-Int", 6)
bundle.putParcelable("intent-Obj", InfoManager.Info("bnvcmjh"))
this.putExtras(bundle)
}
startActivity(intent)
}
setContentView(tvWelcome)
}
} | apache-2.0 | 98ee530ea05a75130653863b381fb957 | 29.4375 | 83 | 0.652055 | 4.591195 | false | false | false | false |
jk1/intellij-community | platform/configuration-store-impl/src/ModuleStoreImpl.kt | 2 | 4173 | /*
* Copyright 2000-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 com.intellij.configurationStore
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.stores.ModuleStore
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.project.isDirectoryBased
import com.intellij.util.containers.computeIfAny
import com.intellij.util.io.exists
import java.nio.file.Paths
private val MODULE_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(StoragePathMacros.MODULE_FILE, false)
private open class ModuleStoreImpl(module: Module, private val pathMacroManager: PathMacroManager) : ModuleStoreBase() {
override val project = module.project
override val storageManager = ModuleStateStorageManager(pathMacroManager.createTrackingSubstitutor(), module)
override final fun getPathMacroManagerForDefaults() = pathMacroManager
// todo what about Upsource? For now this implemented not in the ModuleStoreBase because `project` and `module` are available only in this class (ModuleStoreImpl)
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val result = super.getStorageSpecs(component, stateSpec, operation)
if (!project.isDirectoryBased) {
return result
}
return StreamProviderFactory.EP_NAME.getExtensions(project).computeIfAny {
LOG.runAndLogException { it.customizeStorageSpecs(component, storageManager, stateSpec, result, operation) }
} ?: result
}
}
private class TestModuleStore(module: Module, pathMacroManager: PathMacroManager) : ModuleStoreImpl(module, pathMacroManager) {
private var moduleComponentLoadPolicy: StateLoadPolicy? = null
override fun setPath(path: String, isNew: Boolean) {
super.setPath(path, isNew)
if (!isNew && Paths.get(path).exists()) {
moduleComponentLoadPolicy = StateLoadPolicy.LOAD
}
}
override val loadPolicy: StateLoadPolicy
get() = moduleComponentLoadPolicy ?: (project.stateStore as ComponentStoreImpl).loadPolicy
}
// used in upsource
abstract class ModuleStoreBase : ComponentStoreImpl(), ModuleStore {
override abstract val storageManager: StateStorageManagerImpl
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
return if (storages.isEmpty()) {
listOf(MODULE_FILE_STORAGE_ANNOTATION)
}
else {
super.getStorageSpecs(component, stateSpec, operation)
}
}
override final fun setPath(path: String) {
setPath(path, false)
}
override fun setPath(path: String, isNew: Boolean) {
val isMacroAdded = storageManager.addMacro(StoragePathMacros.MODULE_FILE, path)
// if file not null - update storage
storageManager.getOrCreateStorage(StoragePathMacros.MODULE_FILE, storageCustomizer = {
if (this !is FileBasedStorage) {
// upsource
return@getOrCreateStorage
}
setFile(null, if (isMacroAdded) null else Paths.get(path))
// ModifiableModuleModel#newModule should always create a new module from scratch
// https://youtrack.jetbrains.com/issue/IDEA-147530
if (isMacroAdded) {
// preload to ensure that we will get FileNotFound error (no module file) during init, and not later in some unexpected place (because otherwise will be loaded by demand)
preloadStorageData(isNew)
}
else {
storageManager.updatePath(StoragePathMacros.MODULE_FILE, path)
}
})
}
} | apache-2.0 | 40d1d1dc3dd27fb79a2bfdd7d4c94508 | 39.134615 | 178 | 0.755811 | 4.807604 | false | true | false | false |
marius-m/wt4 | remote/src/test/java/lt/markmerkk/JiraMocks.kt | 1 | 3775 | package lt.markmerkk
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import net.rcarz.jiraclient.Issue
import net.rcarz.jiraclient.JiraClient
import net.rcarz.jiraclient.JiraException
import net.rcarz.jiraclient.RestException
import net.rcarz.jiraclient.User
import net.rcarz.jiraclient.WorkLog
import org.joda.time.DateTime
import org.joda.time.Duration
import java.lang.RuntimeException
object JiraMocks {
fun createJiraUserEmpty(): JiraUser {
return createJiraUser(name = "", displayName = "", email = "", accountId = "")
}
fun createJiraUser(
name: String = "name",
displayName: String = "display_name",
email: String = "email",
accountId: String = "account_id"
): JiraUser {
return JiraUser(
name = name,
displayName = displayName,
email = email,
accountId = accountId
)
}
fun mockJiraClient(): JiraClient {
val jiraClient: JiraClient = mock()
return jiraClient
}
fun mockJiraIssue(
key: String = "TT2-123",
summary: String = "valid_summary",
idUrl: String = "https://jira.com/12345",
uri: String = "https://jira.com"
): Issue {
val issue: Issue = mock()
doReturn(key).whenever(issue).key
doReturn(summary).whenever(issue).summary
doReturn(idUrl).whenever(issue).id
doReturn(uri).whenever(issue).url
return issue
}
fun createRestException(
status: Int,
message: String
): JiraException {
val restException = RestException(
message,
status,
"detailed_$message",
emptyArray()
)
return JiraException(restException.message, restException)
}
fun createAuthException(): JiraException {
val restException = RestException(
"Authorization error",
401,
"auth_error_details",
emptyArray()
)
return JiraException(restException.message, restException)
}
fun createJiraException(): JiraException {
return JiraException("jira_exception", RuntimeException())
}
fun mockWorklog(
timeProvider: TimeProvider,
author: User? = mockAuthor(),
created: DateTime? = timeProvider.now(),
updated: DateTime? = timeProvider.now(),
started: DateTime? = timeProvider.now(),
url: String = "https://jira.ito.lt/rest/api/2/issue/31463/worklog/73051",
comment: String? = "",
durationTimeSpent: Duration = Duration.standardMinutes(10),
): WorkLog {
val worklog: WorkLog = mock()
doReturn(author).whenever(worklog).author
doReturn(comment).whenever(worklog).comment
doReturn(created?.toDate()).whenever(worklog).createdDate
doReturn(updated?.toDate()).whenever(worklog).updatedDate
doReturn(started?.toDate()).whenever(worklog).started
doReturn(url).whenever(worklog).url
doReturn(durationTimeSpent.toStandardSeconds().seconds).whenever(worklog).timeSpentSeconds
return worklog
}
fun mockAuthor(
name: String = "name",
email: String = "[email protected]",
displayName: String = "Display name",
accountId: String = "account_id",
): User {
val author: User = mock()
doReturn(email).whenever(author).email
doReturn(displayName).whenever(author).displayName
doReturn(name).whenever(author).name
doReturn(accountId).whenever(author).accountId
return author
}
} | apache-2.0 | 7f501d57cb496501b11f75a4aa59fa47 | 31.551724 | 98 | 0.617483 | 4.626225 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/common/src/io/ktor/client/request/DefaultHttpRequest.kt | 1 | 799 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.request
import io.ktor.client.call.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import kotlin.coroutines.*
/**
* Default [HttpRequest] implementation.
*/
@InternalAPI
public open class DefaultHttpRequest(override val call: HttpClientCall, data: HttpRequestData) : HttpRequest {
override val coroutineContext: CoroutineContext get() = call.coroutineContext
override val method: HttpMethod = data.method
override val url: Url = data.url
override val content: OutgoingContent = data.body
override val headers: Headers = data.headers
override val attributes: Attributes = data.attributes
}
| apache-2.0 | 443a2e028559c2e630d3705553ac8c24 | 26.551724 | 118 | 0.753442 | 4.25 | false | false | false | false |
google/accompanist | sample/src/main/java/com/google/accompanist/sample/testharness/TestHarnessSample.kt | 1 | 3503 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.accompanist.sample.testharness
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.core.os.LocaleListCompat
import com.google.accompanist.sample.AccompanistSampleTheme
import com.google.accompanist.sample.R
import com.google.accompanist.testharness.TestHarness
import java.util.Locale
/**
* A visual sample for the TestHarness Composable. Note that it should not be used in production.
*/
class TestHarnessSample : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Column(
modifier = Modifier
.padding(16.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
TestHarnessScreen()
TestHarness(size = DpSize(100.dp, 100.dp)) {
TestHarnessScreen("with a set size")
}
TestHarness(darkMode = true) {
TestHarnessScreen("with darkMode enabled")
}
TestHarness(fontScale = 2f) {
TestHarnessScreen("with a big font scale")
}
TestHarness(layoutDirection = LayoutDirection.Rtl) {
TestHarnessScreen("in RTL")
}
TestHarness(locales = LocaleListCompat.create(Locale("ar"))) {
TestHarnessScreen("in Arabic")
}
}
}
}
}
@Preview
@Composable
fun TestHarnessScreen(text: String = "") {
AccompanistSampleTheme {
Surface(
modifier = Modifier
.border(1.dp, Color.LightGray)
.height(100.dp)
.fillMaxWidth()
) {
Text(
stringResource(R.string.this_is_content, text),
modifier = Modifier.padding(8.dp)
)
}
}
}
| apache-2.0 | 9c91d85c82cf8587e3f5e321c9cf147e | 35.489583 | 97 | 0.672566 | 4.670667 | false | true | false | false |
marius-m/wt4 | components/src/main/java/lt/markmerkk/timecounter/WorkGoalForecaster.kt | 1 | 9085 | package lt.markmerkk.timecounter
import lt.markmerkk.entities.LocalTimeGap
import lt.markmerkk.utils.toStringShort
import org.joda.time.DateTime
import org.joda.time.Duration
import org.joda.time.LocalDate
import org.joda.time.LocalTime
import org.slf4j.LoggerFactory
/**
* Forecasts duration of worktime needed to be logged for target date in a week
*
* @param workDayRules rule spec when day starts / ends (+ breaks)
*
* Ex. 1: for monday forecast would be ~8hrs (depending on breaks)
* Ex. 2: for tuesday forecast would be 16hrs (depending on breaks)
*/
class WorkGoalForecaster(
val workDays: WorkDays = WorkDays.asDefault(),
) {
/**
* Returns duration how much time you should have worked for the whole week in sequence
*/
fun forecastWeekDurationShouldWorkedForWholeDay(
targetDate: LocalDate,
): Duration {
val targetWeekDays = workDays
.workDayRulesInSequenceByDate(targetDate = targetDate)
return targetWeekDays.workDuration()
}
/**
* Returns duration how much time you should have worked in perfect conditions for [targetTime]
* Considers whole week in a sequence
*/
fun forecastWeekDurationShouldWorkedForTargetTime(
targetDate: LocalDate,
targetTime: LocalTime,
): Duration {
val targetWeekDayRules = workDays
.workDayRulesInSequenceByDate(targetDate = targetDate)
val targetWeekDayRulesWithoutLast = targetWeekDayRules
.dropLast(1)
val targetWeekDayRuleLast = targetWeekDayRules
.last()
return targetWeekDayRulesWithoutLast.workDuration()
.plus(targetWeekDayRuleLast.workDurationWithTargetEnd(targetTime))
}
/**
* Returns duration how much time you should have worked for the concrete whole day
*/
fun forecastDayDurationShouldWorkedForWholeDay(
targetDate: LocalDate,
): Duration {
val weekDayRuleByDate = workDays.workDayRulesByDate(targetDate)
return weekDayRuleByDate.workDuration
}
/**
* Returns duration how much time you should have worked in perfect conditions for [targetTime]
*/
fun forecastDayDurationShouldWorkedForTargetTime(
targetDate: LocalDate,
targetTime: LocalTime,
): Duration {
val weekDayRuleByDate = workDays.workDayRulesByDate(targetDate)
return weekDayRuleByDate.workDurationWithTargetEnd(targetEndTime = targetTime)
}
/**
* Returns how much time is left to work to finish the day
* When there is no more work left, work left == [dtCurrent]
* @param dtCurrent current date time
* @param durationWorked duration how much time has been logged
*/
fun forecastShouldFinishDay(
dtCurrent: DateTime,
durationWorked: Duration,
): DateTime {
val workDayRuleByDate = workDays.workDayRulesByDate(dtCurrent.toLocalDate())
val dtWorkDayStart = dtCurrent.withTime(workDayRuleByDate.workSchedule.start)
val durationBreak = workDayRuleByDate.timeBreak.breakDurationFromTimeGap(
timeWork = LocalTimeGap.from(
start = workDayRuleByDate.workSchedule.start,
end = dtCurrent.toLocalTime(),
)
)
val durationWorkedOffset = durationWorkedOffsetDay(dtCurrent, durationWorked)
val durationTotalWorkFromStart = workDayRuleByDate.workDuration
.plus(durationWorkedOffset)
.plus(durationBreak)
val dtWorkLeftFromStart = dtWorkDayStart.plus(durationTotalWorkFromStart)
val dtShouldFinish = if (dtWorkLeftFromStart.isBefore(dtCurrent)) {
dtCurrent
} else {
dtWorkLeftFromStart
}
// l.debug(
// "forecastShouldFinishDay(" +
// "dtCurrent: {}," +
// " durationWorkedOffset: {}," +
// " durationBreak: {}," +
// " durationTotalWorkFromStart: {}," +
// " dtWorkLeftFromStart: {}," +
// " dtShouldFinish: {}," +
// ")",
// dtCurrent,
// durationWorkedOffset.toStringShort(),
// durationBreak.toStringShort(),
// durationTotalWorkFromStart.toStringShort(),
// dtWorkLeftFromStart,
// dtShouldFinish,
// )
return dtShouldFinish
}
/**
* Returns how much time is left to work to finish the week
* If work is finished, will return dt == [dtCurrent]
*/
@Deprecated("Incorrectly working function")
fun forecastShouldFinishWeek(
dtCurrent: DateTime,
durationWorked: Duration,
): DateTime {
val workDayRules = workDays.workDayRulesInSequenceByDate(dtCurrent.toLocalDate())
val workDayRuleLast = workDayRules.last()
val durationWeekTotalWork = workDayRules.workDuration()
val durationDayTotalWork = workDayRuleLast.workDuration
val durationWorkedOffset = durationWorkedOffsetWeek(dtCurrent, durationWorked)
val durationDayBreak = workDayRuleLast.timeBreak.breakDurationFromTimeGap(
timeWork = LocalTimeGap.from(
start = workDayRuleLast.workSchedule.start,
end = dtCurrent.toLocalTime(),
)
)
val durationTotalWorkFromStart = durationDayTotalWork
.plus(durationWorkedOffset)
.plus(durationDayBreak)
val dtWorkDayStart = dtCurrent.withTime(workDayRuleLast.workSchedule.start)
val dtWorkLeftFromStart = dtWorkDayStart.plus(durationTotalWorkFromStart)
val dtShouldFinish = if (dtWorkLeftFromStart.isBefore(dtCurrent)) {
dtCurrent
} else {
dtWorkLeftFromStart
}
// l.debug(
// "forecastShouldFinishDay(" +
// "dtCurrent: {}," +
// " durationTotalWork: {}," +
// " durationWorkedOffset: {}," +
// " durationBreak: {}," +
// " durationTotalWorkFromStart: {}," +
// " dtWorkLeftFromStart: {}," +
// " dtShouldFinish: {}," +
// ")",
// dtCurrent,
// durationWeekTotalWork.toStringShort(),
// durationWorkedOffset.toStringShort(),
// durationDayBreak.toStringShort(),
// durationTotalWorkFromStart.toStringShort(),
// dtWorkLeftFromStart,
// dtShouldFinish,
// )
return dtShouldFinish
}
fun dayGoal(dtTarget: DateTime): Duration {
val workDayRuleByDate = workDays.workDayRulesByDate(dtTarget.toLocalDate())
return workDayRuleByDate.workDuration
}
fun dayGoalLeft(
dtTarget: DateTime,
durationWorked: Duration,
): Duration {
val durationDayGoal = dayGoal(dtTarget)
val durationWorkLeft = durationDayGoal.minus(durationWorked)
if (durationWorkLeft.isShorterThan(Duration.ZERO)) {
return Duration.ZERO
}
return durationWorkLeft
}
fun weekGoal(): Duration {
return workDays.workDayRules.workDuration()
}
fun weekGoalLeft(
durationWorked: Duration,
): Duration {
val durationDayGoal = weekGoal()
val durationWorkLeft = durationDayGoal.minus(durationWorked)
if (durationWorkLeft.isShorterThan(Duration.ZERO)) {
return Duration.ZERO
}
return durationWorkLeft
}
fun daySchedule(dtCurrent: DateTime): WorkDayRule {
return workDays.workDayRulesByDate(dtCurrent.toLocalDate())
}
/**
* Returns how much time has worked, based on 'how much should have worked'
* Calculates for a day
* May be either positive or negative
* @param dtCurrent current date time
* @param durationWorked duration how much time has been logged
*/
private fun durationWorkedOffsetDay(
dtCurrent: DateTime,
durationWorked: Duration,
): Duration {
val durationShouldHaveWorked = forecastDayDurationShouldWorkedForTargetTime(
targetDate = dtCurrent.toLocalDate(),
targetTime = dtCurrent.toLocalTime(),
)
return durationShouldHaveWorked.minus(durationWorked)
}
/**
* Returns how much time has worked, based on 'how much should have worked'
* Calculates for a week
* May be either positive or negative
* @param dtCurrent current date time
* @param durationWorked duration how much time has been logged
*/
private fun durationWorkedOffsetWeek(
dtCurrent: DateTime,
durationWorked: Duration,
): Duration {
val durationShouldHaveWorked = forecastWeekDurationShouldWorkedForTargetTime(
targetDate = dtCurrent.toLocalDate(),
targetTime = dtCurrent.toLocalTime(),
)
return durationShouldHaveWorked.minus(durationWorked)
}
companion object {
private val l = LoggerFactory.getLogger(WorkGoalForecaster::class.java)!!
}
} | apache-2.0 | ee5cca0d414d2d7dea3a0c43ae1b46b9 | 36.085714 | 99 | 0.644469 | 4.791667 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/DetachedHeadCamera.kt | 1 | 5877 | package graphics.scenery
import org.joml.Matrix4f
import org.joml.Vector3f
import com.jogamp.opengl.math.Quaternion
import graphics.scenery.backends.Display
import graphics.scenery.controls.TrackerInput
import graphics.scenery.utils.extensions.plus
import graphics.scenery.utils.extensions.times
import org.joml.Quaternionf
import java.io.Serializable
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.PI
import kotlin.math.atan
import kotlin.reflect.KProperty
/**
* Detached Head Camera is a Camera subclass that tracks the head orientation
* in addition to general orientation - useful for HMDs
*
* @author Ulrik Günther <[email protected]>
*/
class DetachedHeadCamera(@Transient var tracker: TrackerInput? = null) : Camera() {
override var width: Int = 0
get() = if(tracker != null && tracker is Display && tracker?.initializedAndWorking() == true) {
(tracker as? Display)?.getRenderTargetSize()?.x() ?: super.width
} else {
super.width
}
set(value) {
super.width = value
field = value
}
override var height: Int = 0
get() = if(tracker != null && tracker is Display && tracker?.initializedAndWorking() == true) {
(tracker as? Display)?.getRenderTargetSize()?.y() ?: super.width
} else {
super.height
}
set(value) {
super.height = value
field = value
}
override var fov: Float = 70.0f
get() = if(tracker != null && tracker is Display && tracker?.initializedAndWorking() == true) {
val proj = (tracker as? Display)?.getEyeProjection(0, nearPlaneDistance, farPlaneDistance)
if(proj != null) {
atan(1.0f / proj.get(1, 1)) * 2.0f * 180.0f / PI.toFloat()
} else {
super.fov
}
} else {
super.fov
}
set(value) {
super.fov = value
field = value
}
/**
* Delegate class for getting a head rotation from a [TrackerInput].
*/
inner class HeadOrientationDelegate {
/**
* Returns the TrackerInput's orientation, or a unit Quaternion.
*/
operator fun getValue(thisRef: Any?, property: KProperty<*>): Quaternionf {
return tracker?.getWorkingTracker()?.getOrientation() ?: Quaternionf(0.0f, 0.0f, 0.0f, 1.0f)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Quaternion) {
throw UnsupportedOperationException()
}
}
/**
* Delegate class for getting a head translation from a [TrackerInput].
*/
inner class HeadPositionDelegate : Serializable {
/**
* Returns the TrackerInput's translation, or a zero vector.
*/
operator fun getValue(thisRef: Any?, property: KProperty<*>): Vector3f {
return tracker?.getWorkingTracker()?.getPosition() ?: Vector3f(0.0f, 0.0f, 0.0f)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Quaternion) {
throw UnsupportedOperationException()
}
}
/** Position of the user's head */
@delegate:Transient
val headPosition: Vector3f by HeadPositionDelegate()
/** Orientation of the user's head */
@delegate:Transient
val headOrientation: Quaternionf by HeadOrientationDelegate()
init {
this.nodeType = "Camera"
this.name = "DetachedHeadCamera-${tracker ?: "${counter.getAndIncrement()}"}"
}
override fun createSpatial(): CameraSpatial {
return object: CameraSpatial(this) {
override var projection: Matrix4f = Matrix4f().identity()
get() = if(tracker != null && tracker is Display && tracker?.initializedAndWorking() == true) {
(tracker as? Display)?.getEyeProjection(0) ?: super.projection
} else {
super.projection
}
set(value) {
super.projection = value
field = value
}
/**
* Returns this camera's transformation matrix, taking an eventually existing [TrackerInput]
* into consideration as well.
*/
override fun getTransformation(): Matrix4f {
val tr = Matrix4f().translate(this.position * (-1.0f))
// val r = Matrix4f.fromQuaternion(this.rotation)
// val hr = Matrix4f.fromQuaternion(this.headOrientation)
return tracker?.getWorkingTracker()?.getPose()?.times(tr) ?: Matrix4f().set(this.rotation) * tr
}
/**
* Returns this camera's transformation for eye with index [eye], taking an eventually existing [TrackerInput]
* into consideration as well.
*/
override fun getTransformationForEye(eye: Int): Matrix4f {
val tr = Matrix4f().translate(this.position * (-1.0f))
// val r = Matrix4f.fromQuaternion(this.rotation)
// val hr = Matrix4f.fromQuaternion(this.headOrientation)
return tracker?.getWorkingTracker()?.getPoseForEye(eye)?.times(tr) ?: Matrix4f().set(this.rotation) * tr
}
/**
* Returns this camera's transformation matrix, including a
* [preRotation] that is applied before the camera's transformation.
*/
override fun getTransformation(preRotation: Quaternionf): Matrix4f {
val tr = Matrix4f().translate(this.position * (-1.0f) + [email protected])
val r = Matrix4f().set(preRotation.mul(this.rotation))
return r * tr
}
}
}
companion object {
protected val counter = AtomicInteger(0)
}
}
| lgpl-3.0 | 3f99e685024f1b6b4deea18da7104914 | 36.666667 | 122 | 0.593261 | 4.590625 | false | false | false | false |
adrianswiatek/numbers-teacher | NumbersTeacher/app/src/main/java/pl/aswiatek/numbersteacher/activity/MainActivity.kt | 1 | 5295 | package pl.aswiatek.numbersteacher.activity
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main.*
import pl.aswiatek.numbersteacher.R
import pl.aswiatek.numbersteacher.businesslogic.AnswerChecker
import pl.aswiatek.numbersteacher.businesslogic.AnswerState
import pl.aswiatek.numbersteacher.businesslogic.KeyboardManager
import pl.aswiatek.numbersteacher.businesslogic.Settings
import pl.aswiatek.numbersteacher.businesslogic.numbergenerator.NumberGenerator
import pl.aswiatek.numbersteacher.listener.AnswerCheckedListener
import pl.aswiatek.numbersteacher.listener.StateChangedListener
class MainActivity : AppCompatActivity(), StateChangedListener, AnswerCheckedListener {
val SETTINGS_REQUEST_CODE = 1
lateinit var mAnimator: Animator
lateinit var mSettings: Settings
lateinit var mGenerator: NumberGenerator
lateinit var mKeyboardManager: KeyboardManager
val mState = AnswerState(this)
val mAnswerChecker = AnswerChecker(this, mState)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mAnimator = Animator(this)
mSettings = getSettings(savedInstanceState)
mKeyboardManager = KeyboardManager(mState, mSettings.answerRadix)
mGenerator = NumberGenerator(mSettings)
getState(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle) {
mState.putTo(outState)
mSettings.putTo(outState)
super.onSaveInstanceState(outState)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_options) {
val intent = Intent(this, SettingsActivity::class.java)
startActivityForResult(intent, SETTINGS_REQUEST_CODE)
return true
}
if (item.itemId == R.id.menu_show_answer) {
AlertDialog.Builder(this)
.setTitle("The answer")
.setMessage(mState.question.toString())
.setPositiveButton("OK") { _, _ -> resetState() }
.create()
.show()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == SETTINGS_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
mSettings = getSettings()
mKeyboardManager = KeyboardManager(mState, mSettings.answerRadix)
mGenerator = NumberGenerator(mSettings)
resetState()
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun getState(savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
recoverState(savedInstanceState)
} else {
resetState()
}
}
private fun getSettings(savedInstanceState: Bundle? = null): Settings {
if (savedInstanceState != null)
return Settings.createFrom(savedInstanceState)
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
if (preferences != null) return Settings.createFrom(preferences)
return Settings.createDefault()
}
private fun recoverState(savedInstanceState: Bundle) = mState.putTo(savedInstanceState)
private fun resetState() {
mState.question = mGenerator.generate()
resetAnswer()
}
private fun resetAnswer() {
mState.answer = 0
}
fun onNumberClicked(view: View) = mKeyboardManager.handle((view as Button).text.toString())
fun onClearClicked(view: View) = mKeyboardManager.handle("")
fun onNextClicked(view: View) = resetState()
private fun setQuestionOnTheScreen() {
number_text_view.animate().alpha(0F).setDuration(256).withEndAction {
number_text_view.text = mState.getFormattedQuestion(mSettings.questionRadix)
number_text_view.animate().alpha(1F).duration = 128
}
}
private fun setAnswerOnTheScreen() {
if (mState.answer != 0) {
answer_text_view.text = mState.getFormattedAnswer(mSettings.answerRadix)
return
}
answer_text_view.animate().alpha(0F).setDuration(256).withEndAction {
answer_text_view.text = mState.getFormattedAnswer(mSettings.answerRadix)
answer_text_view.animate().alpha(1F).duration = 128
}
}
override fun onQuestionChanged() = setQuestionOnTheScreen()
override fun onAnswerChanged() {
setAnswerOnTheScreen()
mAnswerChecker.check()
}
override fun onCorrectAnswerGiven() {
mAnimator.animate()
resetState()
}
override fun onIncorrectAnswerGiven() =
if (mSettings.generateNewIfIncorrect) resetState() else resetAnswer()
} | mit | 08f3bcadc19aa9201cac8eab0d96eb67 | 33.38961 | 95 | 0.69084 | 4.723461 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveRedundantCallsOfConversionMethodsIntention.kt | 1 | 4027 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.isFlexible
@Suppress("DEPRECATION")
class RemoveRedundantCallsOfConversionMethodsInspection : IntentionBasedInspection<KtQualifiedExpression>(
RemoveRedundantCallsOfConversionMethodsIntention::class
), CleanupLocalInspectionTool
class RemoveRedundantCallsOfConversionMethodsIntention : SelfTargetingRangeIntention<KtQualifiedExpression>(
KtQualifiedExpression::class.java,
KotlinBundle.lazyMessage("remove.redundant.calls.of.the.conversion.method")
) {
@ExperimentalUnsignedTypes
@delegate:SafeFieldForPreview
private val targetClassMap: Map<String, String?> by lazy {
mapOf(
"toString()" to String::class.qualifiedName,
"toDouble()" to Double::class.qualifiedName,
"toFloat()" to Float::class.qualifiedName,
"toLong()" to Long::class.qualifiedName,
"toInt()" to Int::class.qualifiedName,
"toChar()" to Char::class.qualifiedName,
"toShort()" to Short::class.qualifiedName,
"toByte()" to Byte::class.qualifiedName,
"toULong()" to ULong::class.qualifiedName,
"toUInt()" to UInt::class.qualifiedName,
"toUShort()" to UShort::class.qualifiedName,
"toUByte()" to UByte::class.qualifiedName
)
}
override fun applyTo(element: KtQualifiedExpression, editor: Editor?) {
element.replaced(element.receiverExpression)
}
override fun applicabilityRange(element: KtQualifiedExpression): TextRange? {
val selectorExpression = element.selectorExpression ?: return null
val selectorExpressionText = selectorExpression.text
val qualifiedName = targetClassMap[selectorExpressionText] ?: return null
return if (element.receiverExpression.isApplicableReceiverExpression(qualifiedName)) {
selectorExpression.textRange
} else {
null
}
}
private fun KotlinType.getFqNameAsString(): String? = constructor.declarationDescriptor?.let {
DescriptorUtils.getFqName(it).asString()
}
private fun KtExpression.isApplicableReceiverExpression(qualifiedName: String): Boolean = when (this) {
is KtStringTemplateExpression -> String::class.qualifiedName
is KtConstantExpression -> getType(analyze())?.getFqNameAsString()
else -> {
val resolvedCall = resolveToCall()
if ((resolvedCall?.call?.callElement as? KtBinaryExpression)?.operationToken in OperatorConventions.COMPARISON_OPERATIONS) {
// Special case here because compareTo returns Int
Boolean::class.qualifiedName
} else {
resolvedCall?.candidateDescriptor?.returnType?.let {
when {
it.isFlexible() -> null
parent !is KtSafeQualifiedExpression && (this is KtSafeQualifiedExpression || it.isMarkedNullable) -> null
else -> it.getFqNameAsString()
}
}
}
}
} == qualifiedName
}
| apache-2.0 | 7260a547418c98f031b53cf1a0fab6d7 | 44.247191 | 136 | 0.705736 | 5.441892 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsIntentionAction.kt | 1 | 2347 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.cutPaste
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInspection.HintAction
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.refactoring.BaseRefactoringIntentionAction
import com.intellij.refactoring.suggested.range
import org.jetbrains.kotlin.idea.KotlinBundle
class MoveDeclarationsIntentionAction(
private val processor: MoveDeclarationsProcessor,
private val bounds: RangeMarker,
private val modificationCount: Long
) : BaseRefactoringIntentionAction(), HintAction {
override fun startInWriteAction() = false
override fun getText() = KotlinBundle.message("text.update.usages.to.reflect.declaration.0.move",
processor.pastedDeclarations.size
)
override fun getFamilyName() = KotlinBundle.message("family.name.update.usages.on.declarations.cut.paste")
override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean {
return PsiModificationTracker.getInstance(processor.project).modificationCount == modificationCount
}
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
processor.performRefactoring()
}
override fun showHint(editor: Editor): Boolean {
val range = bounds.range ?: return false
if (editor.caretModel.offset != range.endOffset) return false
if (PsiModificationTracker.getInstance(processor.project).modificationCount != modificationCount) return false
val hintText = "$text? ${KeymapUtil.getFirstKeyboardShortcutText(
ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS)
)}"
HintManager.getInstance().showQuestionHint(editor, hintText, range.endOffset, range.endOffset) {
processor.performRefactoring()
true
}
return true
}
} | apache-2.0 | c766c691b56a1d0b965d1ec472781f53 | 40.192982 | 120 | 0.768215 | 4.930672 | false | false | false | false |
airbnb/epoxy | epoxy-integrationtest/src/main/java/com/airbnb/epoxy/integrationtest/KotlinViewWithDefaultParams.kt | 1 | 1456 | package com.airbnb.epoxy.integrationtest
import android.content.Context
import android.view.View
import com.airbnb.epoxy.ModelProp
import com.airbnb.epoxy.ModelView
import com.airbnb.epoxy.TextProp
@ModelView(autoLayout = ModelView.Size.WRAP_WIDTH_MATCH_HEIGHT)
class KotlinViewWithDefaultParams(context: Context) : View(context) {
@JvmOverloads
@ModelProp
fun someIntWithDefault(num: Int = IntDefault) {
someIntWithDefaultValue = num
}
var someIntWithDefaultValue = 0
@JvmOverloads
@TextProp
fun someTextWithDefault(msg: CharSequence = TextDefault) {
someTextWithDefaultValue = msg
}
var someTextWithDefaultValue: CharSequence = ""
@JvmOverloads
@ModelProp(group = "group")
fun propInGroupWithDefaultParam(num: Int? = IntGroupDefault) {
groupValue = num
}
@ModelProp(group = "group")
fun otherPropInGroup(num: Int) {
groupValue = num
}
// Make sure that overloads with the same function name and param name are distinguished correctly by type
@JvmOverloads
@ModelProp
fun setImage(image: Map<String, Int> = emptyMap()) {
}
@ModelProp
fun setImage(image: String) {
}
@ModelProp
fun somePropWithoutDefault(num: Int) {
}
var groupValue: Int? = null
companion object {
const val IntDefault = 2
const val IntGroupDefault = 3
const val TextDefault = "hello world"
}
}
| apache-2.0 | 9d6a1f8b79c1108fbba432cf07e0b25a | 23.266667 | 110 | 0.68544 | 4.294985 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToStatic/fixes.kt | 4 | 3705 | // 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.
@file:JvmName("ConvertToStatic")
package org.jetbrains.plugins.groovy.refactoring.convertToStatic
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.light.LightElement
import org.jetbrains.plugins.groovy.intentions.style.AddReturnTypeFix
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.DEF
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
private const val MAX_FIX_ITERATIONS = 5
fun applyErrorFixes(element: GroovyPsiElement) {
repeat(MAX_FIX_ITERATIONS) {
val checker = TypeChecker()
element.accept(TypeCheckVisitor(checker))
if (checker.applyFixes() == 0) {
return
}
}
}
fun applyDeclarationFixes(scope: GroovyPsiElement) {
repeat(MAX_FIX_ITERATIONS) {
collectReferencedEmptyDeclarations(scope).forEach { element ->
when (element) {
is GrMethod -> AddReturnTypeFix.applyFix(scope.project, element)
is GrVariable -> {
val psiType = element.typeGroovy ?: return@forEach
element.setType(psiType)
element.modifierList?.setModifierProperty(DEF, false)
}
}
}
}
}
fun collectReferencedEmptyDeclarations(scope: GroovyPsiElement, recursive: Boolean = true): List<PsiElement> {
val declarationsVisitor = EmptyDeclarationTypeCollector(recursive)
scope.accept(declarationsVisitor)
return declarationsVisitor.elements
}
private class TypeCheckVisitor(val checker: TypeChecker) : GroovyRecursiveElementVisitor() {
override fun visitElement(element: GroovyPsiElement) {
if (PsiUtil.isCompileStatic(element)) {
element.accept(checker)
}
super.visitElement(element)
}
}
private class EmptyDeclarationTypeCollector(private val recursive: Boolean) : GroovyElementVisitor() {
val elements = mutableListOf<PsiElement>()
override fun visitReferenceExpression(referenceExpression: GrReferenceExpression) {
checkReference(referenceExpression)
super.visitReferenceExpression(referenceExpression)
}
private fun checkReference(referenceExpression: GroovyReference) {
val resolveResult = referenceExpression.advancedResolve()
if (!resolveResult.isValidResult) return
val element = resolveResult.element
when (element) {
is GrAccessorMethod -> {
checkField(element.property)
}
is GrField -> {
checkField(element)
}
is LightElement -> return
is GrMethod -> {
if (element.isConstructor) return
element.returnTypeElementGroovy?.let { return }
elements += element
}
}
}
private fun checkField(element: GrField) {
element.declaredType?.let { return }
val initializer = element.initializerGroovy ?: return
initializer.type ?: return
elements += element
}
override fun visitElement(element: GroovyPsiElement) {
if (recursive) {
element.acceptChildren(this)
}
}
} | apache-2.0 | e91eccc18fc76e361c447194cb32c957 | 34.980583 | 140 | 0.754926 | 4.490909 | false | false | false | false |
google/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autoimport/AutoImportTest.kt | 5 | 49550 | // 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.openapi.externalSystem.autoimport
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTrackerSettings.AutoReloadType.*
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.FAILURE
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS
import com.intellij.openapi.externalSystem.autoimport.MockProjectAware.RefreshCollisionPassType
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.INTERNAL
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.Event.*
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.ReloadStatus.IN_PROGRESS
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.Parallel.Companion.parallel
import com.intellij.openapi.util.Ref
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.util.AlarmFactory
import org.jetbrains.concurrency.AsyncPromise
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class AutoImportTest : AutoImportTestCase() {
@Test
fun `test simple modification tracking`() {
test { settingsFile ->
settingsFile.appendString("println 'hello'")
assertState(refresh = 0, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 1, notified = false, event = "revert changes")
settingsFile.appendString("\n ")
assertState(refresh = 1, notified = false, event = "empty modification")
settingsFile.replaceString("println", "print ln")
assertState(refresh = 1, notified = true, event = "split token by space")
settingsFile.replaceString("print ln", "println")
assertState(refresh = 1, notified = false, event = "revert modification")
settingsFile.appendString(" ")
assertState(refresh = 1, notified = false, event = "empty modification")
settingsFile.appendString("//It is comment")
assertState(refresh = 1, notified = false, event = "append comment")
settingsFile.insertStringAfter("println", "/*It is comment*/")
assertState(refresh = 1, notified = false, event = "append comment")
settingsFile.insertString(0, "//")
assertState(refresh = 1, notified = true, event = "comment code")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "empty project refresh")
}
}
@Test
fun `test modification tracking disabled by ES plugin`() {
val autoImportAwareCondition = Ref.create(true)
testWithDummyExternalSystem(autoImportAwareCondition) { settingsFile ->
assertState(refresh = 1, beforeRefresh = 1, afterRefresh = 1, event = "register project without cache")
settingsFile.appendString("println 'hello'")
assertState(refresh = 1, beforeRefresh = 1, afterRefresh = 1, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, beforeRefresh = 2, afterRefresh = 2, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, beforeRefresh = 2, afterRefresh = 2, event = "modification")
autoImportAwareCondition.set(false)
scheduleProjectReload()
assertState(refresh = 3, beforeRefresh = 2, afterRefresh = 2, event = "import with inapplicable autoImportAware")
autoImportAwareCondition.set(true)
scheduleProjectReload()
assertState(refresh = 4, beforeRefresh = 3, afterRefresh = 3, event = "empty project refresh")
}
}
@Test
fun `test simple modification tracking in xml`() {
test {
val settingsFile = createSettingsVirtualFile("settings.xml")
assertState(refresh = 0, notified = true, event = "settings file is created")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project is reloaded")
settingsFile.replaceContent("""
<element>
<name description="This is a my super name">my-name</name>
</element>
""".trimIndent())
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "refresh project")
settingsFile.replaceString("my-name", "my name")
assertState(refresh = 2, notified = true, event = "replace by space")
settingsFile.replaceString("my name", "my-name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("my-name", "my - name")
assertState(refresh = 2, notified = true, event = "split token by spaces")
settingsFile.replaceString("my - name", "my-name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("my-name", " my-name ")
assertState(refresh = 2, notified = false, event = "expand text token by spaces")
settingsFile.insertStringAfter("</name>", " ")
assertState(refresh = 2, notified = false, event = "append space after tag")
settingsFile.insertStringAfter("</name>", "\n ")
assertState(refresh = 2, notified = false, event = "append empty line in file")
settingsFile.replaceString("</name>", "</n am e>")
assertState(refresh = 2, notified = true, event = "split tag by spaces")
settingsFile.replaceString("</n am e>", "</name>")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.replaceString("</name>", "</ name >")
assertState(refresh = 2, notified = false, event = "expand tag brackets by spaces")
settingsFile.replaceString("=", " = ")
assertState(refresh = 2, notified = false, event = "expand attribute definition")
settingsFile.replaceString("my super name", "my super name")
assertState(refresh = 2, notified = true, event = "expand space inside attribute value")
settingsFile.replaceString("my super name", "my super name")
assertState(refresh = 2, notified = false, event = "revert modification")
settingsFile.insertStringAfter("my super name", " ")
assertState(refresh = 2, notified = true, event = "insert space in end of attribute")
settingsFile.replaceString("my super name \"", "my super name\"")
assertState(refresh = 2, notified = false, event = "revert modification")
}
}
@Test
fun `test unrecognized settings file`() {
test {
val settingsFile = createSettingsVirtualFile("settings.elvish")
assertState(refresh = 0, notified = true, event = "settings file is created")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project is reloaded")
settingsFile.appendString("q71Gpj5 .9jR°`N.")
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("9jR°`N", "9`B")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("9`B", "9jR°`N")
assertState(refresh = 2, notified = false, event = "revert changes")
settingsFile.appendString(" ")
assertState(refresh = 2, notified = true, event = "unrecognized empty modification")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "project refresh")
settingsFile.appendString("//1G iT zt^P1Fp")
assertState(refresh = 3, notified = true, event = "unrecognized comment modification")
scheduleProjectReload()
assertState(refresh = 4, notified = false, event = "project refresh")
}
}
@Test
fun `test deletion tracking`() {
test { settingsFile ->
settingsFile.modify(EXTERNAL)
assertState(refresh = 1, notified = false, event = "settings is externally modified")
settingsFile.delete()
assertState(refresh = 1, notified = true, event = "delete registered settings")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
var newSettingsFile = createVirtualFile(SETTINGS_FILE)
assertState(refresh = 2, notified = true, event = "create registered settings")
newSettingsFile.modify(EXTERNAL)
assertState(refresh = 2, notified = true, event = "modify registered settings")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "project refresh")
newSettingsFile.delete()
assertState(refresh = 3, notified = true, event = "delete registered settings")
newSettingsFile = createVirtualFile(SETTINGS_FILE)
assertState(refresh = 3, notified = true, event = "create registered settings immediately after deleting")
newSettingsFile.modify(EXTERNAL)
assertState(refresh = 3, notified = false, event = "modify registered settings immediately after deleting")
}
}
@Test
fun `test directory deletion tracking`() {
test {
val directory = findOrCreateDirectory("directory")
createSettingsVirtualFile("directory/settings.txt")
assertState(refresh = 0, notified = true, event = "settings created")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project reloaded")
directory.delete()
assertState(refresh = 1, notified = true, event = "deleted directory with settings")
findOrCreateDirectory("directory")
assertState(refresh = 1, notified = true, event = "deleted directory created without settings")
createSettingsVirtualFile("directory/settings.txt")
assertState(refresh = 1, notified = false, event = "reverted deleted settings")
}
}
@Test
fun `test modification tracking with several settings files`() {
test { settingsFile ->
settingsFile.replaceContent("println 'hello'")
assertState(refresh = 0, notified = true, event = "settings file is modified")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project is reloaded")
val configFile = createVirtualFile("config.groovy")
assertState(refresh = 1, notified = false, event = "create unregistered settings")
configFile.replaceContent("println('hello')")
assertState(refresh = 1, notified = false, event = "modify unregistered settings")
val scriptFile = createSettingsVirtualFile("script.groovy")
assertState(refresh = 1, notified = true, event = "created new settings file")
scriptFile.replaceContent("println('hello')")
assertState(refresh = 1, notified = true, event = "modify settings file")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 1, notified = true, event = "try to revert changes if has other modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
scriptFile.replaceString("hello", "hi")
assertState(refresh = 2, notified = true, event = "modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = true, event = "try to revert changes if has other modification")
scriptFile.replaceString("hi", "hello")
assertState(refresh = 2, notified = false, event = "revert changes")
}
}
@Test
fun `test modification tracking with several sub projects`() {
val systemId1 = ProjectSystemId("External System 1")
val systemId2 = ProjectSystemId("External System 2")
val projectId1 = ExternalSystemProjectId(systemId1, projectPath)
val projectId2 = ExternalSystemProjectId(systemId2, projectPath)
val projectAware1 = mockProjectAware(projectId1)
val projectAware2 = mockProjectAware(projectId2)
initialize()
val scriptFile1 = createVirtualFile("script1.groovy")
val scriptFile2 = createVirtualFile("script2.groovy")
projectAware1.registerSettingsFile(scriptFile1.path)
projectAware2.registerSettingsFile(scriptFile2.path)
register(projectAware1)
register(projectAware2)
assertProjectAware(projectAware1, refresh = 1, event = "register project without cache")
assertProjectAware(projectAware2, refresh = 1, event = "register project without cache")
assertNotificationAware(event = "register project without cache")
scriptFile1.appendString("println 1")
assertProjectAware(projectAware1, refresh = 1, event = "modification of first settings")
assertProjectAware(projectAware2, refresh = 1, event = "modification of first settings")
assertNotificationAware(projectId1, event = "modification of first settings")
scriptFile2.appendString("println 2")
assertProjectAware(projectAware1, refresh = 1, event = "modification of second settings")
assertProjectAware(projectAware2, refresh = 1, event = "modification of second settings")
assertNotificationAware(projectId1, projectId2, event = "modification of second settings")
scriptFile1.removeContent()
assertProjectAware(projectAware1, refresh = 1, event = "revert changes at second settings")
assertProjectAware(projectAware2, refresh = 1, event = "revert changes at second settings")
assertNotificationAware(projectId2, event = "revert changes at second settings")
scheduleProjectReload()
assertProjectAware(projectAware1, refresh = 1, event = "project refresh")
assertProjectAware(projectAware2, refresh = 2, event = "project refresh")
assertNotificationAware(event = "project refresh")
scriptFile1.replaceContent("println 'script 1'")
scriptFile2.replaceContent("println 'script 2'")
assertProjectAware(projectAware1, refresh = 1, event = "modification of both settings")
assertProjectAware(projectAware2, refresh = 2, event = "modification of both settings")
assertNotificationAware(projectId1, projectId2, event = "modification of both settings")
scheduleProjectReload()
assertProjectAware(projectAware1, refresh = 2, event = "project refresh")
assertProjectAware(projectAware2, refresh = 3, event = "project refresh")
assertNotificationAware(event = "project refresh")
}
@Test
fun `test project link-unlink`() {
test { settingsFile ->
settingsFile.modify(INTERNAL)
assertState(refresh = 0, subscribe = 0, unsubscribe = 0, notified = true, event = "modification")
removeProjectAware()
assertState(refresh = 0, subscribe = 0, unsubscribe = 2, notified = false, event = "remove project")
registerProjectAware()
assertState(refresh = 1, subscribe = 2, unsubscribe = 2, notified = false, event = "register project without cache")
}
}
@Test
fun `test external modification tracking`() {
test {
var settingsFile = it
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 1, notified = false, event = "untracked external modification")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "internal modification")
settingsFile.replaceStringInIoFile("hi", "settings")
assertState(refresh = 1, notified = true, event = "untracked external modification during internal modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "refresh project")
modification {
assertState(refresh = 2, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("settings", "modified settings")
assertState(refresh = 2, notified = false, event = "external modification")
}
assertState(refresh = 3, notified = false, event = "complete external modification")
modification {
assertState(refresh = 3, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("modified settings", "simple settings")
assertState(refresh = 3, notified = false, event = "external modification")
settingsFile.replaceStringInIoFile("simple settings", "modified settings")
assertState(refresh = 3, notified = false, event = "revert external modification")
}
assertState(refresh = 3, notified = false, event = "complete external modification")
modification {
assertState(refresh = 3, notified = false, event = "start external modification")
settingsFile.deleteIoFile()
assertState(refresh = 3, notified = false, event = "external deletion")
}
assertState(refresh = 4, notified = false, event = "complete external modification")
modification {
assertState(refresh = 4, notified = false, event = "start external modification")
settingsFile = createIoFile(SETTINGS_FILE)
assertState(refresh = 4, notified = false, event = "external creation")
settingsFile.replaceContentInIoFile("println 'settings'")
assertState(refresh = 4, notified = false, event = "external modification")
}
assertState(refresh = 5, notified = false, event = "complete external modification")
modification {
assertState(refresh = 5, notified = false, event = "start first external modification")
settingsFile.replaceStringInIoFile("settings", "hello")
assertState(refresh = 5, notified = false, event = "first external modification")
modification {
assertState(refresh = 5, notified = false, event = "start second external modification")
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 5, notified = false, event = "second external modification")
}
assertState(refresh = 5, notified = false, event = "complete second external modification")
}
assertState(refresh = 6, notified = false, event = "complete first external modification")
modification {
assertState(refresh = 6, notified = false, event = "start external modification")
settingsFile.replaceStringInIoFile("println", "print")
assertState(refresh = 6, notified = false, event = "external modification")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 6, notified = false, event = "internal modification during external modification")
settingsFile.replaceStringInIoFile("hello", "settings")
assertState(refresh = 6, notified = false, event = "external modification")
}
assertState(refresh = 6, notified = true, event = "complete external modification")
scheduleProjectReload()
assertState(refresh = 7, notified = false, event = "refresh project")
}
}
@Test
fun `test tracker store and restore`() {
val projectAware = mockProjectAware()
val settingsFile = findOrCreateVirtualFile(SETTINGS_FILE)
projectAware.registerSettingsFile(settingsFile.path)
var state = testProjectTrackerState(projectAware) {
assertState(refresh = 1, notified = false, event = "register project without cache")
settingsFile.replaceContent("println 'hello'")
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
}
state = testProjectTrackerState(projectAware, state) {
assertState(refresh = 0, notified = false, event = "register project with correct cache")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 0, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project refresh")
}
settingsFile.replaceStringInIoFile("hi", "hello")
state = testProjectTrackerState(projectAware, state) {
assertState(refresh = 1, notified = false, event = "register project with external modifications")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project refresh")
}
state = testProjectTrackerState(projectAware, state) {
assertState(refresh = 0, notified = false, event = "register project with correct cache")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 0, notified = true, event = "modification")
}
testProjectTrackerState(projectAware, state) {
assertState(refresh = 1, notified = false, event = "register project with previous modifications")
}
}
fun `test move and rename settings files`() {
test("settings.groovy") { settingsFile ->
registerSettingsFile("script.groovy")
registerSettingsFile("dir/script.groovy")
registerSettingsFile("dir1/script.groovy")
registerSettingsFile("dir/dir1/script.groovy")
var scriptFile = settingsFile.copy("script.groovy")
assertState(refresh = 0, notified = true, event = "copy to registered settings")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project refresh")
scriptFile.delete()
assertState(refresh = 1, notified = true, event = "delete file")
scriptFile = settingsFile.copy("script.groovy")
assertState(refresh = 1, notified = false, event = "revert delete by copy")
val configurationFile = settingsFile.copy("configuration.groovy")
assertState(refresh = 1, notified = false, event = "copy to registered settings")
configurationFile.delete()
assertState(refresh = 1, notified = false, event = "delete file")
val dir = findOrCreateDirectory("dir")
val dir1 = findOrCreateDirectory("dir1")
assertState(refresh = 1, notified = false, event = "create directory")
scriptFile.move(dir)
assertState(refresh = 1, notified = true, event = "move settings to directory")
scriptFile.move(projectRoot)
assertState(refresh = 1, notified = false, event = "revert move settings")
scriptFile.move(dir1)
assertState(refresh = 1, notified = true, event = "move settings to directory")
dir1.move(dir)
assertState(refresh = 1, notified = true, event = "move directory with settings to other directory")
scriptFile.move(projectRoot)
assertState(refresh = 1, notified = false, event = "revert move settings")
scriptFile.move(dir)
assertState(refresh = 1, notified = true, event = "move settings to directory")
dir.rename("dir1")
assertState(refresh = 1, notified = true, event = "rename directory with settings")
scriptFile.move(projectRoot)
assertState(refresh = 1, notified = false, event = "revert move settings")
settingsFile.rename("configuration.groovy")
assertState(refresh = 1, notified = true, event = "rename")
settingsFile.rename("settings.groovy")
assertState(refresh = 1, notified = false, event = "revert rename")
}
}
fun `test document changes between save`() {
test { settingsFile ->
val settingsDocument = settingsFile.asDocument()
settingsDocument.replaceContent("println 'hello'")
assertState(refresh = 0, notified = true, event = "change")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "refresh project")
settingsDocument.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "change")
settingsDocument.replaceString("hi", "hello")
assertState(refresh = 1, notified = false, event = "revert change")
settingsDocument.replaceString("hello", "hi")
assertState(refresh = 1, notified = true, event = "change")
settingsDocument.save()
assertState(refresh = 1, notified = true, event = "save")
settingsDocument.replaceString("hi", "hello")
assertState(refresh = 1, notified = false, event = "revert change after save")
settingsDocument.save()
assertState(refresh = 1, notified = false, event = "save reverted changes")
}
}
fun `test processing of failure refresh`() {
test { settingsFile ->
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 1, notified = false, event = "external change")
setRefreshStatus(FAILURE)
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 2, notified = true, event = "external change with failure refresh")
scheduleProjectReload()
assertState(refresh = 3, notified = true, event = "failure project refresh")
setRefreshStatus(SUCCESS)
scheduleProjectReload()
assertState(refresh = 4, notified = false, event = "project refresh")
settingsFile.replaceString("hi", "hello")
assertState(refresh = 4, notified = true, event = "modify")
setRefreshStatus(FAILURE)
scheduleProjectReload()
assertState(refresh = 5, notified = true, event = "failure project refresh")
settingsFile.replaceString("hello", "hi")
assertState(refresh = 5, notified = true, event = "try to revert changes after failure refresh")
setRefreshStatus(SUCCESS)
scheduleProjectReload()
assertState(refresh = 6, notified = false, event = "project refresh")
}
}
fun `test files generation during refresh`() {
test {
val settingsFile = createVirtualFile(SETTINGS_FILE)
assertState(refresh = 0, notified = false, event = "some file is created")
onceDuringRefresh {
registerSettingsFile(settingsFile)
}
forceRefreshProject()
assertState(refresh = 1, notified = false, event = "settings file is registered during reload")
settingsFile.delete()
assertState(refresh = 1, notified = true, event = "settings file is deleted")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project is reloaded")
onceDuringRefresh {
createIoFileUnsafe(SETTINGS_FILE).writeText(SAMPLE_TEXT)
}
forceRefreshProject()
assertState(refresh = 3, notified = false, event = "settings file is externally created during reload")
onceDuringRefresh {
findFile(SETTINGS_FILE).modify(INTERNAL)
}
forceRefreshProject()
assertState(refresh = 4, notified = true, event = "settings file is internally modified during reload")
}
}
fun `test disabling of auto-import`() {
val projectAware = mockProjectAware()
val settingsFile = findOrCreateVirtualFile(SETTINGS_FILE)
projectAware.registerSettingsFile(settingsFile.path)
var state = testProjectTrackerState(projectAware) {
assertState(refresh = 1, autoReloadType = SELECTIVE, notified = false, event = "register project without cache")
setAutoReloadType(NONE)
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "disable project auto-import")
settingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 1, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
}
state = testProjectTrackerState(projectAware, state) {
// Open modified project with disabled auto-import for external changes
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "register modified project")
scheduleProjectReload()
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "refresh project")
// Checkout git branch, that has additional linked project
withLinkedProject("module", SETTINGS_FILE) { moduleSettingsFile ->
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "register project without cache with disabled auto-import")
moduleSettingsFile.replaceContentInIoFile("println 'hello'")
assertState(refresh = 0, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
}
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "remove modified linked project")
setAutoReloadType(SELECTIVE)
assertState(refresh = 1, autoReloadType = SELECTIVE, notified = false, event = "enable auto-import for project without modifications")
setAutoReloadType(NONE)
assertState(refresh = 1, autoReloadType = NONE, notified = false, event = "disable project auto-import")
settingsFile.replaceStringInIoFile("hello", "hi")
assertState(refresh = 1, autoReloadType = NONE, notified = true, event = "modification with disabled auto-import")
setAutoReloadType(SELECTIVE)
assertState(refresh = 2, autoReloadType = SELECTIVE, notified = false, event = "enable auto-import for modified project")
}
testProjectTrackerState(projectAware, state) {
assertState(refresh = 0, autoReloadType = SELECTIVE, notified = false, event = "register project with correct cache")
}
}
@Test
fun `test activation of auto-import`() {
val systemId = ProjectSystemId("External System")
val projectId1 = ExternalSystemProjectId(systemId, projectPath)
val projectId2 = ExternalSystemProjectId(systemId, "$projectPath/sub-project")
val projectAware1 = mockProjectAware(projectId1)
val projectAware2 = mockProjectAware(projectId2)
initialize()
register(projectAware1, activate = false)
assertProjectAware(projectAware1, refresh = 0, event = "register project")
assertNotificationAware(projectId1, event = "register project")
assertActivationStatus(event = "register project")
activate(projectId1)
assertProjectAware(projectAware1, refresh = 1, event = "activate project")
assertNotificationAware(event = "activate project")
assertActivationStatus(projectId1, event = "activate project")
register(projectAware2, activate = false)
assertProjectAware(projectAware1, refresh = 1, event = "register project 2")
assertProjectAware(projectAware2, refresh = 0, event = "register project 2")
assertNotificationAware(projectId2, event = "register project 2")
assertActivationStatus(projectId1, event = "register project 2")
registerSettingsFile(projectAware1, "settings.groovy")
registerSettingsFile(projectAware2, "sub-project/settings.groovy")
val settingsFile1 = createIoFile("settings.groovy")
val settingsFile2 = createIoFile("sub-project/settings.groovy")
assertProjectAware(projectAware1, refresh = 2, event = "externally created both settings files, but project 2 is inactive")
assertProjectAware(projectAware2, refresh = 0, event = "externally created both settings files, but project 2 is inactive")
settingsFile1.replaceContentInIoFile("println 'hello'")
settingsFile2.replaceContentInIoFile("println 'hello'")
assertProjectAware(projectAware1, refresh = 3, event = "externally modified both settings files, but project 2 is inactive")
assertProjectAware(projectAware2, refresh = 0, event = "externally modified both settings files, but project 2 is inactive")
assertNotificationAware(projectId2, event = "externally modified both settings files, but project 2 is inactive")
assertActivationStatus(projectId1, event = "externally modified both settings files, but project 2 is inactive")
settingsFile1.replaceString("hello", "Hello world!")
settingsFile2.replaceString("hello", "Hello world!")
assertProjectAware(projectAware1, refresh = 3, event = "internally modify settings")
assertProjectAware(projectAware2, refresh = 0, event = "internally modify settings")
assertNotificationAware(projectId1, projectId2, event = "internally modify settings")
assertActivationStatus(projectId1, event = "internally modify settings")
scheduleProjectReload()
assertProjectAware(projectAware1, refresh = 4, event = "refresh project")
assertProjectAware(projectAware2, refresh = 1, event = "refresh project")
assertNotificationAware(event = "refresh project")
assertActivationStatus(projectId1, projectId2, event = "refresh project")
}
@Test
fun `test merging of refreshes with different nature`() {
test { settingsFile ->
enableAsyncExecution()
waitForProjectRefresh {
parallel {
thread {
settingsFile.modify(EXTERNAL)
}
thread {
forceRefreshProject()
}
}
}
assertState(refresh = 1, notified = false, event = "settings files is modified and project is reloaded at same moment")
}
}
@Test
fun `test enabling-disabling internal-external changes importing`() {
test { settingsFile ->
settingsFile.modify(INTERNAL)
assertState(refresh = 0, notified = true, autoReloadType = SELECTIVE, event = "internal modification")
scheduleProjectReload()
assertState(refresh = 1, notified = false, autoReloadType = SELECTIVE, event = "refresh project")
settingsFile.modify(EXTERNAL)
assertState(refresh = 2, notified = false, autoReloadType = SELECTIVE, event = "external modification")
setAutoReloadType(ALL)
settingsFile.modify(INTERNAL)
assertState(refresh = 3, notified = false, autoReloadType = ALL, event = "internal modification with enabled auto-reload")
settingsFile.modify(EXTERNAL)
assertState(refresh = 4, notified = false, autoReloadType = ALL, event = "external modification with enabled auto-reload")
setAutoReloadType(NONE)
settingsFile.modify(INTERNAL)
assertState(refresh = 4, notified = true, autoReloadType = NONE, event = "internal modification with disabled auto-reload")
settingsFile.modify(EXTERNAL)
assertState(refresh = 4, notified = true, autoReloadType = NONE, event = "external modification with disabled auto-reload")
setAutoReloadType(SELECTIVE)
assertState(refresh = 4, notified = true, autoReloadType = SELECTIVE,
event = "enable auto-reload external changes with internal and external modifications")
setAutoReloadType(ALL)
assertState(refresh = 5, notified = false, autoReloadType = ALL, event = "enable auto-reload of any changes")
setAutoReloadType(NONE)
settingsFile.modify(INTERNAL)
assertState(refresh = 5, notified = true, autoReloadType = NONE, event = "internal modification with disabled auto-reload")
settingsFile.modify(EXTERNAL)
assertState(refresh = 5, notified = true, autoReloadType = NONE, event = "external modification with disabled auto-reload")
setAutoReloadType(ALL)
assertState(refresh = 6, notified = false, autoReloadType = ALL, event = "enable auto-reload of any changes")
}
}
@Test
fun `test failure auto-reload with enabled auto-reload of any changes`() {
test { settingsFile ->
setAutoReloadType(ALL)
setRefreshStatus(FAILURE)
settingsFile.modify(INTERNAL)
assertState(refresh = 1, notified = true, autoReloadType = ALL, event = "failure modification with enabled auto-reload")
settingsFile.modify(INTERNAL)
assertState(refresh = 2, notified = true, autoReloadType = ALL, event = "failure modification with enabled auto-reload")
setRefreshStatus(SUCCESS)
scheduleProjectReload()
assertState(refresh = 3, notified = false, autoReloadType = ALL, event = "refresh project")
setRefreshStatus(FAILURE)
onceDuringRefresh {
setRefreshStatus(SUCCESS)
settingsFile.modify(INTERNAL)
}
settingsFile.modify(INTERNAL)
assertState(refresh = 5, notified = false, autoReloadType = ALL, event = "success modification after failure")
}
}
@Test
fun `test up-to-date promise after modifications with enabled auto-import`() {
test { settingsFile ->
for (collisionPassType in RefreshCollisionPassType.values()) {
resetAssertionCounters()
setRefreshCollisionPassType(collisionPassType)
setAutoReloadType(SELECTIVE)
onceDuringRefresh {
settingsFile.modify(EXTERNAL)
}
settingsFile.modify(EXTERNAL)
assertState(refresh = 2, notified = false, autoReloadType = SELECTIVE, event = "auto-reload inside reload ($collisionPassType)")
setAutoReloadType(ALL)
onceDuringRefresh {
settingsFile.modify(INTERNAL)
}
settingsFile.modify(INTERNAL)
assertState(refresh = 4, notified = false, autoReloadType = ALL, event = "auto-reload inside reload ($collisionPassType)")
}
}
}
@Test
fun `test providing explicit reload`() {
test { settingsFile ->
onceDuringRefresh {
assertFalse("implicit reload after external modification", it.isExplicitReload)
}
settingsFile.modify(EXTERNAL)
assertState(refresh = 1, notified = false, event = "external modification")
settingsFile.modify(INTERNAL)
assertState(refresh = 1, notified = true, event = "internal modification")
onceDuringRefresh {
assertTrue("explicit reload after explicit scheduling of project reload", it.isExplicitReload)
}
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project reload")
}
}
@Test
fun `test settings files modification partition`() {
test {
val settingsFile1 = createSettingsVirtualFile("settings1.groovy")
val settingsFile2 = createSettingsVirtualFile("settings2.groovy")
val settingsFile3 = createSettingsVirtualFile("settings3.groovy")
assertState(refresh = 0, notified = true, event = "settings files creation")
onceDuringRefresh {
assertFalse(it.hasUndefinedModifications)
assertEquals(pathsOf(), it.settingsFilesContext.updated)
assertEquals(pathsOf(settingsFile1, settingsFile2, settingsFile3), it.settingsFilesContext.created)
assertEquals(pathsOf(), it.settingsFilesContext.deleted)
}
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "project reload")
settingsFile1.delete()
settingsFile2.appendLine("println 'hello'")
settingsFile3.appendLine("")
assertState(refresh = 1, notified = true, event = "settings files modification")
onceDuringRefresh {
assertFalse(it.hasUndefinedModifications)
assertEquals(pathsOf(settingsFile2), it.settingsFilesContext.updated)
assertEquals(pathsOf(), it.settingsFilesContext.created)
assertEquals(pathsOf(settingsFile1), it.settingsFilesContext.deleted)
}
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "project reload")
settingsFile2.delete()
settingsFile3.delete()
markDirty()
assertState(refresh = 2, notified = true, event = "settings files deletion")
onceDuringRefresh {
assertTrue(it.hasUndefinedModifications)
assertEquals(pathsOf(), it.settingsFilesContext.updated)
assertEquals(pathsOf(), it.settingsFilesContext.created)
assertEquals(pathsOf(settingsFile2, settingsFile3), it.settingsFilesContext.deleted)
}
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "project reload")
}
}
@Test
fun `test settings files cache`() {
test {
val settings1File = createSettingsVirtualFile("settings1.groovy")
val settings2File = createSettingsVirtualFile("settings2.groovy")
assertState(refresh = 0, settingsAccess = 2, notified = true, event = "settings files creation")
val configFile1 = createVirtualFile("file1.config")
val configFile2 = createVirtualFile("file2.config")
assertState(refresh = 0, settingsAccess = 4, notified = true, event = "non settings files creation")
scheduleProjectReload()
assertState(refresh = 1, settingsAccess = 5, notified = false, event = "project reload")
configFile1.modify(INTERNAL)
configFile2.modify(INTERNAL)
configFile1.modify(EXTERNAL)
configFile2.modify(EXTERNAL)
assertState(refresh = 1, settingsAccess = 5, notified = false, event = "non settings files modification")
settings1File.modify(INTERNAL)
settings2File.modify(INTERNAL)
assertState(refresh = 1, settingsAccess = 5, notified = true, event = "internal settings files modification")
scheduleProjectReload()
assertState(refresh = 2, settingsAccess = 6, notified = false, event = "project reload")
settings1File.modify(EXTERNAL)
assertState(refresh = 3, settingsAccess = 7, notified = false, event = "external settings file modification")
registerSettingsFile("settings3.groovy")
val settings3File = settings2File.copy("settings3.groovy")
assertState(refresh = 3, settingsAccess = 8, notified = true, event = "copy settings file")
settings1File.modify(INTERNAL)
settings2File.modify(INTERNAL)
settings3File.modify(INTERNAL)
assertState(refresh = 3, settingsAccess = 8, notified = true, event = "internal settings files modification")
scheduleProjectReload()
assertState(refresh = 4, settingsAccess = 9, notified = false, event = "project reload")
settings3File.modify(INTERNAL)
assertState(refresh = 4, settingsAccess = 9, notified = true, event = "internal settings file modification")
settings3File.revert()
assertState(refresh = 4, settingsAccess = 9, notified = false, event = "revert modification in settings file")
registerSettingsFile("settings4.groovy")
configFile1.rename("settings4.groovy")
assertState(refresh = 4, settingsAccess = 10, notified = true, event = "rename config file into settings file")
configFile1.modify(INTERNAL)
assertState(refresh = 4, settingsAccess = 10, notified = true, event = "modify settings file")
configFile1.rename("file1.config")
assertState(refresh = 4, settingsAccess = 11, notified = false, event = "revert config file rename")
registerSettingsFile("my-dir/file1.config")
val myDir = findOrCreateDirectory("my-dir")
// Implementation detail, settings file cache resets on any file creation
assertState(refresh = 4, settingsAccess = 12, notified = false, event = "created directory")
configFile1.move(myDir)
assertState(refresh = 4, settingsAccess = 13, notified = true, event = "move config file")
configFile1.modify(INTERNAL)
assertState(refresh = 4, settingsAccess = 13, notified = true, event = "modify config file")
configFile1.move(projectRoot)
assertState(refresh = 4, settingsAccess = 14, notified = false, event = "revert config file move")
}
}
@Test
fun `test configuration for unknown file type`() {
test("unknown") { settingsFile ->
settingsFile.replaceContent(byteArrayOf(1, 2, 3))
assertState(refresh = 0, notified = true, event = "modification")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "reload")
settingsFile.replaceContent(byteArrayOf(1, 2, 3))
assertState(refresh = 1, notified = false, event = "empty modification")
settingsFile.replaceContent(byteArrayOf(3, 2, 1))
assertState(refresh = 1, notified = true, event = "modification")
settingsFile.replaceContent(byteArrayOf(1, 2, 3))
assertState(refresh = 1, notified = false, event = "revert modification")
}
}
@Test
fun `test reload during reload`() {
test { settingsFile ->
enableAsyncExecution()
val expectedRefreshes = 10
val latch = CountDownLatch(expectedRefreshes)
duringRefresh(expectedRefreshes) {
latch.countDown()
latch.await()
}
beforeRefresh(expectedRefreshes - 1) {
forceRefreshProject()
}
waitForProjectRefresh(expectedRefreshes) {
forceRefreshProject()
}
assertState(refresh = expectedRefreshes, notified = false, event = "reloads")
waitForProjectRefresh {
settingsFile.modify(EXTERNAL)
}
assertState(refresh = expectedRefreshes + 1, notified = false, event = "external modification")
}
}
@Test
fun `test modification during reload`() {
test { settingsFile ->
enableAsyncExecution()
setDispatcherMergingSpan(10)
val expectedRefreshes = 10
duringRefresh(expectedRefreshes - 1) {
settingsFile.modify(EXTERNAL)
}
waitForProjectRefresh(expectedRefreshes) {
settingsFile.modify(EXTERNAL)
}
assertState(refresh = expectedRefreshes, notified = false, event = "reloads")
}
}
@Test
fun `test generation during reload`() {
test {
onceDuringRefresh {
createSettingsVirtualFile("settings1.cfg")
}
forceRefreshProject()
assertState(refresh = 1, notified = false, event = "create file during reload")
onceDuringRefresh {
createSettingsVirtualFile("settings2.cfg")
.replaceContent("{ name: project }")
}
forceRefreshProject()
assertState(refresh = 2, notified = false, event = "create file and modify it during reload")
findOrCreateVirtualFile("settings2.cfg")
.appendLine("{ type: Java }")
assertState(refresh = 2, notified = true, event = "internal modification")
}
}
@Test
fun `test merge project reloads`() {
test { settingsFile ->
enableAsyncExecution()
setDispatcherMergingSpan(100)
val alarmFactory = AlarmFactory.getInstance()
val alarm = alarmFactory.create()
repeat(10) { iteration ->
val promise = AsyncPromise<Unit>()
alarm.addRequest({
waitForProjectRefresh {
markDirty()
scheduleProjectReload()
}
promise.setResult(Unit)
}, 500)
waitForProjectRefresh {
settingsFile.modify(EXTERNAL)
}
PlatformTestUtil.waitForPromise(promise, TimeUnit.SECONDS.toMillis(10))
assertState(refresh = iteration + 1, notified = false, event = "project reload")
}
}
}
@Test
fun `test handle explicit settings files list change event`() {
initialize()
setAutoReloadType(ALL)
val settingsFile1 = createVirtualFile("script1.groovy").path
val settingsFile2 = createVirtualFile("script2.groovy").path
val projectAware = mockProjectAware()
projectAware.registerSettingsFile(settingsFile1)
register(projectAware)
assertProjectAware(projectAware, refresh = 1, event = "register project")
projectAware.notifySettingsFilesListChanged()
assertProjectAware(projectAware, refresh = 1, event = "handle settings files list change event when nothing actually changed")
projectAware.registerSettingsFile(settingsFile2)
projectAware.notifySettingsFilesListChanged()
assertProjectAware(projectAware, refresh = 2, event = "handle settings files list change event when file added")
}
@Test
fun `test partial ignoring settings files modification events`() {
test {
ignoreSettingsFileWhen("ignored.groovy") { it.event == UPDATE }
val ignoredSettingsFile = createSettingsVirtualFile("ignored.groovy")
assertState(refresh = 0, notified = true, event = "settings file creation")
scheduleProjectReload()
assertState(refresh = 1, notified = false, event = "reload")
ignoredSettingsFile.modify()
assertState(refresh = 1, notified = false, event = "settings file ignored modification")
markDirty()
ignoredSettingsFile.modify()
assertState(refresh = 1, notified = true, event = "settings file ignored modification with dirty AI state")
scheduleProjectReload()
assertState(refresh = 2, notified = false, event = "reload")
ignoredSettingsFile.delete()
assertState(refresh = 2, notified = true, event = "settings files deletion")
scheduleProjectReload()
assertState(refresh = 3, notified = false, event = "reload")
ignoreSettingsFileWhen("build.lock") { it.reloadStatus == IN_PROGRESS && it.modificationType == EXTERNAL }
val propertiesFile = createSettingsVirtualFile("build.lock")
assertState(refresh = 3, notified = true, event = "settings file creation")
onceDuringRefresh {
propertiesFile.modify(EXTERNAL)
}
scheduleProjectReload()
assertState(refresh = 4, notified = false, event = "ignored settings file creation during reload")
propertiesFile.modify(EXTERNAL)
assertState(refresh = 5, notified = false, event = "settings file modification")
onceDuringRefresh {
propertiesFile.modify(INTERNAL)
}
markDirty()
scheduleProjectReload()
assertState(refresh = 6, notified = true, event = "settings file modification during reload")
}
}
} | apache-2.0 | 068c22fd1cceeb3324b8b93db73afeed | 45.005571 | 140 | 0.698771 | 4.684852 | false | true | false | false |
JetBrains/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/coroutineStackFrameProxys.kt | 1 | 3414 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.proxy
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl
import com.sun.jdi.Location
import com.sun.jdi.ObjectReference
import com.sun.jdi.StackFrame
import com.sun.jdi.Value
import org.jetbrains.kotlin.idea.debugger.coroutine.data.ContinuationVariableValueDescriptorImpl
import org.jetbrains.kotlin.idea.debugger.base.util.safeStackFrame
import org.jetbrains.kotlin.idea.debugger.base.util.safeThreadProxy
import org.jetbrains.kotlin.idea.debugger.base.util.wrapEvaluateException
import org.jetbrains.kotlin.idea.debugger.core.stackFrame.KotlinStackFrameProxyImpl
class SkipCoroutineStackFrameProxyImpl(
threadProxy: ThreadReferenceProxyImpl,
stackFrame: StackFrame,
indexFromBottom: Int
) : StackFrameProxyImpl(threadProxy, stackFrame, indexFromBottom)
class CoroutineStackFrameProxyImpl(
private val location: Location?,
val spilledVariables: List<JavaValue>,
threadProxy: ThreadReferenceProxyImpl,
stackFrame: StackFrame,
indexFromBottom: Int
) : KotlinStackFrameProxyImpl(threadProxy, stackFrame, indexFromBottom) {
val continuation = wrapEvaluateException { super.thisObject() }
private val coroutineScope by lazy { extractCoroutineScope() }
fun updateSpilledVariableValue(name: String, value: Value?) {
val descriptor = spilledVariables.find { it.name == name }?.descriptor as? ContinuationVariableValueDescriptorImpl ?: return
descriptor.updateValue(value)
}
fun isCoroutineScopeAvailable() = coroutineScope != null
override fun location(): Location? =
location
override fun thisObject() =
coroutineScope ?: continuation
override fun dispatchReceiver() = continuation
private fun extractCoroutineScope(): ObjectReference? {
if (continuation == null) {
return null
}
val debugProcess = virtualMachine.debugProcess as? DebugProcessImpl ?: return null
val suspendContext = debugProcess.suspendManager.pausedContext ?: return null
val evaluationContext = EvaluationContextImpl(suspendContext, this)
return CoroutineScopeExtractor.extractCoroutineScope(continuation, evaluationContext)
}
}
fun safeSkipCoroutineStackFrameProxy(frameProxy: StackFrameProxyImpl): StackFrameProxyImpl {
val threadProxy = frameProxy.safeThreadProxy() ?: return frameProxy
val stackFrame = frameProxy.safeStackFrame() ?: return frameProxy
return SkipCoroutineStackFrameProxyImpl(threadProxy, stackFrame, frameProxy.indexFromBottom)
}
fun safeCoroutineStackFrameProxy(
location: Location?,
spilledVariables: List<JavaValue>,
frameProxy: StackFrameProxyImpl
): StackFrameProxyImpl {
val threadProxy = frameProxy.safeThreadProxy() ?: return frameProxy
val stackFrame = frameProxy.safeStackFrame() ?: return frameProxy
return CoroutineStackFrameProxyImpl(
location,
spilledVariables,
threadProxy,
stackFrame,
frameProxy.indexFromBottom
)
}
| apache-2.0 | 4042d3cb33480dbc4a80308e622328ca | 40.13253 | 158 | 0.778266 | 5.276662 | false | false | false | false |
square/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/Response.kt | 2 | 12197 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.Closeable
import java.io.IOException
import java.net.HttpURLConnection.HTTP_PROXY_AUTH
import java.net.HttpURLConnection.HTTP_UNAUTHORIZED
import okhttp3.ResponseBody.Companion.asResponseBody
import okhttp3.internal.commonAddHeader
import okhttp3.internal.commonBody
import okhttp3.internal.commonCacheControl
import okhttp3.internal.commonCacheResponse
import okhttp3.internal.commonClose
import okhttp3.internal.commonCode
import okhttp3.internal.commonEmptyResponse
import okhttp3.internal.commonHeader
import okhttp3.internal.commonHeaders
import okhttp3.internal.commonIsRedirect
import okhttp3.internal.commonIsSuccessful
import okhttp3.internal.commonMessage
import okhttp3.internal.commonNetworkResponse
import okhttp3.internal.commonNewBuilder
import okhttp3.internal.commonPriorResponse
import okhttp3.internal.commonProtocol
import okhttp3.internal.commonRemoveHeader
import okhttp3.internal.commonRequest
import okhttp3.internal.commonToString
import okhttp3.internal.commonTrailers
import okhttp3.internal.connection.Exchange
import okhttp3.internal.http.parseChallenges
import okio.Buffer
actual class Response internal constructor(
@get:JvmName("request") actual val request: Request,
@get:JvmName("protocol") actual val protocol: Protocol,
@get:JvmName("message") actual val message: String,
@get:JvmName("code") actual val code: Int,
/**
* Returns the TLS handshake of the connection that carried this response, or null if the
* response was received without TLS.
*/
@get:JvmName("handshake") val handshake: Handshake?,
/** Returns the HTTP headers. */
@get:JvmName("headers") actual val headers: Headers,
@get:JvmName("body") actual val body: ResponseBody,
@get:JvmName("networkResponse") actual val networkResponse: Response?,
@get:JvmName("cacheResponse") actual val cacheResponse: Response?,
@get:JvmName("priorResponse") actual val priorResponse: Response?,
/**
* Returns a [timestamp][System.currentTimeMillis] taken immediately before OkHttp
* transmitted the initiating request over the network. If this response is being served from the
* cache then this is the timestamp of the original request.
*/
@get:JvmName("sentRequestAtMillis") val sentRequestAtMillis: Long,
/**
* Returns a [timestamp][System.currentTimeMillis] taken immediately after OkHttp
* received this response's headers from the network. If this response is being served from the
* cache then this is the timestamp of the original response.
*/
@get:JvmName("receivedResponseAtMillis") val receivedResponseAtMillis: Long,
@get:JvmName("exchange") internal val exchange: Exchange?,
private var trailersFn: (() -> Headers)
) : Closeable {
internal actual var lazyCacheControl: CacheControl? = null
@JvmName("-deprecated_request")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "request"),
level = DeprecationLevel.ERROR)
fun request(): Request = request
@JvmName("-deprecated_protocol")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "protocol"),
level = DeprecationLevel.ERROR)
fun protocol(): Protocol = protocol
@JvmName("-deprecated_code")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "code"),
level = DeprecationLevel.ERROR)
fun code(): Int = code
actual val isSuccessful: Boolean = commonIsSuccessful
@JvmName("-deprecated_message")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "message"),
level = DeprecationLevel.ERROR)
fun message(): String = message
@JvmName("-deprecated_handshake")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "handshake"),
level = DeprecationLevel.ERROR)
fun handshake(): Handshake? = handshake
actual fun headers(name: String): List<String> = commonHeaders(name)
@JvmOverloads
actual fun header(name: String, defaultValue: String?): String? = commonHeader(name, defaultValue)
@JvmName("-deprecated_headers")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "headers"),
level = DeprecationLevel.ERROR)
fun headers(): Headers = headers
/**
* Returns the trailers after the HTTP response, which may be empty. It is an error to call this
* before the entire HTTP response body has been consumed.
*/
@Throws(IOException::class)
actual fun trailers(): Headers = trailersFn()
@Throws(IOException::class)
actual fun peekBody(byteCount: Long): ResponseBody {
val peeked = body.source().peek()
val buffer = Buffer()
peeked.request(byteCount)
buffer.write(peeked, minOf(byteCount, peeked.buffer.size))
return buffer.asResponseBody(body.contentType(), buffer.size)
}
@JvmName("-deprecated_body")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "body"),
level = DeprecationLevel.ERROR)
fun body() = body
actual fun newBuilder(): Builder = commonNewBuilder()
/** Returns true if this response redirects to another resource. */
actual val isRedirect: Boolean = commonIsRedirect
@JvmName("-deprecated_networkResponse")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "networkResponse"),
level = DeprecationLevel.ERROR)
fun networkResponse(): Response? = networkResponse
@JvmName("-deprecated_cacheResponse")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "cacheResponse"),
level = DeprecationLevel.ERROR)
fun cacheResponse(): Response? = cacheResponse
@JvmName("-deprecated_priorResponse")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "priorResponse"),
level = DeprecationLevel.ERROR)
fun priorResponse(): Response? = priorResponse
/**
* Returns the RFC 7235 authorization challenges appropriate for this response's code. If the
* response code is 401 unauthorized, this returns the "WWW-Authenticate" challenges. If the
* response code is 407 proxy unauthorized, this returns the "Proxy-Authenticate" challenges.
* Otherwise this returns an empty list of challenges.
*
* If a challenge uses the `token68` variant instead of auth params, there is exactly one
* auth param in the challenge at key null. Invalid headers and challenges are ignored.
* No semantic validation is done, for example that `Basic` auth must have a `realm`
* auth param, this is up to the caller that interprets these challenges.
*/
fun challenges(): List<Challenge> {
return headers.parseChallenges(
when (code) {
HTTP_UNAUTHORIZED -> "WWW-Authenticate"
HTTP_PROXY_AUTH -> "Proxy-Authenticate"
else -> return emptyList()
}
)
}
@get:JvmName("cacheControl") actual val cacheControl: CacheControl
get() = commonCacheControl
@JvmName("-deprecated_cacheControl")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "cacheControl"),
level = DeprecationLevel.ERROR)
fun cacheControl(): CacheControl = cacheControl
@JvmName("-deprecated_sentRequestAtMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "sentRequestAtMillis"),
level = DeprecationLevel.ERROR)
fun sentRequestAtMillis(): Long = sentRequestAtMillis
@JvmName("-deprecated_receivedResponseAtMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "receivedResponseAtMillis"),
level = DeprecationLevel.ERROR)
fun receivedResponseAtMillis(): Long = receivedResponseAtMillis
actual override fun close() = commonClose()
actual override fun toString(): String = commonToString()
actual open class Builder {
internal actual var request: Request? = null
internal actual var protocol: Protocol? = null
internal actual var code = -1
internal actual var message: String? = null
internal var handshake: Handshake? = null
internal actual var headers: Headers.Builder
internal actual var body: ResponseBody = commonEmptyResponse
internal actual var networkResponse: Response? = null
internal actual var cacheResponse: Response? = null
internal actual var priorResponse: Response? = null
internal var sentRequestAtMillis: Long = 0
internal var receivedResponseAtMillis: Long = 0
internal var exchange: Exchange? = null
internal actual var trailersFn: (() -> Headers) = { Headers.headersOf() }
actual constructor() {
headers = Headers.Builder()
}
internal actual constructor(response: Response) {
this.request = response.request
this.protocol = response.protocol
this.code = response.code
this.message = response.message
this.handshake = response.handshake
this.headers = response.headers.newBuilder()
this.body = response.body
this.networkResponse = response.networkResponse
this.cacheResponse = response.cacheResponse
this.priorResponse = response.priorResponse
this.sentRequestAtMillis = response.sentRequestAtMillis
this.receivedResponseAtMillis = response.receivedResponseAtMillis
this.exchange = response.exchange
this.trailersFn = response.trailersFn
}
actual open fun request(request: Request) = commonRequest(request)
actual open fun protocol(protocol: Protocol) =commonProtocol(protocol)
actual open fun code(code: Int) = commonCode(code)
actual open fun message(message: String) = commonMessage(message)
open fun handshake(handshake: Handshake?) = apply {
this.handshake = handshake
}
actual open fun header(name: String, value: String) = commonHeader(name, value)
actual open fun addHeader(name: String, value: String) = commonAddHeader(name, value)
actual open fun removeHeader(name: String) = commonRemoveHeader(name)
actual open fun headers(headers: Headers) = commonHeaders(headers)
actual open fun body(body: ResponseBody) = commonBody(body)
actual open fun networkResponse(networkResponse: Response?) = commonNetworkResponse(networkResponse)
actual open fun cacheResponse(cacheResponse: Response?) = commonCacheResponse(cacheResponse)
actual open fun priorResponse(priorResponse: Response?) = commonPriorResponse(priorResponse)
actual open fun trailers(trailersFn: (() -> Headers)): Builder = commonTrailers(trailersFn)
open fun sentRequestAtMillis(sentRequestAtMillis: Long) = apply {
this.sentRequestAtMillis = sentRequestAtMillis
}
open fun receivedResponseAtMillis(receivedResponseAtMillis: Long) = apply {
this.receivedResponseAtMillis = receivedResponseAtMillis
}
internal fun initExchange(exchange: Exchange) {
this.exchange = exchange
this.trailersFn = { exchange.trailers() }
}
actual open fun build(): Response {
check(code >= 0) { "code < 0: $code" }
return Response(
checkNotNull(request) { "request == null" },
checkNotNull(protocol) { "protocol == null" },
checkNotNull(message) { "message == null" },
code,
handshake,
headers.build(),
body,
networkResponse,
cacheResponse,
priorResponse,
sentRequestAtMillis,
receivedResponseAtMillis,
exchange,
trailersFn
)
}
}
}
| apache-2.0 | d37658970c191f2074e3b2f4c941915f | 34.768328 | 104 | 0.721243 | 4.674971 | false | false | false | false |
Leifzhang/AndroidRouter | RouterLib/src/main/java/com/kronos/router/utils/FragmentForResult.kt | 2 | 1974 | package com.kronos.router.utils
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import kotlin.properties.Delegates
class FragmentForResult : Fragment() {
var onSuccess: () -> Unit = {}
var onFail: () -> Unit = {}
var clazz: Class<out Any>? = null
private var code by Delegates.notNull<Int>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
code = arguments?.getInt("requestCode", 0) ?: 0
val intent = Intent()
clazz?.let { intent.setClass(requireContext(), it) }
startActivityForResult(intent, code)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == code) {
if (resultCode == Activity.RESULT_OK) {
onSuccess.invoke()
} else {
onFail.invoke()
}
}
}
}
fun AppCompatActivity.startForResult(code: Int, clazz: Class<out Any>, bundle: Bundle? = null,
onSuccess: () -> Unit = {}, onFail: () -> Unit = {}) {
var fragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as FragmentForResult?
if (fragment == null) {
fragment = FragmentForResult()
}
fragment.onSuccess = onSuccess
fragment.onFail = onFail
fragment.clazz = clazz
val mBundle = Bundle()
bundle?.apply {
mBundle.putAll(this)
}
mBundle.putInt("requestCode", code)
fragment.arguments = bundle
supportFragmentManager.beginTransaction().apply {
if (fragment.isAdded) {
remove(fragment)
}
add(fragment, FRAGMENT_TAG)
}.commitNowAllowingStateLoss()
}
private const val FRAGMENT_TAG = "FragmentForResult" | mit | 4422196d66e4b1f9f0b4e6f7100b03d8 | 29.859375 | 95 | 0.640831 | 4.677725 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/parser/CabalConstructs.kt | 1 | 9979 | package org.jetbrains.cabal.parser
import org.jetbrains.cabal.parser.*
import com.intellij.psi.tree.IElementType
import kotlin.Pair
import java.util.*
import org.jetbrains.cabal.parser.CabalTokelTypes as CT
class FieldsBuilder {
val map : MutableMap<String, Pair<IElementType, Function2<CabalParser, Int, Boolean>>> =
HashMap()
fun field(name : String , elementType : IElementType, f : CabalParser.(Int) -> Boolean) {
map.put(name, Pair(elementType, f))
}
fun addAll(fields : Map<String, Pair<IElementType, Function2<CabalParser, Int, Boolean>>>) {
map.putAll(fields)
}
fun build(): MutableMap<String, Pair<IElementType, Function2<CabalParser, Int, Boolean>>> {
return map
}
}
fun makeFields(body : FieldsBuilder.() -> Unit) : Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> {
val builder = FieldsBuilder()
builder.body()
return builder.build()
}
// https://github.com/ghc/packages-Cabal/blob/master/Cabal/Distribution/PackageDescription/Parse.hs
val PKG_DESCR_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("name", CT.NAME_FIELD, { parseIdValue(CT.NAME) })
field("version", CT.VERSION, { parseVersionValue() } )
field("cabal-version", CT.CABAL_VERSION, { parseSimpleVersionConstraint() })
field("build-type", CT.BUILD_TYPE_FIELD, { parseIdValue(CT.BUILD_TYPE) })
field("license", CT.LICENSE, { parseIdValue(CT.IDENTIFIER) })
field("license-file", CT.LICENSE_FILES, { parsePath() })
field("copyright", CT.SINGLE_VAL, CabalParser::parseFreeForm)
field("author", CT.SINGLE_VAL, CabalParser::parseFreeForm)
field("maintainer", CT.SINGLE_VAL, { parseFreeLine(CT.E_MAIL) })
field("stability", CT.SINGLE_VAL, CabalParser::parseFreeForm)
field("homepage", CT.SINGLE_VAL, { parseTokenValue(CT.URL) })
field("bug-reports", CT.SINGLE_VAL, { parseTokenValue(CT.URL) })
field("package-url", CT.SINGLE_VAL, { parseTokenValue(CT.URL) })
field("synopsis", CT.SINGLE_VAL, CabalParser::parseFreeForm)
field("description", CT.SINGLE_VAL, CabalParser::parseFreeForm)
field("category", CT.SINGLE_VAL, CabalParser::parseFreeForm)
field("tested-with", CT.TESTED_WITH, CabalParser::parseCompilerList)
field("data-files", CT.DATA_FILES, CabalParser::parsePathList)
field("data-dir", CT.DATA_DIR, { parsePath() })
field("extra-source-files", CT.EXTRA_SOURCE, CabalParser::parsePathList)
field("extra-tmp-files", CT.EXTRA_TMP, CabalParser::parsePathList)
}
val BUILD_INFO_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("build-depends", CT.BUILD_DEPENDS, { l -> parseConstraintList(l) })
field("other-modules", CT.OTHER_MODULES, CabalParser::parseIdList)
field("hs-source-dirs", CT.HS_SOURCE_DIRS, CabalParser::parsePathList)
field("hs-source-dir", CT.HS_SOURCE_DIRS, { parsePath() })
field("extensions", CT.EXTENSIONS, CabalParser::parseIdList)
field("build-tools", CT.BUILD_TOOLS, { l -> parseConstraintList(l) })
field("buildable", CT.BUILDABLE, { parseBool() })
field("ghc-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("ghc-prof-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("ghc-shared-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("hugs-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("nhc98-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("jhc-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("includes", CT.INCLUDES, CabalParser::parsePathList)
field("install-includes", CT.INSTALL_INCLUDES, CabalParser::parsePathList)
field("include-dirs", CT.INCLUDE_DIRS, CabalParser::parsePathList)
field("c-sources", CT.C_SOURCES, CabalParser::parsePathList)
field("extra-libraries", CT.MULTI_VAL, CabalParser::parseTokenList)
field("extra-lib-dirs", CT.EXTRA_LIB_DIRS, CabalParser::parsePathList)
field("cc-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("cpp-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("ld-options", CT.MULTI_VAL, CabalParser::parseOptionList)
field("pkgconfig-depends", CT.PKG_CONFIG_DEPENDS, { l -> parseConstraintList(l) })
field("frameworks", CT.MULTI_VAL, CabalParser::parseTokenList)
field("default-extensions", CT.MULTI_VAL, CabalParser::parseIdList)
field("other-extensions", CT.MULTI_VAL, CabalParser::parseIdList)
field("default-language", CT.SINGLE_VAL, { parseIdValue(CT.LANGUAGE) })
field("other-languages", CT.MULTI_VAL, CabalParser::parseLanguageList)
}
val LIBRARY_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("exposed-modules", CT.EXPOSED_MODULES, CabalParser::parseIdList)
field("exposed", CT.EXPOSED, { parseBool() })
addAll(BUILD_INFO_FIELDS)
}
val EXECUTABLE_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("main-is", CT.MAIN_FILE, { parsePath() } )
addAll(BUILD_INFO_FIELDS)
}
val TEST_SUITE_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("type", CT.TYPE, { parseIdValue(CT.TEST_SUITE_TYPE) })
field("main-is", CT.MAIN_FILE, { parsePath() })
field("test-module", CT.TEST_MODULE, { parseIdValue(CT.IDENTIFIER) })
addAll(BUILD_INFO_FIELDS)
}
val BENCHMARK_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("type", CT.TYPE, { parseIdValue(CT.BENCHMARK_TYPE) })
field("main-is", CT.MAIN_FILE, { parsePath() })
addAll(BUILD_INFO_FIELDS)
}
val FLAG_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("description", CT.SINGLE_VAL, CabalParser::parseFreeForm)
field("default", CT.BOOL_FIELD, { parseBool() })
field("manual", CT.BOOL_FIELD, { parseBool() })
}
val SOURCE_REPO_FIELDS: Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>> = makeFields {
field("location", CT.REPO_LOCATION, { parseTokenValue(CT.URL) })
field("type", CT.TYPE, { parseIdValue(CT.REPO_TYPE) })
field("subdir", CT.REPO_SUBDIR, { parsePath() })
field("module", CT.REPO_MODULE, { parseTokenValue(CT.TOKEN) })
field("tag", CT.REPO_TAG, { parseTokenValue(CT.TOKEN) })
field("branch", CT.SINGLE_VAL, { parseTokenValue(CT.TOKEN) })
}
val SECTION_TYPES: Map<String, IElementType> = mapOf(
"flag" to CT.FLAG ,
"executable" to CT.EXECUTABLE ,
"library" to CT.LIBRARY ,
"test-suite" to CT.TEST_SUITE ,
"benchmark" to CT.BENCHMARK ,
"if" to CT.IF_CONDITION ,
"else" to CT.ELSE_CONDITION,
"source-repository" to CT.SOURCE_REPO
)
private fun parseFun(f : CabalParser.(Int) -> Boolean) = f
val SECTIONS: Map<String, Pair< CabalParser.(Int) -> Boolean,
Map<String, Pair<IElementType, CabalParser.(Int) -> Boolean>>?
>> = mapOf(
"executable" to Pair(parseFun { parseSectionName() }, EXECUTABLE_FIELDS) ,
"library" to Pair(parseFun { true }, LIBRARY_FIELDS) ,
"test-suite" to Pair(parseFun { this.parseSectionName()}, TEST_SUITE_FIELDS) ,
"benchmark" to Pair(parseFun { this.parseSectionName()}, BENCHMARK_FIELDS) ,
"flag" to Pair(parseFun { this.parseSectionName()}, FLAG_FIELDS) ,
"source-repository" to Pair(parseFun { this.parseRepoKinds()}, SOURCE_REPO_FIELDS),
"if" to Pair(CabalParser::parseFullCondition, null) ,
"else" to Pair(parseFun { true}, null)
)
val TOP_SECTION_NAMES: List<String> = listOf(
"flag",
"executable",
"library",
"test-suite",
"benchmark",
"source-repository"
)
val IF_ELSE: List<String> = listOf(
"if",
"else"
)
val BUILD_INFO_SECTIONS: List<String> = listOf(
"executable",
"library",
"test-suite",
"benchmark"
)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
val REPO_KIND_VALS : List<String> = listOf(
"this",
"head"
)
val REPO_TYPE_VALS : List<String> = listOf(
"darcs",
"git",
"svn",
"cvs",
"mercurial",
"hg",
"bazaar",
"bzr",
"arch",
"monotone"
)
val TS_TYPE_VALS : List<String> = listOf(
"exitcode-stdio-1.0",
"detailed-0.9",
"detailed-1.0"
)
val BENCH_TYPE_VALS: List<String> = listOf(
"exitcode-stdio-1.0"
)
val BUILD_TYPE_VALS : List<String> = listOf(
"Simple",
"Configure",
"Custom",
"Make"
)
val BOOL_VALS : List<String> = listOf(
"true",
"True",
"false",
"False"
)
val COMPILER_VALS : List<String> = listOf(
"ghc",
"nhc",
"yhc",
"hugs",
"hbc",
"helium",
"jhc",
"lhc"
)
val LANGUAGE_VALS : List<String> = listOf(
"Haskell98",
"Haskell2010"
)
| apache-2.0 | 8e0edbd8ed296e282dbceee2d85d6f14 | 39.565041 | 169 | 0.588035 | 3.648629 | false | false | false | false |
allotria/intellij-community | platform/object-serializer/testSrc/ObjectSerializerTest.kt | 3 | 5500 | // 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.serialization
import com.intellij.openapi.util.SystemInfo
import com.intellij.testFramework.assertions.Assertions.assertThat
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestName
import java.io.File
import java.nio.file.Paths
import java.util.*
import kotlin.collections.HashMap
class ObjectSerializerTest {
@Rule
@JvmField
val testName = TestName()
private fun <T : Any> test(bean: T, writeConfiguration: WriteConfiguration = defaultTestWriteConfiguration): T {
return test(bean, testName, writeConfiguration)
}
@Test
fun threadLocalPooledBlockAllocatorProvider() {
testThreadLocalPooledBlockAllocatorProvider()
}
@Test
fun `same bean binding regardless of type parameters`() {
val serializer = ObjectSerializer()
getBinding(TestGenericBean::class.java, serializer)
assertThat(getBindingCount(getBindingProducer(serializer))).isEqualTo(1)
}
@Test
fun `int and null string`() {
test(TestBean())
}
@Test
fun `int and string`() {
test(TestBean(foo = "bar"))
}
@Test
fun `int as object`() {
val bean = TestBean()
bean.intAsObject = 4212
test(bean)
}
@Test
fun `boolean as null object`() {
test(TestBoolBean())
}
@Test
fun `boolean as object`() {
val bean = TestBoolBean()
bean.boolAsObject = false
test(bean)
}
@Test
fun `float as null object`() {
test(TestFloatBean())
}
@Test
fun `float as object`() {
val bean = TestFloatBean()
bean.doubleAsObject = 1412.123
bean.floatAsObject = 54.12f
test(bean)
}
@Test
fun `self class reference`() {
test(TestObjectBean())
}
@Test
fun `recursive reference`() {
val bean = TestObjectBean()
bean.bean = bean
test(bean)
}
@Test
fun `several recursive reference`() {
val bean = TestObjectBean()
val bean2 = TestObjectBean()
bean.bean = bean2
bean2.bean = bean
// test SkipNullAndEmptySerializationFilter
test(bean, defaultTestWriteConfiguration.copy(filter = SkipNullAndEmptySerializationFilter))
}
@Test
fun `array of string`() {
test(TestArrayBean(list = arrayOf("foo", "bar")))
}
@Test
fun `array of objects`() {
test(TestArrayBean(children = arrayOf(TestBean(foo = "foo"), TestBean(foo = "or bar"))))
}
@Test
fun `byte array`() {
test(TestByteArray(data = Base64.getEncoder().encode("some data".toByteArray())))
}
@Test
fun `bean with long array`() {
test(TestLongArray())
}
@Test
fun enum() {
val bean = TestEnumBean()
bean.color = TestEnum.RED
test(bean)
}
@Test
fun `file and path`() {
assumeTrue(!SystemInfo.isWindows)
@Suppress("unused")
class TestBean {
@JvmField
var f = File("/foo")
@JvmField
var p = Paths.get("/bar")
}
test(TestBean())
}
@Test
fun `interface type for field`() {
class TestInterfaceBean {
@JvmField
@field:Property(allowedTypes = [Circle::class, Rectangle::class])
var shape: Shape? = null
}
val bean = TestInterfaceBean()
bean.shape = Circle()
test(bean)
}
@Test
fun `interface type for map value - allowSubTypes`() {
class TestInterfaceBean {
@JvmField
val shape: MutableMap<String, Shape> = HashMap()
}
val bean = TestInterfaceBean()
bean.shape.put("first", Circle())
test(bean, defaultTestWriteConfiguration.copy(allowAnySubTypes = true))
}
@Test
fun `interface type for field - allowSubTypes`() {
class TestInterfaceBean {
@JvmField
var shape: Shape? = null
}
val bean = TestInterfaceBean()
bean.shape = Circle()
test(bean, defaultTestWriteConfiguration.copy(allowAnySubTypes = true))
}
}
private interface Shape
private class Circle : Shape {
@JvmField
var name: String? = null
}
private class Rectangle : Shape {
@JvmField
var length: Int = -1
}
internal enum class TestEnum {
RED, BLUE
}
private class TestEnumBean {
@JvmField
var color: TestEnum = TestEnum.BLUE
}
private class TestByteArray @JvmOverloads constructor(@Suppress("unused") @JvmField var data: ByteArray? = null)
private class TestLongArray {
@JvmField
val field: Array<Long> = arrayOf(1, 2, Long.MAX_VALUE, Long.MIN_VALUE)
}
private class TestArrayBean(
@JvmField var list: Array<String>? = null,
/* test set to final field */@JvmField val children: Array<TestBean> = arrayOf()
)
internal class TestObjectBean {
@JvmField
var bean: TestObjectBean? = null
@JvmField
val list = mutableListOf<String>()
@JvmField
val children = mutableListOf<TestObjectBean>()
}
@Suppress("unused")
private class TestBean(@JvmField var foo: String? = null) {
@JvmField
var short: Short = 4
@JvmField
var long = Long.MAX_VALUE
@JvmField
var counter = 42
@JvmField
var intAsObject: Int? = null
}
@Suppress("unused")
private class TestBoolBean {
@JvmField
var boolAsObject: Boolean? = null
@JvmField
var bool = false
}
@Suppress("unused")
private class TestFloatBean {
@JvmField
var doubleAsObject: Double? = null
@JvmField
var floatAsObject: Float? = null
@JvmField
var double: Double = 9.2
@JvmField
var float: Float = 0.4f
}
private class TestGenericBean<T> {
@JvmField
var data: TestGenericBean<T>? = null
} | apache-2.0 | 6e92bf05e254858f7499385ad6528997 | 19.680451 | 140 | 0.673091 | 3.814147 | false | true | false | false |
square/okio | okio/src/jvmMain/kotlin/okio/FileSystem.kt | 1 | 5459 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import okio.Path.Companion.toPath
import okio.internal.ResourceFileSystem
import okio.internal.commonCopy
import okio.internal.commonCreateDirectories
import okio.internal.commonDeleteRecursively
import okio.internal.commonExists
import okio.internal.commonListRecursively
import okio.internal.commonMetadata
actual abstract class FileSystem {
@Throws(IOException::class)
actual abstract fun canonicalize(path: Path): Path
@Throws(IOException::class)
actual fun metadata(path: Path): FileMetadata = commonMetadata(path)
@Throws(IOException::class)
actual abstract fun metadataOrNull(path: Path): FileMetadata?
@Throws(IOException::class)
actual fun exists(path: Path): Boolean = commonExists(path)
@Throws(IOException::class)
actual abstract fun list(dir: Path): List<Path>
actual abstract fun listOrNull(dir: Path): List<Path>?
actual open fun listRecursively(dir: Path, followSymlinks: Boolean): Sequence<Path> =
commonListRecursively(dir, followSymlinks)
fun listRecursively(dir: Path): Sequence<Path> = listRecursively(dir, followSymlinks = false)
@Throws(IOException::class)
actual abstract fun openReadOnly(file: Path): FileHandle
@Throws(IOException::class)
actual abstract fun openReadWrite(file: Path, mustCreate: Boolean, mustExist: Boolean): FileHandle
@Throws(IOException::class)
fun openReadWrite(file: Path): FileHandle =
openReadWrite(file, mustCreate = false, mustExist = false)
@Throws(IOException::class)
actual abstract fun source(file: Path): Source
@Throws(IOException::class)
@JvmName("-read")
actual inline fun <T> read(file: Path, readerAction: BufferedSource.() -> T): T {
return source(file).buffer().use {
it.readerAction()
}
}
@Throws(IOException::class)
actual abstract fun sink(file: Path, mustCreate: Boolean): Sink
@Throws(IOException::class)
fun sink(file: Path): Sink = sink(file, mustCreate = false)
@Throws(IOException::class)
@JvmName("-write")
actual inline fun <T> write(file: Path, mustCreate: Boolean, writerAction: BufferedSink.() -> T): T {
return sink(file, mustCreate = mustCreate).buffer().use {
it.writerAction()
}
}
@Throws(IOException::class)
actual abstract fun appendingSink(file: Path, mustExist: Boolean): Sink
@Throws(IOException::class)
fun appendingSink(file: Path): Sink = appendingSink(file, mustExist = false)
@Throws(IOException::class)
actual abstract fun createDirectory(dir: Path, mustCreate: Boolean)
@Throws(IOException::class)
fun createDirectory(dir: Path) = createDirectory(dir, mustCreate = false)
@Throws(IOException::class)
actual fun createDirectories(dir: Path, mustCreate: Boolean): Unit =
commonCreateDirectories(dir, mustCreate)
@Throws(IOException::class)
fun createDirectories(dir: Path): Unit = createDirectories(dir, mustCreate = false)
@Throws(IOException::class)
actual abstract fun atomicMove(source: Path, target: Path)
@Throws(IOException::class)
actual open fun copy(source: Path, target: Path): Unit = commonCopy(source, target)
@Throws(IOException::class)
actual abstract fun delete(path: Path, mustExist: Boolean)
@Throws(IOException::class)
fun delete(path: Path) = delete(path, mustExist = false)
@Throws(IOException::class)
actual open fun deleteRecursively(fileOrDirectory: Path, mustExist: Boolean): Unit =
commonDeleteRecursively(fileOrDirectory, mustExist)
@Throws(IOException::class)
fun deleteRecursively(fileOrDirectory: Path): Unit =
deleteRecursively(fileOrDirectory, mustExist = false)
@Throws(IOException::class)
actual abstract fun createSymlink(source: Path, target: Path)
actual companion object {
/**
* The current process's host file system. Use this instance directly, or dependency inject a
* [FileSystem] to make code testable.
*/
@JvmField
val SYSTEM: FileSystem = run {
try {
Class.forName("java.nio.file.Files")
return@run NioSystemFileSystem()
} catch (e: ClassNotFoundException) {
return@run JvmSystemFileSystem()
}
}
@JvmField
actual val SYSTEM_TEMPORARY_DIRECTORY: Path = System.getProperty("java.io.tmpdir").toPath()
/**
* A read-only file system holding the classpath resources of the current process. If a resource
* is available with [ClassLoader.getResource], it is also available via this file system.
*
* In applications that compose multiple class loaders, this holds only the resources of
* whichever class loader includes Okio classes. Use [ClassLoader.asResourceFileSystem] for the
* resources of a specific class loader.
*/
@JvmField
val RESOURCES: FileSystem = ResourceFileSystem(
classLoader = ResourceFileSystem::class.java.classLoader,
indexEagerly = false,
)
}
}
| apache-2.0 | faef93cbf6b02615fa64e911b7d8cbc1 | 33.333333 | 103 | 0.731636 | 4.244946 | false | false | false | false |
EGF2/android-client | egf2-generator/src/main/kotlin/com/eigengraph/egf2/generator/mappers/ObjectMapper.kt | 1 | 3496 | package com.eigengraph.egf2.generator.mappers
import com.eigengraph.egf2.generator.EGF2Generator
import com.eigengraph.egf2.generator.Field
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.MethodSpec
import org.jetbrains.annotations.NotNull
import java.util.*
import javax.lang.model.element.Modifier
class ObjectMapper(targetPackage: String) : Mapper(targetPackage) {
override fun getField(field: Field, custom_schemas: LinkedHashMap<String, LinkedList<Field>>): FieldSpec {
val fs: FieldSpec.Builder
val jd = java.lang.String.join(", ", field.object_types)
fs = FieldSpec.builder(String::class.java, field.name, Modifier.PUBLIC).addJavadoc("Objects: \$L", jd)
if (field.default != null) fs.initializer("\$L", field.default)
if (field.required) fs.addAnnotation(NotNull::class.java)
return fs.build()
}
override fun deserialize(field: Field, supername: String, deserialize: MethodSpec.Builder, custom_schemas: LinkedHashMap<String, LinkedList<Field>>) {
deserialize.addStatement("String \$L = null", field.name)
deserialize.beginControlFlow("if(jsonObject.has(\"\$L\"))", field.name)
deserialize.addStatement("JsonElement je = jsonObject.get(\"\$L\")", field.name)
deserialize.beginControlFlow("if (je.isJsonPrimitive())")
deserialize.addStatement("\$L = jsonObject.get(\"\$L\").getAsString()", field.name, field.name)
deserialize.nextControlFlow("else if (je.isJsonObject())")
val cache = ClassName.get(EGF2Generator.packageFramework, "EGF2Cache")
if (field.object_types?.size == 1) {
if (!EGF2Generator.back_end_only.contains(field.object_types?.get(0)) && !EGF2Generator.excludeModels.contains(field.object_types?.get(0))) {
val clazz = ClassName.get(targetPackage + EGF2Generator.packageModels, EGF2Generator.getName(field.object_types?.get(0) as String))
deserialize.addStatement("final \$T \$L = context.deserialize(jsonObject.get(\"\$L\"), \$T.class)", clazz, field.name + "Object", field.name, clazz)
deserialize.addStatement("\$L = \$LObject.id", field.name, field.name)
deserialize.addStatement("\$L.INSTANCE.addObject(\$L, \$LObject, null)", cache, field.name, field.name)
}
} else {
val jsonObject = ClassName.get("com.google.gson", "JsonObject")
deserialize.addStatement("final \$T \$LJO = jsonObject.get(\"\$L\").getAsJsonObject()", jsonObject, field.name, field.name)
deserialize.addStatement("final \$T ot = \$LJO.get(\"object_type\").getAsString()", String::class.java, field.name)
deserialize.beginControlFlow("switch (ot)")
field.object_types?.forEach {
if (!EGF2Generator.back_end_only.contains(it) && !EGF2Generator.excludeModels.contains(it)) {
deserialize.beginControlFlow("case \"\$L\":", it)
val clazz = ClassName.get(targetPackage + EGF2Generator.packageModels, EGF2Generator.getName(it))
deserialize.addStatement("final \$T \$L = context.deserialize(jsonObject.get(\"\$L\"), \$T.class)", clazz, field.name + "Object", field.name, clazz)
deserialize.addStatement("\$L = \$LObject.id", field.name, field.name)
deserialize.addStatement("\$L.INSTANCE.addObject(\$L, \$LObject, null)", cache, field.name, field.name)
deserialize.addStatement("break")
deserialize.endControlFlow()
}
}
deserialize.endControlFlow()
}
deserialize.endControlFlow()
deserialize.endControlFlow()
deserialize.addStatement("\$L.\$L = \$L", supername, field.name, field.name)
deserialize.addCode("\n")
}
} | mit | dc5fb5a482eb1a5aee38fbc9e30ebc56 | 54.507937 | 153 | 0.728261 | 3.660733 | false | false | false | false |
zdary/intellij-community | plugins/filePrediction/test/com/intellij/filePrediction/candidates/FilePredictionCandidateProviderTest.kt | 12 | 17527 | package com.intellij.filePrediction.candidates
import com.intellij.filePrediction.FilePredictionTestDataHelper
import com.intellij.filePrediction.FilePredictionTestProjectBuilder
import com.intellij.filePrediction.predictor.model.unregisterCandidateProvider
import com.intellij.filePrediction.references.ExternalReferencesResult
import com.intellij.filePrediction.references.FilePredictionReferencesHelper
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.builders.ModuleFixtureBuilder
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase
import com.intellij.testFramework.fixtures.ModuleFixture
import com.intellij.util.containers.ContainerUtil
import java.util.concurrent.Callable
import java.util.concurrent.TimeUnit
class FilePredictionCandidateProviderTest : CodeInsightFixtureTestCase<ModuleFixtureBuilder<ModuleFixture>>() {
override fun isCommunity(): Boolean = true
override fun getBasePath(): String {
return "${FilePredictionTestDataHelper.defaultTestData}/candidates"
}
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val testName = super.getTestName(lowercaseFirstLetter)
return testName.replace("_", "/")
}
private fun doTestRecent(builder: FilePredictionTestProjectBuilder, vararg expected: Pair<String, String>) {
doTestInternal(builder.openMain(), FilePredictionRecentFilesProvider(), 5, *expected)
}
private fun doTestRefs(builder: FilePredictionTestProjectBuilder, vararg expected: String) {
val expectedWithSource = expected.map { it to "reference" }.toTypedArray()
doTestInternal(builder, FilePredictionReferenceProvider(), 5, *expectedWithSource)
}
private fun doTestNeighbor(builder: FilePredictionTestProjectBuilder, vararg expected: String) {
val expectedWithSource = expected.map { it to "neighbor" }.toTypedArray()
doTestInternal(builder, FilePredictionNeighborFilesProvider(), 10, *expectedWithSource)
}
private fun doTest(builder: FilePredictionTestProjectBuilder, vararg expected: Pair<String, String>) {
unregisterCandidateProvider(FilePredictionRecentSessionsProvider())
doTestInternal(builder, CompositeCandidateProvider(), 10, *expected)
}
private fun doTestInternal(builder: FilePredictionTestProjectBuilder,
provider: FilePredictionCandidateProvider,
limit: Int,
vararg expected: Pair<String, String>) {
val root = builder.create(myFixture)
assertNotNull("Cannot create test project", root)
val file = FilePredictionTestDataHelper.findMainTestFile(root)
assertNotNull("Cannot find file with '${FilePredictionTestDataHelper.DEFAULT_MAIN_FILE}' name", file)
val result: ExternalReferencesResult = ApplicationManager.getApplication().executeOnPooledThread(Callable {
FilePredictionReferencesHelper.calculateExternalReferences(myFixture.project, file!!).value
}).get(1, TimeUnit.SECONDS)
val candidates = provider.provideCandidates(myFixture.project, file, result.references, limit)
val actual = candidates.map {
FileUtil.getRelativePath(root.path, it.file.path, '/') to StringUtil.toLowerCase(it.source.name)
}.toSet()
assertEquals(ContainerUtil.newHashSet(*expected), actual)
}
fun testReference_single() {
val builder =
FilePredictionTestProjectBuilder().addFile(
"com/test/MainTest.java", "import com.test.ui.Baz;"
).addFile("com/test/ui/Baz.java")
doTestRefs(builder, "com/test/ui/Baz.java")
}
fun testReference_multiple() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.ui.Baz;
import com.test.component.Foo;
import com.test.Helper;
""".trimIndent()).addFiles(
"com/test/Helper.java",
"com/test/ui/Baz.java",
"com/test/component/Foo.java"
)
doTestRefs(
builder,
"com/test/Helper.java",
"com/test/ui/Baz.java",
"com/test/component/Foo.java"
)
}
fun testReference_moreThanLimit() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.component.Foo1;
import com.test.component.Foo2;
import com.test.component.Foo3;
import com.test.component.Foo4;
import com.test.component.Foo5;
import com.test.component.Foo6;
import com.test.component.Foo7;
import com.test.component.Foo8;
import com.test.component.Foo9;
import com.test.component.Foo10;
""".trimIndent()).addFiles(
"com/test/component/Foo1.java",
"com/test/component/Foo2.java",
"com/test/component/Foo3.java",
"com/test/component/Foo4.java",
"com/test/component/Foo5.java",
"com/test/component/Foo6.java",
"com/test/component/Foo7.java",
"com/test/component/Foo8.java",
"com/test/component/Foo9.java",
"com/test/component/Foo10.java"
)
doTestRefs(
builder,
"com/test/component/Foo1.java",
"com/test/component/Foo2.java",
"com/test/component/Foo3.java",
"com/test/component/Foo4.java",
"com/test/component/Foo5.java"
)
}
fun testReference_anotherPackage() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import org.another.component.Foo1;
import org.another.component.Foo2;
import org.another.component.Foo3;
import org.another.component.Foo4;
import org.another.component.Foo5;
import org.another.component.Foo6;
import org.another.component.Foo7;
import org.another.component.Foo8;
import org.another.component.Foo9;
import org.another.component.Foo10;
""".trimIndent()).addFiles(
"org/another/component/Foo1.java",
"org/another/component/Foo2.java",
"org/another/component/Foo3.java",
"org/another/component/Foo4.java",
"org/another/component/Foo5.java",
"org/another/component/Foo6.java",
"org/another/component/Foo7.java",
"org/another/component/Foo8.java",
"org/another/component/Foo9.java",
"org/another/component/Foo10.java"
)
doTestRefs(
builder,
"org/another/component/Foo1.java",
"org/another/component/Foo2.java",
"org/another/component/Foo3.java",
"org/another/component/Foo4.java",
"org/another/component/Foo5.java"
)
}
fun testNeighbor_single() {
val builder =
FilePredictionTestProjectBuilder().addFiles(
"com/test/MainTest.txt",
"com/test/Foo.txt"
)
doTestNeighbor(builder, "com/test/Foo.txt")
}
fun testNeighbor_multiple() {
val builder =
FilePredictionTestProjectBuilder().addFiles(
"com/test/MainTest.txt",
"com/test/Foo.txt",
"com/Bar.csv"
)
doTestNeighbor(
builder,
"com/test/Foo.txt",
"com/Bar.csv"
)
}
fun testNeighbor_sameDir() {
val builder =
FilePredictionTestProjectBuilder().addFiles(
"com/test/MainTest.txt",
"com/test/Foo1.txt",
"com/test/Foo2.txt",
"com/test/Foo3.txt",
"com/test/Foo4.txt"
)
doTestNeighbor(
builder,
"com/test/Foo1.txt",
"com/test/Foo2.txt",
"com/test/Foo3.txt",
"com/test/Foo4.txt"
)
}
fun testNeighbor_parentDir() {
val builder =
FilePredictionTestProjectBuilder().addFiles(
"com/test/MainTest.txt",
"com/Foo1.txt",
"com/Foo2.txt",
"com/Foo3.txt"
)
doTestNeighbor(
builder,
"com/Foo1.txt",
"com/Foo2.txt",
"com/Foo3.txt"
)
}
fun testNeighbor_moreThanLimit() {
val builder =
FilePredictionTestProjectBuilder().addFiles(
"com/test/MainTest.txt",
"com/test/Foo1.txt",
"com/test/Foo2.txt",
"com/test/Foo3.txt",
"com/test/Foo4.txt",
"com/test/Foo5.txt",
"com/test/Foo6.txt",
"com/test/Foo7.txt",
"com/test/Foo8.txt",
"com/test/Foo9.txt",
"com/test/Foo10.txt",
"com/test/Foo11.txt",
"com/test/Foo12.txt"
)
doTestNeighbor(
builder,
"com/test/Foo1.txt",
"com/test/Foo2.txt",
"com/test/Foo3.txt",
"com/test/Foo4.txt",
"com/test/Foo5.txt",
"com/test/Foo6.txt",
"com/test/Foo7.txt",
"com/test/Foo8.txt",
"com/test/Foo9.txt",
"com/test/Foo10.txt"
)
}
fun testRecent_single() {
val builder = FilePredictionTestProjectBuilder("com")
.open("com/test/ui/Baz.java")
doTestRecent(builder, "com/test/ui/Baz.java" to "open")
}
fun testRecent_multiple() {
val builder = FilePredictionTestProjectBuilder("com")
.open("com/test/ui/Baz.java")
.open("com/test/component/Bar.java")
.open("com/test/Foo.java")
doTestRecent(
builder,
"com/test/ui/Baz.java" to "open",
"com/test/component/Bar.java" to "open",
"com/test/Foo.java" to "open"
)
}
fun testRecent_notOpened() {
val builder = FilePredictionTestProjectBuilder("com")
.open("com/test/ui/Baz.java")
.open("com/test/component/Bar.java")
.close("com/test/component/Bar.java")
.open("com/test/Foo.java")
.close("com/test/ui/Baz.java")
.close("com/test/Foo.java")
doTestRecent(
builder,
"com/test/ui/Baz.java" to "recent",
"com/test/component/Bar.java" to "recent",
"com/test/Foo.java" to "recent"
)
}
fun testRecent_opened() {
val builder = FilePredictionTestProjectBuilder("com")
.open("com/test/Foo1.java")
.open("com/test/Foo2.java")
.open("com/test/Foo3.java").close("com/test/Foo3.java")
.open("com/test/Foo4.java").close("com/test/Foo4.java")
.open("com/test/Foo5.java").close("com/test/Foo5.java")
.open("com/test/Foo6.java").close("com/test/Foo6.java")
.open("com/test/Foo7.java").close("com/test/Foo7.java")
.open("com/test/Foo8.java").close("com/test/Foo8.java")
.open("com/test/Foo9.java").close("com/test/Foo9.java")
.open("com/test/Foo10.java").close("com/test/Foo10.java")
.open("com/test/Foo11.java").close("com/test/Foo11.java")
.open("com/test/Foo12.java").close("com/test/Foo12.java")
.open("com/test/Foo13.java").close("com/test/Foo13.java")
.open("com/test/Foo14.java").close("com/test/Foo14.java")
.open("com/test/Foo15.java").close("com/test/Foo15.java")
doTestRecent(
builder,
"com/test/Foo1.java" to "open",
"com/test/Foo2.java" to "open",
"com/test/Foo13.java" to "recent",
"com/test/Foo14.java" to "recent",
"com/test/Foo15.java" to "recent"
)
}
fun testComposite_sameDir() {
val builder =
FilePredictionTestProjectBuilder().addFile(
"com/test/MainTest.java", "import com.test.Helper;"
).addFiles(
"com/test/Helper.java",
"com/test/Foo.txt"
)
doTest(
builder,
"com/test/Helper.java" to "reference",
"com/test/Foo.txt" to "neighbor"
)
}
fun testComposite_childDirs() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.ui.Baz;
import com.test.component.Foo;
import com.test.Helper;
""".trimIndent()
).addFiles(
"com/test/Helper.java",
"com/test/Foo.txt",
"com/test/ui/Baz.java",
"com/test/component/Foo.java"
)
doTest(
builder,
"com/test/Helper.java" to "reference",
"com/test/ui/Baz.java" to "reference",
"com/test/component/Foo.java" to "reference",
"com/test/Foo.txt" to "neighbor"
)
}
fun testComposite_childAndParentsDirs() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.ui.Baz;
import com.test.component.Foo;
import com.test.Helper;
""".trimIndent()
).addFiles(
"com/Bar.txt",
"com/test/Foo.txt",
"com/test/Helper.java",
"com/test/ui/Baz.java",
"com/test/component/Foo.java"
)
doTest(
builder,
"com/test/Helper.java" to "reference",
"com/test/ui/Baz.java" to "reference",
"com/test/component/Foo.java" to "reference",
"com/test/Foo.txt" to "neighbor",
"com/Bar.txt" to "neighbor"
)
}
fun testComposite_anotherPackage() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.ui.Baz;
import com.test.component.Foo;
import com.test.Helper;
""".trimIndent()
).addFiles(
"org/NotIncludedFile.txt",
"com/Bar.txt",
"com/test/Foo.txt",
"com/test/Helper.java",
"com/test/ui/Baz.java",
"com/test/component/Foo.java"
)
doTest(
builder,
"com/test/Helper.java" to "reference",
"com/test/ui/Baz.java" to "reference",
"com/test/component/Foo.java" to "reference",
"com/test/Foo.txt" to "neighbor",
"com/Bar.txt" to "neighbor"
)
}
fun testComposite_moreThanLimitRef() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.component.Foo1;
import com.test.component.Foo2;
import com.test.component.Foo3;
import com.test.component.Foo4;
import com.test.component.Foo5;
import com.test.component.Foo6;
import com.test.component.Foo7;
import com.test.component.Foo8;
import com.test.component.Foo9;
import com.test.component.Foo10;
""".trimIndent()
).addFiles(
"com/test/Neighbor.txt",
"com/test/component/Foo1.java",
"com/test/component/Foo2.java",
"com/test/component/Foo3.java",
"com/test/component/Foo4.java",
"com/test/component/Foo5.java",
"com/test/component/Foo6.java",
"com/test/component/Foo7.java",
"com/test/component/Foo8.java",
"com/test/component/Foo9.java",
"com/test/component/Foo10.java"
)
doTest(
builder,
"com/test/component/Foo1.java" to "reference",
"com/test/component/Foo2.java" to "reference",
"com/test/component/Foo3.java" to "reference",
"com/test/Neighbor.txt" to "neighbor"
)
}
fun testComposite_moreThanLimitNeighbor() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.ui.Baz;
""".trimIndent()
).addFiles(
"com/test/ui/Baz.java",
"com/test/Foo1.txt",
"com/test/Foo2.txt",
"com/test/Foo3.txt",
"com/test/Foo4.txt",
"com/test/Foo5.txt",
"com/test/Foo6.txt",
"com/test/Foo7.txt",
"com/test/Foo8.txt",
"com/test/Foo9.txt",
"com/test/Foo10.txt",
"com/test/Foo11.txt",
"com/test/Foo12.txt"
)
doTest(
builder,
"com/test/ui/Baz.java" to "reference",
"com/test/Foo1.txt" to "neighbor",
"com/test/Foo2.txt" to "neighbor",
"com/test/Foo3.txt" to "neighbor",
"com/test/Foo4.txt" to "neighbor"
)
}
fun testComposite_moreThanLimit() {
val builder =
FilePredictionTestProjectBuilder().addFile("com/test/MainTest.java", """
import com.test.ui.Baz1;
import com.test.ui.Baz2;
import com.test.ui.Baz3;
import com.test.ui.Baz4;
import com.test.ui.Baz5;
import com.test.ui.Baz6;
import com.test.ui.Baz7;
import com.test.ui.Baz8;
import com.test.ui.Baz9;
import com.test.ui.Baz10;
""".trimIndent()
).addFiles(
"com/test/ui/Baz1.java",
"com/test/ui/Baz2.java",
"com/test/ui/Baz3.java",
"com/test/ui/Baz4.java",
"com/test/ui/Baz5.java",
"com/test/ui/Baz6.java",
"com/test/ui/Baz7.java",
"com/test/ui/Baz8.java",
"com/test/ui/Baz9.java",
"com/test/ui/Baz10.java",
"com/test/Foo1.txt",
"com/test/Foo2.txt",
"com/test/Foo3.txt",
"com/test/Foo4.txt",
"com/test/Foo5.txt",
"com/test/Foo6.txt",
"com/test/Foo7.txt",
"com/test/Foo8.txt",
"com/test/Foo9.txt",
"com/test/Foo10.txt",
"com/test/Foo11.txt",
"com/test/Foo12.txt"
)
doTest(
builder,
"com/test/ui/Baz1.java" to "reference",
"com/test/ui/Baz2.java" to "reference",
"com/test/ui/Baz3.java" to "reference",
"com/test/Foo1.txt" to "neighbor",
"com/test/Foo2.txt" to "neighbor",
"com/test/Foo3.txt" to "neighbor"
)
}
fun testComposite_differentSources() {
val builder =
FilePredictionTestProjectBuilder().addFile(
"com/test/MainTest.java", "import com.test.Helper;"
).addFiles(
"com/test/Helper.java",
"com/test/Foo.txt"
).open("com/test/Foo.txt"
).open("com/test/ui/Component.java").openMain()
doTest(
builder,
"com/test/Helper.java" to "neighbor",
"com/test/Foo.txt" to "neighbor",
"com/test/ui/Component.java" to "open"
)
}
} | apache-2.0 | a1966fd936013853ded890f881e23fd4 | 31.519481 | 111 | 0.628744 | 3.502598 | false | true | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/modules/ModulesViewModel.kt | 1 | 3736 | package org.mtransit.android.ui.modules
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import org.mtransit.android.data.AgencyProperties
import org.mtransit.android.data.DataSourceType
import org.mtransit.android.datasource.DataSourcesRepository
import org.mtransit.android.ui.view.common.PairMediatorLiveData
import javax.inject.Inject
@HiltViewModel
class ModulesViewModel @Inject constructor(
private val dataSourcesRepository: DataSourcesRepository,
) : ViewModel() {
companion object {
private const val FAKE_AGENCIES_COUNT = 0
// private const val FAKE_AGENCIES_COUNT = 10 // DEBUG
private const val ADD_FAKE_AGENCIES = FAKE_AGENCIES_COUNT > 0
}
private val _filteredAgencies = dataSourcesRepository.readingAllAgencies().map { agencies ->
agencies.filter { agency ->
agency.type != DataSourceType.TYPE_PLACE
&& agency.type != DataSourceType.TYPE_MODULE
}
}
private val sortByPkgOrMaxValid = MutableLiveData(true)
val agencies: LiveData<List<AgencyProperties>?> =
PairMediatorLiveData(_filteredAgencies, sortByPkgOrMaxValid).map { (newFilteredAgencies, newSortByPkgOrMaxValid) ->
if (ADD_FAKE_AGENCIES) { // DEBUG
return@map newFilteredAgencies
?.toMutableList()
?.apply {
(0..FAKE_AGENCIES_COUNT).forEach { idx ->
add(
AgencyProperties(
"fake$idx",
DataSourceType.TYPE_MODULE,
"$idx",
"$idx name",
"FFFFFF",
org.mtransit.android.commons.LocationUtils.THE_WORLD,
org.mtransit.android.commons.Constants.MAIN_APP_PACKAGE_NAME,
idx.toLong(),
idx,
isInstalled = true,
isEnabled = true,
isRTS = false,
logo = null,
maxValidSec = 0, // unlimited
trigger = 0
)
)
}
}?.sortedWith(
if (newSortByPkgOrMaxValid != false) {
compareBy { it.pkg }
} else {
compareBy { it.maxValidSecSorted }
}
)
} // DEBUG
newFilteredAgencies?.sortedWith(
if (newSortByPkgOrMaxValid != false) {
compareBy { it.pkg }
} else {
compareBy { it.maxValidSecSorted }
}
)
}
fun flipSort() {
this.sortByPkgOrMaxValid.postValue(this.sortByPkgOrMaxValid.value == false)
}
fun refreshAvailableVersions() {
viewModelScope.launch {
dataSourcesRepository.refreshAvailableVersions() // time check skipped
}
}
fun forceRefreshAvailableVersions() {
viewModelScope.launch {
dataSourcesRepository.refreshAvailableVersions(forceAppUpdateRefresh = true) // time check skipped
}
}
} | apache-2.0 | 0c062ba67804ae0a1abc29b5c5c16e96 | 37.927083 | 123 | 0.522216 | 5.695122 | false | false | false | false |
benoitletondor/EasyBudget | Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/db/impl/RoomDB.kt | 1 | 4187 | /*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.db.impl
import android.content.Context
import androidx.room.*
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.benoitletondor.easybudgetapp.db.impl.entity.ExpenseEntity
import com.benoitletondor.easybudgetapp.db.impl.entity.RecurringExpenseEntity
import com.benoitletondor.easybudgetapp.helper.localDateFromTimestamp
import com.benoitletondor.easybudgetapp.model.RecurringExpenseType
import java.time.LocalDate
const val DB_NAME = "easybudget.db"
@Database(exportSchema = false,
version = 6,
entities = [
ExpenseEntity::class,
RecurringExpenseEntity::class
])
@TypeConverters(TimestampConverters::class)
abstract class RoomDB : RoomDatabase() {
abstract fun expenseDao(): ExpenseDao
companion object {
fun create(context: Context): RoomDB = Room
.databaseBuilder(context, RoomDB::class.java, DB_NAME)
.addMigrations(migrationFrom1To2, migrationFrom2To3, migrationToRoom, addCheckedField, migrateTimestamps)
.build()
}
}
private class TimestampConverters {
@TypeConverter
fun dateFromTimestamp(value: Long?): LocalDate? {
return value?.let { LocalDate.ofEpochDay(it) }
}
@TypeConverter
fun dateToTimestamp(date: LocalDate?): Long? {
return date?.toEpochDay()
}
}
private val migrateTimestamps = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
val cursor = database.query("SELECT _expense_id,date FROM expense")
while(cursor.moveToNext()) {
val id = cursor.getLong(cursor.getColumnIndexOrThrow("_expense_id"))
val timestamp = cursor.getLong(cursor.getColumnIndexOrThrow("date"))
val localDate = localDateFromTimestamp(timestamp)
val newTimestamp = localDate.toEpochDay()
database.execSQL("UPDATE expense SET date = $newTimestamp WHERE _expense_id = $id")
}
val cursorRecurring = database.query("SELECT _expense_id,recurringDate FROM monthlyexpense")
while(cursorRecurring.moveToNext()) {
val id = cursorRecurring.getLong(cursorRecurring.getColumnIndexOrThrow("_expense_id"))
val timestamp = cursorRecurring.getLong(cursorRecurring.getColumnIndexOrThrow("recurringDate"))
val localDate = localDateFromTimestamp(timestamp)
val newTimestamp = localDate.toEpochDay()
database.execSQL("UPDATE monthlyexpense SET recurringDate = $newTimestamp WHERE _expense_id = $id")
}
}
}
private val addCheckedField = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE expense ADD COLUMN checked INTEGER NOT NULL DEFAULT 0")
}
}
private val migrationToRoom = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
// No-op, simple migration from SQLite to Room
}
}
private val migrationFrom2To3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE monthlyexpense ADD COLUMN type text not null DEFAULT '"+ RecurringExpenseType.MONTHLY+"'")
}
}
private val migrationFrom1To2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("UPDATE expense SET amount = amount * 100")
database.execSQL("UPDATE monthlyexpense SET amount = amount * 100")
}
}
| apache-2.0 | cac1a3aa7c8e41290cb97986335fa6e7 | 36.720721 | 128 | 0.7091 | 4.616318 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/BlackListPanel.kt | 1 | 5734 | // 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 com.intellij.codeInsight.hints
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.hints.settings.Diff
import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings
import com.intellij.lang.Language
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.colors.CodeInsightColors.ERRORS_ATTRIBUTES
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.fileTypes.FileTypes
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.EditorTextField
import com.intellij.ui.layout.*
import java.awt.Component
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JPanel
class BlackListDialog(val language: Language, private val patternToAdd: String? = null) : DialogWrapper(null) {
lateinit var myEditor: EditorTextField
private var myPatternsAreValid = true
init {
title = "Parameter Name Hints Blacklist"
init()
}
override fun createCenterPanel(): JComponent? {
return createBlacklistPanel(language)
}
private fun createBlacklistPanel(language: Language): JPanel? {
val provider = InlayParameterHintsExtension.forLanguage(language)
if (!provider.isBlackListSupported) return null
val blackList = getLanguageBlackList(language)
val finalText = if (patternToAdd != null) {
blackList + "\n" + patternToAdd
}
else {
blackList
}
val editorTextField = createBlacklistEditorField(finalText)
editorTextField.alignmentX = Component.LEFT_ALIGNMENT
editorTextField.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
updateOkEnabled(editorTextField)
}
})
updateOkEnabled(editorTextField)
myEditor = editorTextField
return panel {
row {
row {
right {
link("Reset") {
setLanguageBlacklistToDefault(language)
}
}
}
row {
editorTextField(grow)
}
row {
baseLanguageComment(provider)?.also {
commentRow(it)
}
commentRow(getBlacklistExplanationHTML(language))
}
}
}
}
private fun baseLanguageComment(provider: InlayParameterHintsProvider): String? {
return provider.blackListDependencyLanguage
?.let { CodeInsightBundle.message("inlay.hints.base.blacklist.description", it.displayName) }
}
private fun setLanguageBlacklistToDefault(language: Language) {
val provider = InlayParameterHintsExtension.forLanguage(language)
val defaultBlacklist = provider!!.defaultBlackList
myEditor.text = StringUtil.join(defaultBlacklist, "\n")
}
private fun updateOkEnabled(editorTextField: EditorTextField) {
val text = editorTextField.text
val invalidLines = getBlackListInvalidLineNumbers(text)
myPatternsAreValid = invalidLines.isEmpty()
okAction.isEnabled = myPatternsAreValid
val editor = editorTextField.editor
if (editor != null) {
highlightErrorLines(invalidLines, editor)
}
}
override fun doOKAction() {
super.doOKAction()
val blacklist = myEditor.text
storeBlackListDiff(language, blacklist)
}
private fun storeBlackListDiff(language: Language, text: String) {
val updatedBlackList = text.split("\n").filter { e -> e.trim { it <= ' ' }.isNotEmpty() }.toSet()
val provider = InlayParameterHintsExtension.forLanguage(language)
val defaultBlackList = provider.defaultBlackList
val diff = Diff.build(defaultBlackList, updatedBlackList)
ParameterNameHintsSettings.getInstance().setBlackListDiff(getLanguageForSettingKey(language), diff)
ParameterHintsPassFactory.forceHintsUpdateOnNextPass()
}
}
private fun getLanguageBlackList(language: Language): String {
val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return ""
val diff = ParameterNameHintsSettings.getInstance().getBlackListDiff(getLanguageForSettingKey(language))
val blackList = diff.applyOn(hintsProvider.defaultBlackList)
return StringUtil.join(blackList, "\n")
}
private fun createBlacklistEditorField(text: String): EditorTextField {
val document = EditorFactory.getInstance().createDocument(text)
val field = EditorTextField(document, null, FileTypes.PLAIN_TEXT, false, false)
field.preferredSize = Dimension(400, 350)
field.addSettingsProvider { editor ->
editor.setVerticalScrollbarVisible(true)
editor.setHorizontalScrollbarVisible(true)
editor.settings.additionalLinesCount = 2
highlightErrorLines(getBlackListInvalidLineNumbers(text), editor)
}
return field
}
private fun highlightErrorLines(lines: List<Int>, editor: Editor) {
val attributes = editor.colorsScheme.getAttributes(ERRORS_ATTRIBUTES)
val document = editor.document
val totalLines = document.lineCount
val model = editor.markupModel
model.removeAllHighlighters()
lines.stream()
.filter { current -> current < totalLines }
.forEach { line -> model.addLineHighlighter(line!!, HighlighterLayer.ERROR, attributes) }
}
private fun getBlacklistExplanationHTML(language: Language): String {
val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return CodeInsightBundle.message(
"inlay.hints.blacklist.pattern.explanation")
return hintsProvider.blacklistExplanationHTML
} | apache-2.0 | 0c487b3301f86b9e08665135596b257d | 34.184049 | 140 | 0.753401 | 4.742763 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/RootModelBridgeImpl.kt | 2 | 7114 | // 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.ide.impl.legacyBridge.module.roots
import com.intellij.configurationStore.deserializeAndLoadState
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.ModuleOrderEnumerator
import com.intellij.openapi.roots.impl.RootModelBase
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.CompilerModuleExtensionBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge.Companion.findModuleEntity
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageOnStorage
import org.jdom.Element
import org.jetbrains.annotations.NotNull
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
internal class RootModelBridgeImpl(internal val moduleEntity: ModuleEntity?,
val storage: WorkspaceEntityStorage,
private val itemUpdater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?,
private val rootModel: ModuleRootModelBridge,
internal val updater: (((WorkspaceEntityStorageDiffBuilder) -> Unit) -> Unit)?) : RootModelBase(), Disposable {
private val module: ModuleBridge = rootModel.moduleBridge
private val extensions by lazy {
loadExtensions(storage = storage, module = module, writable = false, parentDisposable = this)
}
private val orderEntriesArray: Array<OrderEntry> by lazy {
val moduleEntity = moduleEntity ?: return@lazy emptyArray<OrderEntry>()
moduleEntity.dependencies.mapIndexed { index, e ->
toOrderEntry(e, index, rootModel, itemUpdater)
}.toTypedArray()
}
val contentEntities: List<ContentRootEntity> by lazy {
val moduleEntity = moduleEntity ?: return@lazy emptyList<ContentRootEntity>()
return@lazy moduleEntity.contentRoots.toList()
}
private val contentEntriesList by lazy {
val moduleEntity = moduleEntity ?: return@lazy emptyList<ContentEntryBridge>()
val contentEntries = moduleEntity.contentRoots.toMutableList()
contentEntries.sortBy { it.url.url }
contentEntries.map { contentRoot ->
ContentEntryBridge(rootModel, contentRoot.sourceRoots.toList(), contentRoot, updater)
}
}
private var disposedStackTrace: Throwable? = null
private val isDisposed = AtomicBoolean(false)
override fun dispose() {
val alreadyDisposed = isDisposed.getAndSet(true)
if (alreadyDisposed) {
val trace = disposedStackTrace
if (trace != null) {
throw IllegalStateException("${javaClass.name} was already disposed", trace)
}
else throw IllegalStateException("${javaClass.name} was already disposed")
} else if (Disposer.isDebugMode()) {
disposedStackTrace = Throwable()
}
}
override fun getModule(): ModuleBridge = module
// TODO Deduplicate this code with other two root model implementations
private val compilerModuleExtension by lazy {
CompilerModuleExtensionBridge(module, entityStorage = VersionedEntityStorageOnStorage(storage), diff = null)
}
private val compilerModuleExtensionClass = CompilerModuleExtension::class.java
override fun <T : Any?> getModuleExtension(klass: Class<T>): T? {
if (compilerModuleExtensionClass.isAssignableFrom(klass)) {
@Suppress("UNCHECKED_CAST")
return compilerModuleExtension as T
}
return extensions.filterIsInstance(klass).firstOrNull()
}
override fun getOrderEntries() = orderEntriesArray
override fun getContent() = contentEntriesList
override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null)
companion object {
internal fun toOrderEntry(
item: ModuleDependencyItem,
index: Int,
rootModelBridge: ModuleRootModelBridge,
updater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?
): OrderEntryBridge {
return when (item) {
is ModuleDependencyItem.Exportable.ModuleDependency -> ModuleOrderEntryBridge(rootModelBridge, index, item, updater)
is ModuleDependencyItem.Exportable.LibraryDependency -> {
LibraryOrderEntryBridge(rootModelBridge, index, item, updater)
}
is ModuleDependencyItem.SdkDependency -> SdkOrderEntryBridge(rootModelBridge, index, item)
is ModuleDependencyItem.InheritedSdkDependency -> InheritedSdkOrderEntryBridge(rootModelBridge, index, item)
is ModuleDependencyItem.ModuleSourceDependency -> ModuleSourceOrderEntryBridge(rootModelBridge, index, item)
}
}
internal fun loadExtensions(storage: WorkspaceEntityStorage,
module: ModuleBridge,
writable: Boolean,
parentDisposable: Disposable): Set<ModuleExtension> {
val result = TreeSet<ModuleExtension> { o1, o2 ->
Comparing.compare(o1.javaClass.name, o2.javaClass.name)
}
val moduleEntity = storage.findModuleEntity(module)
val rootManagerElement = moduleEntity?.customImlData?.rootManagerTagCustomData?.let { JDOMUtil.load(it) }
for (extension in ModuleRootManagerEx.MODULE_EXTENSION_NAME.getExtensions(module)) {
val readOnlyExtension = loadExtension(extension, parentDisposable, rootManagerElement)
if (writable) {
val modifiableExtension = readOnlyExtension.getModifiableModel(true).also {
Disposer.register(parentDisposable, it)
}
result.add(modifiableExtension)
} else {
result.add(readOnlyExtension)
}
}
return result
}
private fun loadExtension(extension: ModuleExtension,
parentDisposable: Disposable,
rootManagerElement: @NotNull Element?): @NotNull ModuleExtension {
val readOnlyExtension = extension.getModifiableModel(false).also {
Disposer.register(parentDisposable, it)
}
if (rootManagerElement != null) {
if (readOnlyExtension is PersistentStateComponent<*>) {
deserializeAndLoadState(readOnlyExtension, rootManagerElement)
}
else {
@Suppress("DEPRECATION")
readOnlyExtension.readExternal(rootManagerElement)
}
}
return readOnlyExtension
}
}
}
| apache-2.0 | 5e1d30bd0296471ce3f4410d795b8dd4 | 42.115152 | 146 | 0.727579 | 5.549142 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/sql/Dialect.kt | 1 | 1008 | package slatekit.data.sql
import slatekit.data.core.Table
import slatekit.data.syntax.Types
import slatekit.query.Op
/**
* Contains syntax builders to build Sql and/or Prepared Sql/statements
*/
open class Dialect(val types: Types = Types(),
val aggr: Aggregates = Aggregates(),
val encodeChar:Char = '`') {
/**
* Encodes the name using the encode char e.g. column1 = `column1`
*/
fun encode(name:String): String = "${encodeChar}${name}${encodeChar}"
open fun op(op: Op): String = op.text
}
interface Provider<TId, T> where TId: kotlin.Comparable<TId>, T: Any {
val dialect: Dialect
/**
* Builds insert statement sql/prepared sql
*/
val insert: Insert<TId, T>
/**
* Builds update statement sql/prepared sql
*/
val update: Update<TId, T>
fun select(table:Table): slatekit.query.Select
fun patch (table:Table): slatekit.query.Update
fun delete(table:Table): slatekit.query.Delete
}
| apache-2.0 | 77219f234f8858fdc3ca53badf0bdb6e | 22.44186 | 73 | 0.641865 | 3.906977 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ObjCInterop.kt | 1 | 7904 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.backend.konan.descriptors.getStringValue
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.ExternalOverridabilityCondition
import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
private val interopPackageName = InteropBuiltIns.FqNames.packageName
private val objCObjectFqName = interopPackageName.child(Name.identifier("ObjCObject"))
private val objCClassFqName = interopPackageName.child(Name.identifier("ObjCClass"))
private val externalObjCClassFqName = interopPackageName.child(Name.identifier("ExternalObjCClass"))
private val objCMethodFqName = interopPackageName.child(Name.identifier("ObjCMethod"))
private val objCBridgeFqName = interopPackageName.child(Name.identifier("ObjCBridge"))
fun ClassDescriptor.isObjCClass(): Boolean =
this.getAllSuperClassifiers().any { it.fqNameSafe == objCObjectFqName } &&
this.containingDeclaration.fqNameSafe != interopPackageName
fun KotlinType.isObjCObjectType(): Boolean =
TypeUtils.getClassDescriptor(this)
?.getAllSuperClassifiers()
?.any { it.fqNameSafe == objCObjectFqName }
?: false
fun ClassDescriptor.isExternalObjCClass(): Boolean = this.isObjCClass() &&
this.parentsWithSelf.filterIsInstance<ClassDescriptor>().any {
it.annotations.findAnnotation(externalObjCClassFqName) != null
}
fun ClassDescriptor.isObjCMetaClass(): Boolean = this.getAllSuperClassifiers().any {
it.fqNameSafe == objCClassFqName
}
fun FunctionDescriptor.isObjCClassMethod() =
this.containingDeclaration.let { it is ClassDescriptor && it.isObjCClass() }
fun FunctionDescriptor.isExternalObjCClassMethod() =
this.containingDeclaration.let { it is ClassDescriptor && it.isExternalObjCClass() }
// Special case: methods from Kotlin Objective-C classes can be called virtually from bridges.
fun FunctionDescriptor.canObjCClassMethodBeCalledVirtually(overriddenDescriptor: FunctionDescriptor) =
overriddenDescriptor.isOverridable && this.kind.isReal && !this.isExternalObjCClassMethod()
fun ClassDescriptor.isKotlinObjCClass(): Boolean = this.isObjCClass() && !this.isExternalObjCClass()
data class ObjCMethodInfo(val descriptor: FunctionDescriptor,
val bridge: FunctionDescriptor,
val selector: String,
val encoding: String,
val imp: String)
private fun CallableDescriptor.getBridgeAnnotation() =
this.annotations.findAnnotation(objCBridgeFqName)
private fun FunctionDescriptor.decodeObjCMethodAnnotation(): ObjCMethodInfo? {
assert (this.kind.isReal)
val methodAnnotation = this.annotations.findAnnotation(objCMethodFqName) ?: return null
val packageFragment = this.parents.filterIsInstance<PackageFragmentDescriptor>().single()
val bridgeName = methodAnnotation.getStringValue("bridge")
val bridge = packageFragment.getMemberScope()
.getContributedFunctions(Name.identifier(bridgeName), NoLookupLocation.FROM_BACKEND)
.single()
val bridgeAnnotation = bridge.getBridgeAnnotation()!!
return ObjCMethodInfo(
descriptor = this,
bridge = bridge,
selector = methodAnnotation.getStringValue("selector"),
encoding = bridgeAnnotation.getStringValue("encoding"),
imp = bridgeAnnotation.getStringValue("imp")
)
}
/**
* @param onlyExternal indicates whether to accept overriding methods from Kotlin classes
*/
private fun FunctionDescriptor.getObjCMethodInfo(onlyExternal: Boolean): ObjCMethodInfo? {
if (this.kind.isReal) {
this.decodeObjCMethodAnnotation()?.let { return it }
if (onlyExternal) {
return null
}
}
return this.overriddenDescriptors.asSequence().mapNotNull { it.getObjCMethodInfo(onlyExternal) }.firstOrNull()
}
fun FunctionDescriptor.getExternalObjCMethodInfo(): ObjCMethodInfo? = this.getObjCMethodInfo(onlyExternal = true)
fun FunctionDescriptor.getObjCMethodInfo(): ObjCMethodInfo? = this.getObjCMethodInfo(onlyExternal = false)
/**
* Describes method overriding rules for Objective-C methods.
*
* This class is applied at [org.jetbrains.kotlin.resolve.OverridingUtil] as configured with
* `META-INF/services/org.jetbrains.kotlin.resolve.ExternalOverridabilityCondition` resource.
*/
class ObjCOverridabilityCondition : ExternalOverridabilityCondition {
override fun getContract() = ExternalOverridabilityCondition.Contract.BOTH
override fun isOverridable(
superDescriptor: CallableDescriptor,
subDescriptor: CallableDescriptor,
subClassDescriptor: ClassDescriptor?
): ExternalOverridabilityCondition.Result {
assert(superDescriptor.name == subDescriptor.name)
val superClass = superDescriptor.containingDeclaration as? ClassDescriptor
val subClass = subDescriptor.containingDeclaration as? ClassDescriptor
if (superClass == null || !superClass.isObjCClass() || subClass == null) {
return ExternalOverridabilityCondition.Result.UNKNOWN
}
return if (areSelectorsEqual(superDescriptor, subDescriptor)) {
// Also check the method signatures if the subclass is user-defined:
if (subClass.isExternalObjCClass()) {
ExternalOverridabilityCondition.Result.OVERRIDABLE
} else {
ExternalOverridabilityCondition.Result.UNKNOWN
}
} else {
ExternalOverridabilityCondition.Result.INCOMPATIBLE
}
}
private fun areSelectorsEqual(first: CallableDescriptor, second: CallableDescriptor): Boolean {
// The original Objective-C method selector is represented as
// function name and parameter names (except first).
if (first.valueParameters.size != second.valueParameters.size) {
return false
}
first.valueParameters.forEachIndexed { index, parameter ->
if (index > 0 && parameter.name != second.valueParameters[index].name) {
return false
}
}
return true
}
}
fun ConstructorDescriptor.getObjCInitMethod(): FunctionDescriptor? {
return this.annotations.findAnnotation(FqName("kotlinx.cinterop.ObjCConstructor"))?.let {
val initSelector = it.getStringValue("initSelector")
this.constructedClass.unsubstitutedMemberScope.getContributedDescriptors().asSequence()
.filterIsInstance<FunctionDescriptor>()
.single { it.getExternalObjCMethodInfo()?.selector == initSelector }
}
}
fun inferObjCSelector(descriptor: FunctionDescriptor): String = if (descriptor.valueParameters.isEmpty()) {
descriptor.name.asString()
} else {
buildString {
append(descriptor.name)
append(':')
descriptor.valueParameters.drop(1).forEach {
append(it.name)
append(':')
}
}
} | apache-2.0 | 5772cbbdf19f1457fd15a72337abe976 | 39.747423 | 114 | 0.721027 | 5.112549 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/adapters/MoviesAdapter.kt | 1 | 1746 | package tech.salroid.filmy.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import tech.salroid.filmy.FilmyApplication.Companion.context
import tech.salroid.filmy.data.local.db.entity.Movie
import tech.salroid.filmy.databinding.CustomRowBinding
import tech.salroid.filmy.utility.toReadableDate
class MoviesAdapter(
private var movies: List<Movie> = emptyList(),
private val clickListener: ((Movie) -> Unit)? = null
) : RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MoviesViewHolder {
val binding = CustomRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MoviesViewHolder(binding)
}
override fun onBindViewHolder(holder: MoviesViewHolder, position: Int) {
holder.bindData(movies[position])
}
override fun getItemCount(): Int = movies.size
fun swapData(newMovies: List<Movie>) {
this.movies = newMovies
notifyDataSetChanged() //TODO improvement required
}
inner class MoviesViewHolder(private val binding: CustomRowBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.main.setOnClickListener {
clickListener?.invoke(movies[adapterPosition])
}
}
fun bindData(movie: Movie) {
binding.movieName.text = movie.title
binding.movieYear.text = movie.releaseDate?.toReadableDate()
Glide.with(context)
.load("http://image.tmdb.org/t/p/w342${movie.posterPath}")
.into(binding.poster)
}
}
} | apache-2.0 | 679b8066267d7263d310b4dc28d1bad2 | 33.254902 | 98 | 0.697022 | 4.582677 | false | false | false | false |
AndroidX/androidx | benchmark/benchmark-common/src/main/java/androidx/benchmark/ThreadPriority.kt | 3 | 5651 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark
import android.os.Build
import android.os.Process
import android.util.Log
import androidx.annotation.GuardedBy
import androidx.benchmark.BenchmarkState.Companion.TAG
import java.io.File
import java.io.IOException
internal object ThreadPriority {
/**
* Max priority for a linux process, see docs of android.os.Process
*
* For some reason, constant not provided as platform API.
*/
const val HIGH_PRIORITY = -20
private const val BENCH_THREAD_PRIORITY = HIGH_PRIORITY
/**
* Set JIT lower than bench thread, to reduce chance of it preempting during measurement
*/
private const val JIT_THREAD_PRIORITY =
HIGH_PRIORITY + Process.THREAD_PRIORITY_LESS_FAVORABLE * 5
private const val TASK_PATH = "/proc/self/task"
private const val JIT_THREAD_NAME = "Jit thread pool"
private val JIT_TID: Int?
val JIT_INITIAL_PRIORITY: Int
init {
if (Build.VERSION.SDK_INT >= 24) {
// JIT thread expected to exist on N+ devices
val tidsToNames = File(TASK_PATH).listFiles()?.associateBy(
{
// tid
it.name.toInt()
},
{
// thread name
try {
File(it, "comm").readLines().firstOrNull() ?: ""
} catch (e: IOException) {
// if we fail to read thread name, file may not exist because thread
// died. Expect no error reading Jit thread name, so just name thread
// incorrectly.
"ERROR READING THREAD NAME"
}
}
)
if (tidsToNames.isNullOrEmpty()) {
Log.d(TAG, "NOTE: Couldn't find threads in this process for priority pinning.")
JIT_TID = null
} else {
JIT_TID =
tidsToNames.filter { it.value.startsWith(JIT_THREAD_NAME) }.keys.firstOrNull()
if (JIT_TID == null) {
Log.d(TAG, "NOTE: Couldn't JIT thread, threads found:")
tidsToNames.forEach {
Log.d(TAG, " tid: ${it.key}, name:'${it.value}'")
}
}
}
} else {
JIT_TID = null
}
JIT_INITIAL_PRIORITY = if (JIT_TID != null) Process.getThreadPriority(JIT_TID) else 0
}
private val lock = Any()
@GuardedBy("lock")
private var initialTid: Int = -1
@GuardedBy("lock")
private var initialPriority: Int = Int.MAX_VALUE
/*
* [android.os.Process.getThreadPriority] is not very clear in which conditions it will fail,
* so setting JIT / benchmark thread priorities are best-effort for now
*/
private fun setThreadPriority(label: String, tid: Int, priority: Int): Boolean {
// Tries to acquire the thread priority
val previousPriority = try {
Process.getThreadPriority(tid)
} catch (e: IllegalArgumentException) {
return false
}
// Tries to set the thread priority
try {
Process.setThreadPriority(tid, priority)
} catch (e: SecurityException) {
return false
}
// Checks and returns whether the priority changed
val newPriority = Process.getThreadPriority(tid)
if (newPriority != previousPriority) {
Log.d(
TAG,
"Set $tid ($label) to priority $priority. Was $previousPriority, now $newPriority"
)
return true
}
return false
}
/**
* Bump thread priority of the current thread and JIT to be high, resetting any other bumped
* thread.
*
* Only one benchmark thread can be be bumped at a time.
*/
fun bumpCurrentThreadPriority() = synchronized(lock) {
val myTid = Process.myTid()
if (initialTid == myTid) {
// already bumped
return
}
// ensure we don't have multiple threads bumped at once
resetBumpedThread()
initialTid = myTid
initialPriority = Process.getThreadPriority(initialTid)
setThreadPriority("Bench thread", initialTid, BENCH_THREAD_PRIORITY)
if (JIT_TID != null) {
setThreadPriority("Jit", JIT_TID, JIT_THREAD_PRIORITY)
}
}
fun resetBumpedThread() = synchronized(lock) {
if (initialTid > 0) {
setThreadPriority("Bench thread", initialTid, initialPriority)
if (JIT_TID != null) {
setThreadPriority("Jit", JIT_TID, JIT_INITIAL_PRIORITY)
}
initialTid = -1
}
}
fun getJit(): Int {
checkNotNull(JIT_TID) { "Jit thread not found!" }
return Process.getThreadPriority(JIT_TID)
}
fun get(): Int {
return Process.getThreadPriority(Process.myTid())
}
} | apache-2.0 | 463bf9e362ad5fa77e951abbaa0fa040 | 32.443787 | 98 | 0.577597 | 4.557258 | false | false | false | false |
smmribeiro/intellij-community | platform/object-serializer/src/stateProperties/CollectionStoredProperty.kt | 10 | 2786 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.serialization.stateProperties
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.JsonSchemaType
import com.intellij.openapi.components.StoredProperty
import com.intellij.openapi.components.StoredPropertyBase
import com.intellij.util.SmartList
// Technically, it is not possible to proxy write operations because a collection can be mutated via iterator.
// So, even if Kotlin could create a delegate for us, to track mutations via an iterator we have to re-implement collection/map.
/**
* `AbstractCollectionBinding` modifies collection directly, so we cannot use `null` as a default value and have to return an empty list.
*/
open class CollectionStoredProperty<E : Any, C : MutableCollection<E>>(protected val value: C, private val defaultValue: String?) : StoredPropertyBase<C>() {
override val jsonType: JsonSchemaType
get() = JsonSchemaType.ARRAY
override fun isEqualToDefault() = if (defaultValue == null) value.isEmpty() else value.size == 1 && value.firstOrNull() == defaultValue
override fun getValue(thisRef: BaseState) = value
override fun setValue(thisRef: BaseState, @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") newValue: C) {
if (doSetValue(value, newValue)) {
thisRef.intIncrementModificationCount()
}
}
private fun doSetValue(old: C, new: C): Boolean {
if (old == new) {
return false
}
old.clear()
old.addAll(new)
return true
}
override fun equals(other: Any?) = this === other || (other is CollectionStoredProperty<*, *> && value == other.value && defaultValue == other.defaultValue)
override fun hashCode() = value.hashCode()
override fun toString() = "$name = ${if (isEqualToDefault()) "" else value.joinToString(" ")}"
override fun setValue(other: StoredProperty<C>): Boolean {
@Suppress("UNCHECKED_CAST")
return doSetValue(value, (other as CollectionStoredProperty<E, C>).value)
}
@Suppress("FunctionName")
fun __getValue() = value
}
internal class ListStoredProperty<T : Any> : CollectionStoredProperty<T, SmartList<T>>(SmartList(), null) {
private var modCount = 0L
private var lastItemModCount = 0L
override fun getModificationCount(): Long {
modCount = value.modificationCount.toLong()
var itemModCount = 0L
for (item in value) {
if (item is BaseState) {
itemModCount += item.modificationCount
}
else {
// or all values are BaseState or not
return modCount
}
}
if (itemModCount != lastItemModCount) {
lastItemModCount = itemModCount
modCount++
}
return modCount
}
} | apache-2.0 | 45f51891a07d44fad732ab845b910f30 | 34.730769 | 158 | 0.713927 | 4.408228 | false | false | false | false |
smmribeiro/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/SourceRootPropertiesHelper.kt | 2 | 8585 | // 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.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import org.jdom.Element
import org.jetbrains.jps.model.JpsDummyElement
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.JpsElementFactory
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.module.UnknownSourceRootType
import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension
import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer
import org.jetbrains.jps.model.serialization.module.UnknownSourceRootPropertiesSerializer
object SourceRootPropertiesHelper {
@Suppress("UNCHECKED_CAST")
fun <P : JpsElement?> findSerializer(rootType: JpsModuleSourceRootType<P>): JpsModuleSourceRootPropertiesSerializer<P>? {
val serializer = if (rootType is UnknownSourceRootType) {
UnknownSourceRootPropertiesSerializer.forType(rootType as UnknownSourceRootType)
}
else {
JpsModelSerializerExtension.getExtensions()
.flatMap { it.moduleSourceRootPropertiesSerializers }
.firstOrNull { it.type == rootType }
}
return serializer as JpsModuleSourceRootPropertiesSerializer<P>?
}
internal fun hasEqualProperties(entity: SourceRootEntity, sourceRoot: JpsModuleSourceRoot): Boolean {
val properties = sourceRoot.properties
val javaSourceEntity = entity.asJavaSourceRoot()
if (javaSourceEntity != null) {
return properties is JavaSourceRootProperties && javaSourceEntity.generated == properties.isForGeneratedSources
&& javaSourceEntity.packagePrefix == properties.packagePrefix
}
val javaResourceEntity = entity.asJavaResourceRoot()
if (javaResourceEntity != null) {
return properties is JavaResourceRootProperties && javaResourceEntity.generated == properties.isForGeneratedSources
&& javaResourceEntity.relativeOutputPath == properties.relativeOutputPath
}
val customEntity = entity.asCustomSourceRoot()
if (customEntity == null) {
return properties is JpsDummyElement
}
val serializer = findSerializer(sourceRoot.rootType as JpsModuleSourceRootType<JpsElement>)
?: return false
val propertiesXml = savePropertiesToString(serializer, properties)
return propertiesXml == customEntity.propertiesXmlTag
}
private fun <P : JpsElement?> savePropertiesToString(serializer: JpsModuleSourceRootPropertiesSerializer<P>, properties: P): String {
val sourceElement = Element(JpsModuleRootModelSerializer.SOURCE_FOLDER_TAG)
serializer.saveProperties(properties, sourceElement)
return JDOMUtil.writeElement(sourceElement)
}
internal fun applyChanges(diff: WorkspaceEntityStorageBuilder, entity: SourceRootEntity, actualSourceRootData: JpsModuleSourceRoot) {
if (hasEqualProperties(entity, actualSourceRootData)) {
return
}
val properties = actualSourceRootData.properties
val javaSourceEntity = entity.asJavaSourceRoot()
val javaResourceEntity = entity.asJavaResourceRoot()
if (javaSourceEntity != null && properties is JavaSourceRootProperties) {
diff.modifyEntity(ModifiableJavaSourceRootEntity::class.java, javaSourceEntity) {
generated = properties.isForGeneratedSources
packagePrefix = properties.packagePrefix
}
}
else if (javaResourceEntity != null && properties is JavaResourceRootProperties) {
diff.modifyEntity(ModifiableJavaResourceRootEntity::class.java, javaResourceEntity) {
generated = properties.isForGeneratedSources
relativeOutputPath = properties.relativeOutputPath
}
}
else {
val customEntity = entity.asCustomSourceRoot() ?: return
val serializer = findSerializer(actualSourceRootData.rootType as JpsModuleSourceRootType<JpsElement>)
?: return
val propertiesXml = savePropertiesToString(serializer, properties)
diff.modifyEntity(ModifiableCustomSourceRootPropertiesEntity::class.java, customEntity) {
propertiesXmlTag = propertiesXml
}
}
}
internal fun <P : JpsElement> addPropertiesEntity(diff: WorkspaceEntityStorageDiffBuilder,
sourceRootEntity: SourceRootEntity,
properties: P,
serializer: JpsModuleSourceRootPropertiesSerializer<P>) {
when (serializer.typeId) {
JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID, JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID -> diff.addJavaSourceRootEntity(
sourceRoot = sourceRootEntity,
generated = (properties as JavaSourceRootProperties).isForGeneratedSources,
packagePrefix = properties.packagePrefix
)
JpsJavaModelSerializerExtension.JAVA_RESOURCE_ROOT_ID, JpsJavaModelSerializerExtension.JAVA_TEST_RESOURCE_ROOT_ID -> diff.addJavaResourceRootEntity(
sourceRoot = sourceRootEntity,
generated = (properties as JavaResourceRootProperties).isForGeneratedSources,
relativeOutputPath = properties.relativeOutputPath
)
else -> if (properties !is JpsDummyElement) {
diff.addCustomSourceRootPropertiesEntity(
sourceRoot = sourceRootEntity,
propertiesXmlTag = savePropertiesToString(serializer, properties)
)
}
}
}
internal fun loadRootProperties(entity: SourceRootEntity,
rootType: JpsModuleSourceRootType<out JpsElement>,
url: String): JpsModuleSourceRoot {
val javaExtensionService = JpsJavaExtensionService.getInstance()
val rootProperties = when (entity.rootType) {
JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID, JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID -> {
val javaSourceRoot = entity.asJavaSourceRoot()
javaExtensionService.createSourceRootProperties(
javaSourceRoot?.packagePrefix ?: "", javaSourceRoot?.generated ?: false)
}
JpsJavaModelSerializerExtension.JAVA_RESOURCE_ROOT_ID, JpsJavaModelSerializerExtension.JAVA_TEST_RESOURCE_ROOT_ID -> {
val javaResourceRoot = entity.asJavaResourceRoot()
javaExtensionService.createResourceRootProperties(
javaResourceRoot?.relativeOutputPath ?: "", false)
}
else -> loadCustomRootProperties(entity, rootType)
}
return (@Suppress("UNCHECKED_CAST")
JpsElementFactory.getInstance().createModuleSourceRoot(url, rootType as JpsModuleSourceRootType<JpsElement>, rootProperties))
}
internal fun loadCustomRootProperties(entity: SourceRootEntity, rootType: JpsModuleSourceRootType<out JpsElement>): JpsElement {
val elementFactory = JpsElementFactory.getInstance()
val customSourceRoot = entity.asCustomSourceRoot()
if (customSourceRoot == null || customSourceRoot.propertiesXmlTag.isEmpty()) return rootType.createDefaultProperties()
val serializer = findSerializer(rootType)
if (serializer == null) {
LOG.warn("Module source root type $rootType (${entity.rootType}) is not registered as JpsModelSerializerExtension")
return elementFactory.createDummyElement()
}
return try {
val element = JDOMUtil.load(customSourceRoot.propertiesXmlTag)
element.setAttribute(JpsModuleRootModelSerializer.SOURCE_ROOT_TYPE_ATTRIBUTE, entity.rootType)
serializer.loadProperties(element)
}
catch (t: Throwable) {
LOG.error("Unable to deserialize source root '${entity.rootType}' from xml '${customSourceRoot.propertiesXmlTag}': ${t.message}", t)
elementFactory.createDummyElement()
}
}
private val LOG = logger<SourceRootPropertiesHelper>()
} | apache-2.0 | 519d7fca8af9d74a40fb4b1573d380f9 | 48.062857 | 154 | 0.752009 | 5.651745 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/intentions/GrChangeModifiersFix.kt | 4 | 2914 | // 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.plugins.groovy.annotator.intentions
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.util.parentOfType
import com.intellij.util.castSafelyTo
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
class GrChangeModifiersFix(private val modifiersToRemove: List<String>,
val modifierToInsert: String?,
@Nls private val textRepresentation: String,
val removeModifierUnderCaret : Boolean = false)
: IntentionAction {
val modifiersToRemoveSet = modifiersToRemove.toSet()
override fun startInWriteAction(): Boolean = true
override fun getText(): String {
return textRepresentation
}
override fun getFamilyName(): String = GroovyBundle.message("intention.family.name.replace.modifiers")
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
editor ?: return false
file ?: return false
return true // intended to be invoked alongside with an inspection
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
editor ?: return
file ?: return
val elementUnderCaret = file.findElementAt(editor.caretModel.offset) ?: return
val owner = elementUnderCaret.parentOfType<PsiModifierListOwner>() ?: return
val elementUnderCaretRepresentation = elementUnderCaret.text
val modifiers = owner.modifierList?.castSafelyTo<GrModifierList>()?.modifiers ?: return
var hasRequiredModifier = false
for (modifier in modifiers) {
val modifierRepresentation = if (modifier is PsiAnnotation) modifier.qualifiedName else modifier.text
if (modifierRepresentation == modifierToInsert) {
hasRequiredModifier = true
}
if (!removeModifierUnderCaret && modifierRepresentation == elementUnderCaretRepresentation) {
continue
}
if (modifierRepresentation in modifiersToRemove) {
modifier.delete()
}
}
if (!hasRequiredModifier && modifierToInsert != null) {
if (modifierToInsert in GrModifier.GROOVY_MODIFIERS || modifierToInsert in PsiModifier.MODIFIERS) {
owner.modifierList?.setModifierProperty(modifierToInsert, true)
} else {
owner.modifierList?.addAnnotation(modifierToInsert)
}
}
}
} | apache-2.0 | 3b125083fc7575cef0c8ccc4ff315b70 | 41.246377 | 158 | 0.743308 | 5.041522 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt | 1 | 3900 | package info.nightscout.androidaps.plugins.source
import android.content.Intent
import android.os.Handler
import android.os.HandlerThread
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.isRunningTest
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.PI
import kotlin.math.sin
@Singleton
class RandomBgPlugin @Inject constructor(
injector: HasAndroidInjector,
resourceHelper: ResourceHelper,
aapsLogger: AAPSLogger,
private val virtualPumpPlugin: VirtualPumpPlugin,
private val buildHelper: BuildHelper,
private val sp: SP,
private val nsUpload: NSUpload
) : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name)
.pluginIcon(R.drawable.ic_dice)
.pluginName(R.string.randombg)
.shortName(R.string.randombg_short)
.preferencesId(R.xml.pref_bgsource)
.description(R.string.description_source_randombg),
aapsLogger, resourceHelper, injector
), BgSourceInterface {
private val loopHandler : Handler = Handler(HandlerThread(RandomBgPlugin::class.java.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable
companion object {
const val interval = 5L // minutes
}
init {
refreshLoop = Runnable {
handleNewData(Intent())
loopHandler.postDelayed(refreshLoop, T.mins(interval).msecs())
}
}
override fun advancedFilteringSupported(): Boolean {
return true
}
override fun onStart() {
super.onStart()
loopHandler.postDelayed(refreshLoop, T.mins(interval).msecs())
}
override fun onStop() {
super.onStop()
loopHandler.removeCallbacks(refreshLoop)
}
override fun specialEnableCondition(): Boolean {
return isRunningTest() || virtualPumpPlugin.isEnabled(PluginType.PUMP) && buildHelper.isEngineeringMode()
}
override fun handleNewData(intent: Intent) {
if (!isEnabled(PluginType.BGSOURCE)) return
val min = 70
val max = 190
val cal = GregorianCalendar()
val currentMinute = cal.get(Calendar.MINUTE) + (cal.get(Calendar.HOUR_OF_DAY) % 2) * 60
val bgMgdl = min + ((max - min) + (max - min) * sin(currentMinute / 120.0 * 2 * PI))/2
val bgReading = BgReading()
bgReading.value = bgMgdl
bgReading.date = DateUtil.now()
bgReading.raw = bgMgdl
if (MainApp.getDbHelper().createIfNotExists(bgReading, "RandomBG")) {
if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false))
nsUpload.uploadBg(bgReading, "AndroidAPS-RandomBG")
if (sp.getBoolean(R.string.key_dexcomg5_xdripupload, false))
nsUpload.sendToXdrip(bgReading)
}
aapsLogger.debug(LTag.BGSOURCE, "Generated BG: $bgReading")
}
}
| agpl-3.0 | 296e1a1b734fde692752b2807752b0ec | 36.5 | 140 | 0.735897 | 4.362416 | false | false | false | false |
RyanSkraba/beam | examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/cookbook/CombinePerKeyExamples.kt | 11 | 7381 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.kotlin.cookbook
import com.google.api.services.bigquery.model.TableFieldSchema
import com.google.api.services.bigquery.model.TableRow
import com.google.api.services.bigquery.model.TableSchema
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO
import org.apache.beam.sdk.io.gcp.bigquery.WriteResult
import org.apache.beam.sdk.metrics.Metrics
import org.apache.beam.sdk.options.*
import org.apache.beam.sdk.transforms.*
import org.apache.beam.sdk.values.KV
import org.apache.beam.sdk.values.PCollection
/**
* An example that reads the public 'Shakespeare' data, and for each word in the dataset that is
* over a given length, generates a string containing the list of play names in which that word
* appears, and saves this information to a bigquery table.
*
*
* Note: Before running this example, you must create a BigQuery dataset to contain your output
* table.
*
*
* To execute this pipeline locally, specify the BigQuery table for the output:
*
* <pre>`--output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
`</pre> *
*
*
* To change the runner, specify:
*
* <pre>`--runner=YOUR_SELECTED_RUNNER
`</pre> *
*
* See examples/java/README.md for instructions about how to configure different runners.
*
*
* The BigQuery input table defaults to `publicdata:samples.shakespeare` and can be
* overridden with `--input`.
*/
object CombinePerKeyExamples {
// Use the shakespeare public BigQuery sample
private const val SHAKESPEARE_TABLE = "publicdata:samples.shakespeare"
// We'll track words >= this word length across all plays in the table.
private const val MIN_WORD_LENGTH = 9
/**
* Examines each row in the input table. If the word is greater than or equal to MIN_WORD_LENGTH,
* outputs word, play_name.
*/
internal class ExtractLargeWordsFn : DoFn<TableRow, KV<String, String>>() {
private val smallerWords = Metrics.counter(ExtractLargeWordsFn::class.java, "smallerWords")
@ProcessElement
fun processElement(c: ProcessContext) {
val row = c.element()
val playName = row["corpus"] as String
val word = row["word"] as String
if (word.length >= MIN_WORD_LENGTH) {
c.output(KV.of(word, playName))
} else {
// Track how many smaller words we're not including. This information will be
// visible in the Monitoring UI.
smallerWords.inc()
}
}
}
/**
* Prepares the data for writing to BigQuery by building a TableRow object containing a word with
* a string listing the plays in which it appeared.
*/
internal class FormatShakespeareOutputFn : DoFn<KV<String, String>, TableRow>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = TableRow().set("word", c.element().key).set("all_plays", c.element().value)
c.output(row)
}
}
/**
* Reads the public 'Shakespeare' data, and for each word in the dataset over a given length,
* generates a string containing the list of play names in which that word appears. It does this
* via the Combine.perKey transform, with the ConcatWords combine function.
*
*
* Combine.perKey is similar to a GroupByKey followed by a ParDo, but has more restricted
* semantics that allow it to be executed more efficiently. These records are then formatted as BQ
* table rows.
*/
internal class PlaysForWord : PTransform<PCollection<TableRow>, PCollection<TableRow>>() {
override fun expand(rows: PCollection<TableRow>): PCollection<TableRow> {
// row... => <word, play_name> ...
val words = rows.apply(ParDo.of(ExtractLargeWordsFn()))
// word, play_name => word, all_plays ...
val wordAllPlays = words.apply<PCollection<KV<String, String>>>(Combine.perKey(ConcatWords()))
// <word, all_plays>... => row...
return wordAllPlays.apply(ParDo.of(FormatShakespeareOutputFn()))
}
}
/**
* A 'combine function' used with the Combine.perKey transform. Builds a comma-separated string of
* all input items. So, it will build a string containing all the different Shakespeare plays in
* which the given input word has appeared.
*/
class ConcatWords : SerializableFunction<Iterable<String>, String> {
override fun apply(input: Iterable<String>): String {
val all = StringBuilder()
for (item in input) {
if (item.isNotEmpty()) {
if (all.isEmpty()) {
all.append(item)
} else {
all.append(",")
all.append(item)
}
}
}
return all.toString()
}
}
/**
* Options supported by [CombinePerKeyExamples].
*
*
* Inherits standard configuration options.
*/
interface Options : PipelineOptions {
@get:Description("Table to read from, specified as <project_id>:<dataset_id>.<table_id>")
@get:Default.String(SHAKESPEARE_TABLE)
var input: String
@get:Description("Table to write to, specified as <project_id>:<dataset_id>.<table_id>. The dataset_id must already exist")
@get:Validation.Required
var output: String
}
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).withValidation() as Options
val p = Pipeline.create(options)
// Build the table schema for the output table.
val fields = arrayListOf<TableFieldSchema>(
TableFieldSchema().setName("word").setType("STRING"),
TableFieldSchema().setName("all_plays").setType("STRING")
)
val schema = TableSchema().setFields(fields)
p.apply(BigQueryIO.readTableRows().from(options.input))
.apply(PlaysForWord())
.apply<WriteResult>(
BigQueryIO.writeTableRows()
.to(options.output)
.withSchema(schema)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE))
p.run().waitUntilFinish()
}
}
| apache-2.0 | bac5e27c5e72859a6b223f9435322a57 | 38.470588 | 131 | 0.644357 | 4.251728 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/tasks/RealmBaseTasksRecyclerViewAdapter.kt | 1 | 6593 | package com.habitrpg.android.habitica.ui.adapter.tasks
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.helpers.TaskFilterHelper
import com.habitrpg.android.habitica.models.responses.TaskDirection
import com.habitrpg.android.habitica.models.tasks.ChecklistItem
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.ui.viewHolders.tasks.BaseTaskViewHolder
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.functions.Action
import io.reactivex.subjects.PublishSubject
import io.realm.*
abstract class RealmBaseTasksRecyclerViewAdapter<VH : BaseTaskViewHolder>(
private var unfilteredData: OrderedRealmCollection<Task>?,
private val hasAutoUpdates: Boolean,
private val layoutResource: Int,
private val taskFilterHelper: TaskFilterHelper?
) : RealmRecyclerViewAdapter<Task, VH>(null, false), TaskRecyclerViewAdapter {
private var updateOnModification: Boolean = false
override var ignoreUpdates: Boolean = false
private val resultsListener: OrderedRealmCollectionChangeListener<RealmResults<Task>> by lazy {
OrderedRealmCollectionChangeListener<RealmResults<Task>> { _, changeSet ->
buildChangeSet(changeSet)
}
}
private val listListener: OrderedRealmCollectionChangeListener<RealmList<Task>> by lazy {
OrderedRealmCollectionChangeListener<RealmList<Task>> { _, changeSet ->
buildChangeSet(changeSet)
}
}
private fun buildChangeSet(changeSet: OrderedCollectionChangeSet) {
if (ignoreUpdates) return
if (changeSet.state == OrderedCollectionChangeSet.State.INITIAL) {
notifyDataSetChanged()
return
}
// For deletions, the adapter has to be notified in reverse order.
val deletions = changeSet.deletionRanges
for (i in deletions.indices.reversed()) {
val range = deletions[i]
notifyItemRangeRemoved(range.startIndex + dataOffset(), range.length)
}
val insertions = changeSet.insertionRanges
for (range in insertions) {
notifyItemRangeInserted(range.startIndex + dataOffset(), range.length)
}
if (!updateOnModification) {
return
}
val modifications = changeSet.changeRanges
for (range in modifications) {
notifyItemRangeChanged(range.startIndex + dataOffset(), range.length)
}
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
data?.takeIf { it.isValid }?.addListener()
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
data?.takeIf { it.isValid }?.removeListener()
}
override fun updateData(tasks: OrderedRealmCollection<Task>?) {
data?.takeIf { it.isValid }?.removeListener()
tasks?.takeIf { it.isValid }?.addListener()
super.updateData(tasks)
}
private fun OrderedRealmCollection<Task>.addListener() {
when (this) {
is RealmResults<Task> -> addChangeListener(resultsListener)
is RealmList<Task> -> addChangeListener(listListener)
else -> throw IllegalArgumentException("RealmCollection not supported: $javaClass")
}
}
private fun OrderedRealmCollection<Task>.removeListener() {
when (this) {
is RealmResults<Task> -> removeChangeListener(resultsListener)
is RealmList<Task> -> removeChangeListener(listListener)
else -> throw IllegalArgumentException("RealmCollection not supported: $javaClass")
}
}
private var errorButtonEventsSubject = PublishSubject.create<String>()
override val errorButtonEvents: Flowable<String> = errorButtonEventsSubject.toFlowable(BackpressureStrategy.DROP)
protected var taskScoreEventsSubject = PublishSubject.create<Pair<Task, TaskDirection>>()
override val taskScoreEvents: Flowable<Pair<Task, TaskDirection>> = taskScoreEventsSubject.toFlowable(BackpressureStrategy.DROP)
protected var checklistItemScoreSubject = PublishSubject.create<Pair<Task, ChecklistItem>>()
override val checklistItemScoreEvents: Flowable<Pair<Task, ChecklistItem>> = checklistItemScoreSubject.toFlowable(BackpressureStrategy.DROP)
protected var taskOpenEventsSubject = PublishSubject.create<Task>()
override val taskOpenEvents: Flowable<Task> = taskOpenEventsSubject.toFlowable(BackpressureStrategy.DROP)
private val isDataValid: Boolean
get() = data?.isValid ?: false
init {
check(!(unfilteredData != null && unfilteredData?.isManaged == false)) { "Only use this adapter with managed RealmCollection, " + "for un-managed lists you can just use the BaseRecyclerViewAdapter" }
this.updateOnModification = true
filter()
}
override fun getItemId(index: Int): Long = index.toLong()
override fun getItemCount(): Int = if (isDataValid) data?.size ?: 0 else 0
override fun getItem(index: Int): Task? = if (isDataValid) data?.get(index) else null
override fun updateUnfilteredData(data: OrderedRealmCollection<Task>?) {
unfilteredData = data
updateData(data)
}
override fun onBindViewHolder(holder: VH, position: Int) {
val item = getItem(position)
if (item != null) {
holder.bind(item, position)
holder.errorButtonClicked = Action {
errorButtonEventsSubject.onNext("")
}
}
}
internal fun getContentView(parent: ViewGroup): View = getContentView(parent, layoutResource)
private fun getContentView(parent: ViewGroup, layoutResource: Int): View =
LayoutInflater.from(parent.context).inflate(layoutResource, parent, false)
final override fun filter() {
val unfilteredData = this.unfilteredData ?: return
if (taskFilterHelper != null) {
val query = taskFilterHelper.createQuery(unfilteredData)
if (query != null) {
updateData(query.findAll())
}
}
}
override fun getTaskIDAt(position: Int): String {
return data?.get(position)?.id ?: ""
}
}
| gpl-3.0 | 45f90f73d8e1a845579b6e1ee5c1b3fe | 39.993631 | 207 | 0.685272 | 5.224247 | false | false | false | false |
ingokegel/intellij-community | platform/dvcs-impl/src/com/intellij/dvcs/ignore/IgnoredToExcludedSynchronizer.kt | 1 | 12776 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.dvcs.ignore
import com.intellij.CommonBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ide.projectView.actions.MarkExcludeRootAction
import com.intellij.ide.util.PropertiesComponent
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FilesProcessorImpl
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.IGNORED_TO_EXCLUDE_NOT_FOUND
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.VcsIgnoreManagerImpl
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType
import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager
import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog
import com.intellij.openapi.vcs.ignore.IgnoredToExcludedSynchronizerConstants.ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.util.Alarm
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity
import java.util.*
private val LOG = logger<IgnoredToExcludedSynchronizer>()
private val excludeAction = object : MarkExcludeRootAction() {
fun exclude(module: Module, dirs: Collection<VirtualFile>) = runInEdt { modifyRoots(module, dirs.toTypedArray()) }
}
/**
* Shows [EditorNotifications] in .ignore files with suggestion to exclude ignored directories.
* Silently excludes them if [VcsConfiguration.MARK_IGNORED_AS_EXCLUDED] is enabled.
*
* Not internal service. Can be used directly in related modules.
*/
@Service
class IgnoredToExcludedSynchronizer(project: Project) : FilesProcessorImpl(project, project) {
private val queue = MergingUpdateQueue("IgnoredToExcludedSynchronizer", 1000, true, null, this, null, Alarm.ThreadToUse.POOLED_THREAD)
init {
val connection = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(connection, MyRootChangeListener())
}
/**
* In case if the project roots changed (e.g. by build tools) then the directories shown in notification can be outdated.
* Filter directories which excluded or containing source roots and expire notification if needed.
*/
private fun updateNotificationState() {
if (synchronizationTurnOff()) return
if (isFilesEmpty()) return
queue.queue(Update.create("update") {
val fileIndex = ProjectFileIndex.getInstance(project)
val sourceRoots = getProjectSourceRoots(project)
val acquiredFiles = selectValidFiles()
LOG.debug("updateNotificationState, acquiredFiles", acquiredFiles)
val filesToRemove = acquiredFiles
.asSequence()
.filter { file -> runReadAction { fileIndex.isExcluded(file) } || sourceRoots.contains(file) }
.toList()
LOG.debug("updateNotificationState, filesToRemove", filesToRemove)
if (removeFiles(filesToRemove)) {
EditorNotifications.getInstance(project).updateAllNotifications()
}
})
}
fun isNotEmpty() = !isFilesEmpty()
fun clearFiles(files: Collection<VirtualFile>) = removeFiles(files)
fun getValidFiles() = with(ChangeListManager.getInstance(project)) { selectValidFiles().filter(this::isIgnoredFile) }
private fun wasAskedBefore() = PropertiesComponent.getInstance(project).getBoolean(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, false)
fun muteForCurrentProject() {
PropertiesComponent.getInstance(project).setValue(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, true)
clearFiles()
}
fun mutedForCurrentProject() = wasAskedBefore() && !needDoForCurrentProject()
override fun doActionOnChosenFiles(files: Collection<VirtualFile>) {
if (files.isEmpty()) return
markIgnoredAsExcluded(project, files)
}
override fun doFilterFiles(files: Collection<VirtualFile>) = files.filter(VirtualFile::isValid)
override fun needDoForCurrentProject() = VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED
fun ignoredUpdateFinished(ignoredPaths: Collection<FilePath>) {
ProgressManager.checkCanceled()
if (synchronizationTurnOff()) return
if (mutedForCurrentProject()) return
processIgnored(ignoredPaths)
}
private fun processIgnored(ignoredPaths: Collection<FilePath>) {
val ignoredDirs =
determineIgnoredDirsToExclude(project, ignoredPaths)
if (allowShowNotification()) {
processFiles(ignoredDirs)
val editorNotifications = EditorNotifications.getInstance(project)
FileEditorManager.getInstance(project).openFiles
.forEach { openFile ->
if (openFile.fileType is IgnoreFileType) {
editorNotifications.updateNotifications(openFile)
}
}
}
else if (needDoForCurrentProject()) {
doActionOnChosenFiles(doFilterFiles(ignoredDirs))
}
}
private inner class MyRootChangeListener : WorkspaceModelChangeListener {
override fun changed(event: VersionedStorageChange) {
// listen content roots, source roots, excluded roots
if (event.getChanges(ContentRootEntity::class.java).isNotEmpty()) {
updateNotificationState()
}
}
}
}
private fun markIgnoredAsExcluded(project: Project, files: Collection<VirtualFile>) {
val ignoredDirsByModule =
files
.groupBy { ModuleUtil.findModuleForFile(it, project) }
//if the directory already excluded then ModuleUtil.findModuleForFile return null and this will filter out such directories from processing.
.filterKeys(Objects::nonNull)
for ((module, ignoredDirs) in ignoredDirsByModule) {
excludeAction.exclude(module!!, ignoredDirs)
}
}
private fun getProjectSourceRoots(project: Project): Set<VirtualFile> = runReadAction {
OrderEnumerator.orderEntries(project).withoutSdk().withoutLibraries().sources().usingCache().roots.toHashSet()
}
private fun containsShelfDirectoryOrUnderIt(filePath: FilePath, shelfPath: String) =
FileUtil.isAncestor(shelfPath, filePath.path, false) ||
FileUtil.isAncestor(filePath.path, shelfPath, false)
private fun determineIgnoredDirsToExclude(project: Project, ignoredPaths: Collection<FilePath>): List<VirtualFile> {
val sourceRoots = getProjectSourceRoots(project)
val fileIndex = ProjectFileIndex.getInstance(project)
val shelfPath = ShelveChangesManager.getShelfPath(project)
return ignoredPaths
.asSequence()
.filter(FilePath::isDirectory)
//shelf directory usually contains in project and excluding it prevents local history to work on it
.filterNot { containsShelfDirectoryOrUnderIt(it, shelfPath) }
.mapNotNull(FilePath::getVirtualFile)
.filterNot { runReadAction { fileIndex.isExcluded(it) } }
//do not propose to exclude if there is a source root inside
.filterNot { ignored -> sourceRoots.contains(ignored) }
.toList()
}
private fun selectFilesToExclude(project: Project, ignoredDirs: List<VirtualFile>): Collection<VirtualFile> {
val dialog = IgnoredToExcludeSelectDirectoriesDialog(project, ignoredDirs)
if (!dialog.showAndGet()) return emptyList()
return dialog.selectedFiles
}
private fun allowShowNotification() = Registry.`is`("vcs.propose.add.ignored.directories.to.exclude", true)
private fun synchronizationTurnOff() = !Registry.`is`("vcs.enable.add.ignored.directories.to.exclude", true)
class IgnoredToExcludeNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() {
companion object {
private val KEY: Key<EditorNotificationPanel> = Key.create("IgnoredToExcludeNotificationProvider")
}
override fun getKey(): Key<EditorNotificationPanel> = KEY
private fun canCreateNotification(project: Project, file: VirtualFile) =
file.fileType is IgnoreFileType &&
with(project.service<IgnoredToExcludedSynchronizer>()) {
!synchronizationTurnOff() &&
allowShowNotification() &&
!mutedForCurrentProject() &&
isNotEmpty()
}
private fun showIgnoredAction(project: Project) {
val allFiles = project.service<IgnoredToExcludedSynchronizer>().getValidFiles()
if (allFiles.isEmpty()) return
val userSelectedFiles = selectFilesToExclude(project, allFiles)
if (userSelectedFiles.isEmpty()) return
with(project.service<IgnoredToExcludedSynchronizer>()) {
markIgnoredAsExcluded(project, userSelectedFiles)
clearFiles(userSelectedFiles)
}
}
private fun muteAction(project: Project) = Runnable {
project.service<IgnoredToExcludedSynchronizer>().muteForCurrentProject()
EditorNotifications.getInstance(project).updateNotifications(this@IgnoredToExcludeNotificationProvider)
}
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (!canCreateNotification(project, file)) return null
return EditorNotificationPanel(fileEditor, EditorNotificationPanel.Status.Info).apply {
icon(AllIcons.General.Information)
text = message("ignore.to.exclude.notification.message")
createActionLabel(message("ignore.to.exclude.notification.action.view")) { showIgnoredAction(project) }
createActionLabel(message("ignore.to.exclude.notification.action.mute"), muteAction(project))
createActionLabel(message("ignore.to.exclude.notification.action.details")) {
BrowserUtil.browse("https://www.jetbrains.com/help/idea/content-roots.html#folder-categories")
}
}
}
}
internal class CheckIgnoredToExcludeAction : DumbAwareAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.project != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
runModalTask(ActionsBundle.message("action.CheckIgnoredAndNotExcludedDirectories.progress"), project, true) {
VcsIgnoreManagerImpl.getInstanceImpl(project).awaitRefreshQueue()
val ignoredFilePaths = ChangeListManager.getInstance(project).ignoredFilePaths
val dirsToExclude = determineIgnoredDirsToExclude(project, ignoredFilePaths)
if (dirsToExclude.isEmpty()) {
VcsNotifier.getInstance(project)
.notifyMinorInfo(IGNORED_TO_EXCLUDE_NOT_FOUND, "", message("ignore.to.exclude.no.directories.found"))
}
else {
val userSelectedFiles = selectFilesToExclude(project, dirsToExclude)
if (userSelectedFiles.isNotEmpty()) {
markIgnoredAsExcluded(project, userSelectedFiles)
}
}
}
}
}
// do not use SelectFilesDialog.init because it doesn't provide clear statistic: what exactly dialog shown/closed, action clicked
private class IgnoredToExcludeSelectDirectoriesDialog(
project: Project?,
files: List<VirtualFile>
) : SelectFilesDialog(project, files, message("ignore.to.exclude.notification.notice"), null, true, true) {
init {
title = message("ignore.to.exclude.view.dialog.title")
selectedFiles = files
setOKButtonText(message("ignore.to.exclude.view.dialog.exclude.action"))
setCancelButtonText(CommonBundle.getCancelButtonText())
init()
}
}
| apache-2.0 | bcc1852d426e8c0e827d8d0327a1d0f2 | 41.304636 | 146 | 0.777004 | 4.703976 | false | false | false | false |
siosio/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/GenericNotifierImpl.kt | 1 | 4051 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.util.ModalityUiUtil.invokeLaterIfNeeded
import com.intellij.util.ui.UIUtil
import java.util.*
import javax.swing.event.HyperlinkEvent
abstract class GenericNotifierImpl<T, Key>(@JvmField protected val myProject: Project,
private val myGroupId: String,
@NlsContexts.NotificationTitle private val myTitle: String,
private val myType: NotificationType) {
private val myState = HashMap<Key, MyNotification>()
private val myListener = MyListener()
private val myLock = Any()
protected val allCurrentKeys get() = synchronized(myLock) { myState.keys.toList() }
val isEmpty get() = synchronized(myLock) { myState.isEmpty() }
protected abstract fun ask(obj: T, description: String?): Boolean
protected abstract fun getKey(obj: T): Key
protected abstract fun getNotificationContent(obj: T): @NlsContexts.NotificationContent String
protected fun getStateFor(key: Key) = synchronized(myLock) { myState.containsKey(key) }
fun clear() {
val notifications = synchronized(myLock) {
val currentNotifications = myState.values.toList()
myState.clear()
currentNotifications
}
invokeLaterIfNeeded(Runnable {
for (notification in notifications) {
notification.expire()
}
}, ModalityState.NON_MODAL, myProject.disposed)
}
private fun expireNotification(notification: MyNotification) = UIUtil.invokeLaterIfNeeded { notification.expire() }
open fun ensureNotify(obj: T): Boolean {
val notification = synchronized(myLock) {
val key = getKey(obj)
if (myState.containsKey(key)) return false
val objNotification = MyNotification(myGroupId, myTitle, getNotificationContent(obj), myType, myListener, obj)
myState[key] = objNotification
objNotification
}
if (onFirstNotification(obj)) {
removeLazyNotification(obj)
return true
}
Notifications.Bus.notify(notification, myProject)
return false
}
protected open fun onFirstNotification(obj: T) = false
fun removeLazyNotificationByKey(key: Key) {
val notification = synchronized(myLock) { myState.remove(key) }
if (notification != null) {
expireNotification(notification)
}
}
fun removeLazyNotification(obj: T) = removeLazyNotificationByKey(getKey(obj))
private inner class MyListener : NotificationListener {
override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) {
val concreteNotification = notification as GenericNotifierImpl<T, Key>.MyNotification
val obj = concreteNotification.obj
if (ask(obj, event.description)) {
synchronized(myLock) {
myState.remove(getKey(obj))
}
expireNotification(concreteNotification)
}
}
}
protected inner class MyNotification(groupId: String,
@NlsContexts.NotificationTitle title: String,
@NlsContexts.NotificationContent content: String,
type: NotificationType,
listener: NotificationListener?,
val obj: T) : Notification(groupId, title, content, type) {
init {
listener?.let { setListener(listener) }
}
override fun expire() {
super.expire()
synchronized(myLock) {
myState.remove(getKey(obj))
}
}
}
}
| apache-2.0 | cbb9b5aef2726d8ca235e77804b0810f | 36.859813 | 140 | 0.679585 | 4.98278 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/draw/path/ShadowLineChartView.kt | 1 | 3164 | package com.zeke.demo.draw.path
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import com.zeke.demo.base.BasePracticeView
/**
* author:ZekeWang
* date:2021/6/15
* description:
* 带内容渐变色填充的折线图
*/
class ShadowLineChartView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BasePracticeView(context, attrs, defStyleAttr) {
//
private var mPath: Path = Path()
private var mShaderPath: Path = Path()
private var mShaderPaint: Paint = Paint()
private var mPaintRect: Paint
private var mBaseLinePaint: Paint
private var bounds = RectF()
private var mLine = RectF()
private var dots = arrayOf(
arrayOf( 0, 10, 20, 30, 35, 37, 38, 40, 50, 51, 52, 55, 60,70,80, 90,100), //Time
arrayOf(60,180,120,150,200,220,240,250,245,240,260,280,100,60,80,120,100) //Value
)
init {
val h = dots[0]
val v = dots[1]
for (i in h.indices) {
val dx = h[i].toFloat() * 10
val dy = v[i].toFloat() * 1.2f
if (i == 0) {
mPath.moveTo(dx, dy)
mShaderPath.moveTo(dx,dy)
mLine.left = dx
} else {
mPath.lineTo(dx, dy)
mShaderPath.lineTo(dx,dy)
if (i == h.lastIndex) {
//封闭shader
mShaderPath.lineTo(dx,500f)
mShaderPath.lineTo(0f,500f)
mShaderPath.close()
mLine.right = dx
}
}
}
//平均值线
mLine.top = 200f
mLine.bottom = 200f
with(paint) {
style = Paint.Style.STROKE
strokeWidth = 10f
isAntiAlias = true
pathEffect = CornerPathEffect(6f)
color = Color.parseColor("#FAE847") // 动态设置 橙黄色
}
mPaintRect = Paint(paint)
mPaintRect.strokeWidth = 2f
mBaseLinePaint = Paint(mPaintRect)
with(mShaderPaint) {
isAntiAlias = true
strokeWidth = 2f
val shadeColors = arrayOf(
Color.parseColor("#D6C105"),
Color.TRANSPARENT
)
val positions = arrayOf(0.2f, 1.0f)
shader = LinearGradient(
0f, 0f, 0f, 350f,
shadeColors.toIntArray(), positions.toFloatArray(),
Shader.TileMode.CLAMP
)
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.translate(100f,0f)
setBackgroundColor(Color.parseColor("#303030"))
mPath.computeBounds(bounds, false)
canvas.drawPath(mPath, paint)
canvas.drawPath(mShaderPath, mShaderPaint)
// canvas.drawRoundRect(bounds, 0f, 0f, mPaintRect)
//
// mPaintRect.color = Color.parseColor("#9C7A48") // 动态设置
// canvas.drawLine(mLine.left, mLine.top, mLine.right, mLine.bottom, mBaseLinePaint)
}
override fun getViewHeight(): Int {
return 600
}
} | gpl-2.0 | cb6ca2ba11bbd90cbdb130dad41d8f61 | 28.254717 | 91 | 0.549677 | 3.899371 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/embedview/EmbedLinkPresenter.kt | 1 | 2932 | package io.github.feelfreelinux.wykopmobilny.ui.modules.embedview
import io.github.feelfreelinux.wykopmobilny.api.embed.ExternalApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.reactivex.Single
import java.net.URI
import java.net.URL
class EmbedLinkPresenter(
val schedulers: Schedulers,
private val embedApi: ExternalApi
) : BasePresenter<EmbedView>() {
companion object {
const val GFYCAT_MATCHER = "gfycat.com"
const val COUB_MATCHER = "coub.com"
const val STREAMABLE_MATCHER = "streamable.com"
const val YOUTUBE_MATCHER = "youtube.com"
const val SIMPLE_YOUTUBE_MATCHER = "youtu.be"
}
lateinit var linkDomain: String
lateinit var mp4Url: String
fun playUrl(url: String) {
linkDomain = if (!url.contains(GFYCAT_MATCHER)) {
url.getDomainName()
} else {
GFYCAT_MATCHER
}
when (linkDomain) {
GFYCAT_MATCHER -> {
val id = url.formatGfycat()
embedApi.getGfycat(id)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({
mp4Url = it.gfyItem.mp4Url
view?.playUrl(URL(it.gfyItem.webmUrl))
}, { view?.showErrorDialog(it) })
}
COUB_MATCHER -> {
val id = url.removeSuffix("/").substringAfterLast("/view/")
embedApi.getCoub(id)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.playCoub(it) }, { view?.showErrorDialog(it) })
}
STREAMABLE_MATCHER -> {
val id = url.removeSuffix("/").substringAfterLast("/")
embedApi.getStreamableUrl(id)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({
mp4Url = it.toString()
view?.playUrl(it)
}, { view?.showErrorDialog(it) })
}
SIMPLE_YOUTUBE_MATCHER, YOUTUBE_MATCHER -> view?.exitAndOpenYoutubeActivity()
else -> {
Single.just(url)
}
}
}
private fun String.formatGfycat(): String {
return this
.replace(".gif", "")
.replace(".mp4", "")
.replace(".webm", "")
.replace("-size_restricted", "")
.removeSuffix("/").substringAfterLast("/")
}
private fun String.getDomainName(): String {
val uri = URI(this)
val domain = uri.host
return if (domain.startsWith("www.")) domain.substring(4) else domain
}
} | mit | 44fa0151605a26eade2db10c0478dd33 | 33.104651 | 89 | 0.550477 | 4.683706 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/buildscript/GradleBuildScriptBuilderUtil.kt | 5 | 1574 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("GradleBuildScriptBuilderUtil")
package org.jetbrains.plugins.gradle.frameworkSupport.buildscript
import org.gradle.util.GradleVersion
fun getKotlinVersion(gradleVersion: GradleVersion): String {
return if (isSupportedKotlin4(gradleVersion)) "1.4.32" else "1.3.50"
}
fun getGroovyVersion(): String {
return "3.0.5"
}
fun getJunit4Version(): String {
return "4.12"
}
fun getJunit5Version(): String {
return "5.8.1"
}
fun isSupportedJavaLibraryPlugin(gradleVersion: GradleVersion): Boolean {
return gradleVersion.baseVersion >= GradleVersion.version("3.4")
}
fun isSupportedImplementationScope(gradleVersion: GradleVersion): Boolean {
return isSupportedJavaLibraryPlugin(gradleVersion)
}
fun isSupportedRuntimeOnlyScope(gradleVersion: GradleVersion): Boolean {
return isSupportedJavaLibraryPlugin(gradleVersion)
}
fun isSupportedTaskConfigurationAvoidance(gradleVersion: GradleVersion): Boolean {
return gradleVersion.baseVersion >= GradleVersion.version("4.9")
}
fun isSupportedJUnit5(gradleVersion: GradleVersion): Boolean {
return gradleVersion.baseVersion >= GradleVersion.version("4.7")
}
fun isSupportedKotlin4(gradleVersion: GradleVersion): Boolean {
return gradleVersion.baseVersion >= GradleVersion.version("5.6.2")
}
fun isSupportedGroovyApache(groovyVersion: String) : Boolean {
val majorVersion = groovyVersion.split(".").firstOrNull()?.let(Integer::valueOf) ?: 0
return majorVersion >= 4
}
| apache-2.0 | 433211ce5de8da362dbfd11a3ebbf867 | 29.269231 | 120 | 0.78526 | 4.348066 | false | false | false | false |
Commit451/Easel | easel/src/main/java/com/commit451/easel/progressbar.kt | 1 | 997 | package com.commit451.easel
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.os.Build
import androidx.annotation.ColorInt
import android.widget.ProgressBar
fun ProgressBar.tint(@ColorInt color: Int, skipIndeterminate: Boolean = false) {
val sl = ColorStateList.valueOf(color)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressTintList = sl
secondaryProgressTintList = sl
if (!skipIndeterminate) {
indeterminateTintList = sl
}
} else {
var mode: PorterDuff.Mode = PorterDuff.Mode.SRC_IN
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
mode = PorterDuff.Mode.MULTIPLY
}
if (!skipIndeterminate && indeterminateDrawable != null) {
indeterminateDrawable.setColorFilter(color, mode)
}
if (progressDrawable != null) {
progressDrawable.setColorFilter(color, mode)
}
}
} | apache-2.0 | 7cab1165dba681792903420addab989c | 33.413793 | 80 | 0.672016 | 4.450893 | false | false | false | false |
androidx/androidx | datastore/datastore-rxjava3/src/main/java/androidx/datastore/rxjava3/RxDataStoreDelegate.kt | 3 | 4623 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.rxjava3
import android.content.Context
import androidx.annotation.GuardedBy
import androidx.datastore.core.DataMigration
import androidx.datastore.core.Serializer
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Creates a property delegate for a single process DataStore. This should only be called once
* in a file (at the top level), and all usages of the DataStore should use a reference the same
* Instance. The receiver type for the property delegate must be an instance of [Context].
*
* This should only be used from a single application in a single classloader in a single process.
*
* Example usage:
* ```
* val Context.myRxDataStore by rxDataStore("filename", serializer)
*
* class SomeClass(val context: Context) {
* fun update(): Single<Settings> = context.myRxDataStore.updateDataAsync {...}
* }
* ```
*
* @param fileName the filename relative to Context.filesDir that DataStore acts on. The File is
* obtained by calling File(context.filesDir, "datastore/$fileName")). No two instances of DataStore
* should act on the same file at the same time.
* @param corruptionHandler The corruptionHandler is invoked if DataStore encounters a
* [androidx.datastore.core.CorruptionException] when attempting to read data. CorruptionExceptions
* are thrown by serializers when data can not be de-serialized.
* @param produceMigrations produce the migrations. The ApplicationContext is passed in to these
* callbacks as a parameter. DataMigrations are run before any access to data can occur. Each
* producer and migration may be run more than once whether or not it already succeeded
* (potentially because another migration failed or a write to disk failed.)
* @param scheduler The scheduler in which IO operations and transform functions will execute.
*
* @return a property delegate that manages a datastore as a singleton.
*/
@Suppress("MissingJvmstatic")
public fun <T : Any> rxDataStore(
fileName: String,
serializer: Serializer<T>,
corruptionHandler: ReplaceFileCorruptionHandler<T>? = null,
produceMigrations: (Context) -> List<DataMigration<T>> = { listOf() },
scheduler: Scheduler = Schedulers.io()
): ReadOnlyProperty<Context, RxDataStore<T>> {
return RxDataStoreSingletonDelegate(
fileName,
serializer,
corruptionHandler,
produceMigrations,
scheduler
)
}
/**
* Delegate class to manage DataStore as a singleton.
*/
internal class RxDataStoreSingletonDelegate<T : Any> internal constructor(
private val fileName: String,
private val serializer: Serializer<T>,
private val corruptionHandler: ReplaceFileCorruptionHandler<T>?,
private val produceMigrations: (Context) -> List<DataMigration<T>> = { listOf() },
private val scheduler: Scheduler
) : ReadOnlyProperty<Context, RxDataStore<T>> {
private val lock = Any()
@GuardedBy("lock")
@Volatile
private var INSTANCE: RxDataStore<T>? = null
/**
* Gets the instance of the DataStore.
*
* @param thisRef must be an instance of [Context]
* @param property not used
*/
override fun getValue(thisRef: Context, property: KProperty<*>): RxDataStore<T> {
return INSTANCE ?: synchronized(lock) {
if (INSTANCE == null) {
val applicationContext = thisRef.applicationContext
INSTANCE = with(RxDataStoreBuilder(applicationContext, fileName, serializer)) {
setIoScheduler(scheduler)
produceMigrations(applicationContext).forEach {
addDataMigration(it)
}
corruptionHandler?.let { setCorruptionHandler(it) }
build()
}
}
INSTANCE!!
}
}
} | apache-2.0 | edfa4556cafff58ed0e055f54dab11da | 38.862069 | 100 | 0.712092 | 4.850997 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/solver/types/PrimitiveColumnTypeAdapter.kt | 3 | 5649 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.solver.types
import androidx.room.compiler.codegen.CodeLanguage
import androidx.room.compiler.codegen.XCodeBlock
import androidx.room.compiler.codegen.XTypeName
import androidx.room.compiler.codegen.XTypeName.Companion.PRIMITIVE_BYTE
import androidx.room.compiler.codegen.XTypeName.Companion.PRIMITIVE_CHAR
import androidx.room.compiler.codegen.XTypeName.Companion.PRIMITIVE_DOUBLE
import androidx.room.compiler.codegen.XTypeName.Companion.PRIMITIVE_FLOAT
import androidx.room.compiler.codegen.XTypeName.Companion.PRIMITIVE_INT
import androidx.room.compiler.codegen.XTypeName.Companion.PRIMITIVE_LONG
import androidx.room.compiler.codegen.XTypeName.Companion.PRIMITIVE_SHORT
import androidx.room.compiler.processing.XProcessingEnv
import androidx.room.compiler.processing.XType
import androidx.room.parser.SQLTypeAffinity
import androidx.room.solver.CodeGenScope
/**
* Adapters for all primitives that has direct cursor mappings.
*/
class PrimitiveColumnTypeAdapter(
out: XType,
typeAffinity: SQLTypeAffinity,
val primitive: Primitive,
) : ColumnTypeAdapter(out, typeAffinity) {
companion object {
enum class Primitive(
val typeName: XTypeName,
val cursorGetter: String,
val stmtSetter: String,
) {
INT(PRIMITIVE_INT, "getInt", "bindLong"),
SHORT(PRIMITIVE_SHORT, "getShort", "bindLong"),
BYTE(PRIMITIVE_BYTE, "getShort", "bindLong"),
LONG(PRIMITIVE_LONG, "getLong", "bindLong"),
CHAR(PRIMITIVE_CHAR, "getInt", "bindLong"),
FLOAT(PRIMITIVE_FLOAT, "getFloat", "bindDouble"),
DOUBLE(PRIMITIVE_DOUBLE, "getDouble", "bindDouble"),
}
private fun getAffinity(primitive: Primitive) = when (primitive) {
Primitive.INT, Primitive.SHORT, Primitive.BYTE, Primitive.LONG, Primitive.CHAR ->
SQLTypeAffinity.INTEGER
Primitive.FLOAT, Primitive.DOUBLE ->
SQLTypeAffinity.REAL
}
fun createPrimitiveAdapters(
processingEnvironment: XProcessingEnv
): List<PrimitiveColumnTypeAdapter> {
return Primitive.values().map {
PrimitiveColumnTypeAdapter(
out = processingEnvironment.requireType(it.typeName),
typeAffinity = getAffinity(it),
primitive = it
)
}
}
}
private val cursorGetter = primitive.cursorGetter
private val stmtSetter = primitive.stmtSetter
override fun bindToStmt(
stmtName: String,
indexVarName: String,
valueVarName: String,
scope: CodeGenScope
) {
// These primitives don't have an exact statement setter.
val castFunction = when (primitive) {
Primitive.INT, Primitive.SHORT, Primitive.BYTE, Primitive.CHAR -> "toLong"
Primitive.FLOAT -> "toDouble"
else -> null
}
val valueExpr = when (scope.language) {
CodeLanguage.JAVA -> {
// For Java, with the language's primitive type casting, value variable can be
// used as bind argument directly.
XCodeBlock.of(scope.language, "%L", valueVarName)
}
CodeLanguage.KOTLIN -> {
// For Kotlin, a converter function is emitted when a cast is needed.
if (castFunction != null) {
XCodeBlock.of(scope.language, "%L.%L()", valueVarName, castFunction)
} else {
XCodeBlock.of(scope.language, "%L", valueVarName)
}
}
}
scope.builder
.addStatement("%L.%L(%L, %L)", stmtName, stmtSetter, indexVarName, valueExpr)
}
override fun readFromCursor(
outVarName: String,
cursorVarName: String,
indexVarName: String,
scope: CodeGenScope
) {
scope.builder.addStatement(
"%L = %L",
outVarName,
XCodeBlock.of(
scope.language,
"%L.%L(%L)",
cursorVarName,
cursorGetter,
indexVarName
).let {
// These primitives don't have an exact cursor getter.
val castFunction = when (primitive) {
Primitive.BYTE -> "toByte"
Primitive.CHAR -> "toChar"
else -> null
} ?: return@let it
when (it.language) {
// For Java a cast will suffice
CodeLanguage.JAVA -> {
XCodeBlock.ofCast(it.language, out.asTypeName(), it)
}
// For Kotlin a converter function is emitted
CodeLanguage.KOTLIN -> {
XCodeBlock.of(it.language, "%L.%L()", it, castFunction)
}
}
}
)
}
}
| apache-2.0 | b7d5b2a630b8b8542f2cf75ab0a06a05 | 37.168919 | 94 | 0.602762 | 4.895147 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/animation/transitions/CrossfaderTransition.kt | 2 | 1968 | package org.thoughtcrime.securesms.animation.transitions
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.transition.Transition
import android.transition.TransitionValues
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
@RequiresApi(21)
class CrossfaderTransition(context: Context, attrs: AttributeSet?) : Transition(context, attrs) {
companion object {
private const val WIDTH = "CrossfaderTransition.WIDTH"
}
override fun captureStartValues(transitionValues: TransitionValues) {
if (transitionValues.view is Crossfadeable) {
transitionValues.values[WIDTH] = transitionValues.view.width
}
}
override fun captureEndValues(transitionValues: TransitionValues) {
if (transitionValues.view is Crossfadeable) {
transitionValues.values[WIDTH] = transitionValues.view.width
}
}
override fun createAnimator(sceneRoot: ViewGroup?, startValues: TransitionValues?, endValues: TransitionValues?): Animator? {
if (startValues == null || endValues == null) {
return null
}
val startWidth = (startValues.values[WIDTH] ?: 0) as Int
val endWidth = (endValues.values[WIDTH] ?: 0) as Int
val view: Crossfadeable = endValues.view as? Crossfadeable ?: return null
val reverse = startWidth > endWidth
return ValueAnimator.ofFloat(0f, 1f).apply {
addUpdateListener {
view.onCrossfadeAnimationUpdated(it.animatedValue as Float, reverse)
}
doOnStart {
view.onCrossfadeStarted(reverse)
}
doOnEnd {
view.onCrossfadeFinished(reverse)
}
}
}
interface Crossfadeable {
fun onCrossfadeAnimationUpdated(progress: Float, reverse: Boolean)
fun onCrossfadeStarted(reverse: Boolean)
fun onCrossfadeFinished(reverse: Boolean)
}
}
| gpl-3.0 | f534ae6c964f340568bc93826686fada | 30.238095 | 127 | 0.745935 | 4.422472 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/MagnifierSamples.kt | 3 | 3137 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.MagnifierStyle
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.magnifier
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
@OptIn(ExperimentalFoundationApi::class)
@Sampled
@Composable
fun MagnifierSample() {
// When the magnifier center position is Unspecified, it is hidden.
// Hide the magnifier until a drag starts.
var magnifierCenter by remember { mutableStateOf(Offset.Unspecified) }
if (!MagnifierStyle.Default.isSupported) {
Text("Magnifier is not supported on this platform.")
} else {
Box(
Modifier
.magnifier(
sourceCenter = { magnifierCenter },
zoom = 2f
)
.pointerInput(Unit) {
detectDragGestures(
// Show the magnifier at the original pointer position.
onDragStart = { magnifierCenter = it },
// Make the magnifier follow the finger while dragging.
onDrag = { _, delta -> magnifierCenter += delta },
// Hide the magnifier when the finger lifts.
onDragEnd = { magnifierCenter = Offset.Unspecified },
onDragCancel = { magnifierCenter = Offset.Unspecified }
)
}
.drawBehind {
// Some concentric circles to zoom in on.
for (diameter in 2 until size.maxDimension.toInt() step 10) {
drawCircle(
color = Color.Black,
radius = diameter / 2f,
style = Stroke()
)
}
}
)
}
}
| apache-2.0 | 0c002fceb4f752f575aba6c797cde455 | 39.217949 | 81 | 0.638827 | 5.263423 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/helpers/FirSuperEntriesProvider.kt | 3 | 2564 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.contributors.helpers
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.types.KtClassType
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferencesInRange
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
internal object FirSuperEntriesProvider {
fun KtAnalysisSession.getSuperClassesAvailableForSuperCall(context: PsiElement): List<KtNamedClassOrObjectSymbol> {
val containingClass = context.getStrictParentOfType<KtClassOrObject>() ?: return emptyList()
val containingClassSymbol = containingClass.getClassOrObjectSymbol()
return containingClassSymbol.superTypes.mapNotNull { superType ->
val classType = superType as? KtNonErrorClassType ?: return@mapNotNull null
classType.classSymbol as? KtNamedClassOrObjectSymbol
}
}
}
internal object SuperCallInsertionHandler : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val lookupObject = item.`object` as SuperCallLookupObject
replaceWithClassIdAndShorten(lookupObject, context)
context.insertSymbolAndInvokeCompletion(symbol = ".")
}
private fun replaceWithClassIdAndShorten(
lookupObject: SuperCallLookupObject,
context: InsertionContext
) {
val replaceTo = lookupObject.replaceTo ?: return
context.document.replaceString(context.startOffset, context.tailOffset, replaceTo)
context.commitDocument()
if (lookupObject.shortenReferencesInReplaced) {
val targetFile = context.file as KtFile
shortenReferencesInRange(targetFile, TextRange(context.startOffset, context.tailOffset))
}
}
}
internal interface SuperCallLookupObject {
val replaceTo: String?
val shortenReferencesInReplaced: Boolean
} | apache-2.0 | aeaf5ed5c01e412ecf109cd8ffa77bdb | 44.803571 | 158 | 0.784711 | 5.057199 | false | false | false | false |
nsk-mironov/sento | sento-compiler/src/main/kotlin/io/mironov/sento/compiler/common/OptionalAware.kt | 1 | 2137 | package io.mironov.sento.compiler.common
import io.mironov.sento.compiler.annotations.Metadata
import io.mironov.sento.compiler.annotations.data
import io.mironov.sento.compiler.annotations.kind
import io.mironov.sento.compiler.annotations.strings
import io.mironov.sento.compiler.reflect.AnnotationSpec
import io.mironov.sento.compiler.reflect.ClassSpec
import io.mironov.sento.compiler.reflect.FieldSpec
import io.mironov.sento.compiler.reflect.MethodSpec
import kotlin.reflect.jvm.internal.impl.serialization.ClassData
import kotlin.reflect.jvm.internal.impl.serialization.jvm.JvmProtoBufUtil
internal class OptionalAware(private val spec: ClassSpec) {
private companion object {
private val IS_ANNOTATION_OPTIONAL: (spec: AnnotationSpec) -> Boolean = {
it.type == Types.OPTIONAL
}
private val IS_ANNOTATION_NULLABLE: (spec: AnnotationSpec) -> Boolean = {
it.type.className.endsWith(".Nullable")
}
private val IS_ANNOTATION_NOT_NULL: (spec: AnnotationSpec) -> Boolean = {
it.type.className.endsWith(".NotNull")
}
}
private val metadata by lazy(LazyThreadSafetyMode.NONE) {
createKotlinMetaData()
}
fun isOptional(field: FieldSpec): Boolean {
if (field.annotations.any(IS_ANNOTATION_NOT_NULL)) {
return false
}
if (field.annotations.any(IS_ANNOTATION_NULLABLE)) {
return true
}
if (field.annotations.any(IS_ANNOTATION_OPTIONAL)) {
return true
}
val resolver = metadata?.nameResolver ?: return false
val proto = metadata?.classProto ?: return false
return proto.propertyList.any {
resolver.getName(it.name).asString() == field.name && it.returnType.nullable
}
}
fun isOptional(method: MethodSpec): Boolean {
return method.annotations.any(IS_ANNOTATION_OPTIONAL)
}
private fun createKotlinMetaData(): ClassData? {
val annotation = spec.getAnnotation<Metadata>() ?: return null
if (annotation.kind != Metadata.KIND_CLASS) {
return null
}
val strings = annotation.strings
val data = annotation.data
return JvmProtoBufUtil.readClassDataFrom(data, strings)
}
}
| apache-2.0 | 00af488a5967fd260b9fecf392de9e22 | 29.528571 | 82 | 0.729527 | 4.22332 | false | false | false | false |
jwren/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/MakeNoArgVoidFix.kt | 1 | 2535 | // 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.codeInspection.test.junit
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.lang.jvm.JvmMethod
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmPrimitiveTypeKind
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.SmartPointerManager
import com.intellij.util.castSafelyTo
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.getUParentForIdentifier
class MakeNoArgVoidFix(
private val methodName: @NlsSafe String,
private val makeStatic: Boolean,
private val newVisibility: JvmModifier? = null
) : LocalQuickFix {
override fun getName(): String = JvmAnalysisBundle.message("jvm.fix.make.no.arg.void.descriptor", methodName)
override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.fix.make.no.arg.void.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val containingFile = descriptor.psiElement.containingFile ?: return
val javaMethod = getUParentForIdentifier(descriptor.psiElement)?.castSafelyTo<UMethod>()?.javaPsi ?: return
val methodPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaMethod)
methodPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod ->
createChangeTypeActions(jvmMethod, typeRequest(JvmPrimitiveTypeKind.VOID.name, emptyList())).forEach {
it.invoke(project, null, containingFile)
}
}
methodPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod ->
createChangeParametersActions(jvmMethod, setMethodParametersRequest(emptyMap<String, JvmType>().entries)).forEach {
it.invoke(project, null, containingFile)
}
}
if (newVisibility != null) {
methodPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(newVisibility, true)).forEach {
it.invoke(project, null, containingFile)
}
}
}
methodPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach {
it.invoke(project, null, containingFile)
}
}
}
} | apache-2.0 | 2967aa449e40d143b7588e42295110d0 | 42.724138 | 121 | 0.765286 | 4.510676 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/configurationStore/storeUtil.kt | 4 | 9016 | // 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.configurationStore
import com.intellij.diagnostic.PluginException
import com.intellij.ide.IdeBundle
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginUtil
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.TransactionGuardImpl
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.processOpenedProjects
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ExceptionUtil
import com.intellij.util.concurrency.annotations.RequiresEdt
import kotlinx.coroutines.runBlocking
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CalledInAny
import java.nio.file.Path
import java.util.concurrent.CancellationException
private val LOG = Logger.getInstance("#com.intellij.openapi.components.impl.stores.StoreUtil")
/**
* Only for Java clients.
* Kotlin clients should use corresponding package-level suspending functions.
*/
class StoreUtil private constructor() {
companion object {
/**
* Do not use this method in tests, instead directly save using state store.
*/
@JvmOverloads
@JvmStatic
@CalledInAny
fun saveSettings(componentManager: ComponentManager, forceSavingAllSettings: Boolean = false) {
runInAutoSaveDisabledMode {
runBlocking {
com.intellij.configurationStore.saveSettings(componentManager, forceSavingAllSettings)
}
}
}
/**
* Save all unsaved documents and project settings. Must be called from EDT.
* Use with care because it blocks EDT. Any new usage should be reviewed.
*/
@RequiresEdt
@JvmStatic
fun saveDocumentsAndProjectSettings(project: Project) {
FileDocumentManager.getInstance().saveAllDocuments()
saveSettings(project)
}
/**
* Save all unsaved documents, project and application settings. Must be called from EDT.
* Use with care because it blocks EDT. Any new usage should be reviewed.
*
* @param forceSavingAllSettings if `true` [Storage.useSaveThreshold] attribute will be ignored and settings of all components will be saved
*/
@RequiresEdt
@JvmStatic
fun saveDocumentsAndProjectsAndApp(forceSavingAllSettings: Boolean) {
runInAutoSaveDisabledMode {
FileDocumentManager.getInstance().saveAllDocuments()
runBlocking {
saveProjectsAndApp(forceSavingAllSettings)
}
}
}
}
}
@CalledInAny
suspend fun saveSettings(componentManager: ComponentManager, forceSavingAllSettings: Boolean = false): Boolean {
if (ApplicationManager.getApplication().isDispatchThread) {
(TransactionGuardImpl.getInstance() as TransactionGuardImpl).assertWriteActionAllowed()
}
try {
componentManager.stateStore.save(forceSavingAllSettings = forceSavingAllSettings)
return true
}
catch (e: CancellationException) {
return false
}
catch (e: UnresolvedReadOnlyFilesException) {
LOG.info(e)
}
catch (e: Throwable) {
if (ApplicationManager.getApplication().isUnitTestMode) {
LOG.error("Save settings failed", e)
}
else {
LOG.warn("Save settings failed", e)
}
val messagePostfix = IdeBundle.message("notification.content.please.restart.0", ApplicationNamesInfo.getInstance().fullProductName,
(if (ApplicationManager.getApplication().isInternal) "<p>" + ExceptionUtil.getThrowableText(e) + "</p>" else ""))
val pluginId = PluginUtil.getInstance().findPluginId(e)
val group = NotificationGroupManager.getInstance().getNotificationGroup("Settings Error")
val notification = if (pluginId == null || (ApplicationInfo.getInstance() as ApplicationInfoEx).isEssentialPlugin(pluginId)) {
group.createNotification(IdeBundle.message("notification.title.unable.to.save.settings"),
IdeBundle.message("notification.content.failed.to.save.settings", messagePostfix),
NotificationType.ERROR)
}
else {
PluginManagerCore.disablePlugin(pluginId)
group.createNotification(IdeBundle.message("notification.title.unable.to.save.plugin.settings"),
IdeBundle.message("notification.content.plugin.failed.to.save.settings.and.has.been.disabled", pluginId.idString, messagePostfix),
NotificationType.ERROR)
}
notification.notify(componentManager as? Project)
}
return false
}
fun <T> getStateSpec(persistentStateComponent: PersistentStateComponent<T>): State {
return getStateSpecOrError(persistentStateComponent.javaClass)
}
fun getStateSpecOrError(componentClass: Class<out PersistentStateComponent<*>>): State {
return getStateSpec(componentClass)
?: throw PluginException.createByClass("No @State annotation found in $componentClass", null, componentClass)
}
fun getStateSpec(originalClass: Class<*>): State? {
var aClass = originalClass
while (true) {
val stateSpec = aClass.getAnnotation(State::class.java)
if (stateSpec != null) {
return stateSpec
}
aClass = aClass.superclass ?: break
}
return null
}
/**
* Returns the path to the storage file for the given [PersistentStateComponent].
* The storage file is defined by [Storage.value] of the [State] annotation, and is located under the APP_CONFIG directory.
*
* Returns null if there is no State or Storage annotation on the given class.
*
* *NB:* Don't use this method without a strict reason: the storage location is an implementation detail.
*/
@ApiStatus.Internal
fun getPersistentStateComponentStorageLocation(clazz: Class<*>): Path? {
return getDefaultStoragePathSpec(clazz)?.let { fileSpec ->
ApplicationManager.getApplication().getService(IComponentStore::class.java).storageManager.expandMacro(fileSpec)
}
}
/**
* Returns the default storage file specification for the given [PersistentStateComponent] as defined by [Storage.value]
*/
fun getDefaultStoragePathSpec(clazz: Class<*>): String? {
return getStateSpec(clazz)?.let { getDefaultStoragePathSpec(it) }
}
fun getDefaultStoragePathSpec(state: State): String? {
val storage = state.storages.find { !it.deprecated }
return storage?.let { getStoragePathSpec(storage) }
}
fun getStoragePathSpec(storage: Storage): String {
@Suppress("DEPRECATION")
val pathSpec = storage.value.ifEmpty { storage.file }
return if (storage.roamingType == RoamingType.PER_OS) getOsDependentStorage(pathSpec) else pathSpec
}
fun getOsDependentStorage(storagePathSpec: String): String {
return getPerOsSettingsStorageFolderName() + "/" + storagePathSpec
}
fun getPerOsSettingsStorageFolderName(): String {
if (SystemInfo.isMac) return "mac"
if (SystemInfo.isWindows) return "windows"
if (SystemInfo.isLinux) return "linux"
if (SystemInfo.isFreeBSD) return "freebsd"
return if (SystemInfo.isUnix) "unix" else "other_os"
}
/**
* @param forceSavingAllSettings Whether to force save non-roamable component configuration.
*/
@CalledInAny
suspend fun saveProjectsAndApp(forceSavingAllSettings: Boolean, onlyProject: Project? = null) {
StoreReloadManager.getInstance().reloadChangedStorageFiles()
val start = System.currentTimeMillis()
saveSettings(ApplicationManager.getApplication(), forceSavingAllSettings)
if (onlyProject == null) {
saveAllProjects(forceSavingAllSettings)
}
else {
saveSettings(onlyProject, forceSavingAllSettings = true)
}
val duration = System.currentTimeMillis() - start
if (duration > 1000 || LOG.isDebugEnabled) {
LOG.info("saveProjectsAndApp took $duration ms")
}
}
@CalledInAny
private suspend fun saveAllProjects(forceSavingAllSettings: Boolean) {
processOpenedProjects { project ->
saveSettings(project, forceSavingAllSettings)
}
}
inline fun <T> runInAutoSaveDisabledMode(task: () -> T): T {
SaveAndSyncHandler.getInstance().disableAutoSave().use {
return task()
}
}
inline fun runInAllowSaveMode(isSaveAllowed: Boolean = true, task: () -> Unit) {
val app = ApplicationManagerEx.getApplicationEx()
if (isSaveAllowed == app.isSaveAllowed) {
task()
return
}
app.isSaveAllowed = isSaveAllowed
try {
task()
}
finally {
app.isSaveAllowed = !isSaveAllowed
}
} | apache-2.0 | 21c893c8becf4292d082c4217a34d479 | 35.804082 | 158 | 0.751996 | 4.795745 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/CollectingGroovyInferenceSession.kt | 5 | 7290 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.intentions.style.inference
import com.intellij.openapi.util.RecursionManager
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.*
import com.intellij.psi.impl.source.resolve.graphInference.InferenceBound
import com.intellij.psi.impl.source.resolve.graphInference.InferenceVariable
import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.Position.METHOD_PARAMETER
import org.jetbrains.plugins.groovy.lang.resolve.api.ArgumentMapping
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.PsiCallParameter
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.*
class CollectingGroovyInferenceSession(
private val typeParams: Array<PsiTypeParameter>,
context: PsiElement,
contextSubstitutor: PsiSubstitutor = PsiSubstitutor.EMPTY,
private val proxyMethodMapping: Map<String, GrParameter> = emptyMap(),
private val ignoreClosureArguments: Set<GrParameter> = emptySet(),
private val skipClosureArguments: Boolean = false,
private val expressionFilters: Set<(GrExpression) -> Boolean> = emptySet(),
private val depth: Int = 0
) : GroovyInferenceSession(typeParams, contextSubstitutor, context, skipClosureArguments, expressionFilters) {
companion object {
private const val MAX_DEPTH = 127
private const val OBSERVING_DISTANCE = 10
fun getContextSubstitutor(resolveResult: GroovyMethodResult,
nearestCall: GrCall): PsiSubstitutor = RecursionManager.doPreventingRecursion(resolveResult, true) {
val collectingSession = CollectingGroovyInferenceSession(nearestCall.parentOfType<GrMethod>()!!.typeParameters, nearestCall)
findExpression(nearestCall)?.let(collectingSession::addExpression)
collectingSession.inferSubst(resolveResult)
} ?: PsiSubstitutor.EMPTY
}
private fun substituteForeignTypeParameters(type: PsiType?): PsiType? {
return type?.accept(object : PsiTypeMapper() {
override fun visitClassType(classType: PsiClassType): PsiType {
if (classType.isTypeParameter()) {
return myInferenceVariables.find { it.delegate.name == classType.canonicalText }?.type() ?: classType
}
else {
return classType
}
}
})
}
override fun addConstraint(constraint: ConstraintFormula?) {
if (constraint is MethodCallConstraint) {
val method = constraint.result.candidate?.method ?: return
if (method.returnTypeElement == null) {
return super.addConstraint(MethodCallConstraint(null, constraint.result, constraint.context))
}
}
return super.addConstraint(constraint)
}
override fun substituteWithInferenceVariables(type: PsiType?): PsiType? =
substituteForeignTypeParameters(super.substituteWithInferenceVariables(type))
override fun inferSubst(result: GroovyResolveResult): PsiSubstitutor {
repeatInferencePhases()
val nested = findSession(result) ?: return PsiSubstitutor.EMPTY
for (param in typeParams) {
nested.getInferenceVariable(substituteWithInferenceVariables(param.type())).instantiation = param.type()
}
return nested.result()
}
override fun startNestedSession(params: Array<PsiTypeParameter>,
siteSubstitutor: PsiSubstitutor,
context: PsiElement,
result: GroovyResolveResult,
f: (GroovyInferenceSession) -> Unit) {
if (depth >= MAX_DEPTH) {
var place = context
repeat(OBSERVING_DISTANCE) {
place = place.parent ?: place
}
throw AssertionError("Inference process has gone too deep on ${context.text} in ${place.text}")
}
val nestedSession = CollectingGroovyInferenceSession(params, context, siteSubstitutor, proxyMethodMapping, ignoreClosureArguments,
skipClosureArguments, expressionFilters, depth + 1)
nestedSession.propagateVariables(this)
f(nestedSession)
mirrorInnerVariables(nestedSession)
nestedSessions[result] = nestedSession
this.propagateVariables(nestedSession)
for ((vars, rightType) in nestedSession.myIncorporationPhase.captures) {
this.myIncorporationPhase.addCapture(vars, rightType)
}
}
private fun mirrorInnerVariables(session: CollectingGroovyInferenceSession) {
for (variable in session.inferenceVariables) {
if (variable in this.inferenceVariables) {
mirrorBound(variable, InferenceBound.LOWER, session)
mirrorBound(variable, InferenceBound.EQ, session)
mirrorBound(variable, InferenceBound.UPPER, session)
}
}
}
private fun mirrorBound(outerVariable: InferenceVariable, bound: InferenceBound, session: CollectingGroovyInferenceSession) {
for (boundType in outerVariable.getBounds(bound)) {
val innerVariable = session.getInferenceVariable(boundType)?.takeIf { it !in this.inferenceVariables } ?: continue
InferenceVariable.addBound(innerVariable.type(), outerVariable.type(), negateInferenceBound(bound), session)
}
}
private fun negateInferenceBound(bound: InferenceBound): InferenceBound =
when (bound) {
InferenceBound.LOWER -> InferenceBound.UPPER
InferenceBound.EQ -> InferenceBound.EQ
InferenceBound.UPPER -> InferenceBound.LOWER
}
override fun initArgumentConstraints(mapping: ArgumentMapping<PsiCallParameter>?, inferenceSubstitutor: PsiSubstitutor) {
if (mapping == null) return
val substitutor = inferenceSubstitutor.putAll(inferenceSubstitution)
for ((expectedType, argument) in mapping.expectedTypes) {
val parameter = mapping.targetParameter(argument)?.psi
if (proxyMethodMapping[parameter?.name] in ignoreClosureArguments && argument.type.isClosureTypeDeep()) {
continue
}
val resultingParameter = substituteWithInferenceVariables(proxyMethodMapping[parameter?.name]?.type ?: expectedType)
if (argument is ExpressionArgument) {
val leftType = substitutor.substitute(contextSubstitutor.substitute(resultingParameter))
addConstraint(ExpressionConstraint(ExpectedType(leftType, METHOD_PARAMETER), argument.expression))
}
else {
val type = argument.type
if (type != null) {
addConstraint(TypeConstraint(substitutor.substitute(resultingParameter), type, context))
}
}
}
}
}
| apache-2.0 | adf42fae420d89fea28e946120e944b0 | 46.960526 | 140 | 0.742112 | 4.879518 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemsTreeVisitor.kt | 10 | 2078 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.FileProblem
import com.intellij.analysis.problemsView.Problem
import com.intellij.openapi.vfs.VfsUtil.isAncestor
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.tree.TreeVisitor
import com.intellij.util.ui.tree.TreeUtil
import javax.swing.tree.TreePath
internal interface ProblemsTreeVisitor : TreeVisitor {
override fun visit(path: TreePath) = when (val node = TreeUtil.getLastUserObject(path)) {
is Root -> visitRoot(node)
is FileNode -> visitFile(node)
is GroupNode -> visitGroup(node)
is ProblemNode -> visitProblem(node)
else -> TreeVisitor.Action.SKIP_CHILDREN
}
fun visitRoot(root: Root) = TreeVisitor.Action.CONTINUE
fun visitFile(node: FileNode): TreeVisitor.Action
fun visitGroup(node: GroupNode) = TreeVisitor.Action.SKIP_CHILDREN
fun visitProblem(node: ProblemNode) = TreeVisitor.Action.SKIP_CHILDREN
}
internal class FileNodeFinder(private val file: VirtualFile) : ProblemsTreeVisitor {
override fun visitFile(node: FileNode) = when {
node.file == file -> TreeVisitor.Action.INTERRUPT
isAncestor(node.file, file, true) -> TreeVisitor.Action.CONTINUE
else -> TreeVisitor.Action.SKIP_CHILDREN
}
}
internal class ProblemNodeFinder(private val problem: Problem) : ProblemsTreeVisitor {
override fun visitFile(node: FileNode) = when {
problem !is FileProblem -> TreeVisitor.Action.SKIP_CHILDREN
isAncestor(node.file, problem.file, false) -> TreeVisitor.Action.CONTINUE
else -> TreeVisitor.Action.SKIP_CHILDREN
}
override fun visitGroup(node: GroupNode) = when (node.group) {
problem.group -> TreeVisitor.Action.CONTINUE
else -> TreeVisitor.Action.SKIP_CHILDREN
}
override fun visitProblem(node: ProblemNode) = when (node.problem) {
problem -> TreeVisitor.Action.INTERRUPT
else -> TreeVisitor.Action.SKIP_CHILDREN
}
}
| apache-2.0 | 222ea2404d0987082169d86cb672da7d | 38.207547 | 140 | 0.763234 | 4.106719 | false | false | false | false |
mr-max/anko | dsl/testData/functional/sdk21/PropertyTest.kt | 3 | 4178 | public var android.widget.ImageView.imageURI: android.net.Uri?
get() = throw AnkoException("'android.widget.ImageView.imageURI' property does not have a getter")
set(v) = setImageURI(v)
public var android.widget.ImageView.imageBitmap: android.graphics.Bitmap?
get() = throw AnkoException("'android.widget.ImageView.imageBitmap' property does not have a getter")
set(v) = setImageBitmap(v)
public var android.widget.TextView.enabled: Boolean
get() = throw AnkoException("'android.widget.TextView.enabled' property does not have a getter")
set(v) = setEnabled(v)
public var android.widget.TextView.textColor: Int
get() = throw AnkoException("'android.widget.TextView.textColor' property does not have a getter")
set(v) = setTextColor(v)
public var android.widget.TextView.hintTextColor: Int
get() = throw AnkoException("'android.widget.TextView.hintTextColor' property does not have a getter")
set(v) = setHintTextColor(v)
public var android.widget.TextView.linkTextColor: Int
get() = throw AnkoException("'android.widget.TextView.linkTextColor' property does not have a getter")
set(v) = setLinkTextColor(v)
public var android.widget.TextView.lines: Int
get() = throw AnkoException("'android.widget.TextView.lines' property does not have a getter")
set(v) = setLines(v)
public var android.widget.TextView.singleLine: Boolean
get() = throw AnkoException("'android.widget.TextView.singleLine' property does not have a getter")
set(v) = setSingleLine(v)
public var android.widget.LinearLayout.gravity: Int
get() = throw AnkoException("'android.widget.LinearLayout.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.Gallery.gravity: Int
get() = throw AnkoException("'android.widget.Gallery.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.AbsListView.selectorResource: Int
get() = throw AnkoException("'android.widget.AbsListView.selectorResource' property does not have a getter")
set(v) = setSelector(v)
public var android.widget.CalendarView.selectedDateVerticalBarResource: Int
get() = throw AnkoException("'android.widget.CalendarView.selectedDateVerticalBarResource' property does not have a getter")
set(v) = setSelectedDateVerticalBar(v)
public var android.widget.CheckedTextView.checkMarkDrawableResource: Int
get() = throw AnkoException("'android.widget.CheckedTextView.checkMarkDrawableResource' property does not have a getter")
set(v) = setCheckMarkDrawable(v)
public var android.widget.TextView.hintResource: Int
get() = throw AnkoException("'android.widget.TextView.hintResource' property does not have a getter")
set(v) = setHint(v)
public var android.widget.TextView.textResource: Int
get() = throw AnkoException("'android.widget.TextView.textResource' property does not have a getter")
set(v) = setText(v)
public var android.widget.Toolbar.logoResource: Int
get() = throw AnkoException("'android.widget.Toolbar.logoResource' property does not have a getter")
set(v) = setLogo(v)
public var android.widget.Toolbar.logoDescriptionResource: Int
get() = throw AnkoException("'android.widget.Toolbar.logoDescriptionResource' property does not have a getter")
set(v) = setLogoDescription(v)
public var android.widget.Toolbar.navigationContentDescriptionResource: Int
get() = throw AnkoException("'android.widget.Toolbar.navigationContentDescriptionResource' property does not have a getter")
set(v) = setNavigationContentDescription(v)
public var android.widget.Toolbar.navigationIconResource: Int
get() = throw AnkoException("'android.widget.Toolbar.navigationIconResource' property does not have a getter")
set(v) = setNavigationIcon(v)
public var android.widget.Toolbar.subtitleResource: Int
get() = throw AnkoException("'android.widget.Toolbar.subtitleResource' property does not have a getter")
set(v) = setSubtitle(v)
public var android.widget.Toolbar.titleResource: Int
get() = throw AnkoException("'android.widget.Toolbar.titleResource' property does not have a getter")
set(v) = setTitle(v) | apache-2.0 | 01ddb2c1310c8ceecae075b66d8e3046 | 49.349398 | 128 | 0.762805 | 4.056311 | false | false | false | false |
Coding/Coding-Android | push-coding/src/main/java/net/coding/program/push/CodingPush.kt | 1 | 2184 | package net.coding.program.push
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import net.coding.program.push.huawei.HuaweiPush
import net.coding.program.push.xiaomi.CommonPushClick
import net.coding.program.push.xiaomi.EventUnbindToken
import net.coding.program.push.xiaomi.PushAction
import net.coding.program.push.xiaomi.XiaomiPush
import org.greenrobot.eventbus.EventBus
/**
* Created by chenchao on 2017/11/2.
*/
object CodingPush {
// private var context: Context? = null
internal var pushAction: PushAction? = null
internal var usePush: Boolean = false // 企业版不使用,用户在设置里面设置了不使用也不启用
internal var clickPush: CommonPushClick? = null
fun initApplication(context: Context, clickPushAction: CommonPushClick) {
this.clickPush = clickPushAction
if (Rom.isEmui()) {
Log.d(PushAction.TAG, "use huawei push")
HuaweiPush.initApplication(clickPushAction)
} else { // default device use xiaomi push
if (pushAction == null) {
pushAction = XiaomiPush()
}
if (pushAction!!.init(context, clickPushAction)) {
}
}
}
fun onCreate(context: Activity, gk: String) {
if (Rom.isEmui()) {
HuaweiPush.onCreate(context, gk)
}
}
fun onDestroy() {
if (Rom.isEmui()) {
HuaweiPush.onDestroy()
}
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
return if (Rom.isEmui()) {
HuaweiPush.onActivityResult(requestCode, resultCode, data)
} else false
}
fun bindGK(context: Context, gk: String) {
if (Rom.isEmui()) {
HuaweiPush.requestToken()
} else {
pushAction?.bindGK(context, gk)
}
}
fun unbindGK(context: Context, gk: String) {
if (Rom.isEmui()) {
HuaweiPush.deleteToken()
} else {
pushAction?.unbindGK(context, gk)
}
EventBus.getDefault().postSticky(EventUnbindToken())
}
}
| mit | 4a9608ef8e137123fdc28d374bd60950 | 27.105263 | 85 | 0.626873 | 3.821109 | false | false | false | false |
y2k/AppExpress | app/src/main/kotlin/y2k/appexpress/MainActivity.kt | 1 | 4011 | package y2k.appexpress
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
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 android.widget.Button
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import rx.Subscription
import y2k.appexpress.models.App
import y2k.appexpress.models.AppService
import y2k.appexpress.models.CloudStorageService
import y2k.appexpress.models.PackageService
//
// Created by y2k on 1/1/16.
//
class MainActivity : AppCompatActivity() {
val service = AppService(this, PackageService(this), CloudStorageService())
var items = emptyList<App>()
private var subscription: Subscription? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val list = findViewById(R.id.list) as RecyclerView
list.layoutManager = LinearLayoutManager(this)
list.adapter = AppAdapter()
val progress = findViewById(R.id.progress)
list.alpha = 0f
subscription = service
.getApps()
.subscribe({
items = it
list.adapter.notifyDataSetChanged()
progress.animate().alpha(0f)
list.animate().alpha(1f)
}, {
it.printStackTrace()
progress.animate().alpha(0f)
Toast.makeText(this, getString(R.string.error, it), Toast.LENGTH_LONG).show()
})
}
override fun onDestroy() {
super.onDestroy()
subscription?.unsubscribe()
}
inner class AppAdapter : RecyclerView.Adapter<ViewHolder>() {
init {
setHasStableIds(true)
}
override fun getItemCount(): Int {
return items.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder? {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_app, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val app = items[position]
holder.title.text = "${app.info.title} (${app.info.packageName})"
holder.subTitle.text = getString(R.string.version, app.info.serverVersion)
holder.installed.isChecked = app.installed
holder.installed.text =
if (app.installed) getString(R.string.installed_version, app.installedVersion)
else getString(R.string.not_installed)
holder.action.apply {
visibility = View.VISIBLE
isEnabled = true
setOnClickListener(null)
when (app.state) {
App.State.NotInstalled -> {
setText(R.string.install)
setOnClickListener { service.installApp(app) }
}
App.State.HasUpdate -> {
setText(R.string.update)
setOnClickListener { service.installApp(app) }
}
App.State.InProgress -> {
setText(R.string.updating)
isEnabled = false
}
else -> visibility = View.GONE
}
}
}
override fun getItemId(position: Int): Long {
return items[position].id
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val title = view.findViewById(R.id.title) as TextView
val subTitle = view.findViewById(R.id.subTitle) as TextView
val installed = view.findViewById(R.id.installed) as CheckBox
val action = view.findViewById(R.id.action) as Button
}
} | gpl-2.0 | 982adcbddcc2afee438d89fa21c4b0a9 | 32.157025 | 101 | 0.600848 | 4.775 | false | false | false | false |
GoogleContainerTools/google-container-tools-intellij | skaffold/src/main/kotlin/com/google/container/tools/skaffold/SkaffoldLabels.kt | 1 | 1937 | /*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.container.tools.skaffold
import com.google.common.annotations.VisibleForTesting
import com.google.container.tools.core.PluginInfo
import com.intellij.openapi.application.ApplicationInfo
const val IDE_LABEL = "ide"
const val IDE_VERSION_LABEL = "ideVersion"
const val PLUGIN_VERSION_LABEL = "ijPluginVersion"
/**
* Maintains list of Kubernetes labels - string based key-value pairs used by Skaffold to apply
* to all deployments. [getDefaultLabels] function supplies default set of labels used for all
* deployments.
*/
class SkaffoldLabels {
companion object {
/**
* Default set of labels for all Skaffold-based deployments. Includes IDE type and
* version, plugin version.
*/
val defaultLabels: SkaffoldLabels by lazy {
populateDefaultLabels()
}
@VisibleForTesting
fun populateDefaultLabels(): SkaffoldLabels {
return SkaffoldLabels().apply {
this.labels[IDE_LABEL] = PluginInfo.instance.platformPrefix
this.labels[IDE_VERSION_LABEL] = ApplicationInfo.getInstance().getStrictVersion()
this.labels[PLUGIN_VERSION_LABEL] = PluginInfo.instance.pluginVersion
}
}
}
val labels: MutableMap<String, String> = mutableMapOf()
}
| apache-2.0 | cecf48baa5dc9787b840ad08035a6d55 | 35.54717 | 97 | 0.705731 | 4.483796 | false | false | false | false |
egf2-guide/guide-android | app/src/main/kotlin/com/eigengraph/egf2/guide/ui/anko/PostActivityLayout.kt | 1 | 5734 | package com.eigengraph.egf2.guide.ui.anko
import android.graphics.Color
import android.os.Build
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CollapsingToolbarLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.text.InputType
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.eigengraph.egf2.guide.R
import com.eigengraph.egf2.guide.ui.PostActivity
import com.eigengraph.egf2.guide.util.actionBarSize
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.tintedEditText
import org.jetbrains.anko.appcompat.v7.tintedTextView
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.collapsingToolbarLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.support.v4.swipeRefreshLayout
class PostActivityLayout : IActivityLayout {
override fun bind(activity: AppCompatActivity): View = activity.UI {
var collapsingToolbar: CollapsingToolbarLayout? = null
var toolbar: Toolbar? = null
val p8 = dip(8)
val p48 = dip(48)
coordinatorLayout {
fitsSystemWindows = true
appBarLayout {
fitsSystemWindows = true
collapsingToolbar = collapsingToolbarLayout {
fitsSystemWindows = true
expandedTitleMarginStart = p48
expandedTitleMarginEnd = p48
setContentScrimResource(R.color.colorPrimary)
(activity as PostActivity).imageView = imageView {
fitsSystemWindows = true
id = R.id.post_item_image
scaleType = ImageView.ScaleType.CENTER_CROP
layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams = CollapsingToolbarLayout.LayoutParams(layoutParams as FrameLayout.LayoutParams)
(layoutParams as CollapsingToolbarLayout.LayoutParams).collapseMode = CollapsingToolbarLayout.LayoutParams.COLLAPSE_MODE_PARALLAX
}
toolbar = toolbar(R.style.AppTheme_AppBarOverlay) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) elevation = 4f
activity.setSupportActionBar(this)
activity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
activity.supportActionBar?.title = ""
layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, actionBarSize())
layoutParams = CollapsingToolbarLayout.LayoutParams(layoutParams as FrameLayout.LayoutParams)
(layoutParams as CollapsingToolbarLayout.LayoutParams).collapseMode = CollapsingToolbarLayout.LayoutParams.COLLAPSE_MODE_PIN
}
}.lparams(matchParent, matchParent)
}.lparams(matchParent, dip(250))
verticalLayout {
verticalLayout {
backgroundColor = Color.WHITE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) elevation = 4f
(activity as PostActivity).author = tintedTextView {
id = R.id.post_item_creator
topPadding = p8
leftPadding = p8
rightPadding = p8
textSize = 12f
}.lparams(width = matchParent, height = wrapContent)
linearLayout {
orientation = LinearLayout.HORIZONTAL
(activity as PostActivity).text = tintedEditText {
id = R.id.post_item_text
leftPadding = p8
rightPadding = p8
bottomPadding = p8
textSize = 16f
inputType = InputType.TYPE_NULL
//inputType = InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE or InputType.TYPE_TEXT_FLAG_MULTI_LINE or InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE
imeOptions = EditorInfo.IME_FLAG_NO_ENTER_ACTION
singleLine = false
background = null
}.lparams(width = matchParent, height = wrapContent) { weight = 1f }
(activity as PostActivity).btnEdit = imageButton {
imageResource = R.drawable.border_color
visibility = View.GONE
}
}.lparams(width = matchParent, height = wrapContent)
}
(activity as PostActivity).swipe = swipeRefreshLayout {
(activity as PostActivity).list = recyclerView {
clipToPadding = true
layoutManager = LinearLayoutManager(ctx, LinearLayoutManager.VERTICAL, false)
bottomPadding = p48
addOnScrollListener((activity as PostActivity).scrollListener)
}.lparams(matchParent, wrapContent) {
//weight = 1f
}
}
}.lparams(width = matchParent, height = matchParent) {
behavior = AppBarLayout.ScrollingViewBehavior()
}
linearLayout {
orientation = LinearLayout.HORIZONTAL
backgroundColor = Color.WHITE
gravity = Gravity.CENTER
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) elevation = 4f
(activity as PostActivity).message = tintedEditText {
hint = "Message"
leftPadding = p8
rightPadding = p8
}.lparams(matchParent, wrapContent) {
weight = 1f
}
(activity as PostActivity).send = imageButton {
imageResource = R.drawable.send
onClick { (activity as PostActivity).sendMessage() }
}.lparams(p48, p48)
}.lparams(width = matchParent, height = wrapContent) {
gravity = Gravity.BOTTOM
}
}
//(collapsingToolbar?.layoutParams as AppBarLayout.LayoutParams).scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED
(collapsingToolbar?.layoutParams as AppBarLayout.LayoutParams).scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
}.view
override fun unbind(activity: AppCompatActivity) {
}
} | mit | 5bb3857366a729beade55a524c687895 | 38.013605 | 187 | 0.749215 | 4.250556 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/settings/preference/SoftButtonActionPreference.kt | 1 | 1139 | package jp.hazuki.yuzubrowser.legacy.settings.preference
import android.content.Context
import android.util.AttributeSet
import androidx.preference.Preference
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.view.SoftButtonActionActivity
class SoftButtonActionPreference(context: Context, attrs: AttributeSet?) : Preference(context, attrs) {
private val actionId: Int
private val actionType: Int
private val title: String
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.ActionListPreference)
actionType = a.getInt(R.styleable.ActionListPreference_actionGroup, 0)
actionId = a.getInt(R.styleable.ActionListPreference_actionId, 0)
title = a.getString(R.styleable.ActionListPreference_android_title)!!
require(actionType != 0) { "mActionType is zero" }
require(actionId != 0) { "actionId is zero" }
a.recycle()
}
override fun onClick() {
super.onClick()
val intent = SoftButtonActionActivity.createIntent(context, title, actionType, actionId, 0)
context.startActivity(intent)
}
}
| apache-2.0 | 44681a2319205cc53b040f5790d2668b | 36.966667 | 103 | 0.731343 | 4.449219 | false | false | false | false |
Adven27/Exam | exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/builder/DataSetBuilder.kt | 1 | 3252 | package io.github.adven27.concordion.extensions.exam.db.builder
import org.dbunit.dataset.CachedDataSet
import org.dbunit.dataset.IDataSet
import org.dbunit.dataset.ITableMetaData
import org.dbunit.dataset.stream.BufferedConsumer
import org.dbunit.dataset.stream.IDataSetConsumer
import java.util.HashMap
@Suppress("TooManyFunctions")
class DataSetBuilder(private val stringPolicy: IStringPolicy = CaseInsensitiveStringPolicy()) : IDataSetManipulator {
private var dataSet = CachedDataSet()
private var consumer: IDataSetConsumer = BufferedConsumer(dataSet)
private val tableNameToMetaData = HashMap<String, TableMetaDataBuilder>()
private var currentTableName: String? = null
init {
consumer.startDataSet()
}
fun newRowTo(tableName: String): DataRowBuilder {
return DataRowBuilder(this, tableName)
}
fun build(): IDataSet {
endTableIfNecessary()
consumer.endDataSet()
return dataSet
}
/**
* {@inheritDoc}
*/
override fun add(row: BasicDataRowBuilder): DataSetBuilder {
row.fillUndefinedColumns()
notifyConsumer(extractValues(row, updateTableMetaData(row)))
return this
}
private fun extractValues(row: BasicDataRowBuilder, metaData: ITableMetaData): Array<Any?> =
row.values(metaData.columns)
private fun notifyConsumer(values: Array<Any?>) = consumer.row(values)
private fun updateTableMetaData(row: BasicDataRowBuilder): ITableMetaData {
val builder = metaDataBuilderFor(row.tableName)
val previousNumberOfColumns = builder.numberOfColumns()
val metaData = builder.with(row.toMetaData()).build()
val newNumberOfColumns = metaData.columns.size
val addedNewColumn = newNumberOfColumns > previousNumberOfColumns
handleTable(metaData, addedNewColumn)
return metaData
}
private fun handleTable(metaData: ITableMetaData, addedNewColumn: Boolean) {
when {
isNewTable(metaData.tableName) -> {
endTableIfNecessary()
startTable(metaData)
}
addedNewColumn -> startTable(metaData)
}
}
private fun startTable(metaData: ITableMetaData) {
currentTableName = metaData.tableName
consumer.startTable(metaData)
}
private fun endTable() {
consumer.endTable()
currentTableName = null
}
private fun endTableIfNecessary() {
if (hasCurrentTable()) {
endTable()
}
}
private fun hasCurrentTable() = currentTableName != null
private fun isNewTable(tableName: String) =
!hasCurrentTable() || !stringPolicy.areEqual(currentTableName!!, tableName)
private fun metaDataBuilderFor(tableName: String): TableMetaDataBuilder = tableNameToMetaData.getOrPut(
stringPolicy.toKey(tableName),
{ createNewTableMetaDataBuilder(tableName) }
)
private fun createNewTableMetaDataBuilder(tableName: String) = TableMetaDataBuilder(tableName, stringPolicy)
}
interface IDataSetManipulator {
/**
* Added a row so that a Dataset can be manipulated or created.
* @param row
*/
fun add(row: BasicDataRowBuilder): DataSetBuilder
}
| mit | 48ec117dcaae6fdf468096961710da10 | 30.269231 | 117 | 0.695572 | 4.645714 | false | false | false | false |
luhaoaimama1/JavaZone | JavaTest_Zone/src/算法/算法书籍/压缩/Huffman.kt | 1 | 6036 | package 算法.算法书籍.压缩
import edu.princeton.cs.algs4.MinPQ
import java.io.*
/**
* tips: 这里面注意的点
* 因为是压缩是读取两次。所以你的关闭流后重新打开流不然 你读取的值 直接是结尾 更好的办法是用数组装下 那么第二次就不用读取了 但是这样会占用大量内存 如果一个很大的东西这就不行了 。所以还是这样写把
*
* 这里面写的全是位 如果你用byte就会导致缓存失败
*/
class Huffman {
companion object {
@JvmStatic
fun main(args: Array<String>) {
Huffman().compress()
Huffman().unCompress()
}
}
val source = File(".", "${s}a.jpg")
val compress = File(".", "${s}a-huffman-compress.jpg")
val uncompress = File(".", "${s}a-huffman-uncompress.jpg")
private val R = 256
fun unCompress() {
val inbs = BufferedInputStream(FileInputStream(compress))
val outbs = BufferedOutputStream(FileOutputStream(uncompress))
//读取霍夫曼单词查找树
val root = readTree(inbs)
println(root)
//读取byte频率
val freq = Integer.parseInt(inbs.readBit(16), 2)
var node = root
//循环频率 根据霍夫曼编码 在 霍夫曼单词树中查找值。查到了 回到root
for (i in 0 until freq) {
var value = 0
while (inbs.readBit().apply {
value = this
} != -1) {
node = if (value == 0) node.left!!
else node.right!!
if (node.byteValue != -1) {
outbs.writeBit(node.byteValue, 8)
node = root
break
}
}
}
outbs.writeBitFlush()
outbs.close()
}
fun compress() {
val freqs = IntArray(R)
//读取一遍 记录每个byte 的频率
var inbs = BufferedInputStream(FileInputStream(source))
var byte = 0
while (inbs.read().apply {
byte = this
} != -1) {
freqs[byte] = freqs[byte] + 1
}
inbs.close()
inbs = BufferedInputStream(FileInputStream(source))
//构建霍夫曼 单词查找树
val root = buildTree(freqs)
//构建个字典(数组也行 key就是下标) key byte,value是霍夫曼编码 (value我认为是"字符串比较好" 因为要写入不同的bit如果用byte活int记录的话还得记录几个bit)。 就是从上到下遍历。直到叶节点结束
val st = Array<String>(R) { "" }
buildMap(root, "", st)
val outbs = BufferedOutputStream(FileOutputStream(compress))
// 写入霍夫曼单词查找树
writeTree(root, outbs)
//写入频率
outbs.writeBit(root.freq, 16)
//读取 byte 根据字典查到 霍夫曼编码 写入
while (inbs.read().apply {
byte = this
} != -1) {
val s = st[byte]
for (i in 0..s.lastIndex) {
outbs.writeBit(s[i] == '1')
}
}
outbs.writeBitFlush() //防止最后一个bit缓存丢失
outbs.close()
}
//从上到下 从左到右读读 读到叶子节点的话 把映射码写入。不是叶子节点的话。继续读
fun readTree(ins: BufferedInputStream): Node {
val value = ins.readBit()
if (value == 1) return Node(0, Integer.parseInt(ins.readBit(8), 2), null, null)
return Node(0, -1, readTree(ins), readTree(ins))
}
//从上到下 从左到右 写入。 如果是叶子节点写入1
fun writeTree(node: Node, bos: BufferedOutputStream) {
if (node.isLeaf()) {
bos.writeBit(true)
bos.writeBit(node.byteValue, 8)
} else {
bos.writeBit(false)
node.left?.let {
writeTree(it, bos)
}
node.right?.let {
writeTree(it, bos)
}
}
}
//构建个数组 key byte,value是霍夫曼编码 (value我认为是"字符串比较好" 因为要写入不同的bit如果用byte活int记录的话还得记录几个bit)。 就是从上到下遍历。直到叶节点结束
fun buildMap(node: Node, s: String, st: Array<String>) {
if (node.isLeaf()) {
st[node.byteValue] = s
return
}
node.left?.let {
buildMap(it, s + "0", st)
}
node.right?.let {
buildMap(it, s + "1", st)
}
}
/**
* @return 返回 霍夫曼 单词查找树 的根节点
*/
fun buildTree(freq: IntArray): Node {
val pq = MinPQ<Node>(object : Comparator<Node> {
override fun compare(o1: Node?, o2: Node?): Int {
val v1 = o1?.byteValue ?: 0
val v2 = o2?.byteValue ?: 0
return v1 - v2
}
})
//对所有字符 建立节点 并加入到 最小队列中
for (i in 0 until R) {
if (freq[i] != 0) {
pq.insert(Node(freq[i], i, null, null))
}
}
//取出两个最小的 建立一个空的父亲(连接到这两最小的 并且频率为子的和)。把这个节点放入队列中 。循环到完毕即可
while (pq.size() > 1) {
val min1 = pq.delMin()
val min2 = pq.delMin()
pq.insert(Node(min1.freq + min2.freq, -1, min1, min2))
}
return pq.delMin()
}
inner class Node {
var freq = 0
var byteValue = -1 //对应的 byte值
var left: Node? = null
var right: Node? = null
constructor(freq: Int, byteValue: Int, left: Node?, right: Node?) {
this.freq = freq
this.byteValue = byteValue
this.left = left
this.right = right
}
fun isLeaf() = left == null && right == null
}
} | epl-1.0 | 0473a4b0b5f71b920d9702214d808e06 | 26.938889 | 125 | 0.504375 | 3.164254 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/resource/RestResourceCalls.kt | 1 | 19989 | package org.evomaster.core.problem.rest.resource
import org.evomaster.core.Lazy
import org.evomaster.core.database.DbAction
import org.evomaster.core.database.DbActionUtils
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.enterprise.EnterpriseActionGroup
import org.evomaster.core.problem.external.service.ApiExternalServiceAction
import org.evomaster.core.problem.util.ParamUtil
import org.evomaster.core.problem.util.RestResourceTemplateHandler
import org.evomaster.core.problem.util.BindingBuilder
import org.evomaster.core.problem.util.inference.SimpleDeriveResourceBinding
import org.evomaster.core.search.*
import org.evomaster.core.search.Individual.GeneFilter
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.service.Randomness
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* the class is used to structure actions regarding resources.
* @property template is a resource template, e.g., POST-GET
* @property node is a resource node which creates [this] call. Note that [node] could null if it is not created by [ResourceSampler]
* @property mainActions is a sequence of actions in the [RestResourceCalls] that follows [template]
* @property dbActions are used to initialize data for rest actions, either select from db or insert new data into db
* @param withBinding specifies whether to build binding between rest genes
* @param randomness is required when [withBinding] is true
*
*/
class RestResourceCalls(
val template: CallsTemplate? = null,
val node: RestResourceNode? = null,
children: MutableList<out ActionComponent>,
withBinding: Boolean = false,
randomness: Randomness? = null
) : ActionTree(
children,
{ k -> DbAction::class.java.isAssignableFrom(k) || EnterpriseActionGroup::class.java.isAssignableFrom(k) }
) {
constructor(
template: CallsTemplate? = null, node: RestResourceNode? = null, actions: List<RestCallAction>,
dbActions: List<DbAction>, withBinding: Boolean = false, randomness: Randomness? = null
) :
this(template, node,
mutableListOf<ActionComponent>().apply {
addAll(dbActions);
addAll(actions.map { a -> EnterpriseActionGroup(mutableListOf(a), RestCallAction::class.java) })
}, withBinding, randomness)
companion object {
private val log: Logger = LoggerFactory.getLogger(RestResourceCalls::class.java)
}
init {
if (withBinding) {
Lazy.assert { randomness != null }
buildBindingGene(randomness)
}
}
override val children: MutableList<ActionComponent>
get() = super.children as MutableList<ActionComponent>
fun doInitialize(randomness: Randomness? = null) {
children.flatMap { it.flatten() }.forEach { it.doInitialize(randomness) }
}
private val mainActions: List<RestCallAction>
get() {
return children.flatMap { it.flatten() }.filterIsInstance<RestCallAction>()
}
private val dbActions: List<DbAction>
get() {
return children.flatMap { it.flatten() }.filterIsInstance<DbAction>()
}
private val externalServiceActions: List<ApiExternalServiceAction>
get() {
return children.flatMap { it.flatten() }.filterIsInstance<ApiExternalServiceAction>()
}
/**
* build gene binding among rest actions, ie, [mainActions]
* e.g., a sequence of actions
* 0, POST /A
* 1, POST /A/{a}
* 2, POST /A/{a}/B
* 3, GET /A/{a}/B/{b}
* (0-2) actions bind values based on the action at 3
*/
private fun buildBindingGene(randomness: Randomness?) {
if (mainActions.size == 1) return
(0 until mainActions.size - 1).forEach {
mainActions[it].bindBasedOn(mainActions.last(), randomness)
}
}
/**
* presents whether the SQL is
* 1) for creating missing resources for POST or
* 2) POST-POST
*/
var is2POST = false
/**
* represents the resource preparation status
*/
var status = ResourceStatus.NOT_FOUND
/**
* whether the call can be deleted during structure mutation
*/
var isDeletable = true
/**
* this call should be before [shouldBefore]
*/
val shouldBefore = mutableListOf<String>()
/**
* the dependency is built between [this] and [depends] in this individual
* the dependency here means that there exist binding genes among the calls.
*/
val depends = mutableSetOf<String>()
final override fun copy(): RestResourceCalls {
val copy = super.copy()
if (copy !is RestResourceCalls)
throw IllegalStateException("mismatched type: the type should be RestResourceCall, but it is ${this::class.java.simpleName}")
return copy
}
override fun copyContent(): RestResourceCalls {
val copy = RestResourceCalls(
template,
node,
children.map { it.copy() as ActionComponent }.toMutableList(),
withBinding = false, randomness = null
)
copy.isDeletable = isDeletable
copy.shouldBefore.addAll(shouldBefore)
copy.is2POST = is2POST
copy.depends.addAll(depends)
return copy
}
/**
* @return genes that represents this resource, i.e., longest action in this resource call
*/
fun seeGenes(filter: GeneFilter = GeneFilter.NO_SQL): List<out Gene> {
return when (filter) {
GeneFilter.NO_SQL -> mainActions.flatMap(RestCallAction::seeTopGenes)
GeneFilter.ONLY_SQL -> seeMutableSQLGenes()
//FIXME would need to return External ones as well
GeneFilter.ALL -> seeMutableSQLGenes().plus(mainActions.flatMap(RestCallAction::seeTopGenes))
else -> throw IllegalArgumentException("there is no initialization in an ResourceCall")
}
}
/**
* @return actions with specified action [filter]
*/
fun seeActions(filter: ActionFilter): List<out Action> {
return when (filter) {
ActionFilter.ALL -> dbActions.plus(externalServiceActions).plus(mainActions)
ActionFilter.INIT, ActionFilter.ONLY_SQL -> dbActions
ActionFilter.NO_INIT, ActionFilter.NO_SQL -> externalServiceActions.plus(mainActions)
ActionFilter.MAIN_EXECUTABLE -> mainActions
ActionFilter.ONLY_EXTERNAL_SERVICE -> externalServiceActions
ActionFilter.NO_EXTERNAL_SERVICE -> dbActions.plus(mainActions)
}
}
/**
* @return size of action with specified action [filter]
*/
fun seeActionSize(filter: ActionFilter): Int {
return seeActions(filter).size
}
/**
* reset dbactions with [actions]
*/
fun resetDbAction(actions: List<DbAction>) {
killChildren { it is DbAction }
/*
keep db action in the front of rest resource call,
otherwise it might be a problem to get corresponding action result
*/
addChildren(0, actions)
(getRoot() as? RestIndividual)?.cleanBrokenBindingReference()
}
/**
* remove dbaction based on [removePredict]
*/
fun removeDbActionIf(removePredict: (DbAction) -> Boolean) {
val removed = dbActions.filter { removePredict(it) }
resetDbAction(removed)
}
private fun removeDbActions(remove: List<DbAction>) {
val removedGenes = remove.flatMap { it.seeTopGenes() }.flatMap { it.flatView() }
killChildren(remove)
(dbActions.plus(mainActions).flatMap { it.seeTopGenes() }).flatMap { it.flatView() }.filter { it.isBoundGene() }
.forEach {
it.cleanRemovedGenes(removedGenes)
}
}
/**
* @return the mutable SQL genes and they do not bind with any of Rest Actions
*
* */
private fun seeMutableSQLGenes(): List<out Gene> = getResourceNode()
.getMutableSQLGenes(dbActions, getRestTemplate(), is2POST)
/**
* bind this with other [relatedResourceCalls]
* @param relatedResourceCalls to be bound with [this]
* @param doRemoveDuplicatedTable specifies whether to remove duplicated db actions on this
* e.g., for resource C, table C is created, in addition, A and B are also created since B refers to them,
* in this case, if the following handling is related to A and B, we do not further create A and B once [doRemoveDuplicatedTable] is true
*/
fun bindWithOtherRestResourceCalls(
relatedResourceCalls: MutableList<RestResourceCalls>,
cluster: ResourceCluster,
doRemoveDuplicatedTable: Boolean,
randomness: Randomness?
) {
// handling [this.dbActions]
if (this.dbActions.isNotEmpty() && doRemoveDuplicatedTable) {
removeDuplicatedDbActions(relatedResourceCalls, cluster, doRemoveDuplicatedTable)
}
// bind with rest actions
mainActions.forEach { current ->
relatedResourceCalls.forEach { call ->
call.seeActions(ActionFilter.NO_SQL).forEach { previous ->
if (previous is RestCallAction) {
val dependent = current.bindBasedOn(previous, randomness = randomness)
if (dependent) {
setDependentCall(call)
}
}
}
}
}
// synchronize values based on rest actions
syncValues(true)
}
/*
verify the binding which is only useful for debugging
//TODO shouldn't this called as an assertion in some test cases???
*/
fun verifyBindingGenes(other: List<RestResourceCalls>): Boolean {
val currentAll = seeActions(ActionFilter.ALL).flatMap { it.seeTopGenes() }.flatMap { it.flatView() }
val otherAll =
other.flatMap { it.seeActions(ActionFilter.ALL) }.flatMap { it.seeTopGenes() }.flatMap { it.flatView() }
currentAll.forEach { g ->
val root = g.getRoot()
val ok = root is RestResourceCalls || root is RestIndividual
if (!ok)
return false
if (g.isBoundGene()) {
val inside = g.bindingGeneIsSubsetOf(currentAll.plus(otherAll))
if (!inside)
return false
}
}
return true
}
fun repairFK(previous: List<DbAction>) {
if (!DbActionUtils.verifyForeignKeys(previous.plus(dbActions))) {
val current = previous.toMutableList()
dbActions.forEach { d ->
val ok = DbActionUtils.repairFk(d, current)
if (!ok.first) {
throw IllegalStateException("fail to find pk in the previous dbactions")
}
current.add(d)
}
Lazy.assert { DbActionUtils.verifyForeignKeys(previous.plus(dbActions)) }
}
}
/**
* synchronize values in this call
* @param withRest specifies whether to synchronize values based on rest actions ([withRest] is true) or db actions ([withRest] is false)
*/
private fun syncValues(withRest: Boolean = true) {
(if (withRest) mainActions else dbActions).forEach {
it.seeTopGenes().flatMap { i -> i.flatView() }.forEach { g ->
g.syncBindingGenesBasedOnThis()
}
}
}
private fun removeDuplicatedDbActions(
calls: List<RestResourceCalls>,
cluster: ResourceCluster,
doRemoveDuplicatedTable: Boolean
) {
val dbRelatedToTables =
calls.flatMap { it.seeActions(ActionFilter.ONLY_SQL) as List<DbAction> }.map { it.table.name }.toHashSet()
val dbactionInOtherCalls = calls.flatMap { it.seeActions(ActionFilter.ONLY_SQL) as List<DbAction> }
// remove duplicated dbactions
if (doRemoveDuplicatedTable) {
val dbActionsToRemove = this.dbActions.filter { dbRelatedToTables.contains(it.table.name) }
if (dbActionsToRemove.isNotEmpty()) {
removeDbActions(dbActionsToRemove)
val frontDbActions = dbactionInOtherCalls.toMutableList()
this.dbActions
.forEach { db ->
// fix fk with front dbactions
val ok = DbActionUtils.repairFk(db, frontDbActions)
if (!ok.first) {
throw IllegalStateException("cannot fix the fk of ${db.getResolvedName()}")
}
ok.second?.forEach { ddb ->
val frontCall = calls.find { it.seeActions(ActionFilter.ONLY_SQL).contains(ddb) }
if (frontCall != null){
setDependentCall(frontCall)
// handling rest action binding with the fixed db which is in a different call
if (dbactionInOtherCalls.contains(ddb)) {
bindRestActionBasedOnDbActions(listOf(ddb), cluster, false, false)
}
}else{
Lazy.assert { dbActions.contains(ddb) }
}
}
frontDbActions.add(db)
}
}
}
}
private fun setDependentCall(calls: RestResourceCalls) {
calls.isDeletable = false
calls.shouldBefore.add(getResourceNodeKey())
depends.add(getResourceNodeKey())
}
/**
* init dbactions for [this] RestResourceCall which would build binding relationship with its rest [mainActions].
* @param dbActions specified the dbactions to be initialized for this call
* @param cluster specified the resource cluster
* @param forceBindParamBasedOnDB specified whether to force to bind values of params in rest actions based on dbactions
* @param dbRemovedDueToRepair specified whether any db action is removed due to repair process.
* Note that dbactions might be truncated in the db repair process, thus the table related to rest actions might be removed.
* @param bindWith specified a list of resource call which might be bound with [this]
*/
fun initDbActions(
dbActions: List<DbAction>,
cluster: ResourceCluster,
forceBindParamBasedOnDB: Boolean,
dbRemovedDueToRepair: Boolean,
bindWith: List<RestResourceCalls>? = null
) {
bindWith?.forEach { p ->
val dependent = p.seeActions(ActionFilter.ONLY_SQL).any { dbActions.contains(it) }
if (dependent) {
setDependentCall(p)
}
}
if (this.dbActions.isNotEmpty()) throw IllegalStateException("dbactions of this RestResourceCall is not empty")
// db action should add in the front of rest actions
addChildren(0, dbActions)
bindRestActionBasedOnDbActions(dbActions, cluster, forceBindParamBasedOnDB, dbRemovedDueToRepair)
}
private fun bindRestActionBasedOnDbActions(
dbActions: List<DbAction>,
cluster: ResourceCluster,
forceBindParamBasedOnDB: Boolean,
dbRemovedDueToRepair: Boolean
) {
val paramInfo = getResourceNode().getPossiblyBoundParams(template!!.template, is2POST)
val paramToTables = SimpleDeriveResourceBinding.generateRelatedTables(paramInfo, this, dbActions)
if (paramToTables.isEmpty()) return
for (restaction in mainActions) {
var list = paramToTables[restaction]
if (list == null) list = paramToTables.filter { restaction.getName() == it.key.getName() }.values.run {
if (this.isEmpty()) null else this.first()
}
if (list != null && list.isNotEmpty()) {
BindingBuilder.bindRestAndDbAction(
restaction,
cluster.getResourceNode(restaction, true)!!,
list,
dbActions,
forceBindParamBasedOnDB,
dbRemovedDueToRepair,
true
)
}
}
}
/**
* build the binding between [this] with other [restResourceCalls]
*/
fun bindRestActionsWith(restResourceCalls: RestResourceCalls, randomness: Randomness?) {
if (restResourceCalls.getResourceNode().path != getResourceNode().path)
throw IllegalArgumentException("target to bind refers to a different resource node, i.e., target (${restResourceCalls.getResourceNode().path}) vs. this (${getResourceNode().path})")
val params = restResourceCalls.mainActions.flatMap { it.parameters }
mainActions.forEach { ac ->
if (ac.parameters.isNotEmpty()) {
ac.bindBasedOn(ac.path, params, randomness)
}
}
}
/**
* removing all binding which refers to [this] RestResourceCalls
*/
fun removeThisFromItsBindingGenes() {
(dbActions.plus(mainActions)).forEach { a ->
a.removeThisFromItsBindingGenes()
}
}
/**
* employing the longest action to represent a group of calls on a resource
*/
private fun longestPath(): RestCallAction {
val candidates = ParamUtil.selectLongestPathAction(mainActions)
return candidates.first()
}
/**
* @return the template of [this] resource handling
*/
fun extractTemplate(): String {
return RestResourceTemplateHandler.getStringTemplateByCalls(this)
}
private fun getParamsInCall(): List<Param> = mainActions.flatMap { it.parameters }
/**
* @return the resolved path of this resource handling based on values of params
*
*/
fun getResolvedKey(): String {
return node?.path?.resolve(getParamsInCall()) ?: throw IllegalStateException("node is null")
}
/**
* @return a path of resource handling
*/
fun getResourceKey(): String {
if (node != null) return getResolvedKey()
if (mainActions.size == 1)
return mainActions.first().path.toString()
throw IllegalArgumentException("there are multiple rest actions in a call, but the call lacks the resource node")
}
/**
* @return the string of template of this resource handling
*/
fun getRestTemplate() = template?.template ?: RestResourceTemplateHandler.getStringTemplateByActions(mainActions)
/**
* @return the resource node of this resource handling
*/
fun getResourceNode(): RestResourceNode =
node ?: throw IllegalArgumentException("the individual does not have resource structure")
/**
* @return the path of resource node of this resource handling
*/
fun getResourceNodeKey(): String = getResourceNode().getName()
/**
* @return whether the resource handling is mutatable
*
* if the action is bounded with existing data from db, it is not mutable
*/
fun isMutable() = dbActions.none {
it.representExistingData
}
}
enum class ResourceStatus(val value: Int) {
CREATED_SQL(2),
/**
* DO NOT require resource
*/
NOT_NEEDED(1),
/**
* resource is created
*/
CREATED_REST(0),
/**
* require resource, but not enough length for post actions
*/
NOT_ENOUGH_LENGTH(-1),
/**
* require resource, but do not find post action
*/
NOT_FOUND(-2),
/**
* require resource, but post action requires another resource which cannot be created
*/
NOT_FOUND_DEPENDENT(-3)
} | lgpl-3.0 | e45842e9afe012ebbf0a27a7fe8e2c97 | 35.881919 | 193 | 0.624493 | 4.800432 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/encoding/ExtendedPaneStringMapperInputStream.kt | 1 | 1120 | package io.oversec.one.crypto.encoding
import android.util.SparseIntArray
import java.io.IOException
import java.io.InputStream
class ExtendedPaneStringMapperInputStream(
private val src: String,
private val reverseMapping: SparseIntArray
) : InputStream() {
private var off = 0
@Throws(IOException::class)
override fun read(): Int {
try {
val cp = src.codePointAt(off)
var res = reverseMapping.get(cp, Integer.MIN_VALUE)
if (res == Integer.MIN_VALUE) {
//this is probably a fill character, just ignore it
off = src.offsetByCodePoints(off, 1)
res = reverseMapping.get(cp, Integer.MIN_VALUE)
if (res == Integer.MIN_VALUE) {
throw UnmappedCodepointException(cp, off)
}
}
off = src.offsetByCodePoints(off, 1)
return res
} catch (ex: StringIndexOutOfBoundsException) {
return -1
}
}
class UnmappedCodepointException(private val mCodepoint: Int, val offset: Int) : IOException()
}
| gpl-3.0 | 6be5abee59c7d45c25b78ed87d159cc0 | 28.473684 | 98 | 0.604464 | 4.462151 | false | false | false | false |
Litote/kmongo | kmongo-rxjava2-core-tests/src/main/kotlin/org/litote/kmongo/rxjava2/KMongoRxBaseTest.kt | 1 | 1817 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo.rxjava2
import com.mongodb.reactivestreams.client.MongoCollection
import de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion
import org.junit.Rule
import org.junit.experimental.categories.Category
import org.litote.kmongo.JacksonMappingCategory
import org.litote.kmongo.KMongoRootTest
import org.litote.kmongo.NativeMappingCategory
import org.litote.kmongo.SerializationMappingCategory
import org.litote.kmongo.defaultMongoTestVersion
import org.litote.kmongo.model.Friend
import kotlin.reflect.KClass
/**
*
*/
@Category(JacksonMappingCategory::class, NativeMappingCategory::class, SerializationMappingCategory::class)
open class KMongoRxBaseTest<T : Any>(mongoServerVersion: IFeatureAwareVersion = defaultMongoTestVersion) :
KMongoRootTest() {
@Suppress("LeakingThis")
@Rule
@JvmField
val rule = RxFlapdoodleRule(getDefaultCollectionClass(), version = mongoServerVersion)
val col by lazy { rule.col }
val database by lazy { rule.database }
inline fun <reified T : Any> getCollection(): MongoCollection<T> = rule.getCollection<T>()
@Suppress("UNCHECKED_CAST")
open fun getDefaultCollectionClass(): KClass<T> = Friend::class as KClass<T>
} | apache-2.0 | c70816ca75722240f31bd8f9c25727a3 | 34.647059 | 107 | 0.776004 | 4.157895 | false | true | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/about/AboutFragment.kt | 1 | 4004 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Thibault Wittemberg <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.about
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import cx.ring.R
import android.view.Menu
import android.view.MenuInflater
import android.content.Intent
import android.net.Uri
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import java.lang.Exception
import com.google.android.material.snackbar.Snackbar
import cx.ring.BuildConfig
import cx.ring.client.HomeActivity
import cx.ring.databinding.FragAboutBinding
class AboutFragment : Fragment() {
private var binding: FragAboutBinding? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragAboutBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setHasOptionsMenu(true)
binding!!.apply {
release.text = getString(R.string.app_release, BuildConfig.VERSION_NAME)
logo.setOnClickListener { openWebsite(getString(R.string.app_website)) }
sflLogo.setOnClickListener { openWebsite(getString(R.string.savoirfairelinux_website)) }
contributeContainer.setOnClickListener { openWebsite(getString(R.string.ring_contribute_website)) }
licenseContainer.setOnClickListener { openWebsite(getString(R.string.gnu_license_website)) }
emailReportContainer.setOnClickListener { sendFeedbackEmail() }
credits.setOnClickListener { creditsClicked() }
}
}
override fun onResume() {
super.onResume()
(requireActivity() as HomeActivity).setToolbarTitle(R.string.menu_item_about)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.clear()
}
private fun sendFeedbackEmail() {
val emailIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + "[email protected]"))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "[" + getText(R.string.app_name) + " Android - " + BuildConfig.VERSION_NAME + "]")
launchSystemIntent(emailIntent, R.string.no_email_app_installed)
}
private fun creditsClicked() {
val dialog: BottomSheetDialogFragment = AboutBottomSheetDialogFragment()
dialog.show(childFragmentManager, dialog.tag)
}
private fun openWebsite(url: String) {
launchSystemIntent(Intent(Intent.ACTION_VIEW, Uri.parse(url)), R.string.no_browser_app_installed)
}
private fun launchSystemIntent(intentToLaunch: Intent, @StringRes missingRes: Int) {
try {
startActivity(intentToLaunch)
} catch (e: Exception) {
val rootView = view
if (rootView != null) {
Snackbar.make(rootView, getText(missingRes), Snackbar.LENGTH_SHORT).show()
}
}
}
} | gpl-3.0 | 67a27ee99d833e9981fc71792298b5d0 | 37.883495 | 133 | 0.709041 | 4.424309 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/speakerdetails/presentationmodel/SpeakerDetailsSessionDelegate.kt | 1 | 2042 | package com.openconference.speakerdetails
import android.support.annotation.DrawableRes
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import butterknife.bindView
import com.hannesdorfmann.adapterdelegates2.AbsListItemAdapterDelegate
import com.openconference.R
import com.openconference.model.Session
import com.openconference.speakerdetails.presentationmodel.SpeakerDetailsItem
import com.openconference.speakerdetails.presentationmodel.SpeakerSessionItem
/**
*
*
* @author Hannes Dorfmann
*/
class SpeakerDetailsSessionDelegate(val inflater: LayoutInflater, val clickListener: (Session) -> Unit) : AbsListItemAdapterDelegate<SpeakerSessionItem, SpeakerDetailsItem, SpeakerDetailsSessionDelegate.SessionViewHolder>() {
override fun isForViewType(item: SpeakerDetailsItem, items: MutableList<SpeakerDetailsItem>?,
position: Int) = item is SpeakerSessionItem
override fun onBindViewHolder(item: SpeakerSessionItem,
viewHolder: SessionViewHolder) {
viewHolder.session = item.session
viewHolder.bind(if (item.showIcon) R.drawable.ic_sessions_details else null,
item.session.title()!!)
}
override fun onCreateViewHolder(parent: ViewGroup): SessionViewHolder =
SessionViewHolder(inflater.inflate(R.layout.item_details_icon_text, parent, false),
clickListener)
class SessionViewHolder(v: View, val clickListener: (Session) -> Unit) : RecyclerView.ViewHolder(
v) {
lateinit var session: Session
init {
v.setOnClickListener { clickListener(session) }
}
val icon by bindView<ImageView>(R.id.icon)
val text by bindView<TextView>(R.id.text)
inline fun bind(@DrawableRes iconRes: Int?, t: String) {
if (iconRes == null) {
icon.visibility = View.INVISIBLE
} else {
icon.setImageDrawable(itemView.resources.getDrawable(iconRes))
}
text.text = t
}
}
} | apache-2.0 | d2661ca492416735f4fa2d987d2fe4c9 | 31.951613 | 225 | 0.763467 | 4.568233 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/testFixtures/kotlin/org/gradle/kotlin/dsl/fixtures/AbstractDslTest.kt | 3 | 2876 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.kotlin.dsl.fixtures
import org.gradle.api.Project
import org.gradle.internal.classpath.ClassPath
import java.io.File
abstract class AbstractDslTest : TestWithTempFiles() {
private
val dslTestFixture: DslTestFixture by lazy {
DslTestFixture(root)
}
protected
val kotlinDslEvalBaseCacheDir: File
get() = dslTestFixture.kotlinDslEvalBaseCacheDir
protected
val kotlinDslEvalBaseTempDir: File
get() = dslTestFixture.kotlinDslEvalBaseTempDir
/**
* Evaluates the given Kotlin [script] against this [Project] writing compiled classes
* to sub-directories of [baseCacheDir] using [scriptCompilationClassPath].
*/
fun Project.eval(
script: String,
baseCacheDir: File = kotlinDslEvalBaseCacheDir,
baseTempDir: File = kotlinDslEvalBaseTempDir,
scriptCompilationClassPath: ClassPath = testRuntimeClassPath,
scriptRuntimeClassPath: ClassPath = ClassPath.EMPTY
) =
dslTestFixture.evalScript(
script,
this,
baseCacheDir,
baseTempDir,
scriptCompilationClassPath,
scriptRuntimeClassPath
)
}
class DslTestFixture(private val testDirectory: File) {
val kotlinDslEvalBaseCacheDir: File by lazy {
testDirectory.resolve("kotlin-dsl-eval-cache").apply {
mkdirs()
}
}
val kotlinDslEvalBaseTempDir: File by lazy {
testDirectory.resolve("kotlin-dsl-eval-temp").apply {
mkdirs()
}
}
/**
* Evaluates the given Kotlin [script] against this [Project] writing compiled classes
* to sub-directories of [baseCacheDir] using [scriptCompilationClassPath].
*/
fun evalScript(
script: String,
target: Any,
baseCacheDir: File = kotlinDslEvalBaseCacheDir,
baseTempDir: File = kotlinDslEvalBaseTempDir,
scriptCompilationClassPath: ClassPath = testRuntimeClassPath,
scriptRuntimeClassPath: ClassPath = ClassPath.EMPTY
) =
eval(
script,
target,
baseCacheDir,
baseTempDir,
scriptCompilationClassPath,
scriptRuntimeClassPath
)
}
| apache-2.0 | d176c1c4dc0a56a8b08ecc80f0733004 | 28.649485 | 90 | 0.671419 | 4.81742 | false | true | false | false |
Maxr1998/MaxLock | app/src/main/java/de/Maxr1998/xposed/maxlock/ui/settings_new/SettingsActivity.kt | 1 | 15596 | /*
* MaxLock, an Xposed applock module for Android
* Copyright (C) 2014-2018 Max Rumpf alias Maxr1998
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Maxr1998.xposed.maxlock.ui.settings_new
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.transition.Fade
import android.transition.TransitionManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER
import android.widget.ProgressBar
import android.widget.Switch
import androidx.activity.viewModels
import androidx.annotation.IntDef
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.Group
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.haibison.android.lockpattern.LockPatternActivity
import de.Maxr1998.modernpreferences.PreferenceScreen
import de.Maxr1998.modernpreferences.PreferencesAdapter
import de.Maxr1998.xposed.maxlock.Common
import de.Maxr1998.xposed.maxlock.Common.*
import de.Maxr1998.xposed.maxlock.R
import de.Maxr1998.xposed.maxlock.ui.SettingsActivity
import de.Maxr1998.xposed.maxlock.ui.lockscreen.LockView
import de.Maxr1998.xposed.maxlock.ui.settings.applist.AppListAdapter
import de.Maxr1998.xposed.maxlock.ui.settings_new.screens.AppListScreen
import de.Maxr1998.xposed.maxlock.util.*
import java.util.*
class SettingsActivity : AppCompatActivity(), AuthenticationSucceededListener, PreferencesAdapter.OnScreenChangeListener {
private val settingsViewModel by viewModels<SettingsViewModel>()
private val originalTitle by lazy { applicationName.toString() }
private val preferencesAdapter get() = settingsViewModel.preferencesAdapter
private val viewRoot by lazyView<ViewGroup>(R.id.content_view_settings)
private var masterSwitch: Switch? = null
private val uiComponents by lazyView<Group>(R.id.ui_components)
private val recyclerView by lazyView<RecyclerView>(android.R.id.list)
private val progress by lazyView<ProgressBar>(android.R.id.progress)
private val lockscreen by lazyView<LockView>(R.id.lockscreen)
private var ctConnection: CustomTabsServiceConnection? = null
private var ctSession: CustomTabsSession? = null
private val devicePolicyManager by lazy { getSystemService<DevicePolicyManager>() }
private val deviceAdmin by lazy { ComponentName(this, SettingsActivity.UninstallProtectionReceiver::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
Util.setTheme(this)
super.onCreate(savedInstanceState)
// Setup UI and Toolbar
setContentView(R.layout.activity_new_settings)
setSupportActionBar(findViewById(R.id.toolbar))
// Setup Preferences
if (recyclerView.adapter == null) {
recyclerView.adapter = preferencesAdapter.apply {
onScreenChangeListener = this@SettingsActivity
restoreAndObserveScrollPosition(recyclerView)
}
}
// Applies the custom screen if needed
applyCurrentCustomScreen()
// Restore state if possible/needed
savedInstanceState?.apply {
// Restore preference adapter state from saved state, if needed
getParcelable<PreferencesAdapter.SavedState>(PREFS_SAVED_STATE)
?.let(preferencesAdapter::loadSavedState)
// Restore screen
if (settingsViewModel.customScreenStack.isEmpty()) {
// TODO: Restore whole stack
when (val screen = getInt(SCREEN_SAVED_STATE)) {
SCREEN_DEFAULT -> return@apply
else -> openCustomScreen(screen)
}
}
}
// Setup event listeners
observePreferenceClicks()
// Initialize custom tabs service
bindCustomTabsService()
}
override fun onStart() {
super.onStart()
if (devicePolicyManager?.isAdminActive(deviceAdmin) == true) {
settingsViewModel.prefUninstall.apply {
titleRes = R.string.pref_uninstall
summaryRes = -1
requestRebind()
}
}
if (settingsViewModel.refreshPrefDonate())
settingsViewModel.prefDonate.requestRebind()
// Show lockscreen if needed
if (settingsViewModel.locked && !prefs.getString(Common.LOCKING_TYPE, "").isNullOrEmpty()) {
uiComponents.isVisible = false
setupWindow(true)
lockscreen.isVisible = true
}
}
private fun setupWindow(showWallpaper: Boolean) {
window.setFlags(if (showWallpaper) FLAG_SHOW_WALLPAPER else 0, FLAG_SHOW_WALLPAPER)
window.statusBarColor = if (showWallpaper) Color.TRANSPARENT else getColorCompat(R.color.primary_red_dark)
if (showWallpaper) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
window.decorView.apply {
systemUiVisibility = systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv()
}
}
applyCustomBackground()
window.navigationBarColor = Color.TRANSPARENT
} else {
withAttrs(android.R.attr.windowBackground, android.R.attr.navigationBarColor) {
val res = getResourceId(0, R.color.windowBackground)
window.setBackgroundDrawableResource(res)
window.navigationBarColor = getColor(1, Color.BLACK)
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
withAttrs(android.R.attr.windowLightNavigationBar) {
if (getBoolean(0, false)) {
window.decorView.apply {
systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
}
}
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.toolbar_menu, menu)
masterSwitch = (menu.findItem(R.id.toolbar_master_switch)?.actionView as? Switch)?.apply {
isChecked = prefsApps.getBoolean(Common.MASTER_SWITCH_ON, true)
setOnCheckedChangeListener { _, b ->
prefsApps.edit().putBoolean(Common.MASTER_SWITCH_ON, b).apply()
}
}
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
masterSwitch?.isChecked = prefsApps.getBoolean(Common.MASTER_SWITCH_ON, true)
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.toolbar_info -> {
val intent = CustomTabsIntent.Builder(ctSession)
.setShowTitle(true)
.enableUrlBarHiding()
.setToolbarColor(ContextCompat.getColor(this, R.color.primary_red))
.build()
intent.launchUrl(this, Common.WEBSITE_URI)
return true
}
android.R.id.home -> {
onBackPressed()
return false
}
else -> return false
}
}
override fun onAuthenticationSucceeded() {
TransitionManager.beginDelayedTransition(window.decorView as ViewGroup, Fade())
setupWindow(false)
uiComponents.isVisible = true
lockscreen.isVisible = false
settingsViewModel.locked = false
}
override fun onScreenChanged(screen: PreferenceScreen, subScreen: Boolean) {
supportActionBar?.setDisplayHomeAsUpEnabled(subScreen)
title = when {
screen.title.startsWith(getString(R.string.app_name)) -> getString(R.string.pref_screen_about)
screen.titleRes != -1 -> getString(screen.titleRes)
screen.title.isNotEmpty() -> screen.title
else -> originalTitle
}
recyclerView.scrollToPosition(0)
}
private fun openCustomScreen(@CustomScreen id: Int) {
val screen = settingsViewModel.customScreens.get(id) ?: when (id) {
SCREEN_APP_LIST -> AppListScreen(this)
else -> throw RuntimeException("The specified screen id doesn't exist")
}.also { settingsViewModel.customScreens.put(id, it) }
settingsViewModel.customScreenStack.push(screen)
applyCurrentCustomScreen()
}
private fun applyCurrentCustomScreen() {
if (settingsViewModel.customScreenStack.isEmpty())
return
val screen = settingsViewModel.customScreenStack.last()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
setTitle(screen.titleRes)
if (screen.hasOptionsMenu)
invalidateOptionsMenu()
screen.adapter?.let {
recyclerView.adapter = it
}
screen.view?.let {
viewRoot.addView(it, ViewGroup.LayoutParams.MATCH_PARENT, 0)
it.updateLayoutParams<ConstraintLayout.LayoutParams> {
topToBottom = R.id.toolbar
bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
}
}
screen.progressLiveData?.apply {
progress.isVisible = true
observe(this@SettingsActivity, Observer {
progress.isVisible = false
})
}
}
private fun observePreferenceClicks() {
settingsViewModel.activityPreferenceClickListener.observe(this, Observer { preferenceKey ->
when (preferenceKey) {
LOCKING_TYPE_PASSWORD -> setupPassword(null)
LOCKING_TYPE_PATTERN -> {
val intent = Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null, this, LockPatternActivity::class.java)
startActivityForResult(intent, KUtil.getPatternCode(-1))
}
CHOOSE_APPS -> openCustomScreen(SCREEN_APP_LIST)
USE_DARK_STYLE, USE_AMOLED_BLACK -> recreate()
UNINSTALL -> {
if (devicePolicyManager?.isAdminActive(deviceAdmin) != true) {
val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin)
startActivity(intent)
} else {
devicePolicyManager?.removeActiveAdmin(deviceAdmin)
settingsViewModel.prefUninstall.apply {
titleRes = R.string.pref_prevent_uninstall
summaryRes = R.string.pref_prevent_uninstall_summary
requestRebind()
}
val uninstall = Intent(Intent.ACTION_DELETE)
uninstall.flags = Intent.FLAG_ACTIVITY_NEW_TASK
uninstall.data = Uri.parse("package:de.Maxr1998.xposed.maxlock")
startActivity(uninstall)
}
}
SEND_FEEDBACK -> prepareSendFeedback()
}
})
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
BUG_REPORT_STORAGE_PERMISSION_REQUEST_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PERMISSION_GRANTED)
finishSendFeedback()
}
}
}
override fun onBackPressed() {
val stack = settingsViewModel.customScreenStack
if (stack.isNotEmpty()) {
progress.isVisible = false
stack.pop()
if (stack.isNotEmpty())
applyCurrentCustomScreen()
else recyclerView.apply {
onScreenChanged(preferencesAdapter.currentScreen, preferencesAdapter.isInSubScreen())
invalidateOptionsMenu()
adapter = preferencesAdapter
}
} else if (!preferencesAdapter.goBack())
super.onBackPressed()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(SCREEN_SAVED_STATE, when (recyclerView.adapter?.javaClass) {
AppListAdapter::class.java -> SCREEN_APP_LIST
else -> SCREEN_DEFAULT
})
outState.putParcelable(PREFS_SAVED_STATE, preferencesAdapter.getSavedState())
}
override fun onDestroy() {
preferencesAdapter.onScreenChangeListener = null
recyclerView.adapter = null
ctConnection?.let(this::unbindService)
super.onDestroy()
}
// Chrome custom tabs
private fun bindCustomTabsService() {
val ctPackageName = CustomTabsClient.getPackageName(this, Arrays.asList(
"com.android.chrome", "com.chrome.beta", "com.chrome.dev", "org.mozilla.firefox", "org.mozilla.firefox_beta"
)) ?: return
ctConnection = object : CustomTabsServiceConnection() {
override fun onCustomTabsServiceConnected(componentName: ComponentName, customTabsClient: CustomTabsClient) {
customTabsClient.warmup(0)
customTabsClient.newSession(CustomTabsCallback())?.let {
ctSession = it
val maxr1998Website = Bundle()
maxr1998Website.putParcelable(CustomTabsService.KEY_URL, Common.MAXR1998_URI)
val technoSparksProfile = Bundle()
technoSparksProfile.putParcelable(CustomTabsService.KEY_URL, Common.TECHNO_SPARKS_URI)
it.mayLaunchUrl(Common.WEBSITE_URI, null, Arrays.asList(maxr1998Website, technoSparksProfile))
}
}
override fun onServiceDisconnected(name: ComponentName) {}
}
CustomTabsClient.bindCustomTabsService(this, ctPackageName, ctConnection)
}
companion object {
const val SCREEN_SAVED_STATE = "screen_state"
const val PREFS_SAVED_STATE = "prefs_state"
const val SCREEN_DEFAULT = 0
const val SCREEN_APP_LIST = 1
}
@IntDef(SCREEN_DEFAULT, SCREEN_APP_LIST)
@Retention(AnnotationRetention.SOURCE)
annotation class CustomScreen
} | gpl-3.0 | 36ab038de3a5d62ec2db19824da03e2d | 41.966942 | 127 | 0.647987 | 5.058709 | false | false | false | false |
alzhuravlev/MockAppDemo | app/src/main/java/com/crane/mockappdemo/sample1/Fragment3.kt | 1 | 2181 | package com.crane.mockappdemo.sample1
import android.os.Bundle
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.crane.mockapp.annotations.MockAppLayout
import com.crane.mockapp.core.MockApp
import com.crane.mockapp.core.MockAppActivity
import com.crane.mockapp.core.MockAppFragment
import com.crane.mockappdemo.R
import java.lang.IllegalStateException
@MockAppLayout(projectName = "basic_sample", layoutName = "TabLayout")
class Fragment3 : MockAppActivity() {
lateinit var pager: ViewPager
/**
* Override this method to make a custom binding.
* In general it is much easier to use @MockAppView annotation to let library
* bind views by CustomTag (see Binding Views section in the doc)
*/
override fun bindMockAppLayout(view: Any?) {
pager = MockApp.findViewByViewIdPath(view, "Linear1/Pager9")!!
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// id is required by PagerAdapter
pager.id = R.id.VIEW_PAGER
pager.adapter = Adapter(supportFragmentManager)
}
}
/**
* Just like extending MockAppActivity you have two options:
* @MockAppLayout or override getProjectId/getProjectName and getLayoutId/getLayoutName
*/
@MockAppLayout(projectName = "basic_sample", layoutName = "FrameLayout")
class MyFragment1 : MockAppFragment() {
}
@MockAppLayout(projectName = "basic_sample", layoutName = "RecyclerView")
class MyFragment2 : MockAppFragment() {
}
@MockAppLayout(projectName = "basic_sample", layoutName = "Tile")
class MyFragment3 : MockAppFragment() {
}
class Adapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> MyFragment1()
1 -> MyFragment2()
2 -> MyFragment3()
else -> throw IllegalStateException("Illegal position: $position")
}
}
override fun getCount(): Int = 3
} | apache-2.0 | 892ea742a7b86258d41dda881373dbcd | 31.088235 | 87 | 0.730857 | 4.268102 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/analysis/state.kt | 1 | 2827 | package edu.kit.iti.formal.automation.analysis
import edu.kit.iti.formal.automation.VariableScope
import edu.kit.iti.formal.automation.datatypes.*
import edu.kit.iti.formal.automation.datatypes.values.MultiDimArrayValue
import edu.kit.iti.formal.automation.datatypes.values.Value
import edu.kit.iti.formal.automation.st.ast.*
import java.util.*
/**
* Computes the "unfolded" state of an PLC program or given scopes.
* @author Alexander Weigl
* @version 1 (12.11.19)
*/
class UnfoldState {
val state = TreeMap<String, Value<*, *>>()
val decls = TreeMap<String, VariableDeclaration>()
fun addPous(pous: PouElements) {
pous.filterIsInstance<GlobalVariableListDeclaration>().forEach {
addScope(it.scope.variables, "")
}
pous.filterIsInstance<ProgramDeclaration>().forEach { addScope(it.scope.variables, it.name) }
}
fun addScope(scope: VariableScope, prefix: String = "") {
scope.forEach { declare(prefix, it) }
}
private fun declare(prefix: String, vd: VariableDeclaration) {
val p = if (prefix.isBlank()) "" else "$prefix."
val s = "$p${vd.name}"
decls[s] = vd
declare(s, vd.initValue!!)
}
fun declare(name: String, value: Value<*, *>) {
value.dataType.accept(
object : DataTypeVisitorNN<Unit> {
override fun defaultVisit(obj: Any) {
state[name] = value
}
override fun visit(arrayType: ArrayType) {
val arrayValue = value.value as MultiDimArrayValue
for (idx in arrayType.allIndices()) {
val n = idx.joinToString(",", "$name[", "]")
val v = arrayValue[idx]
declare(n, v)
decls[n] = VariableDeclaration().also { it.dataType = value.dataType; it.initValue = v }
}
}
override fun visit(recordType: RecordType) {
for (idx in recordType.fields) {
addScope(recordType.fields, name)
}
}
override fun visit(classDataType: ClassDataType) {
if (classDataType is ClassDataType.ClassDt) {
addScope(classDataType.clazz.effectiveVariables, name)
}
}
override fun visit(functionBlockDataType: FunctionBlockDataType) {
addScope(functionBlockDataType.functionBlock.effectiveVariables, name)
}
})
}
}
fun UnfoldState.classInstances() : Map<String, VariableDeclaration> {
return decls
}
| gpl-3.0 | 262d4cdd1bba09a9d3291ca96dcd769b | 35.714286 | 116 | 0.552175 | 4.649671 | false | false | false | false |
AndroidX/constraintlayout | projects/ComposeConstraintLayout/dsl-verification/src/main/java/com/example/dsl_verification/constraint/Guidelines.kt | 2 | 2517 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("DslVerificationKt")
@file:JvmMultifileClass
package com.example.dsl_verification.constraint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.layoutId
import com.example.dsl_verification.constraint.DslVerification.TwoBoxConstraintSet
@Preview
@Composable
fun Test4() {
val constraintSet = ConstraintSet(TwoBoxConstraintSet) {
val box1 = createRefFor("box1")
val guideBott = createGuidelineFromBottom(10.dp)
val guideTop = createGuidelineFromTop(0.5f)
val guideLeft = createGuidelineFromAbsoluteLeft(10.dp)
val guideEnd = createGuidelineFromEnd(0.5f)
constrain(box1) {
linkTo(guideLeft, guideEnd)
linkTo(guideTop, guideBott)
}
}
Column {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.weight(1f, fill = true), constraintSet = constraintSet
) {
Box(
modifier = Modifier
.background(Color.Red)
.layoutId("box1")
)
Box(
modifier = Modifier
.background(Color.Blue)
.layoutId("box2")
)
}
Button(onClick = { }) {
Text(text = "Run")
}
}
} | apache-2.0 | a4fa0c1606de1f545fa693d13d6e9f5d | 32.131579 | 82 | 0.683353 | 4.568058 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/series/HighSeriesOf15Statistic.kt | 1 | 956 | package ca.josephroque.bowlingcompanion.statistics.impl.series
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
/**
* Copyright (C) 2018 Joseph Roque
*
* Highest series of 15 games.
*/
class HighSeriesOf15Statistic(value: Int = 0) : HighSeriesStatistic(value) {
// MARK: Overrides
override val seriesSize = 15
override val titleId = Id
override val id = Id.toLong()
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::HighSeriesOf15Statistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_high_series_of_15
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(value = p.readInt())
}
| mit | 948afac4802c998328e29b0768b9e734 | 25.555556 | 76 | 0.687238 | 4.267857 | false | false | false | false |
duftler/orca | orca-sql/src/main/kotlin/com/netflix/spinnaker/orca/sql/cleanup/TopApplicationExecutionCleanupPollingNotificationAgent.kt | 1 | 5958 | /*
* Copyright 2018 Netflix, 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.netflix.spinnaker.orca.sql.cleanup
import com.netflix.spectator.api.Counter
import com.netflix.spectator.api.Id
import com.netflix.spectator.api.LongTaskTimer
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.kork.core.RetrySupport
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.notifications.AbstractPollingNotificationAgent
import com.netflix.spinnaker.orca.notifications.NotificationClusterLock
import com.netflix.spinnaker.orca.sql.pipeline.persistence.transactional
import org.jooq.DSLContext
import org.jooq.impl.DSL
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.stereotype.Component
import java.util.concurrent.atomic.AtomicInteger
@Component
@ConditionalOnExpression("\${pollers.top-application-execution-cleanup.enabled:false} && !\${execution-repository.redis.enabled:false}")
class TopApplicationExecutionCleanupPollingNotificationAgent(
clusterLock: NotificationClusterLock,
private val jooq: DSLContext,
private val registry: Registry,
private val retrySupport: RetrySupport,
@Value("\${pollers.top-application-execution-cleanup.interval-ms:3600000}") private val pollingIntervalMs: Long,
@Value("\${pollers.top-application-execution-cleanup.threshold:2000}") private val threshold: Int,
@Value("\${pollers.top-application-execution-cleanup.chunk-size:1}") private val chunkSize: Int
) : AbstractPollingNotificationAgent(clusterLock) {
private val log = LoggerFactory.getLogger(TopApplicationExecutionCleanupPollingNotificationAgent::class.java)
private val deletedId: Id
private val errorsCounter: Counter
private val invocationTimer: LongTaskTimer
private val completedStatuses = ExecutionStatus.COMPLETED.map { it.toString() }
init {
deletedId = registry.createId("pollers.topApplicationExecutionCleanup.deleted")
errorsCounter = registry.counter("pollers.topApplicationExecutionCleanup.errors")
invocationTimer = com.netflix.spectator.api.patterns.LongTaskTimer.get(
registry, registry.createId("pollers.topApplicationExecutionCleanup.timing")
)
}
override fun getPollingInterval(): Long {
return pollingIntervalMs
}
override fun getNotificationType(): String {
return TopApplicationExecutionCleanupPollingNotificationAgent::class.java.simpleName
}
override fun tick() {
val timerId = invocationTimer.start()
val startTime = System.currentTimeMillis()
try {
log.info("Agent {} started", notificationType)
performCleanup()
} catch (e: Exception) {
log.error("Agent {} failed to perform cleanup", e)
} finally {
log.info("Agent {} completed in {}ms", notificationType, System.currentTimeMillis() - startTime)
invocationTimer.stop(timerId)
}
}
private fun performCleanup() {
val applicationsWithOldOrchestrations = jooq
.select(DSL.field("application"), DSL.count(DSL.field("id")).`as`("count"))
.from(DSL.table("orchestrations"))
.groupBy(DSL.field("application"))
.having(DSL.count(DSL.field("id")).gt(threshold))
.fetch()
applicationsWithOldOrchestrations.forEach {
val application = it.getValue(DSL.field("application")) as String? ?: return@forEach
try {
val startTime = System.currentTimeMillis()
log.debug("Cleaning up old orchestrations for $application")
val deletedOrchestrationCount = performCleanup(application)
log.debug(
"Cleaned up {} old orchestrations for {} in {}ms",
deletedOrchestrationCount,
application,
System.currentTimeMillis() - startTime
)
} catch (e: Exception) {
log.error("Failed to cleanup old orchestrations for $application", e)
errorsCounter.increment()
}
}
}
/**
* An application can have at most [threshold] completed orchestrations.
*/
private fun performCleanup(application: String): Int {
val deletedExecutionCount = AtomicInteger()
val executionsToRemove = jooq
.select(DSL.field("id"))
.from(DSL.table("orchestrations"))
.where(
DSL.field("application").eq(application).and(
"status IN (${completedStatuses.joinToString(",") { "'$it'" }})"
)
)
.orderBy(DSL.field("build_time").desc())
.limit(threshold, Int.MAX_VALUE)
.fetch()
.map { it.getValue(DSL.field("id")) }
log.debug("Found {} old orchestrations for {}", executionsToRemove.size, application)
executionsToRemove.chunked(chunkSize).forEach { ids ->
deletedExecutionCount.addAndGet(ids.size)
jooq.transactional(retrySupport) {
it.delete(DSL.table("correlation_ids")).where(
"orchestration_id IN (${ids.joinToString(",") { "'$it'" }})"
).execute()
it.delete(DSL.table("orchestration_stages")).where(
"execution_id IN (${ids.joinToString(",") { "'$it'" }})"
).execute()
it.delete(DSL.table("orchestrations")).where(
"id IN (${ids.joinToString(",") { "'$it'" }})"
).execute()
}
registry.counter(deletedId.withTag("application", application)).add(ids.size.toDouble())
}
return deletedExecutionCount.toInt()
}
}
| apache-2.0 | a26d01c5ec8d6cb1052e61d1e93ec332 | 36.949045 | 136 | 0.716012 | 4.326797 | false | false | false | false |
pedronveloso/jPwdHash | src/main/kotlin/pedronveloso/jpwdhash/Main.kt | 1 | 3124 | package pedronveloso.jpwdhash
import joptsimple.OptionParser
import joptsimple.OptionSet
import pedronveloso.jpwdhash.Parameters.PASS
import pedronveloso.jpwdhash.Parameters.URL
import pedronveloso.jpwdhash.hasher.DomainExtractor
import pedronveloso.jpwdhash.hasher.HashedPassword
import java.util.*
class Main {
companion object {
@JvmStatic fun main(args: Array<String>) {
val parser = OptionParser()
parser.accepts(URL, "URL of the domain intended to be hashed").withRequiredArg().required()
parser.accepts(PASS, "Password to use for the hashing process. If you use this option beware that " +
"your command will display your password on the console's history as well as display it on the " +
"screen, this should only be used for automation purposes.").withRequiredArg()
parser.posixlyCorrect(true)
// Display help if sufficient arguments NOT provided
if (args.size != 4 && args.size != 2) {
displayHelp(parser)
return
}
// TODO : Add --help argument
// User can either provide a password or use one in the command line itself (leaks to history though)
val options = if (args.size == 2) {
parser.parse(args.component1(), args.component2())
} else {
parser.parse(args.component1(), args.component2(), args.component3(), args.component4())
}
if (options.has(PASS)) {
execute(options, options.valueOf(PASS) as String)
} else {
askPassword(options)
}
}
private fun displayHelp(parser: OptionParser) {
print("jPwdHash - Command line tool for password hashing.")
print("\nOfficial webpage: https://pedronveloso.github.io/jPwdHash/")
print("\nUsage:\n")
parser.printHelpOn(System.out)
}
private fun askPassword(options: OptionSet) {
val c = System.console()
if (c == null) {
logError("Java Console was not found, reading with Scanner (insecure)")
print("Enter password:")
val scanner = Scanner(System.`in`)
val readPassword = scanner.nextLine()
execute(options, readPassword)
return
}
val readPassword = c.readPassword("Enter password: ")
execute(options, String(readPassword))
}
private fun execute(options: OptionSet, password: String) {
val url = options.valueOf(URL) as String
val domain = getDomain(url)
val hashedPassword = HashedPassword.create(password, domain)
val result = hashedPassword.toString()
print(result)
print("\n")
}
/**
* Get the domain portion of the URL
*/
private fun getDomain(url: String): String {
return DomainExtractor.extractDomain(
url)
}
}
}
| gpl-3.0 | 1a7f37f44c8b4946b68965a50545536c | 35.325581 | 118 | 0.580666 | 4.600884 | false | false | false | false |
manami-project/manami | manami-app/src/test/kotlin/io/github/manamiproject/manami/app/migration/DefaultMetaDataMigrationHandlerTest.kt | 1 | 32828 | package io.github.manamiproject.manami.app.migration
import io.github.manamiproject.manami.app.cache.AnimeCache
import io.github.manamiproject.manami.app.cache.CacheEntry
import io.github.manamiproject.manami.app.cache.PresentValue
import io.github.manamiproject.manami.app.cache.TestAnimeCache
import io.github.manamiproject.manami.app.commands.TestCommandHistory
import io.github.manamiproject.manami.app.events.Event
import io.github.manamiproject.manami.app.events.EventBus
import io.github.manamiproject.manami.app.events.TestEventBus
import io.github.manamiproject.manami.app.lists.Link
import io.github.manamiproject.manami.app.lists.NoLink
import io.github.manamiproject.manami.app.lists.animelist.AnimeListEntry
import io.github.manamiproject.manami.app.lists.ignorelist.IgnoreListEntry
import io.github.manamiproject.manami.app.lists.watchlist.WatchListEntry
import io.github.manamiproject.manami.app.state.State
import io.github.manamiproject.manami.app.state.TestState
import io.github.manamiproject.modb.core.collections.SortedList
import io.github.manamiproject.modb.core.config.Hostname
import io.github.manamiproject.modb.core.models.Anime
import io.github.manamiproject.modb.core.models.Anime.Type.TV
import io.github.manamiproject.modb.kitsu.KitsuConfig
import io.github.manamiproject.modb.mal.MalConfig
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.net.URI
import java.nio.file.Paths
internal class DefaultMetaDataMigrationHandlerTest {
@Nested
inner class CheckMigrationTests {
@Test
fun `throws exception if hostname of current entry ist not provided`() {
// given
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(KitsuConfig.hostname())
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = TestEventBus,
commandHistory = TestCommandHistory,
state = TestState,
)
// when
val result = assertThrows<IllegalArgumentException> {
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
}
// then
assertThat(result).hasMessage("MetaDataProvider [myanimelist.net] is not supported.")
}
@Test
fun `throws exception if hostname of new entry ist not provided`() {
// given
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname())
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = TestEventBus,
commandHistory = TestCommandHistory,
state = TestState,
)
// when
val result = assertThrows<IllegalArgumentException> {
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
}
// then
assertThat(result).hasMessage("MetaDataProvider [kitsu.io] is not supported.")
}
@Test
fun `any AnimeListEntry without a link is being ignored`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
}
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = listOf(
AnimeListEntry(
link = NoLink,
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
episodes = 26,
type = TV,
location = Paths.get("."),
),
)
override fun watchList(): Set<WatchListEntry> = emptySet()
override fun ignoreList(): Set<IgnoreListEntry> = emptySet()
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(1)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `AnimeListEntry without mapping`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = emptySet()
}
val currentAnimeListEntry = AnimeListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
episodes = 26,
type = TV,
location = Paths.get("."),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = listOf(
currentAnimeListEntry,
)
override fun watchList(): Set<WatchListEntry> = emptySet()
override fun ignoreList(): Set<IgnoreListEntry> = emptySet()
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = listOf(currentAnimeListEntry),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `AnimeListEntry having one on one mapping`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val kitsuLink = KitsuConfig.buildAnimeLink("38")
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = setOf(
kitsuLink
)
override fun fetch(key: URI): CacheEntry<Anime> = PresentValue(
Anime(
_title = "Beck",
sources = SortedList(kitsuLink),
)
)
}
val currentAnimeListEntry = AnimeListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
episodes = 26,
type = TV,
location = Paths.get("."),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = listOf(
currentAnimeListEntry
)
override fun watchList(): Set<WatchListEntry> = emptySet()
override fun ignoreList(): Set<IgnoreListEntry> = emptySet()
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = mapOf(
currentAnimeListEntry to Link(kitsuLink)
),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `AnimeListEntry having multiple mappings`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val firstKitsuLink = KitsuConfig.buildAnimeLink("38")
val secondKitsuLink = KitsuConfig.buildAnimeLink("99999999")
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = setOf(
firstKitsuLink,
secondKitsuLink,
)
override fun fetch(key: URI): CacheEntry<Anime> = PresentValue(
Anime(
_title = "Beck",
sources = SortedList(firstKitsuLink, secondKitsuLink),
),
)
}
val currentAnimeListEntry = AnimeListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
episodes = 26,
type = TV,
location = Paths.get("."),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = listOf(
currentAnimeListEntry
)
override fun watchList(): Set<WatchListEntry> = emptySet()
override fun ignoreList(): Set<IgnoreListEntry> = emptySet()
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = mapOf(
currentAnimeListEntry to setOf(Link(firstKitsuLink), Link(secondKitsuLink))
),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `WatchListEntry without mapping`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = emptySet()
}
val currentWatchListEntry = WatchListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = listOf()
override fun watchList(): Set<WatchListEntry> = setOf(
currentWatchListEntry,
)
override fun ignoreList(): Set<IgnoreListEntry> = emptySet()
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = listOf(currentWatchListEntry),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `WatchListEntry having one on one mapping`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val kitsuLink = KitsuConfig.buildAnimeLink("38")
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = setOf(
kitsuLink
)
override fun fetch(key: URI): CacheEntry<Anime> = PresentValue(
Anime(
_title = "Beck",
sources = SortedList(kitsuLink),
)
)
}
val currentWatchListEntry = WatchListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = emptyList()
override fun watchList(): Set<WatchListEntry> = setOf(currentWatchListEntry)
override fun ignoreList(): Set<IgnoreListEntry> = emptySet()
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = mapOf(
currentWatchListEntry to Link(kitsuLink)
),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `WatchListEntry having multiple mappings`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val firstKitsuLink = KitsuConfig.buildAnimeLink("38")
val secondKitsuLink = KitsuConfig.buildAnimeLink("99999999")
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = setOf(
firstKitsuLink,
secondKitsuLink,
)
override fun fetch(key: URI): CacheEntry<Anime> = PresentValue(
Anime(
_title = "Beck",
sources = SortedList(firstKitsuLink, secondKitsuLink),
),
)
}
val currentWatchListEntry = WatchListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = emptyList()
override fun watchList(): Set<WatchListEntry> = setOf(
currentWatchListEntry,
)
override fun ignoreList(): Set<IgnoreListEntry> = emptySet()
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = mapOf(
currentWatchListEntry to setOf(Link(firstKitsuLink), Link(secondKitsuLink))
),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `IgnoreListEntry without mapping`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = emptySet()
}
val currentIgnoreListEntry = IgnoreListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = listOf()
override fun watchList(): Set<WatchListEntry> = emptySet()
override fun ignoreList(): Set<IgnoreListEntry> = setOf(
currentIgnoreListEntry,
)
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = listOf(currentIgnoreListEntry),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = emptyMap(),
)
)
}
@Test
fun `IgnoreListEntry having one on one mapping`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val kitsuLink = KitsuConfig.buildAnimeLink("38")
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = setOf(
kitsuLink
)
override fun fetch(key: URI): CacheEntry<Anime> = PresentValue(
Anime(
_title = "Beck",
sources = SortedList(kitsuLink),
),
)
}
val currentIgnoreListEntry = IgnoreListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = emptyList()
override fun watchList(): Set<WatchListEntry> = emptySet()
override fun ignoreList(): Set<IgnoreListEntry> = setOf(
currentIgnoreListEntry,
)
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = emptyMap(),
ignoreListMappings = mapOf(
currentIgnoreListEntry to Link(kitsuLink)
),
)
)
}
@Test
fun `IgnoreListEntry having multiple mappings`() {
// given
val catchedEvents = mutableListOf<Event>()
val testEventBus = object : EventBus by TestEventBus {
override fun post(event: Event) {
catchedEvents.add(event)
}
}
val firstKitsuLink = KitsuConfig.buildAnimeLink("38")
val secondKitsuLink = KitsuConfig.buildAnimeLink("99999999")
val testCache = object: AnimeCache by TestAnimeCache {
override val availableMetaDataProvider: Set<Hostname>
get() = setOf(MalConfig.hostname(), KitsuConfig.hostname())
override fun mapToMetaDataProvider(uri: URI, metaDataProvider: Hostname): Set<URI> = setOf(
firstKitsuLink,
secondKitsuLink,
)
override fun fetch(key: URI): CacheEntry<Anime> = PresentValue(
Anime(
_title = "Beck",
sources = SortedList(firstKitsuLink, secondKitsuLink),
),
)
}
val currentIgnoreListEntry = IgnoreListEntry(
link = Link("https://myanimelist.net/anime/57"),
title = "Beck",
thumbnail = URI("https://cdn.myanimelist.net/images/anime/11/11636t.jpg"),
)
val testState = object: State by TestState {
override fun animeList(): List<AnimeListEntry> = emptyList()
override fun watchList(): Set<WatchListEntry> = emptySet()
override fun ignoreList(): Set<IgnoreListEntry> = setOf(
currentIgnoreListEntry,
)
}
val defaultMetaDataMigrationHandler = DefaultMetaDataMigrationHandler(
cache = testCache,
eventBus = testEventBus,
commandHistory = TestCommandHistory,
state = testState,
)
// when
defaultMetaDataMigrationHandler.checkMigration(MalConfig.hostname(), KitsuConfig.hostname())
// then
assertThat(catchedEvents).hasSize(2)
assertThat(catchedEvents).containsExactly(
MetaDataMigrationProgressEvent(
finishedTasks = 1,
numberOfTasks = 1,
),
MetaDataMigrationResultEvent(
animeListEntriesWithoutMapping = emptyList(),
animeListEntiresMultipleMappings = emptyMap(),
animeListMappings = emptyMap(),
watchListEntriesWithoutMapping = emptyList(),
watchListEntiresMultipleMappings = emptyMap(),
watchListMappings = emptyMap(),
ignoreListEntriesWithoutMapping = emptyList(),
ignoreListEntiresMultipleMappings = mapOf(
currentIgnoreListEntry to setOf(Link(firstKitsuLink), Link(secondKitsuLink))
),
ignoreListMappings = emptyMap(),
)
)
}
}
} | agpl-3.0 | f17922efca0ec39a2c14acb53db2bb3d | 41.034571 | 111 | 0.546424 | 5.920289 | false | true | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/unicodeKeyboard/UnicodeActivity.kt | 1 | 7465 | package com.itachi1706.cheesecakeutilities.modules.unicodeKeyboard
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.itachi1706.cheesecakeutilities.BaseModuleActivity
import com.itachi1706.cheesecakeutilities.R
import kotlinx.android.synthetic.main.activity_viewpager_frag.*
class UnicodeActivity : BaseModuleActivity() {
override val helpDescription: String
get() {
var message = "List of Unicode emojis that you can click on to copy to your clipboard for use everywhere else :D"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) message += "\n\nYou can even drag and drop emojis into textboxes when you are in Android's Multi Window mode by long clicking the emoji!"
return message
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_viewpager_frag)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
view_pager.adapter = UnicodeTabAdapter(this)
TabLayoutMediator(tab_layout, view_pager) { tab, position -> tab.text = tabs[position] }.attach()
}
class UnicodeTabAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
override fun getItemCount(): Int { return 43 } // 4 tabs
override fun createFragment(position: Int): Fragment { return UnicodeFragment.newInstance(getUnicodeStringList(position)) }
}
companion object {
val tabs = arrayOf("Emojis", "Kaomojis", "Flip Table", "Misc", "Joy", "Love", "Embarrasment", "Sympathy", "Dissatisfaction", "Anger", "Sadness", "Pain", "Fear", "Indifference", "Confusion", "Doubt",
"Surprise", "Greeting", "Hugging", "Winking", "Apologizing", "Nosebleeding", "Hiding", "Writing", "Running", "Sleeping", "Cat", "Bear", "Dog", "Rabbit",
"Pig", "Bird", "Fish", "Spider", "Friends", "Enemies", "Weapons", "Magic", "Food", "Music", "Games", "Faces", "Special")
fun getUnicodeStringList(position: Int): Array<String> {
return when (position) {
0 -> emojis
1 -> kaomojiOrig
2 -> flipTable
3 -> misc
4 -> Kaomojis.joy
5 -> Kaomojis.love
6 -> Kaomojis.embarrasment
7 -> Kaomojis.sympathy
8 -> Kaomojis.dissatisfaction
9 -> Kaomojis.anger
10 -> Kaomojis.sadness
11 -> Kaomojis.pain
12 -> Kaomojis.fear
13 -> Kaomojis.indifference
14 -> Kaomojis.confusion
15 -> Kaomojis.doubt
16 -> Kaomojis.surprise
17 -> Kaomojis.greeting
18 -> Kaomojis.hugging
19 -> Kaomojis.winking
20 -> Kaomojis.apologizing
21 -> Kaomojis.nosebleeding
22 -> Kaomojis.hidingKaomoji
23 -> Kaomojis.writingKaomoji
24 -> Kaomojis.runningKaomoji
25 -> Kaomojis.sleepingKaomoji
26 -> Kaomojis.cat
27 -> Kaomojis.bear
28 -> Kaomojis.dog
29 -> Kaomojis.rabbit
30 -> Kaomojis.pig
31 -> Kaomojis.bird
32 -> Kaomojis.fish
33 -> Kaomojis.spider
34 -> Kaomojis.friends
35 -> Kaomojis.enemies
36 -> Kaomojis.weapons
37 -> Kaomojis.magic
38 -> Kaomojis.food
39 -> Kaomojis.musicKaomoji
40 -> Kaomojis.gamesKaomoji
41 -> Kaomojis.faces
42 -> Kaomojis.special
else -> arrayOf()
}
}
private val emojis = arrayOf("☻", "☹", "♡", "♥", "❤", "⚘", "❀", "❃", "❁", "✼", "♫", "♪", "☃", "❄", "❅", "❆", "☕", "☂", "★")
private val kaomojiOrig = arrayOf(
"◕‿◕", "。◕‿◕。", "。◕‿‿◕。", "^̮^",
"(◕‿◕)", "(。◕‿◕。)", "(。◕‿‿◕。)", "(^̮^)",
"ʘ‿ʘ", "ಠ_ಠ", "ಠ⌣ಠ", "ಠ‿ಠ",
"(ʘ‿ʘ)", "(ಠ_ಠ)", "(ಠ⌣ಠ)", "(ಠ‿ಠ)",
"♥‿♥", "◔̯◔", "٩◔̯◔۶", "⊙﹏⊙", "(¬_¬)", "(;一_一)",
"(・.◤)", "◕‿↼", "(¬‿¬)", "(づ ̄ ³ ̄)づ",
"ب_ب", "(ಥ_ಥ)", "(ಥ﹏ಥ)", "ლ(ಠ益ಠლ)",
"ʕ•ᴥ•ʔ", "°Д°", "﴾͡๏̯͡๏﴿ O'RLY?", "(ノ◕ヮ◕)ノ*:・゚✧",
"(ᵔᴥᵔ)", "(•ω•)", "☜(⌒▽⌒)☞", "〆(・∀・@)",
"◔ ⌣ ◔", "ლ(´ڡ`ლ)", "ლ,ᔑ•ﺪ͟͠•ᔐ.ლ", "ᕙ(⇀‸↼‶)ᕗ",
"(づ。◕‿‿◕。)づ", "ᄽὁȍ ̪ őὀᄿ", "╭∩╮(-_-)╭∩╮", "凸(-_-)凸",
" ̿ ̿'̿'\\̵͇̿̿\\з=(•_•)=ε/̵͇̿̿/'̿'̿ ̿", "(´・ω・)っ由", "(´・ω・ `)",
"٩(⁎❛ᴗ❛⁎)۶", "(͡° ͜ʖ ͡°)", "¯\\_(ツ)_/¯", "(° ͜ʖ °)",
"¯\\(°_o)/¯", "( ゚ヮ゚)", "ヽ༼ຈل͜ຈ༽ノ", "(︺︹︺)", "/人 ◕ ‿‿ ◕ 人\")
private val flipTable = arrayOf("(╯°□°)╯︵ ┻━┻","(┛◉Д◉)┛彡┻━┻","(ノ≧∇≦)ノ ミ ┸━┸","(ノಠ益ಠ)ノ彡┻━┻","(╯ರ ~ ರ)╯︵ ┻━┻","(┛ಸ_ಸ)┛彡┻━┻","(ノ´・ω・)ノ ミ ┸━┸",
"(ノಥ,_」ಥ)ノ彡┻━┻","(┛✧Д✧))┛彡┻━┻","┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻","┻━┻ ︵ ¯\\(ツ)/¯ ︵ ┻━┻","(ノTДT)ノ ┫:・’.::・┻┻:・’.::・","(ノ`⌒´)ノ ┫:・’.::・┻┻:・’.::・",
"(ノ*`▽´*)ノ ⌒┫ ┻ ┣ ┳","┻━┻ミ\(≧ロ≦\)","┻━┻︵└(՞▃՞ └)","┻━┻︵└(´▃`└)","─=≡Σ((((╯°□°)╯︵ ┻━┻","(ノ`´)ノ ~┻━┻","(-_- )ノ⌒┫ ┻ ┣","(ノ ̄皿 ̄)ノ ⌒=== ┫",
"ノ`⌒´)ノ ┫:・’.::・┻┻","༼ノຈل͜ຈ༽ノ︵┻━┻","ヽ༼ຈل͜ຈ༽ノ⌒┫ ┻ ┣","ミ┻┻(ノ>。<)ノ",".::・┻┻☆()゚O゚)","Take that! (ノ`A”)ノ ⌒┫ ┻ ┣ ┳☆(x x)","(ノ`m´)ノ ~┻━┻ (/o\)",
"⌒┫ ┻ ┣ ⌒┻☆)゚⊿゚)ノWTF!","(ノ≧∇≦)ノ ミ ┸┸)`ν゚)・;’.","ミ(ノ ̄^ ̄)ノ≡≡≡≡≡━┳━☆() ̄□ ̄)/","(╯°□°)╯︵(\\ .o.)\\","┣ヘ(^▽^ヘ)Ξ(゚▽゚*)ノ┳━┳ There we go~♪","┬──┬ ノ( ゜-゜ノ)","┬──┬ ¯\\_(ツ)",
"(ヘ・_・)ヘ┳━┳","ヘ(´° □°)ヘ┳━┳","┣ヘ(≧∇≦ヘ)… (≧∇≦)/┳━┳","┬─┬\uFEFF ︵ /(.□. \\)")
private val misc = arrayOf(" ̳ ̳ ̳ ̳ ͙ ڪ ", "Ƹ̵̡Ӝ̵̨̄Ʒ", "[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]", "▄︻̷̿┻̿═━一", "⌐╦╦═─", "┌─┐\n┴─┴\nಠ_ರೃ", "~~~ ╔͎═͓═͙╗\n~~~ ╚̨̈́═̈́﴾ ̥̂˖̫˖̥ ̂ )", "•_•)\n( •_•)>⌐■-■\n(⌐■_■)")
}
} | mit | d1600b011dec90ef40f7c589246cc043 | 53.176991 | 206 | 0.439144 | 2.069304 | false | false | false | false |
perenecabuto/CatchCatch | android/app/src/main/java/io/perenecabuto/catchcatch/drivers/WebSocketClient.kt | 1 | 2392 | package io.perenecabuto.catchcatch.drivers
import android.os.Handler
import android.os.Looper
import okhttp3.*
import okio.ByteString
class WebSocketClient : WebSocketListener() {
private var disconnectCallback: (() -> Unit)? = null
private var ws: WebSocket? = null
private var client: OkHttpClient? = null
private var connected = false
fun connect(address: String) {
shutdown()
val req = Request.Builder().url(address).build()
client = OkHttpClient.Builder().build()
client?.newWebSocket(req, this)
}
fun shutdown() {
close()
client?.apply { dispatcher().executorService().shutdown() }
}
fun close() {
ws?.close(1000, null)
}
fun onDisconnect(callback: () -> Unit): WebSocketClient {
disconnectCallback = {
if (connected) callback.invoke()
connected = false
}
return this
}
private fun reconnect() {
ws?.request()?.let { req -> client?.newWebSocket(req, this) }
}
override fun onOpen(webSocket: WebSocket?, response: Response?) {
connected = true
ws = webSocket
}
override fun onClosed(webSocket: WebSocket?, code: Int, reason: String?) {
disconnectCallback?.invoke()
}
override fun onFailure(webSocket: WebSocket?, t: Throwable?, response: Response?) {
t?.printStackTrace()
Handler(Looper.getMainLooper()).postDelayed(this::reconnect, 2_000L)
disconnectCallback?.invoke()
}
override fun onClosing(webSocket: WebSocket?, code: Int, reason: String?) {
disconnectCallback?.invoke()
}
override fun onMessage(webSocket: WebSocket?, bytes: ByteString?) {
onMessage(webSocket, bytes.toString())
}
override fun onMessage(webSocket: WebSocket?, text: String?) {
text?.split(delimiters = ',', limit = 2)?.let { split ->
events[split[0]]?.invoke(split[1])
}
}
private val events: HashMap<String, (msg: String) -> Unit> = HashMap()
fun off(): WebSocketClient {
events.clear()
return this
}
fun on(event: String, callback: (String) -> Unit): WebSocketClient {
events[event] = callback
return this
}
fun emit(event: String, msg: String = ""): WebSocketClient {
ws?.send("$event,$msg")
return this
}
} | gpl-3.0 | 2b5bf0dd37bafd05b662c78cce59038e | 25.88764 | 87 | 0.60995 | 4.573614 | false | false | false | false |
Geobert/Efficio | app/src/main/kotlin/fr/geobert/efficio/adapter/DepartmentViewHolder.kt | 1 | 866 | package fr.geobert.efficio.adapter
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import fr.geobert.efficio.R
import fr.geobert.efficio.data.Department
class DepartmentViewHolder(l: View, val listener: OnClickListener) :
RecyclerView.ViewHolder(l), View.OnClickListener {
interface OnClickListener {
fun onClick(d: Department)
}
val name = l.findViewById<TextView>(R.id.dep_name)
var dep: Department? = null
val cardView: CardView = l.findViewById(R.id.card_view)
init {
l.setOnClickListener(this)
}
fun bind(d: Department) {
name.text = d.name
dep = d
}
override fun onClick(p0: View?) {
val d = dep
if (d != null) {
listener.onClick(d)
}
}
} | gpl-2.0 | c0928e4587eac9c55b6136c8cb3af6b7 | 23.771429 | 68 | 0.661663 | 3.866071 | false | false | false | false |
robedmo/vlc-android | vlc-android/src/org/videolan/vlc/media/PlayerController.kt | 1 | 9298 | package org.videolan.vlc.media
import android.net.Uri
import android.support.annotation.MainThread
import android.support.v4.media.session.PlaybackStateCompat
import android.widget.Toast
import kotlinx.coroutines.experimental.CoroutineExceptionHandler
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.newSingleThreadContext
import org.videolan.libvlc.*
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.vlc.R
import org.videolan.vlc.RendererDelegate
import org.videolan.vlc.VLCApplication
import org.videolan.vlc.gui.preferences.PreferencesActivity
import org.videolan.vlc.util.VLCInstance
import org.videolan.vlc.util.VLCOptions
@Suppress("EXPERIMENTAL_FEATURE_WARNING")
class PlayerController : IVLCVout.Callback, MediaPlayer.EventListener {
private val exceptionHandler by lazy(LazyThreadSafetyMode.NONE) { CoroutineExceptionHandler { _, _ -> onPlayerError() } }
private val playerContext by lazy(LazyThreadSafetyMode.NONE) { newSingleThreadContext("vlc-player") }
private val settings by lazy(LazyThreadSafetyMode.NONE) { VLCApplication.getSettings() }
private var mediaplayer = newMediaPlayer()
var switchToVideo = false
var seekable = false
var pausable = false
var previousMediaStats: Media.Stats? = null
private set
@Volatile var playbackState = PlaybackStateCompat.STATE_STOPPED
private set
fun getVout() = mediaplayer.vlcVout
fun getMedia(): Media? = mediaplayer.media
fun play() {
if (mediaplayer.hasMedia()) mediaplayer.play()
}
fun pause(): Boolean {
if (isPlaying() && mediaplayer.hasMedia() && pausable) {
mediaplayer.pause()
return true
}
return false
}
fun stop() {
if (mediaplayer.hasMedia()) mediaplayer.stop()
}
fun releaseMedia() = mediaplayer.media?.let {
it.setEventListener(null)
it.release()
}
private var mediaplayerEventListener: MediaPlayer.EventListener? = null
internal suspend fun startPlayback(media: Media, listener: MediaPlayer.EventListener) {
mediaplayer.setEventListener(null)
mediaplayerEventListener = listener
seekable = true
pausable = true
launch(playerContext+exceptionHandler) {
mediaplayer.media = media
}.join()
mediaplayer.setEventListener(this@PlayerController)
mediaplayer.setEqualizer(VLCOptions.getEqualizerSetFromSettings(VLCApplication.getAppContext()))
mediaplayer.setVideoTitleDisplay(MediaPlayer.Position.Disable, 0)
if (mediaplayer.rate == 1.0f && settings.getBoolean(PreferencesActivity.KEY_PLAYBACK_SPEED_PERSIST, true))
setRate(settings.getFloat(PreferencesActivity.KEY_PLAYBACK_RATE, 1.0f), false)
mediaplayer.play()
}
@MainThread
fun restart() {
val mp = mediaplayer
mediaplayer = newMediaPlayer()
release(mp)
}
fun seek(position: Long, length: Double = getLength().toDouble()) {
if (length > 0.0) setPosition((position / length).toFloat())
else setTime(position)
}
fun setPosition(position: Float) {
if (seekable) mediaplayer.position = position
}
fun setTime(time: Long) {
if (seekable) mediaplayer.time = time
}
fun isPlaying() = playbackState == PlaybackStateCompat.STATE_PLAYING
fun isVideoPlaying() = mediaplayer.vlcVout.areViewsAttached()
fun canSwitchToVideo() = mediaplayer.hasMedia() && mediaplayer.videoTracksCount > 0
fun getVideoTracksCount() = if (mediaplayer.hasMedia()) mediaplayer.videoTracksCount else 0
fun getVideoTracks() = mediaplayer.videoTracks
fun getVideoTrack() = mediaplayer.videoTrack
fun getCurrentVideoTrack() = mediaplayer.currentVideoTrack
fun getAudioTracksCount() = mediaplayer.audioTracksCount
fun getAudioTracks() = mediaplayer.audioTracks
fun getAudioTrack() = mediaplayer.audioTrack
fun setAudioTrack(index: Int) = mediaplayer.setAudioTrack(index)
fun getAudioDelay() = mediaplayer.audioDelay
fun getSpuDelay() = mediaplayer.spuDelay
fun getRate() = mediaplayer.rate
fun setSpuDelay(delay: Long) = mediaplayer.setSpuDelay(delay)
fun setVideoTrackEnabled(enabled: Boolean) = mediaplayer.setVideoTrackEnabled(enabled)
fun addSubtitleTrack(path: String, select: Boolean) = mediaplayer.addSlave(Media.Slave.Type.Subtitle, path, select)
fun addSubtitleTrack(uri: Uri, select: Boolean) = mediaplayer.addSlave(Media.Slave.Type.Subtitle, uri, select)
fun getSpuTracks() = mediaplayer.spuTracks
fun getSpuTrack() = mediaplayer.spuTrack
fun setSpuTrack(index: Int) = mediaplayer.setSpuTrack(index)
fun getSpuTracksCount() = mediaplayer.spuTracksCount
fun setAudioDelay(delay: Long) = mediaplayer.setAudioDelay(delay)
fun setEqualizer(equalizer: MediaPlayer.Equalizer) = mediaplayer.setEqualizer(equalizer)
@MainThread
fun setVideoScale(scale: Float) {
mediaplayer.scale = scale
}
fun setVideoAspectRatio(aspect: String?) {
mediaplayer.aspectRatio = aspect
}
fun setRenderer(renderer: RendererItem?) = mediaplayer.setRenderer(renderer)
fun release(player: MediaPlayer = mediaplayer) {
player.setEventListener(null)
if (isVideoPlaying()) player.vlcVout.detachViews()
launch(playerContext) { player.release() }
playbackState = PlaybackStateCompat.STATE_STOPPED
}
fun setSlaves(media: MediaWrapper) = launch {
val list = MediaDatabase.getInstance().getSlaves(media.location)
for (slave in list) mediaplayer.addSlave(slave.type, Uri.parse(slave.uri), false)
}
private fun newMediaPlayer() : MediaPlayer {
return MediaPlayer(VLCInstance.get()).apply {
VLCOptions.getAout(VLCApplication.getSettings())?.let { setAudioOutput(it) }
setRenderer(RendererDelegate.selectedRenderer)
this.vlcVout.addCallback(this@PlayerController)
}
}
override fun onSurfacesCreated(vlcVout: IVLCVout?) {}
override fun onSurfacesDestroyed(vlcVout: IVLCVout?) {
switchToVideo = false
}
fun getTime() = if (mediaplayer.hasMedia()) mediaplayer.time else 0L
fun setRate(rate: Float, save: Boolean) {
mediaplayer.rate = rate
if (save && settings.getBoolean(PreferencesActivity.KEY_PLAYBACK_SPEED_PERSIST, true))
settings.edit().putFloat(PreferencesActivity.KEY_PLAYBACK_RATE, rate).apply()
}
/**
* Update current media meta and return true if player needs to be updated
*
* @param id of the Meta event received, -1 for none
* @return true if UI needs to be updated
*/
internal fun updateCurrentMeta(id: Int, mw: MediaWrapper?): Boolean {
if (id == Media.Meta.Publisher) return false
mw?.updateMeta(mediaplayer)
return id != Media.Meta.NowPlaying || mw?.nowPlaying !== null
}
fun getLength() = if (mediaplayer.hasMedia()) mediaplayer.length else 0L
fun setPreviousStats() {
val media = mediaplayer.media ?: return
previousMediaStats = media.stats
media.release()
}
fun updateViewpoint(yaw: Float, pitch: Float, roll: Float, fov: Float, absolute: Boolean) = mediaplayer.updateViewpoint(yaw, pitch, roll, fov, absolute)
fun navigate(where: Int) = mediaplayer.navigate(where)
fun getChapters(title: Int) = mediaplayer.getChapters(title)
fun getTitles() = mediaplayer.titles
fun getChapterIdx() = mediaplayer.chapter
fun setChapterIdx(chapter: Int) {
mediaplayer.chapter = chapter
}
fun getTitleIdx() = mediaplayer.title
fun setTitleIdx(title: Int) {
mediaplayer.title = title
}
fun getVolume() = mediaplayer.volume
fun setVolume(volume: Int) = mediaplayer.setVolume(volume)
suspend fun expand(): MediaList? {
return mediaplayer.media?.let {
mediaplayer.setEventListener(null)
val ml = async(playerContext+exceptionHandler) { it.subItems() }.await()
it.release()
mediaplayer.setEventListener(this@PlayerController)
return ml
}
}
override fun onEvent(event: MediaPlayer.Event?) {
if (event === null) return
when(event.type) {
MediaPlayer.Event.Playing -> playbackState = PlaybackStateCompat.STATE_PLAYING
MediaPlayer.Event.Paused -> playbackState = PlaybackStateCompat.STATE_PAUSED
MediaPlayer.Event.Stopped,
MediaPlayer.Event.EncounteredError,
MediaPlayer.Event.EndReached -> playbackState = PlaybackStateCompat.STATE_STOPPED
MediaPlayer.Event.PausableChanged -> pausable = event.pausable
MediaPlayer.Event.SeekableChanged -> seekable = event.seekable
}
mediaplayerEventListener?.onEvent(event)
}
private fun onPlayerError() {
launch(UI) {
restart()
Toast.makeText(VLCApplication.getAppContext(), VLCApplication.getAppContext().getString(R.string.feedback_player_crashed), Toast.LENGTH_LONG).show()
}
}
} | gpl-2.0 | 7a707b8f2cd1999d47893cb9b07e25b9 | 33.958647 | 160 | 0.69886 | 4.566798 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/model/CollectionInfo.kt | 1 | 1658 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.model
import android.content.ContentValues
import com.etesync.syncadapter.model.ServiceDB.Collections
import com.google.gson.GsonBuilder
class CollectionInfo : com.etesync.journalmanager.model.CollectionInfo() {
@Deprecated("")
var id: Long = 0
var serviceID: Int = 0
fun getServiceEntity(data: MyEntityDataStore): ServiceEntity {
return data.findByKey(ServiceEntity::class.java, serviceID)
}
enum class Type {
ADDRESS_BOOK,
CALENDAR,
TASKS,
}
var enumType: Type?
get() = if (super.type != null) Type.valueOf(super.type!!) else null
set(value) {
super.type = value?.name
}
companion object {
fun defaultForServiceType(service: Type): CollectionInfo {
val info = CollectionInfo()
info.displayName = when (service) {
Type.ADDRESS_BOOK -> "My Contacts"
Type.CALENDAR -> "My Calendar"
Type.TASKS -> "My Tasks"
}
info.selected = true
info.enumType = service
return info
}
fun fromJson(json: String): CollectionInfo {
return GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json, CollectionInfo::class.java)
}
}
}
| gpl-3.0 | a9253319f9cc4659b4f2ff0eed82dbe8 | 29.090909 | 123 | 0.636858 | 4.546703 | false | false | false | false |
saru95/DSA | Kotlin/SelectionSort.kt | 1 | 1199 | // cruxiu :)
import java.util.ArrayList
import java.util.Scanner
class SelectionSort {
fun selectionSort(list: Array<Integer>): Array<Integer> {
for (i in 0 until list.size - 1) {
var index = i
for (j in i + 1 until list.size)
if (list[j] < list[index])
index = j
val smallerNumber = list[index].toInt()
list[index] = list[i]
list[i] = smallerNumber
}
return list
}
fun main(a: Array<String>) {
val scanner = Scanner(System.`in`)
val arrayList = ArrayList<Integer>()
System.out.println("Please, enter the elements of the list.")
while (scanner.hasNextInt()) {
arrayList.add(scanner.nextInt())
}
var array = arrayList.toArray(arrayOfNulls<Integer>(0))
System.out.println("Now, we will sort the list. Your list now is:")
for (i in array.indices) {
System.out.println(array[i])
}
array = selectionSort(array)
System.out.println("After sort, your list now is:")
for (i in array.indices) {
System.out.println(array[i])
}
}
}
| mit | a1c06732971f0c0d455f909af2d15788 | 30.552632 | 75 | 0.548791 | 4.02349 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.