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
Masterzach32/SwagBot
src/main/kotlin/util/EmbedTemplates.kt
1
550
package xyz.swagbot.util import discord4j.core.spec.* import io.facet.common.dsl.* val baseTemplate: EmbedCreateSpec = embed { color = BLUE } val errorTemplate: EmbedCreateSpec = embed { color = RED } fun errorTemplate(description: String, throwable: Throwable) = errorTemplate.and { this.description = description throwable::class.simpleName?.let { exceptionName -> field("Exception", exceptionName, true) } if (throwable.localizedMessage.isNotEmpty()) field("Message", throwable.localizedMessage, true) }
gpl-2.0
1e352025d83ff4429794e1751f26c50d
25.238095
82
0.72
4.135338
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/db/room/FeedTitle.kt
1
616
package com.nononsenseapps.feeder.db.room import androidx.room.ColumnInfo import androidx.room.Ignore import com.nononsenseapps.feeder.db.COL_CUSTOM_TITLE import com.nononsenseapps.feeder.db.COL_ID import com.nononsenseapps.feeder.db.COL_TITLE data class FeedTitle @Ignore constructor( @ColumnInfo(name = COL_ID) var id: Long = ID_UNSET, @ColumnInfo(name = COL_TITLE) var title: String = "", @ColumnInfo(name = COL_CUSTOM_TITLE) var customTitle: String = "" ) { constructor() : this(id = ID_UNSET) val displayTitle: String get() = (if (customTitle.isBlank()) title else customTitle) }
gpl-3.0
80227d66735c8d4010e8da03bd054530
33.222222
69
0.730519
3.666667
false
false
false
false
ursjoss/sipamato
core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/AbstractServiceTest.kt
2
2542
package ch.difty.scipamato.core.persistence import ch.difty.scipamato.core.entity.IdScipamatoEntity import ch.difty.scipamato.core.entity.User import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach abstract class AbstractServiceTest<ID : Number, T : IdScipamatoEntity<ID>, R : ReadOnlyRepository<T, ID, *>> { protected var userRepoMock = mockk<UserRepository>() private var creatorMock = mockk<User>() private var modifierMock = mockk<User>() /** * @return the service specific repo mock */ protected abstract val repo: R /** * @return the service specific entity mock */ protected abstract val entity: T @BeforeEach internal fun setUp() { specificSetUp() } /** * Override to set up test fixtures for mocks in the concrete test class */ protected open fun specificSetUp() {} protected fun auditFixture() { every { entity.createdBy } returns CREATOR_ID every { entity.lastModifiedBy } returns MODIFIER_ID every { creatorMock.displayValue } returns "creatingUser" every { creatorMock.fullName } returns "creatingUserFullName" every { modifierMock.displayValue } returns "modifyingUser" every { userRepoMock.findById(CREATOR_ID) } returns creatorMock every { userRepoMock.findById(MODIFIER_ID) } returns modifierMock } @AfterEach internal fun tearDown() { confirmVerified(userRepoMock) specificTearDown() } /** * Override to verify mocks in the specific test class */ protected open fun specificTearDown() {} /** * Call this method to verify the audit names have been set. * * @param times * number of times the methods have been called. */ protected fun verifyAudit(times: Int) { verify(exactly = times) { entity.createdBy } verify(exactly = times) { userRepoMock.findById(CREATOR_ID) } verify(exactly = times) { entity.createdByName = "creatingUser" } verify(exactly = times) { entity.createdByFullName = "creatingUserFullName" } verify(exactly = times) { entity.lastModifiedBy } verify(exactly = times) { userRepoMock.findById(MODIFIER_ID) } verify(exactly = times) { entity.lastModifiedByName = "modifyingUser" } } companion object { const val CREATOR_ID = 10 const val MODIFIER_ID = 20 } }
gpl-3.0
f856e24a0eb234ec99ab77690cfab1d7
30.382716
110
0.673485
4.499115
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/flow/operators/FlatMapMergeTest.kt
1
2911
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlin.test.* class FlatMapMergeTest : FlatMapMergeBaseTest() { override fun <T> Flow<T>.flatMap(mapper: suspend (T) -> Flow<T>): Flow<T> = flatMapMerge(transform = mapper) @Test override fun testFlatMapConcurrency() = runTest { var concurrentRequests = 0 val flow = (1..100).asFlow().flatMapMerge(concurrency = 2) { value -> flow { ++concurrentRequests emit(value) delay(Long.MAX_VALUE) } } val consumer = launch { flow.collect { value -> expect(value) } } repeat(4) { yield() } assertEquals(2, concurrentRequests) consumer.cancelAndJoin() finish(3) } @Test fun testAtomicStart() = runTest { try { coroutineScope { val job = coroutineContext[Job]!! val flow = flow { expect(3) emit(1) } .onCompletion { expect(5) } .flatMapMerge { expect(4) flowOf(it).onCompletion { expectUnreached() } } .onCompletion { expect(6) } launch { expect(1) flow.collect() } launch { expect(2) yield() job.cancel() } } } catch (e: CancellationException) { finish(7) } } @Test fun testCancellationExceptionDownstream() = runTest { val flow = flowOf(1, 2, 3).flatMapMerge { flow { emit(it) throw CancellationException("") } } assertEquals(listOf(1, 2, 3), flow.toList()) } @Test fun testCancellationExceptionUpstream() = runTest { val flow = flow { expect(1) emit(1) expect(2) yield() throw CancellationException("") }.flatMapMerge { flow { expect(3) emit(it) hang { expect(4) } } } assertFailsWith<CancellationException>(flow) finish(5) } @Test fun testCancellation() = runTest { val result = flow { emit(1) emit(2) emit(3) emit(4) expectUnreached() // Cancelled by take emit(5) }.flatMapMerge(2) { v -> flow { emit(v) } } .take(2) .toList() assertEquals(listOf(1, 2), result) } }
apache-2.0
7a895acc1d5ea9f49961236ec6de3ed3
24.094828
112
0.447956
4.967577
false
true
false
false
io53/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/util/CsvExporter.kt
1
3443
package com.ruuvi.station.util import android.content.Context import android.content.Intent import androidx.core.content.FileProvider import android.widget.Toast import com.ruuvi.station.database.RuuviTagRepository import com.ruuvi.station.database.tables.TagSensorReading import java.io.File import java.io.FileWriter import java.text.SimpleDateFormat import java.util.* class CsvExporter(val context: Context) { fun toCsv(tagId: String) { val tag = RuuviTagRepository.get(tagId) val readings = TagSensorReading.getForTag(tagId) val cacheDir = File(context.cacheDir.path + "/export/") cacheDir.mkdirs() val csvFile = File.createTempFile( tag?.id + "_" + Date().time + "_", ".csv", cacheDir ) var fileWriter: FileWriter? val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") try { fileWriter = FileWriter(csvFile.absolutePath) fileWriter.append("timestamp,temperature,humidity,pressure,rssi") if (tag?.dataFormat == 3 || tag?.dataFormat == 5) fileWriter.append(",acceleration x,acceleration y,acceleration z,voltage") if (tag?.dataFormat == 5) fileWriter.append(",movement counter,measurement sequence number") fileWriter.append('\n') readings.forEach { fileWriter.append(df.format(it.createdAt)) fileWriter.append(',') fileWriter.append(it.temperature.toString()) fileWriter.append(',') fileWriter.append(it.humidity.toString()) fileWriter.append(',') fileWriter.append(it.pressure.toString()) fileWriter.append(',') fileWriter.append(it.rssi.toString()) if (tag?.dataFormat == 3 || tag?.dataFormat == 5) { fileWriter.append(',') fileWriter.append(it.accelX.toString()) fileWriter.append(',') fileWriter.append(it.accelY.toString()) fileWriter.append(',') fileWriter.append(it.accelZ.toString()) fileWriter.append(',') fileWriter.append(it.voltage.toString()) } if (tag?.dataFormat == 5) { fileWriter.append(',') fileWriter.append(it.movementCounter.toString()) fileWriter.append(',') fileWriter.append(it.measurementSequenceNumber.toString()) } fileWriter.append('\n') } fileWriter.flush() fileWriter.close() } catch (e: Exception) { Toast.makeText(context, "Failed to create CSV file", Toast.LENGTH_SHORT).show() e.printStackTrace() return } Toast.makeText(context, ".csv created, opening share menu", Toast.LENGTH_SHORT).show() val uri = FileProvider.getUriForFile(context, "com.ruuvi.station.fileprovider", csvFile) val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(Intent.EXTRA_STREAM, uri) sendIntent.type = "text/csv" sendIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION context.startActivity(Intent.createChooser(sendIntent, "RuuviTagEntity "+ tag?.id +" csv export")) } }
mit
5d963f692ab3c875019385ac2bb3c43c
40
136
0.586407
4.890625
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/super/basicproperty.kt
4
396
open class M() { open var b: Int = 0 } class N() : M() { val a : Int get() { super.b = super.b + 1 return super.b + 1 } override var b: Int = a + 1 val superb : Int get() = super.b } fun box(): String { val n = N() n.a n.b n.superb if (n.b == 3 && n.a == 4 && n.superb == 3) return "OK"; return "fail"; }
apache-2.0
42b0d55f0dc6ce44f42b669c5374d47c
15.5
59
0.416667
2.890511
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/render/selfrendering/RawCubeSideInfo.kt
1
1647
package net.ndrei.teslacorelib.render.selfrendering import net.minecraft.client.renderer.texture.TextureAtlasSprite import net.minecraft.util.EnumFacing import net.minecraft.util.math.Vec2f class RawCubeSideInfo( var sprite: TextureAtlasSprite? = null, var from: Vec2f = Vec2f(0.0f, 0.0f), var to: Vec2f = Vec2f(16.0f,16.0f), var bothSides: Boolean = false, var color: Int = -1, var tint: Int = -1) { fun autoUV(cube: RawCube, face: EnumFacing) { when (face.axis!!) { EnumFacing.Axis.X -> { from = Vec2f(((Math.min(cube.p1.z, cube.p2.z) / 2.0)).toFloat(), 16.0f - ((Math.min(cube.p1.y, cube.p2.y) / 2.0)).toFloat()) to = Vec2f(((Math.max(cube.p1.z, cube.p2.z) / 2.0)).toFloat(), 16.0f - ((Math.max(cube.p1.y, cube.p2.y) / 2.0)).toFloat()) } EnumFacing.Axis.Y -> { from = Vec2f(((Math.min(cube.p1.x, cube.p2.x) / 2.0)).toFloat(), 16.0f - ((Math.min(cube.p1.z, cube.p2.z) / 2.0)).toFloat()) to = Vec2f(((Math.max(cube.p1.x, cube.p2.x) / 2.0)).toFloat(), 16.0f - ((Math.max(cube.p1.z, cube.p2.z) / 2.0)).toFloat()) } EnumFacing.Axis.Z -> { from = Vec2f(((Math.min(cube.p1.x, cube.p2.x) / 2.0)).toFloat(), 16.0f - ((Math.min(cube.p1.y, cube.p2.y) / 2.0)).toFloat()) to = Vec2f(((Math.max(cube.p1.x, cube.p2.x) / 2.0)).toFloat(), 16.0f - ((Math.max(cube.p1.y, cube.p2.y) / 2.0)).toFloat()) } } } fun clone() = RawCubeSideInfo(this.sprite, this.from, this.to, this.bothSides, this.color, this.tint) }
mit
f9e3dd0f96dc508de0e1289335cf67d7
48.909091
140
0.55252
2.704433
false
false
false
false
marcospereira/AdventOfCodeKotlin
src/main/kotlin/com/github/marcospereira/Day5.kt
1
3893
package com.github.marcospereira val checkTwiceRule = Regex("(\\p{Alpha})\\1+") val checkBadParts = Regex("ab|cd|pq|xy") val pairTwiceRule = Regex(".*?((\\w\\w)\\w*\\2).*?") val repeatInBetweenRule = Regex(".*?((\\w)\\w\\2).*?") fun String.containsAtLeastThreeVowels() = this.count { "aeiou".contains(it) } >= 3 fun String.anyLetterAppearsTwiceInARow() = checkTwiceRule.containsMatchIn(this) fun String.containsBadParts() = checkBadParts.containsMatchIn(this) fun String.nice1() = containsAtLeastThreeVowels() && anyLetterAppearsTwiceInARow() && !containsBadParts() fun String.containsPairThatAppearsTwice() = pairTwiceRule.containsMatchIn(this) fun String.containsLetterThatRepeatsWithOneInBetween() = repeatInBetweenRule.containsMatchIn(this) fun String.nice2() = containsPairThatAppearsTwice() && containsLetterThatRepeatsWithOneInBetween() /** * ## Day 5: Doesn't He Have Intern-Elves For This? * * Santa needs help figuring out which strings in his text file are * naughty or nice. */ class Day5() : Day() { val words = file.readLines() /** * ### Part One * * A nice string is one with all of the following properties: * * - It contains at least three vowels (aeiou only), like aei, * xazegov, or aeiouaeiouaeiou. * - It contains at least one letter that appears twice in a row, * like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd). * - It does not contain the strings ab, cd, pq, or xy, even if they * are part of one of the other requirements. * * For example: * - `ugknbfddgicrmopn` is nice because it has at least three * vowels (u...i...o...), a double letter (...dd...), and * none of the disallowed substrings. * - `aaa` is nice because it has at least three vowels and a * double letter, even though the letters used by different * rules overlap. * - `jchzalrnumimnmhp` is naughty because it has no double letter. * - `haegwjzuvuyypxyu` is naughty because it contains the string xy. * - `dvszwmarrgswjxmb` is naughty because it contains only one vowel. * * How many strings are nice? */ override fun part1() = words.filter { it.nice1() }.size /** * ### Part Two * * Realizing the error of his ways, Santa has switched to a better model * of determining whether a string is naughty or nice. None of the old * rules apply, as they are all clearly ridiculous. * * Now, a nice string is one with all of the following properties: * * - It contains a pair of any two letters that appears at least twice * in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), * but not like aaa (aa, but it overlaps). * - It contains at least one letter which repeats with exactly one letter * between them, like xyx, abcdefeghi (efe), or even aaa. * * For example: * * - qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) * and a letter that repeats with exactly one letter between them (zxz). * - xxyxx is nice because it has a pair that appears twice and a letter * that repeats with one between, even though the letters used by each * rule overlap. * - uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat * with a single letter between them. ieodomkazucvgmuy is naughty because * it has a repeating letter with one between (odo), but no pair that appears twice. * * How many strings are nice under these new rules? */ override fun part2() = words.filter { it.nice2() }.size companion object { @JvmStatic fun main(args: Array<String>) { Day5().run() } } }
mit
11b0e26c9f463e40b9c0607bc88b4847
41.78022
105
0.638839
3.67611
false
false
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/store/SitReportsStore.kt
1
1695
package au.com.codeka.warworlds.server.store import au.com.codeka.warworlds.common.proto.SituationReport import au.com.codeka.warworlds.server.store.base.BaseStore class SitReportsStore internal constructor(fileName: String) : BaseStore(fileName) { fun save(sitReports: Collection<SituationReport>) { val writer = newWriter() .stmt("INSERT INTO sit_reports (empire_id, star_id, report_time, sit_report)" + " VALUES (?, ?, ?, ?)") for(sitReport in sitReports) { writer.param(0, sitReport.empire_id) writer.param(1, sitReport.star_id) writer.param(2, sitReport.report_time) writer.param(3, sitReport.encode()) writer.execute() } } fun getByEmpireId(empireId: Long, limit: Int): List<SituationReport> { newReader() .stmt( "SELECT sit_report " + "FROM sit_reports " + "WHERE empire_id = ? " + "ORDER BY report_time " + "DESC LIMIT ?") .param(0, empireId) .param(1, limit) .query().use { res -> val sitReports = ArrayList<SituationReport>() while (res.next()) { sitReports.add(SituationReport.ADAPTER.decode(res.getBytes(0))) } return sitReports } } override fun onOpen(diskVersion: Int): Int { var version = diskVersion if (version == 0) { newWriter() .stmt( "CREATE TABLE sit_reports (" + " empire_id INTEGER," + " star_id INTEGER," + " report_time INTEGER," + " sit_report BLOB)") .execute() version++ } return version } }
mit
1a0380cd094e7bcc8f253b0717560646
29.818182
87
0.565192
3.94186
false
false
false
false
smmribeiro/intellij-community
spellchecker/src/com/intellij/spellchecker/grazie/dictionary/WordListAdapter.kt
2
1545
// 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.spellchecker.grazie.dictionary import ai.grazie.spell.lists.WordList import ai.grazie.spell.utils.Distances internal class WordListAdapter : WordList, EditableWordListAdapter() { fun isAlien(word: String): Boolean { return dictionaries.values.all { it.contains(word) == null } && !aggregator.contains(word) } override fun contains(word: String, caseSensitive: Boolean): Boolean { val inDictionary = if (caseSensitive) { dictionaries.values.any { it.contains(word) ?: false } } else { val lowered = word.lowercase() // NOTE: dictionary may not contain lowercase form, but may contain any form in a different case // current dictionary interface does not support caseSensitive dictionaries.values.any { (it.contains(word) ?: false) || it.contains(lowered) ?: false } } return inDictionary || aggregator.contains(word, caseSensitive) } override fun suggest(word: String): LinkedHashSet<String> { val result = LinkedHashSet<String>() for (dictionary in dictionaries.values) { dictionary.consumeSuggestions(word) { val distance = Distances.levenshtein.distance(word, it, SimpleWordList.MAX_LEVENSHTEIN_DISTANCE + 1) if (distance <= SimpleWordList.MAX_LEVENSHTEIN_DISTANCE) { result.add(it) } } } result.addAll(aggregator.suggest(word)) return result } }
apache-2.0
7161aafbd6d736586b03a2dd2e1c05e5
38.615385
140
0.707443
4.109043
false
false
false
false
smmribeiro/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/dotnet/DotnetIconSync.kt
3
4470
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images.sync.dotnet import org.jetbrains.intellij.build.images.generateIconsClasses import org.jetbrains.intellij.build.images.isImage import org.jetbrains.intellij.build.images.shutdownAppScheduledExecutorService import org.jetbrains.intellij.build.images.sync.* import java.util.* fun main() = DotnetIconSync.sync() internal object DotnetIconSync { private class SyncPath(val iconsPath: String, val devPath: String) private val syncPaths = listOf( SyncPath("rider", "Rider/Frontend/rider/icons/resources/rider"), SyncPath("net", "Rider/Frontend/rider/icons/resources/resharper") ) private val committer by lazy(::triggeredBy) private val context = Context().apply { iconFilter = { file -> // need to filter designers' icons using developers' icon-robots.txt iconRepoDir.relativize(file) .let(devRepoDir::resolve) .let(IconRobotsDataReader::isSyncSkipped) .not() } } private val targetWaveNumber by lazy { val prop = "icons.sync.dotnet.wave.number" System.getProperty(prop) ?: error("Specify property $prop") } private val branchForMerge by lazy { val randomPart = UUID.randomUUID().toString().substring(1..4) "net$targetWaveNumber-icons-sync-$randomPart" } private val mergeRobotBuildConfiguration by lazy { val prop = "icons.sync.dotnet.merge.robot.build.conf" System.getProperty(prop) ?: error("Specify property $prop") } private fun step(msg: String) = println("\n** $msg") fun sync() { try { transformIconsToIdeaFormat() syncPaths.forEach(this::sync) generateClasses() if (stageChanges().isEmpty()) { println("Nothing to commit") } else if (isUnderTeamCity()) { createBranchForMerge() commitChanges() pushBranchForMerge() triggerMerge() } println("Done.") } finally { shutdownAppScheduledExecutorService() cleanup(context.iconRepo) } } private fun transformIconsToIdeaFormat() { step("Transforming icons from Dotnet to Idea format..") syncPaths.forEach { val path = context.iconRepo.resolve(it.iconsPath) DotnetIconsTransformation.transformToIdeaFormat(path) } } private fun sync(path: SyncPath) { step("Syncing icons for ${path.devPath}..") context.devRepoDir = context.devRepoRoot.resolve(path.devPath) context.iconRepoDir = context.iconRepo.resolve(path.iconsPath) context.devRepoDir.toFile().walkTopDown().forEach { if (isImage(it)) { it.delete() || error("Unable to delete $it") } } context.iconRepoDir.toFile().walkTopDown().forEach { if (isImage(it) && context.iconFilter(it.toPath())) { val target = context.devRepoDir.resolve(context.iconRepoDir.relativize(it.toPath())) it.copyTo(target.toFile(), overwrite = true) } } } private fun generateClasses() { step("Generating classes..") generateIconsClasses(dbFile = null, config = DotnetIconsClasses(context.devRepoDir.toAbsolutePath().toString())) } private fun stageChanges(): Collection<String> { step("Staging changes..") val changes = gitStatus(context.devRepoRoot, includeUntracked = true).all().filter { val file = context.devRepoRoot.resolve(it) isImage(file) || file.toString().endsWith(".java") } if (changes.isNotEmpty()) { stageFiles(changes, context.devRepoRoot) } return changes } private fun commitChanges() { step("Committing changes..") commit(context.devRepoRoot, "Synced from ${getOriginUrl(context.iconRepo)}", committer.name, committer.email) val commit = commitInfo(context.devRepoRoot) ?: error("Unable to perform commit") println("Committed ${commit.hash} '${commit.subject}'") } private fun createBranchForMerge() { step("Creating branch $branchForMerge..") execute(context.devRepoRoot, GIT, "checkout", "-B", branchForMerge) } private fun pushBranchForMerge() { step("Pushing $branchForMerge..") push(context.devRepoRoot, branchForMerge) } private fun triggerMerge() { step("Triggering merge with $mergeRobotBuildConfiguration..") val response = triggerBuild(mergeRobotBuildConfiguration, branchForMerge) println("Response is $response") } }
apache-2.0
c4ba719d18881b6091dc7d15e11b82bf
32.871212
140
0.694183
4.067334
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/ui/RenameDialog.kt
8
4963
// 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.refactoring.rename.ui import com.intellij.find.FindBundle import com.intellij.ide.util.scopeChooser.ScopeChooserCombo import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts.Label import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.impl.RenameOptions import com.intellij.refactoring.rename.impl.TextOptions import com.intellij.refactoring.ui.NameSuggestionsField import com.intellij.ui.UserActivityWatcher import com.intellij.ui.layout.* import java.awt.event.ActionEvent import java.awt.event.ItemEvent import javax.swing.AbstractAction import javax.swing.Action import javax.swing.JComponent internal class RenameDialog( private val project: Project, @Label private val presentableText: String, initOptions: Options, ) : DialogWrapper(project) { // model private var myTargetName: String = initOptions.targetName private var myCommentsStringsOccurrences: Boolean? = initOptions.renameOptions.textOptions.commentStringOccurrences private var myTextOccurrences: Boolean? = initOptions.renameOptions.textOptions.textOccurrences private var myScope: SearchScope = initOptions.renameOptions.searchScope var preview: Boolean = false private set private val myPreviewAction: Action = object : AbstractAction(RefactoringBundle.message("preview.button")) { override fun actionPerformed(e: ActionEvent) { preview = true okAction.actionPerformed(e) } } // ui private val myDialogPanel: DialogPanel = doCreateCenterPanel() init { title = RefactoringBundle.message("rename.title") setOKButtonText(RefactoringBundle.message("rename.title")) init() installWatcher() } private fun installWatcher() { UserActivityWatcher().apply { addUserActivityListener(::stateChanged) register(myDialogPanel) } } private fun stateChanged() { myDialogPanel.apply() // for some reason DSL UI implementation only updates model from UI only within apply() } override fun createCenterPanel(): JComponent = myDialogPanel override fun createActions(): Array<Action> { return arrayOf(okAction, cancelAction, helpAction, myPreviewAction) } private fun doCreateCenterPanel(): DialogPanel = panel { presentableText() newName() textOccurrenceCheckboxes() searchScope() } private fun LayoutBuilder.presentableText() { row { label(presentableText) } } private fun LayoutBuilder.newName() { row { val labelBuilder = label(RefactoringBundle.message("rename.dialog.new.name.label")) val nameSuggestionsField = NameSuggestionsField(arrayOf(myTargetName), project) nameSuggestionsField.addDataChangedListener { myTargetName = nameSuggestionsField.enteredName } nameSuggestionsField.invoke().constraints(growX).focused() labelBuilder.component.labelFor = nameSuggestionsField } } private fun LayoutBuilder.textOccurrenceCheckboxes() { if (myCommentsStringsOccurrences == null && myTextOccurrences == null) { return } row { cell(isFullWidth = true) { myCommentsStringsOccurrences?.let { checkBox( text = RefactoringBundle.getSearchInCommentsAndStringsText(), getter = { it }, setter = { myCommentsStringsOccurrences = it } ) } myTextOccurrences?.let { checkBox( text = RefactoringBundle.getSearchForTextOccurrencesText(), getter = { it }, setter = { myTextOccurrences = it } ) } } } } private fun LayoutBuilder.searchScope() { if (myScope is LocalSearchScope) { return } val scopeCombo = ScopeChooserCombo(project, true, true, myScope.displayName) Disposer.register(myDisposable, scopeCombo) scopeCombo.comboBox.addItemListener { event -> if (event.stateChange == ItemEvent.SELECTED) { myScope = scopeCombo.selectedScope ?: return@addItemListener } } row { val labelBuilder = label(FindBundle.message("find.scope.label")) scopeCombo.invoke() labelBuilder.component.labelFor = scopeCombo } } fun result(): Options = Options( targetName = myTargetName, renameOptions = RenameOptions( textOptions = TextOptions( commentStringOccurrences = myCommentsStringsOccurrences, textOccurrences = myTextOccurrences, ), searchScope = myScope ) ) data class Options( val targetName: String, val renameOptions: RenameOptions ) }
apache-2.0
7a56208c3b7e9075654d342318a69e2a
31.019355
140
0.72436
4.860921
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleMigrateTest.kt
2
4319
// 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.codeInsight.gradle import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.concurrency.FutureResult import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.configuration.KotlinMigrationProjectService import org.jetbrains.kotlin.idea.configuration.KotlinMigrationProjectService.MigrationTestState import org.jetbrains.kotlin.idea.configuration.MigrationInfo import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.junit.Ignore import org.junit.Test import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException class GradleMigrateTest : GradleImportingTestCase() { @Test @Ignore // Import failed: A problem occurred evaluating project ':app' @TargetVersions("5.3+") fun testMigrateStdlib() { val migrateComponentState = doMigrationTest( beforeText = """ buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.40" } } apply plugin: 'kotlin' dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:1.3.40" } """, //ToDo: Change 1.4-M3 to 1.4.0 version after release afterText = """ buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.0-rc" } } apply plugin: 'kotlin' dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:1.4.0-rc" } """ ) assertEquals(false, migrateComponentState?.hasApplicableTools) assertEquals( MigrationInfo.create( oldStdlibVersion = "1.3.40", oldApiVersion = ApiVersion.KOTLIN_1_3, oldLanguageVersion = LanguageVersion.KOTLIN_1_3, newStdlibVersion = "1.4.0-rc", newApiVersion = ApiVersion.KOTLIN_1_4, newLanguageVersion = LanguageVersion.KOTLIN_1_4 ), migrateComponentState?.migrationInfo ) } @Suppress("SameParameterValue") private fun doMigrationTest(beforeText: String, afterText: String): MigrationTestState? { createProjectSubFile("settings.gradle", "include ':app'") val gradleFile = createProjectSubFile("app/build.gradle", beforeText.trimIndent()) importProject() val document = runReadAction { val gradlePsiFile = PsiManager.getInstance(myProject).findFile(gradleFile) ?: error("Can't find psi file for gradle file") PsiDocumentManager.getInstance(myProject).getDocument(gradlePsiFile) ?: error("Can't find document for gradle file") } runInEdtAndWait { runWriteAction { document.setText(afterText.trimIndent()) } } val importResult = FutureResult<MigrationTestState?>() val migrationProjectComponent = KotlinMigrationProjectService.getInstance(myProject) migrationProjectComponent.setImportFinishListener { migrationState -> importResult.set(migrationState) } importProject() return try { importResult.get(5, TimeUnit.SECONDS) } catch (te: TimeoutException) { throw IllegalStateException("No reply with result from migration component") } finally { migrationProjectComponent.setImportFinishListener(null) } } }
apache-2.0
ab60f82d2f8fd11f1547905f8085504f
35.923077
158
0.639268
5.254258
false
true
false
false
NativeScript/android-runtime
test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/security/classes/SecuredClassRepository.kt
1
4198
package com.telerik.metadata.security.classes import com.telerik.metadata.ClassMapProvider import com.telerik.metadata.parsing.NativeClassDescriptor import com.telerik.metadata.security.filtering.blacklisting.MetadataBlacklist import com.telerik.metadata.security.filtering.input.user.UserPatternsCollection import com.telerik.metadata.security.filtering.matching.impl.PatternMatcherImpl import com.telerik.metadata.security.filtering.whitelisting.MetadataWhitelist import com.telerik.metadata.security.logging.console.MetadataFilterConsoleLogger import java.util.* import kotlin.collections.HashSet object SecuredClassRepository { private val cachedProviders = ArrayList<ClassMapProvider>() private val patternMatcher = PatternMatcherImpl() private val whitelist = MetadataWhitelist(UserPatternsCollection.whitelistEntries, patternMatcher) private val blacklist = MetadataBlacklist(UserPatternsCollection.blacklistEntries, patternMatcher) private val alreadyLoggedClasses = HashSet<Pair<String, String>>() fun addToCache(classMapProvider: ClassMapProvider) { cachedProviders.add(classMapProvider) } private fun NativeClassDescriptor.getSimplifiedClassName() = this.className.substring(this.packageName.length).replace('$', '.').trimStart('.') fun findClass(className: String): SecuredNativeClassDescriptor { val clazz: NativeClassDescriptor? = findClassFromProviders(className) if (clazz != null) { val simplifiedClassName = clazz.getSimplifiedClassName() val isUsageAllowed = isClassUsageAllowed(clazz.packageName, simplifiedClassName) if (isUsageAllowed) { return SecuredNativeClassDescriptor(true, clazz) } } return SecuredNativeClassDescriptor(false, NativeClassDescriptor.Missing) } fun findNearestAllowedClass(className: String): SecuredNativeClassDescriptor { var clazz: NativeClassDescriptor? = findClassFromProviders(className) while (clazz != null) { val simplifiedClassName = clazz.getSimplifiedClassName() val isUsageAllowed = isClassUsageAllowed(clazz.packageName, simplifiedClassName) if (isUsageAllowed) { return SecuredNativeClassDescriptor(true, clazz) } clazz = findClassFromProviders(clazz.superclassName) } return SecuredNativeClassDescriptor(false, NativeClassDescriptor.Missing) } private fun isClassUsageAllowed(packageName: String, className: String): Boolean { val whitelistFilterResult = whitelist.isAllowed(packageName, className) val blacklistFilterResult = blacklist.isAllowed(packageName, className) val packageAndClassNamePair = packageName to className if (whitelistFilterResult.isAllowed && blacklistFilterResult.isAllowed) { if (packageAndClassNamePair !in alreadyLoggedClasses) { MetadataFilterConsoleLogger.logAllowed(packageName, className, whitelistFilterResult, blacklistFilterResult) alreadyLoggedClasses.add(packageAndClassNamePair) } return true } if (packageAndClassNamePair !in alreadyLoggedClasses) { MetadataFilterConsoleLogger.logDisallowed(packageName, className, whitelistFilterResult, blacklistFilterResult) alreadyLoggedClasses.add(packageAndClassNamePair) } return false } private fun findClassFromProviders(className: String): NativeClassDescriptor? { var clazz: NativeClassDescriptor? = null for (classMapProvider in cachedProviders) { clazz = classMapProvider.classMap[className] if (clazz != null) { break } } return clazz } fun getClassNames(): Array<String> { val names = ArrayList<String>() for (classMapProvider in cachedProviders) { for (className in classMapProvider.classMap.keys) { names.add(className) } } val arrClassNames = names.toTypedArray() Arrays.sort(arrClassNames) return arrClassNames } }
apache-2.0
8049d44def8ca7787c6a92b2bc6da02b
39.375
147
0.717246
5.287154
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/util.kt
4
2758
// 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.formatter.trailingComma import com.intellij.lang.ASTNode import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.PsiUtilCore import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtWhenEntry import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.utils.addToStdlib.cast fun trailingCommaIsAllowedOnCallSite(): Boolean = Registry.`is`("kotlin.formatter.allowTrailingCommaOnCallSite") private val TYPES_WITH_TRAILING_COMMA_ON_DECLARATION_SITE = TokenSet.create( KtNodeTypes.TYPE_PARAMETER_LIST, KtNodeTypes.DESTRUCTURING_DECLARATION, KtNodeTypes.WHEN_ENTRY, KtNodeTypes.FUNCTION_LITERAL, KtNodeTypes.VALUE_PARAMETER_LIST, ) private val TYPES_WITH_TRAILING_COMMA_ON_CALL_SITE = TokenSet.create( KtNodeTypes.COLLECTION_LITERAL_EXPRESSION, KtNodeTypes.TYPE_ARGUMENT_LIST, KtNodeTypes.INDICES, KtNodeTypes.VALUE_ARGUMENT_LIST, ) private val TYPES_WITH_TRAILING_COMMA = TokenSet.orSet( TYPES_WITH_TRAILING_COMMA_ON_DECLARATION_SITE, TYPES_WITH_TRAILING_COMMA_ON_CALL_SITE, ) fun PsiElement.canAddTrailingCommaWithRegistryCheck(): Boolean { val type = PsiUtilCore.getElementType(this) ?: return false return type in TYPES_WITH_TRAILING_COMMA_ON_DECLARATION_SITE || trailingCommaIsAllowedOnCallSite() && type in TYPES_WITH_TRAILING_COMMA_ON_CALL_SITE } fun KotlinCodeStyleSettings.addTrailingCommaIsAllowedFor(node: ASTNode): Boolean = addTrailingCommaIsAllowedFor(PsiUtilCore.getElementType(node)) fun KotlinCodeStyleSettings.addTrailingCommaIsAllowedFor(element: PsiElement): Boolean = addTrailingCommaIsAllowedFor(PsiUtilCore.getElementType(element)) private fun KotlinCodeStyleSettings.addTrailingCommaIsAllowedFor(type: IElementType?): Boolean = when (type) { null -> false in TYPES_WITH_TRAILING_COMMA_ON_DECLARATION_SITE -> ALLOW_TRAILING_COMMA in TYPES_WITH_TRAILING_COMMA_ON_CALL_SITE -> ALLOW_TRAILING_COMMA_ON_CALL_SITE || trailingCommaIsAllowedOnCallSite() else -> false } fun PsiElement.canAddTrailingComma(): Boolean = when { this is KtWhenEntry && (isElse || parent.cast<KtWhenExpression>().leftParenthesis == null) -> false this is KtFunctionLiteral && arrow == null -> false else -> PsiUtilCore.getElementType(this) in TYPES_WITH_TRAILING_COMMA }
apache-2.0
420d35fa4a6103b855dfe048d82cb16c
42.793651
158
0.794054
4.262751
false
false
false
false
DroidSmith/TirePressureGuide
tireguide/src/main/java/com/droidsmith/tireguide/Profiles.kt
1
585
package com.droidsmith.tireguide import android.provider.BaseColumns class Profiles : BaseColumns, ProfileColumns { companion object { @JvmField var _ID = 0 @JvmField var PROFILE_NAME = 1 @JvmField var RIDER_TYPE = 2 @JvmField var BODY_WEIGHT = 3 @JvmField var BIKE_WEIGHT = 4 @JvmField var FRONT_TIRE_WIDTH = 5 @JvmField var REAR_TIRE_WIDTH = 6 @JvmField var FRONT_LOAD_PERCENT = 7 @JvmField var REAR_LOAD_PERCENT = 8 } }
apache-2.0
47859fd51fd222bb311cc93dbb76cc95
16.205882
46
0.550427
4.270073
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertCollectionConstructorToFunction.kt
1
2123
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertCollectionConstructorToFunction : SelfTargetingIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.collection.constructor.to.function") ) { private val functionMap = hashMapOf( "java.util.ArrayList.<init>" to "arrayListOf", "kotlin.collections.ArrayList.<init>" to "arrayListOf", "java.util.HashMap.<init>" to "hashMapOf", "kotlin.collections.HashMap.<init>" to "hashMapOf", "java.util.HashSet.<init>" to "hashSetOf", "kotlin.collections.HashSet.<init>" to "hashSetOf", "java.util.LinkedHashMap.<init>" to "linkedMapOf", "kotlin.collections.LinkedHashMap.<init>" to "linkedMapOf", "java.util.LinkedHashSet.<init>" to "linkedSetOf", "kotlin.collections.LinkedHashSet.<init>" to "linkedSetOf" ) override fun isApplicableTo(element: KtCallExpression, caretOffset: Int): Boolean { val fq = element.resolveToCall()?.resultingDescriptor?.fqNameSafe?.asString() ?: return false return functionMap.containsKey(fq) && element.valueArguments.size == 0 } override fun applyTo(element: KtCallExpression, editor: Editor?) { val fq = element.resolveToCall()?.resultingDescriptor?.fqNameSafe?.asString() ?: return val toCall = functionMap[fq] ?: return val callee = element.calleeExpression ?: return callee.replace(KtPsiFactory(element).createIdentifier(toCall)) element.getQualifiedExpressionForSelector()?.replace(element) } }
apache-2.0
ba1689e1dfca4a6b032841f53ef553a2
49.547619
158
0.739991
4.728285
false
false
false
false
siosio/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/StaticInitDeclarationConversion.kt
1
1663
// 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.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.createCompanion import org.jetbrains.kotlin.nj2k.getCompanion import org.jetbrains.kotlin.nj2k.replace import org.jetbrains.kotlin.nj2k.tree.* class StaticInitDeclarationConversion(context : NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) val staticInitDeclarations = element.classBody.declarations.filterIsInstance<JKJavaStaticInitDeclaration>() if (staticInitDeclarations.isEmpty()) return recurse(element) val companion = element.getCompanion() if (companion == null) { element.classBody.declarations = element.classBody.declarations.replace( staticInitDeclarations.first(), createCompanion(staticInitDeclarations.map { it.toKtInitDeclaration() }) ) element.classBody.declarations -= staticInitDeclarations.drop(1) } else { companion.classBody.declarations += staticInitDeclarations.map { it.toKtInitDeclaration() } element.classBody.declarations -= staticInitDeclarations } return recurse(element) } private fun JKJavaStaticInitDeclaration.toKtInitDeclaration() = JKKtInitDeclaration(::block.detached()).withFormattingFrom(this) }
apache-2.0
c941f9361573de8c2d314c741e964c2b
46.542857
158
0.735418
4.891176
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/AlLog.kt
1
1886
package alraune import alraune.entity.* import org.slf4j.LoggerFactory import pieces100.* import vgrechka.* import java.util.* class AlLog { private val log = LoggerFactory.getLogger(AlLog::class.java) enum class Level { Debug, Info, Warning, Error } object Tag { val alrauneStart by myName() } fun error(_message: String?, throwable: Throwable? = null, shitIntoData: (AlLogEntryDataPile) -> Unit = {}): String { val message = _message ?: "<null>" if (throwable != null) log.error(message, throwable) else log.error(message) val incidentCode = UUID.randomUUID().toString() fart(Level.Error, message) { it.throwableStackTrace = throwable?.stackTraceString it.incidentCode = incidentCode shitIntoData(it) } return incidentCode } fun debug(message: String) { log.debug(message) fart(Level.Debug, message) } fun info(message: String) { log.info(message) fart(Level.Info, message) } fun shouldLogToDb() = P100_Global.standaloneTool == null fun fart(level: Level, message: String, shitIntoData: (AlLogEntryDataPile) -> Unit = {}) { if (!shouldLogToDb()) return try { !ObtainDbConnectionDoShitAndClose({AlGlobal.appDataSource}) {con-> val db = AlDbFuns {AlQueryBuilder(con, false)} db.insertEntity(AlLogEntry().fill( dataPile = AlLogEntryDataPile().also { it.level = level it.message = message shitIntoData(it) } )) } } catch (e: Throwable) { log.error("We are fucked, man... Can't even add shit to log table. ${e.message}", e) } } }
apache-2.0
5a84e1314384ec18d835586d33c7e215
27.575758
121
0.560976
4.296128
false
false
false
false
JetBrains/kotlin-native
klib/src/test/testData/TopLevelPropertiesRootPackage.kt
4
801
/* * Copyright 2010-2018 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. */ @file:Suppress("UNUSED_PARAMETER") typealias MyTransformer = (String) -> Int // top-level properties val v1 = 1 val v2 = "hello" val v3: (String) -> Int = { it.length } val v4: MyTransformer = v3
apache-2.0
2eb309aa4992db25ab95309324c96964
29.807692
75
0.722846
3.708333
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinInlayParameterHintsProvider.kt
1
3694
// 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.codeInsight.hints import com.intellij.codeInsight.hints.HintInfo import com.intellij.codeInsight.hints.InlayInfo import com.intellij.codeInsight.hints.InlayParameterHintsProvider import com.intellij.lang.Language import com.intellij.lang.java.JavaLanguage import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallElement import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe @Suppress("UnstableApiUsage") class KotlinInlayParameterHintsProvider : InlayParameterHintsProvider { override fun getDefaultBlackList(): Set<String> = setOf( "*listOf", "*setOf", "*arrayOf", "*ListOf", "*SetOf", "*ArrayOf", "*assert*(*)", "*mapOf", "*MapOf", "kotlin.require*(*)", "kotlin.check*(*)", "*contains*(value)", "*containsKey(key)", "kotlin.lazyOf(value)", "*SequenceBuilder.resume(value)", "*SequenceBuilder.yield(value)", /* Gradle DSL especially annoying hints */ "org.gradle.api.Project.hasProperty(propertyName)", "org.gradle.api.Project.findProperty(propertyName)", "org.gradle.api.Project.file(path)", "org.gradle.api.Project.uri(path)", "jvmArgs(arguments)", "org.gradle.kotlin.dsl.DependencyHandlerScope.*(notation)", "org.gradle.kotlin.dsl.*(dependencyNotation)", "org.gradle.kotlin.dsl.kotlin(module)", "org.gradle.kotlin.dsl.kotlin(module,version)", "org.gradle.kotlin.dsl.project(path,configuration)" ) override fun getHintInfo(element: PsiElement): HintInfo? { if (!(HintType.PARAMETER_HINT.isApplicable(element))) return null val parent: PsiElement = (element as? KtValueArgumentList)?.parent ?: return null return (parent as? KtCallElement)?.let { getMethodInfo(it) } } override fun getParameterHints(element: PsiElement): List<InlayInfo> { return if (HintType.PARAMETER_HINT.isApplicable(element)) HintType.PARAMETER_HINT.provideHints(element) else emptyList() } override fun getBlackListDependencyLanguage(): Language = JavaLanguage.INSTANCE override fun getInlayPresentation(inlayText: String): String = inlayText private fun getMethodInfo(elem: KtCallElement): HintInfo.MethodInfo? { val resolvedCall = elem.resolveToCall() val resolvedCallee = resolvedCall?.candidateDescriptor if (resolvedCallee is FunctionDescriptor) { val paramNames = resolvedCallee.valueParameters.asSequence().map { it.name }.filter { !it.isSpecial }.map(Name::asString).toList() val fqName = if (resolvedCallee is ConstructorDescriptor) resolvedCallee.containingDeclaration.fqNameSafe.asString() else (resolvedCallee.fqNameOrNull()?.asString() ?: return null) return HintInfo.MethodInfo(fqName, paramNames) } return null } } fun PsiElement.isNameReferenceInCall() = this is KtNameReferenceExpression && parent is KtCallExpression
apache-2.0
ff3fad198b228a10f1ceeaf7aebfb638
46.987013
158
0.713319
4.847769
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspClassFileUtility.kt
3
12617
/* * 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.room.compiler.processing.ksp import androidx.room.compiler.processing.XProcessingConfig import com.google.devtools.ksp.symbol.ClassKind import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSNode import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.google.devtools.ksp.symbol.Origin import java.lang.reflect.InvocationHandler import java.lang.reflect.Method import java.lang.reflect.Proxy /** * When a compiled kotlin class is loaded from a `.class` file, its fields are not ordered in the * same way they are declared in code. * This particularly hurts Room where we generate the table structure in that order. * * This class implements a port of https://github.com/google/ksp/pull/260 via reflection until KSP * (or kotlin compiler) fixes the problem. As this uses reflection, it is fail safe such that if it * cannot find the correct order, it will just return in the order KSP returned instead of crashing. * * KSP Bugs: * * https://github.com/google/ksp/issues/250 */ internal object KspClassFileUtility { /** * Sorts the given fields in the order they are declared in the backing class declaration. */ fun orderFields( owner: KSClassDeclaration, fields: List<KspFieldElement> ): List<KspFieldElement> { // no reason to try to load .class if we don't have any fields to sort if (fields.isEmpty()) return fields if (owner.origin == Origin.KOTLIN) { // this is simple and temporary case that KSP can fix. No reason to create a more // complicated comparator for it since it will be removed // https://github.com/google/ksp/issues/727 return orderKotlinSourceFields(owner, fields) } val comparator = getNamesComparator(owner, Type.FIELD, KspFieldElement::name) return if (comparator == null) { fields } else { fields.forEach { // make sure each name gets registered so that if we didn't find it in .class for // whatever reason, we keep the order given from KSP. comparator.register(it.name) } fields.sortedWith(comparator) } } /** * KSP returns properties from primary constructor last instead of first. * https://github.com/google/ksp/issues/727 * This function reverts that. This method traverses declaration hierarchy instead of looking at * the primary constructor's fields as some of them may not be fields. */ private fun orderKotlinSourceFields( owner: KSClassDeclaration, fields: List<KspFieldElement> ): List<KspFieldElement> { val primaryConstructor = owner.primaryConstructor ?: return fields return fields.sortedBy { if (it.declaration.isDeclaredInside(primaryConstructor)) { 0 } else { 1 } } } private fun KSPropertyDeclaration.isDeclaredInside( functionDeclaration: KSFunctionDeclaration ): Boolean { var current: KSNode? = this while (current != null) { if (current == functionDeclaration) { return true } current = current.parent } return false } /** * Sorts the given methods in the order they are declared in the backing class declaration. * Note that this does not check signatures so ordering might break if there are multiple * methods with the same name. */ fun orderMethods( owner: KSClassDeclaration, methods: List<KspMethodElement> ): List<KspMethodElement> { // no reason to try to load .class if we don't have any fields to sort if (methods.isEmpty()) return methods val comparator = getNamesComparator(owner, Type.METHOD, KspMethodElement::jvmName) return if (comparator == null) { methods } else { methods.forEach { // make sure each name gets registered so that if we didn't find it in .class for // whatever reason, we keep the order given from KSP. comparator.register(it.jvmName) } methods.sortedWith(comparator) } } /** * Builds a field names comparator from the given class declaration if and only if its origin * is Kotlin .class. * If it fails to find the order, returns null. */ @Suppress("BanUncheckedReflection") private fun <T> getNamesComparator( ksClassDeclaration: KSClassDeclaration, type: Type, getName: T.() -> String, ): MemberNameComparator<T>? { return try { // this is needed only for compiled kotlin classes // https://github.com/google/ksp/issues/250#issuecomment-761108924 if (ksClassDeclaration.origin != Origin.KOTLIN_LIB) return null // A companion object's `declarations` contains fields declared in the object in KSP, // while KotlinJvmBinaryClass.visitMembers() does not. This leads to unsorted fields. // As a workaround we register all the fields of an enclosing type in hope that we // cover every field in a companion object's KSDeclarationContainer.declarations. val classDeclaration = if ( ksClassDeclaration.isCompanionObject && type == Type.FIELD && ksClassDeclaration.parentDeclaration is KSClassDeclaration) { ksClassDeclaration.parentDeclaration as KSClassDeclaration } else { ksClassDeclaration } val typeReferences = ReflectionReferences.getInstance(classDeclaration) ?: return null val binarySource = getBinarySource(typeReferences, classDeclaration) ?: return null val fieldNameComparator = MemberNameComparator( getName = getName, // we can do strict mode only in classes. For Interfaces, private methods won't // show up in the binary. strictMode = XProcessingConfig.STRICT_MODE && classDeclaration.classKind != ClassKind.INTERFACE ) val invocationHandler = InvocationHandler { _, method, args -> if (method.name == type.visitorName) { val nameAsString = typeReferences.asStringMethod.invoke(args[0]) if (nameAsString is String) { fieldNameComparator.register(nameAsString) } } null } val proxy = Proxy.newProxyInstance( classDeclaration.javaClass.classLoader, arrayOf(typeReferences.memberVisitor), invocationHandler ) typeReferences.visitMembersMethod.invoke(binarySource, proxy, null) fieldNameComparator.seal() fieldNameComparator } catch (ignored: Throwable) { // this is best effort, if it failed, just ignore if (XProcessingConfig.STRICT_MODE) { throw RuntimeException("failed to get fields", ignored) } null } } private fun getBinarySource( typeReferences: ReflectionReferences, ksClassDeclaration: KSClassDeclaration ): Any? { val descriptor = typeReferences.getDescriptorMethod.invoke(ksClassDeclaration) ?: return null if (!typeReferences.deserializedClassDescriptor.isInstance(descriptor)) { return null } val descriptorSrc = typeReferences.descriptorSourceMethod.invoke(descriptor) ?: return null if (!typeReferences.kotlinJvmBinarySourceElement.isInstance(descriptorSrc)) { return null } return typeReferences.binaryClassMethod.invoke(descriptorSrc) ?: return null } /** * Holder object to keep references to class/method instances. */ private class ReflectionReferences private constructor( classLoader: ClassLoader ) { val deserializedClassDescriptor: Class<*> = classLoader.loadClass( "org.jetbrains.kotlin.serialization.deserialization.descriptors" + ".DeserializedClassDescriptor" ) val ksClassDeclarationDescriptorImpl: Class<*> = classLoader.loadClass( "com.google.devtools.ksp.symbol.impl.binary.KSClassDeclarationDescriptorImpl" ) val kotlinJvmBinarySourceElement: Class<*> = classLoader.loadClass( "org.jetbrains.kotlin.load.kotlin.KotlinJvmBinarySourceElement" ) val kotlinJvmBinaryClass: Class<*> = classLoader.loadClass( "org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass" ) val memberVisitor: Class<*> = classLoader.loadClass( "org.jetbrains.kotlin.load.kotlin.KotlinJvmBinaryClass\$MemberVisitor" ) val name: Class<*> = classLoader.loadClass( "org.jetbrains.kotlin.name.Name" ) val getDescriptorMethod: Method = ksClassDeclarationDescriptorImpl .getDeclaredMethod("getDescriptor") val descriptorSourceMethod: Method = deserializedClassDescriptor.getMethod("getSource") val binaryClassMethod: Method = kotlinJvmBinarySourceElement.getMethod("getBinaryClass") val visitMembersMethod: Method = kotlinJvmBinaryClass.getDeclaredMethod( "visitMembers", memberVisitor, ByteArray::class.java ) val asStringMethod: Method = name.getDeclaredMethod("asString") companion object { private val FAILED = Any() private var instance: Any? = null /** * Gets the cached instance or create a new one using the class loader of the given * [ref] parameter. */ fun getInstance(ref: Any): ReflectionReferences? { if (instance == null) { instance = try { ReflectionReferences(ref::class.java.classLoader) } catch (ignored: Throwable) { FAILED } } return instance as? ReflectionReferences } } } private class MemberNameComparator<T>( val getName: T.() -> String, val strictMode: Boolean ) : Comparator<T> { private var nextOrder: Int = 0 private var sealed: Boolean = false private val orders = mutableMapOf<String, Int>() /** * Called when fields are read to lock the ordering. * This is only relevant in tests as at runtime, we just do a best effort (add a new id * for it) and continue. */ fun seal() { sealed = true } /** * Registers the name with the next order id */ fun register(name: String) { getOrder(name) } /** * Gets the order of the name. If it was not seen before, adds it to the list, giving it a * new ID. */ private fun getOrder(name: String) = orders.getOrPut(name) { if (sealed && strictMode) { error("expected to find field/method $name but it is non-existent") } nextOrder++ } override fun compare(elm1: T, elm2: T): Int { return getOrder(elm1.getName()).compareTo(getOrder(elm2.getName())) } } /** * The type of declaration that we want to extract from class descriptor. */ private enum class Type( val visitorName: String ) { FIELD("visitField"), METHOD("visitMethod") } }
apache-2.0
d590e812565093e4c126fa93ff1dd135
37.466463
100
0.62178
5.122615
false
false
false
false
androidx/androidx
development/importMaven/src/main/kotlin/androidx/build/importMaven/JarAndAarAreCompatible.kt
3
1510
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.importMaven import org.gradle.api.artifacts.CacheableRule import org.gradle.api.attributes.AttributeCompatibilityRule import org.gradle.api.attributes.CompatibilityCheckDetails import org.gradle.api.attributes.LibraryElements /** * A [AttributeCompatibilityRule] that makes Gradle consider both aar and jar as compatible * artifacts. */ @CacheableRule abstract class JarAndAarAreCompatible : AttributeCompatibilityRule<LibraryElements> { override fun execute(t: CompatibilityCheckDetails<LibraryElements>) { val consumer = t.consumerValue?.name ?: return val producer = t.producerValue?.name ?: return if (consumer.isAarOrJar() && producer.isAarOrJar()) { t.compatible() } } private fun String.isAarOrJar() = compareTo("jar", ignoreCase = true) == 0 || compareTo("aar", ignoreCase = true) == 0 }
apache-2.0
229434be3d524cd8cfe5a78d7a3a341d
36.75
91
0.733775
4.241573
false
false
false
false
androidx/androidx
sqlite/sqlite-inspection/src/androidTest/java/androidx/sqlite/inspection/test/ProtoExtensions.kt
3
4174
/* * Copyright 2020 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.sqlite.inspection.test import androidx.sqlite.inspection.SqliteInspectorProtocol.CellValue import androidx.sqlite.inspection.SqliteInspectorProtocol.CellValue.OneOfCase import androidx.sqlite.inspection.SqliteInspectorProtocol.Command import androidx.sqlite.inspection.SqliteInspectorProtocol.GetSchemaCommand import androidx.sqlite.inspection.SqliteInspectorProtocol.GetSchemaResponse import androidx.sqlite.inspection.SqliteInspectorProtocol.KeepDatabasesOpenCommand import androidx.sqlite.inspection.SqliteInspectorProtocol.KeepDatabasesOpenResponse import androidx.sqlite.inspection.SqliteInspectorProtocol.QueryCommand import androidx.sqlite.inspection.SqliteInspectorProtocol.QueryParameterValue import androidx.sqlite.inspection.SqliteInspectorProtocol.Response import androidx.sqlite.inspection.SqliteInspectorProtocol.TrackDatabasesCommand import androidx.sqlite.inspection.SqliteInspectorProtocol.TrackDatabasesResponse val CellValue.value: Any? get() = valueType.first val CellValue.type: String get() = valueType.second val CellValue.valueType: Pair<Any?, String> get() = when (oneOfCase) { OneOfCase.STRING_VALUE -> stringValue to "text" OneOfCase.LONG_VALUE -> longValue to "integer" OneOfCase.DOUBLE_VALUE -> doubleValue to "float" OneOfCase.BLOB_VALUE -> blobValue.toByteArray().toTypedArray() to "blob" OneOfCase.ONEOF_NOT_SET -> null to "null" else -> throw IllegalArgumentException() } fun GetSchemaResponse.toTableList(): List<Table> = tablesList.map { t -> Table(t.name, t.columnsList.map { c -> Column(c.name, c.type) }) } object MessageFactory { fun createTrackDatabasesCommand(): Command = Command.newBuilder().setTrackDatabases(TrackDatabasesCommand.getDefaultInstance()).build() fun createTrackDatabasesResponse(): Response = Response.newBuilder().setTrackDatabases(TrackDatabasesResponse.getDefaultInstance()).build() fun createKeepDatabasesOpenCommand(setEnabled: Boolean): Command = Command.newBuilder().setKeepDatabasesOpen( KeepDatabasesOpenCommand.newBuilder().setSetEnabled(setEnabled) ).build() fun createKeepDatabasesOpenResponse(): Response = Response.newBuilder().setKeepDatabasesOpen( KeepDatabasesOpenResponse.getDefaultInstance() ).build() fun createGetSchemaCommand(databaseId: Int): Command = Command.newBuilder().setGetSchema( GetSchemaCommand.newBuilder().setDatabaseId(databaseId).build() ).build() fun createQueryCommand( databaseId: Int, query: String, queryParams: List<String?>? = null, responseSizeLimitHint: Long? = null ): Command = Command.newBuilder().setQuery( QueryCommand.newBuilder() .setDatabaseId(databaseId) .setQuery(query) .also { queryCommandBuilder -> if (queryParams != null) queryCommandBuilder.addAllQueryParameterValues( queryParams.map { param -> QueryParameterValue.newBuilder() .also { builder -> if (param != null) builder.stringValue = param } .build() } ) if (responseSizeLimitHint != null) { queryCommandBuilder.responseSizeLimitHint = responseSizeLimitHint } } .build() ).build() }
apache-2.0
7e93bece9d0feb9d5f668a7ca7fff3d5
43.88172
100
0.699329
4.97497
false
false
false
false
holisticon/ranked
backend/views/wall/src/main/kotlin/WallView.kt
1
3649
@file:Suppress("UNUSED") package de.holisticon.ranked.view.wall import de.holisticon.ranked.model.AbstractMatchSet import de.holisticon.ranked.model.Team import de.holisticon.ranked.model.UserName import de.holisticon.ranked.model.event.MatchCreated import de.holisticon.ranked.model.event.PlayerParticipatedInMatch import de.holisticon.ranked.model.event.TeamWonMatch import de.holisticon.ranked.model.event.TeamWonMatchSet import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import mu.KLogging import org.axonframework.config.ProcessingGroup import org.axonframework.eventhandling.EventHandler import org.axonframework.eventhandling.Timestamp import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.time.Instant import java.time.LocalDateTime import java.time.ZoneOffset @ProcessingGroup(WallView.NAME) @Api(tags = ["News wall"]) @RestController @RequestMapping(value = ["/view"]) class WallView { companion object : KLogging() { const val NAME = "Wall" } val matches: MutableList<Match> = mutableListOf() val playerWins: MutableList<PlayerWin> = mutableListOf() val teamWins: MutableList<TeamWin> = mutableListOf() @ApiOperation(value = "Lists matches.") @GetMapping("/wall/matches") fun matches() = matches @ApiOperation(value = "Lists player wins.") @GetMapping("/wall/players") fun playerWins() = playerWins @ApiOperation(value = "Lists team wins.") @GetMapping("/wall/teams") fun teamWins() = teamWins @EventHandler fun on(e: MatchCreated, @Timestamp timestamp: Instant) { matches.add(Match(teamRed = e.teamRed, teamBlue = e.teamBlue, matchSets = e.matchSets, matchId = e.matchId, date = LocalDateTime.ofInstant(timestamp, ZoneOffset.UTC))) logger.info { "Match created for ${e.matchId}" } } @EventHandler fun on(e: TeamWonMatch, @Timestamp timestamp: Instant) { teamWins.add(TeamWin(e.team, e.looser, Type.MATCH, LocalDateTime.ofInstant(timestamp, ZoneOffset.UTC))) logger.info { "Team ${e.team} won a match vs ${e.looser} " } playerWins.add(PlayerWin(e.team.player1, Type.MATCH, LocalDateTime.ofInstant(timestamp, ZoneOffset.UTC))) logger.info { "Player ${e.team.player1} won a match." } playerWins.add(PlayerWin(e.team.player2, Type.MATCH, LocalDateTime.ofInstant(timestamp, ZoneOffset.UTC))) logger.info { "Player ${e.team.player2} won a match." } } @EventHandler fun on(e: TeamWonMatchSet, @Timestamp timestamp: Instant) { teamWins.add(TeamWin(e.team, e.looser, Type.SET, LocalDateTime.ofInstant(timestamp, ZoneOffset.UTC))) logger.info { "Team ${e.team} won a set vs ${e.looser}" } playerWins.add(PlayerWin(e.team.player1, Type.SET, LocalDateTime.ofInstant(timestamp, ZoneOffset.UTC))) logger.info { "Player ${e.team.player1} won a set." } playerWins.add(PlayerWin(e.team.player2, Type.SET, LocalDateTime.ofInstant(timestamp, ZoneOffset.UTC))) logger.info { "Player ${e.team.player2} won a set." } } @EventHandler fun on(e: PlayerParticipatedInMatch) { logger.info { "Player ${e.player} with ranking ${e.eloRanking} played in match ${e.matchId}" } } } data class Match( val matchId: String, val date: LocalDateTime, val teamRed: Team, val teamBlue: Team, val matchSets: List<AbstractMatchSet> ) data class PlayerWin( val username: UserName, val type: Type, val date: LocalDateTime ) data class TeamWin( val team: Team, val looser: Team, val type: Type, val date: LocalDateTime ) enum class Type { MATCH, SET }
bsd-3-clause
21e388b0d9b01d299e0d5c811886f18b
31.873874
171
0.745136
3.641717
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleKotlinTestUtils.kt
4
3602
// 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.codeInsight.gradle import org.gradle.util.GradleVersion import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion import org.jetbrains.kotlin.tooling.core.isSnapshot import org.jetbrains.kotlin.tooling.core.isStable import org.jetbrains.plugins.gradle.tooling.util.VersionMatcher import java.io.File object GradleKotlinTestUtils { fun listRepositories(useKts: Boolean, gradleVersion: String, kotlinVersion: String? = null) = listRepositories(useKts, GradleVersion.version(gradleVersion), kotlinVersion?.let(::KotlinToolingVersion)) fun listRepositories(useKts: Boolean, gradleVersion: GradleVersion, kotlinVersion: KotlinToolingVersion? = null): String { if (useKts && kotlinVersion != null) return listKtsRepositoriesOptimized(gradleVersion, kotlinVersion) fun gradleVersionMatches(version: String): Boolean = VersionMatcher(gradleVersion).isVersionMatch(version, true) fun MutableList<String>.addUrl(url: String) { this += if (useKts) "maven(\"$url\")" else "maven { url '$url' }" } val repositories = mutableListOf<String>() repositories.add("mavenLocal()") repositories.addUrl("https://cache-redirector.jetbrains.com/repo.maven.apache.org/maven2/") repositories.addUrl("https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap") repositories.addUrl("https://cache-redirector.jetbrains.com/dl.google.com.android.maven2/") repositories.addUrl("https://cache-redirector.jetbrains.com/plugins.gradle.org/m2/") if (!gradleVersionMatches("7.0+")) { repositories.addUrl("https://cache-redirector.jetbrains.com/jcenter/") } return repositories.joinToString("\n") } private fun listKtsRepositoriesOptimized(gradleVersion: GradleVersion, kotlinVersion: KotlinToolingVersion): String { val repositories = mutableListOf<String>() operator fun String.unaryPlus() = repositories.add(this) if (kotlinVersion.isSnapshot) { +"mavenLocal()" } if (!kotlinVersion.isStable) { if (localKotlinGradlePluginExists(kotlinVersion)) { +"mavenLocal()" } else +""" maven("https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/bootstrap") { content { includeVersionByRegex(".*jetbrains.*", ".*", "$kotlinVersion") } } """.trimIndent() } +"""maven("https://cache-redirector.jetbrains.com/repo.maven.apache.org/maven2/")""" +"""maven("https://cache-redirector.jetbrains.com/dl.google.com.android.maven2/")""" +"""maven("https://cache-redirector.jetbrains.com/plugins.gradle.org/m2/")""" if (!VersionMatcher(gradleVersion).isVersionMatch("7.0+", true)) { +"""maven("https://cache-redirector.jetbrains.com/jcenter/")""" } return repositories.joinToString("\n") } } private fun localKotlinGradlePluginExists(kotlinGradlePluginVersion: KotlinToolingVersion): Boolean { val localKotlinGradlePlugin = File(System.getProperty("user.home")) .resolve(".m2/repository") .resolve("org/jetbrains/kotlin/kotlin-gradle-plugin/$kotlinGradlePluginVersion") return localKotlinGradlePlugin.exists() }
apache-2.0
e0d04eaa435b64b71947af1fc377771c
44.594937
158
0.679622
4.582697
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/openapi/roots/impl/FilesScanExecutor.kt
1
9103
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.roots.impl import com.intellij.concurrency.SensitiveProgressWrapper import com.intellij.concurrency.resetThreadContext import com.intellij.model.ModelBranchImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.progress.util.ProgressWrapper import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileFilter import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.impl.VirtualFileEnumeration import com.intellij.util.ExceptionUtil import com.intellij.util.Processor import com.intellij.util.TimeoutUtil import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.ConcurrentBitSet import com.intellij.util.containers.ContainerUtil import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileBasedIndexEx import com.intellij.util.indexing.IdFilter import com.intellij.util.indexing.UnindexedFilesUpdater import com.intellij.util.indexing.roots.IndexableFilesIterator import com.intellij.util.indexing.roots.kind.IndexableSetOrigin import com.intellij.util.indexing.roots.kind.LibraryOrigin import com.intellij.util.indexing.roots.kind.SdkOrigin import com.intellij.util.indexing.roots.kind.SyntheticLibraryOrigin import org.jetbrains.annotations.ApiStatus.Internal import java.util.concurrent.ConcurrentLinkedDeque import java.util.concurrent.Future import java.util.concurrent.FutureTask import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference @Internal object FilesScanExecutor { private val LOG = Logger.getInstance(FilesScanExecutor::class.java) private val THREAD_COUNT = (UnindexedFilesUpdater.getNumberOfScanningThreads() - 1).coerceAtLeast(1) private val ourExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("Scanning", THREAD_COUNT) @JvmStatic fun runOnAllThreads(runnable: Runnable) { val progress = ProgressIndicatorProvider.getGlobalProgressIndicator() val results = ArrayList<Future<*>>() for (i in 0 until THREAD_COUNT) { results.add(ourExecutor.submit { ProgressManager.getInstance().runProcess(runnable, ProgressWrapper.wrap(progress)) }) } resetThreadContext().use { // put the current thread to work too so the total thread count is `getNumberOfScanningThreads` // and avoid thread starvation due to a recursive `runOnAllThreads` invocation runnable.run() for (result in results) { // complete the future to avoid waiting for it forever if `ourExecutor` is fully booked (result as FutureTask<*>).run() ProgressIndicatorUtils.awaitWithCheckCanceled(result) } } } @JvmStatic fun <T> processOnAllThreadsInReadActionWithRetries(deque: ConcurrentLinkedDeque<T>, consumer: (T) -> Boolean): Boolean { return doProcessOnAllThreadsInReadAction(deque, consumer, true) } @JvmStatic fun <T> processOnAllThreadsInReadActionNoRetries(deque: ConcurrentLinkedDeque<T>, consumer: (T) -> Boolean): Boolean { return doProcessOnAllThreadsInReadAction(deque, consumer, false) } private fun <T> doProcessOnAllThreadsInReadAction(deque: ConcurrentLinkedDeque<T>, consumer: (T) -> Boolean, retryCanceled: Boolean): Boolean { val application = ApplicationManager.getApplication() as ApplicationEx return processOnAllThreads(deque) { o -> if (application.isReadAccessAllowed) { return@processOnAllThreads consumer(o) } var result = true val indicator = ProgressIndicatorProvider.getGlobalProgressIndicator() if (!ProgressIndicatorUtils.runInReadActionWithWriteActionPriority( { result = consumer(o) }, indicator?.let { SensitiveProgressWrapper(it) } )) { throw if (retryCanceled) ProcessCanceledException() else StopWorker() } result } } private fun <T> processOnAllThreads(deque: ConcurrentLinkedDeque<T>, processor: (T) -> Boolean): Boolean { ProgressManager.checkCanceled() if (deque.isEmpty()) { return true } val runnersCount = AtomicInteger() val idleCount = AtomicInteger() val error = AtomicReference<Throwable?>() val stopped = AtomicBoolean() val exited = AtomicBoolean() runOnAllThreads { runnersCount.incrementAndGet() var idle = false while (!stopped.get()) { ProgressManager.checkCanceled() if (deque.peek() == null) { if (!idle) { idle = true idleCount.incrementAndGet() } } else if (idle) { idle = false idleCount.decrementAndGet() } if (idle) { if (idleCount.get() == runnersCount.get() && deque.isEmpty()) break TimeoutUtil.sleep(1L) continue } val item = deque.poll() ?: continue try { if (!processor(item)) { stopped.set(true) } if (exited.get() && !stopped.get()) { throw AssertionError("early exit") } } catch (ex: StopWorker) { deque.addFirst(item) runnersCount.decrementAndGet() return@runOnAllThreads } catch (ex: ProcessCanceledException) { deque.addFirst(item) } catch (ex: Throwable) { error.compareAndSet(null, ex) } } exited.set(true) if (!deque.isEmpty() && !stopped.get()) { throw AssertionError("early exit") } } ExceptionUtil.rethrowAllAsUnchecked(error.get()) return !stopped.get() } private fun isLibOrigin(origin: IndexableSetOrigin): Boolean { return origin is LibraryOrigin || origin is SyntheticLibraryOrigin || origin is SdkOrigin } @JvmStatic fun processFilesInScope(includingBinary: Boolean, scope: GlobalSearchScope, idFilter: IdFilter?, processor: Processor<in VirtualFile?>): Boolean { ApplicationManager.getApplication().assertReadAccessAllowed() val project = scope.project ?: return true val fileIndex = ProjectRootManager.getInstance(project).fileIndex val searchInLibs = scope.isSearchInLibraries val deque = ConcurrentLinkedDeque<Any>() ModelBranchImpl.processModifiedFilesInScope(scope) { e: VirtualFile -> deque.add(e) } if (scope is VirtualFileEnumeration) { ContainerUtil.addAll<VirtualFile>(deque, FileBasedIndexEx.toFileIterable((scope as VirtualFileEnumeration).asArray())) } else { deque.addAll((FileBasedIndex.getInstance() as FileBasedIndexEx).getIndexableFilesProviders(project)) } val skippedCount = AtomicInteger() val processedCount = AtomicInteger() val visitedFiles = ConcurrentBitSet.create(deque.size) val fileFilter = VirtualFileFilter { file: VirtualFile -> val fileId = FileBasedIndex.getFileId(file) if (visitedFiles.set(fileId)) return@VirtualFileFilter false val result = (idFilter == null || idFilter.containsFileId(fileId)) && !fileIndex.isExcluded(file) && scope.contains(file) && (includingBinary || file.isDirectory || !file.fileType.isBinary) if (!result) skippedCount.incrementAndGet() result } val consumer = l@ { obj: Any -> ProgressManager.checkCanceled() when (obj) { is IndexableFilesIterator -> { val origin = obj.origin if (!searchInLibs && isLibOrigin(origin)) return@l true obj.iterateFiles(project, { file: VirtualFile -> if (file.isDirectory) return@iterateFiles true deque.add(file) true }, fileFilter) } is VirtualFile -> { processedCount.incrementAndGet() if (!obj.isValid) { return@l true } return@l processor.process(obj) } else -> { throw AssertionError("unknown item: $obj") } } true } val start = System.nanoTime() val result = processOnAllThreadsInReadActionNoRetries(deque, consumer) if (LOG.isDebugEnabled) { LOG.debug("${processedCount.get()} files processed (${skippedCount.get()} skipped) in ${TimeoutUtil.getDurationMillis(start)} ms") } return result } } private class StopWorker : ProcessCanceledException()
apache-2.0
33f946a83e5d504039f0884a4479d8fd
38.582609
136
0.691311
4.74609
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/util/UriUtil.kt
7
3136
// 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.util import java.net.URI fun URI.withFragment(newFragment: String?): URI = URI( scheme, userInfo, host, port, path, query, newFragment ) fun URI.withScheme(newScheme: String): URI = URI( newScheme, userInfo, host, port, path, query, fragment ) fun URI.withPath(newPath: String?): URI = URI( scheme, userInfo, host, port, newPath, query, fragment ) fun URI.withQuery(newQuery: String?): URI = URI( scheme, userInfo, host, port, path, newQuery, fragment ) fun URI.withPort(newPort: Int): URI = URI( scheme, userInfo, host, newPort, path, query, fragment ) fun URI.changeQuery(originalUri: URI, newRawQuery: String): URI = fromRawParts(originalUri.scheme, originalUri.isOpaque, originalUri.rawSchemeSpecificPart, originalUri.rawUserInfo, originalUri.host, originalUri.port, originalUri.authority, originalUri.rawPath, newRawQuery, originalUri.rawFragment ) fun URI.fromRawParts(scheme: String?, isOpaque: Boolean, schemeSpecificPart: String?, userInfo: String?, host: String?, port: Int, authority: String?, path: String?, query: String?, fragment: String?): URI { val sb = StringBuilder() if (!scheme.isNullOrBlank()) { sb.append(scheme) sb.append(':') } if (isOpaque) { sb.append(schemeSpecificPart) } else { if (!host.isNullOrBlank()) { sb.append("//") if (!userInfo.isNullOrBlank()) { sb.append(userInfo) sb.append('@') } val needBrackets = (host.indexOf(':') >= 0 && !host.startsWith("[") && !host.endsWith("]")) if (needBrackets) sb.append('[') sb.append(host) if (needBrackets) sb.append(']') if (port != -1) { sb.append(':') sb.append(port) } } else if (!authority.isNullOrBlank()) { sb.append("//") sb.append(authority) } if (path != null) sb.append(path) if (query != null) { sb.append('?') sb.append(query) } } if (fragment != null) { sb.append('#') sb.append(fragment) } return URI(sb.toString()) } private fun parseParameters(input: String?): Map<String, String> { if (input.isNullOrBlank()) return emptyMap() // TODO Url-decode values? return input .split('&') .mapNotNull { val split = it.split('=', limit = 2) if (split.size != 2) return@mapNotNull null split[0] to split[1] } .toMap() } val URI.fragmentParameters: Map<String, String> get() = parseParameters(fragment) val URI.queryParameters: Map<String, String> get() = parseParameters(query) fun URI.newURIWithFragmentParameters(fragmentParameters: Map<String, String>): URI { val newFragment = fragmentParameters.toList().joinToString(separator = "&") { "${it.first}=${it.second}" } return URI(scheme, userInfo, host, port, path, query, newFragment) }
apache-2.0
fef53fb0131a1ab94b734d84e3134fd0
22.946565
158
0.621811
3.737783
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/RedundantAsSequenceInspection.kt
1
3976
// 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.inspections.collections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.psi.qualifiedExpressionVisitor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RedundantAsSequenceInspection : AbstractKotlinInspection() { companion object { private val asSequenceFqName = FqName("kotlin.collections.asSequence") private val terminations = collectionTerminationFunctionNames.associateWith { FqName("kotlin.sequences.$it") } private val transformationsAndTerminations = collectionTransformationFunctionNames.associateWith { FqName("kotlin.sequences.$it") } + terminations } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(qualified) { val call = qualified.callExpression ?: return val callee = call.calleeExpression ?: return if (callee.text != "asSequence") return val parent = qualified.getQualifiedExpressionForReceiver() val parentCall = parent?.callExpression ?: return val context = qualified.analyze(BodyResolveMode.PARTIAL) val receiverType = qualified.receiverExpression.getType(context) ?: return if (!receiverType.isIterable(DefaultBuiltIns.Instance)) return if (call.getResolvedCall(context)?.isCalling(asSequenceFqName) != true) return if (!parentCall.isTermination(context)) return val grandParentCall = parent.getQualifiedExpressionForReceiver()?.callExpression if (grandParentCall?.isTransformationOrTermination(context) == true) return holder.registerProblem( qualified, callee.textRangeIn(qualified), KotlinBundle.message("inspection.redundant.assequence.call"), RemoveAsSequenceFix() ) }) private fun KtCallExpression.isTermination(context: BindingContext): Boolean { val fqName = terminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isTransformationOrTermination(context: BindingContext): Boolean { val fqName = transformationsAndTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private class RemoveAsSequenceFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.assequence.call.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val qualified = descriptor.psiElement as? KtQualifiedExpression ?: return val commentSaver = CommentSaver(qualified) val replaced = qualified.replaced(qualified.receiverExpression) commentSaver.restore(replaced) } } }
apache-2.0
d7eba1724825a3460597c0b7fcdfc15c
48.7125
158
0.764588
5.204188
false
false
false
false
nonylene/PhotoLinkViewer-Core
photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/dialog/AddOptionButtonDialogFragment.kt
1
2032
package net.nonylene.photolinkviewer.core.dialog import android.app.Dialog import android.os.Bundle import android.preference.PreferenceManager import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import net.nonylene.photolinkviewer.core.R import net.nonylene.photolinkviewer.core.adapter.OptionButtonsPreferenceRecyclerAdapter import net.nonylene.photolinkviewer.core.model.OptionButton import net.nonylene.photolinkviewer.core.tool.getOptionButtons class AddOptionButtonDialogFragment : DialogFragment() { val adapter = OptionButtonsPreferenceRecyclerAdapter { (activity as? Listener)?.onAddingButtonSelected(it) dismiss() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // set custom view val recyclerView = View.inflate(context, R.layout.plv_core_add_option_button_dialog, null) as RecyclerView adapter.setHasStableIds(true) recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(context) val buttons = PreferenceManager.getDefaultSharedPreferences(context) .getOptionButtons().plus(OptionButton.ADD_BUTTON) adapter.buttonList.addAll(OptionButton.values().filterNot { buttons.contains(it) }) adapter.notifyDataSetChanged() return AlertDialog.Builder(context).setView(recyclerView) .setTitle("Select button to add") .setNegativeButton(android.R.string.cancel, null) .create() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) dialog.window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } interface Listener { fun onAddingButtonSelected(button: OptionButton) } }
gpl-2.0
c6943083559ea83f502a77be60464a42
37.339623
114
0.747539
4.992629
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsCallChecker.kt
3
7316
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.resolve.diagnostics import org.jetbrains.kotlin.js.backend.ast.JsFunctionScope import org.jetbrains.kotlin.js.backend.ast.JsProgram import org.jetbrains.kotlin.js.backend.ast.JsRootScope import com.google.gwt.dev.js.parserExceptions.AbortParsingException import com.google.gwt.dev.js.rhino.CodePosition import com.google.gwt.dev.js.rhino.ErrorReporter import com.google.gwt.dev.js.rhino.Utils.isEndOfLine import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1 import org.jetbrains.kotlin.js.parser.parse import org.jetbrains.kotlin.js.patterns.DescriptorPredicate import org.jetbrains.kotlin.js.patterns.PatternBuilder import org.jetbrains.kotlin.js.resolve.LEXICAL_SCOPE_FOR_JS import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtLiteralStringTemplateEntry import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.TemporaryBindingTrace import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant import org.jetbrains.kotlin.resolve.constants.StringValue import org.jetbrains.kotlin.resolve.constants.TypedCompileTimeConstant import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.types.TypeUtils class JsCallChecker( private val constantExpressionEvaluator: ConstantExpressionEvaluator ) : CallChecker { companion object { private val JS_PATTERN: DescriptorPredicate = PatternBuilder.pattern("kotlin.js.js(String)") @JvmStatic fun <F : CallableDescriptor?> ResolvedCall<F>.isJsCall(): Boolean { val descriptor = resultingDescriptor return descriptor is SimpleFunctionDescriptor && JS_PATTERN.apply(descriptor) } @JvmStatic fun extractStringValue(compileTimeConstant: CompileTimeConstant<*>?): String? { return ((compileTimeConstant as? TypedCompileTimeConstant<*>)?.constantValue as? StringValue)?.value } } override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) { if (context.isAnnotationContext || !resolvedCall.isJsCall()) return val expression = resolvedCall.call.callElement if (expression !is KtCallExpression) return val arguments = expression.valueArgumentList?.arguments val argument = arguments?.firstOrNull()?.getArgumentExpression() ?: return val trace = TemporaryBindingTrace.create(context.trace, "JsCallChecker") val evaluationResult = constantExpressionEvaluator.evaluateExpression(argument, trace, TypeUtils.NO_EXPECTED_TYPE) val code = extractStringValue(evaluationResult) if (code == null) { context.trace.report(ErrorsJs.JSCODE_ARGUMENT_SHOULD_BE_CONSTANT.on(argument)) return } trace.commit() val errorReporter = JsCodeErrorReporter(argument, code, context.trace) try { val parserScope = JsFunctionScope(JsRootScope(JsProgram()), "<js fun>") val statements = parse(code, errorReporter, parserScope) if (statements.isEmpty()) { context.trace.report(ErrorsJs.JSCODE_NO_JAVASCRIPT_PRODUCED.on(argument)) } } catch (e: AbortParsingException) { // ignore } @Suppress("UNCHECKED_CAST") context.trace.record(LEXICAL_SCOPE_FOR_JS, resolvedCall as ResolvedCall<FunctionDescriptor>, context.scope) } } class JsCodeErrorReporter( private val nodeToReport: KtExpression, private val code: String, private val trace: BindingTrace ) : ErrorReporter { override fun warning(message: String, startPosition: CodePosition, endPosition: CodePosition) { report(ErrorsJs.JSCODE_WARNING, message, startPosition, endPosition) } override fun error(message: String, startPosition: CodePosition, endPosition: CodePosition) { report(ErrorsJs.JSCODE_ERROR, message, startPosition, endPosition) throw AbortParsingException() } private fun report( diagnosticFactory: DiagnosticFactory1<KtExpression, JsCallData>, message: String, startPosition: CodePosition, endPosition: CodePosition ) { val data = when { nodeToReport.isConstantStringLiteral -> { val reportRange = TextRange(startPosition.absoluteOffset, endPosition.absoluteOffset) JsCallData(reportRange, message) } else -> { val reportRange = nodeToReport.textRange val codeRange = TextRange(code.offsetOf(startPosition), code.offsetOf(endPosition)) JsCallDataWithCode(reportRange, message, code, codeRange) } } val parametrizedDiagnostic = diagnosticFactory.on(nodeToReport, data) trace.report(parametrizedDiagnostic) } private val CodePosition.absoluteOffset: Int get() { val quotesLength = nodeToReport.firstChild.textLength return nodeToReport.textOffset + quotesLength + code.offsetOf(this) } } /** * Calculates an offset from the start of a text for a position, * defined by line and offset in that line. */ private fun String.offsetOf(position: CodePosition): Int { var i = 0 var lineCount = 0 var offsetInLine = 0 while (i < length) { val c = this[i] if (lineCount == position.line && offsetInLine == position.offset) { return i } i++ offsetInLine++ if (isEndOfLine(c.toInt())) { offsetInLine = 0 lineCount++ assert(lineCount <= position.line) } } return length } private val KtExpression.isConstantStringLiteral: Boolean get() = this is KtStringTemplateExpression && entries.all { it is KtLiteralStringTemplateEntry } open class JsCallData(val reportRange: TextRange, val message: String) class JsCallDataWithCode( reportRange: TextRange, message: String, val code: String, val codeRange: TextRange ) : JsCallData(reportRange, message)
apache-2.0
e096b44d88d4c4bbbc901ea942d53b39
37.708995
122
0.718835
4.680742
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasByPackageIndex.kt
1
1046
// 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.stubindex import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StubIndex import com.intellij.psi.stubs.StubIndexKey import org.jetbrains.kotlin.psi.KtTypeAlias class KotlinTopLevelTypeAliasByPackageIndex : AbstractStringStubIndexExtension<KtTypeAlias>(KtTypeAlias::class.java) { override fun getKey(): StubIndexKey<String, KtTypeAlias> = KEY override fun get(s: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> = StubIndex.getElements(KEY, s, project, scope, KtTypeAlias::class.java) companion object { val KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelTypeAliasByPackageIndex::class.java) val INSTANCE = KotlinTopLevelTypeAliasByPackageIndex() @JvmStatic fun getInstance() = INSTANCE } }
apache-2.0
504a4301ac527a28a2412f7578ecb2e6
42.625
158
0.778203
4.669643
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ui/DeferredIconRepaintScheduler.kt
1
3539
// 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.ui import com.intellij.openapi.application.ApplicationManager import com.intellij.ui.tabs.impl.TabLabel import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresEdt import org.jetbrains.annotations.ApiStatus import java.awt.Component import java.awt.Rectangle import javax.swing.* @ApiStatus.Internal class DeferredIconRepaintScheduler { private val repaintScheduler = RepaintScheduler() @RequiresEdt fun createRepaintRequest(c: Component?, x: Int, y: Int): RepaintRequest { val target = getTarget(c) val paintingParent: Component? = SwingUtilities.getAncestorOfClass(PaintingParent::class.java, c) val paintingParentRec: Rectangle? = if (paintingParent == null) null else (paintingParent as PaintingParent).getChildRec(c!!) return RepaintRequest(c, x, y, target, paintingParent, paintingParentRec) } @RequiresEdt fun scheduleRepaint(request: RepaintRequest, iconWidth: Int, iconHeight: Int) { val actualTarget = request.getActualTarget() if (actualTarget == null) { return } val component = request.component if (component == actualTarget) { component.repaint(request.x, request.y, iconWidth, iconHeight) } else { repaintScheduler.pushDirtyComponent(actualTarget, request.paintingParentRec) } } private fun getTarget(c: Component?): Component? { val list = SwingUtilities.getAncestorOfClass(JList::class.java, c) if (list != null) { return list } val tree = SwingUtilities.getAncestorOfClass(JTree::class.java, c) if (tree != null) { return tree } val table = SwingUtilities.getAncestorOfClass(JTable::class.java, c) if (table != null) { return table } val box = SwingUtilities.getAncestorOfClass(JComboBox::class.java, c) if (box != null) { return box } val tabLabel = SwingUtilities.getAncestorOfClass(TabLabel::class.java, c) if (tabLabel != null) { return tabLabel } return c } class RepaintRequest( val component: Component?, val x: Int, val y: Int, val target: Component?, val paintingParent: Component?, val paintingParentRec: Rectangle? ) { fun getActualTarget(): Component? { if (target == null) { return null } if (SwingUtilities.getWindowAncestor(target) != null) { return target } if (paintingParent != null && SwingUtilities.getWindowAncestor(paintingParent) != null) { return paintingParent } return null } } private class RepaintScheduler { private val myAlarm = Alarm() private val myQueue = LinkedHashSet<RepaintSchedulerRequest>() fun pushDirtyComponent(c: Component, rec: Rectangle?) { ApplicationManager.getApplication().assertIsDispatchThread() // assert myQueue accessed from EDT only myAlarm.cancelAllRequests() myAlarm.addRequest({ for (each in myQueue) { val r = each.rectangle if (r == null) { each.component.repaint() } else { each.component.repaint(r.x, r.y, r.width, r.height) } } myQueue.clear() }, 50) myQueue.add(RepaintSchedulerRequest(c, rec)) } } private data class RepaintSchedulerRequest(val component: Component, val rectangle: Rectangle?) }
apache-2.0
6fdde66bc76a6fbaf76e4e7e278773db
29.25641
158
0.680983
4.300122
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/highlighter/KotlinBeforeResolveHighlightingPass.kt
3
2454
// 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.highlighter import com.intellij.codeHighlighting.* import com.intellij.lang.annotation.AnnotationHolder import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiRecursiveElementVisitor import org.jetbrains.kotlin.psi.KtFile class KotlinBeforeResolveHighlightingPass(file: KtFile, document: Document) : AbstractHighlightingPassBase(file, document) { override fun runAnnotatorWithContext(element: PsiElement, holder: AnnotationHolder) { val visitor = BeforeResolveHighlightingVisitor(holder) val extensions = EP_NAME.extensionList.map { it.createVisitor(holder) } element.accept(object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { element.accept(visitor) extensions.forEach(element::accept) super.visitElement(element) } }) } class Factory : TextEditorHighlightingPassFactory { override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { if (file !is KtFile) return null return KotlinBeforeResolveHighlightingPass(file, editor.document) } } class Registrar : TextEditorHighlightingPassFactoryRegistrar { override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) { registrar.registerTextEditorHighlightingPass( Factory(), /* anchor = */ TextEditorHighlightingPassRegistrar.Anchor.BEFORE, /* anchorPassId = */ Pass.UPDATE_FOLDING, /* needAdditionalIntentionsPass = */ false, /* inPostHighlightingPass = */ false ) } } companion object { val EP_NAME = ExtensionPointName.create<BeforeResolveHighlightingExtension>("org.jetbrains.kotlin.beforeResolveHighlightingVisitor") } } interface BeforeResolveHighlightingExtension { fun createVisitor(holder: AnnotationHolder): AbstractHighlightingVisitor }
apache-2.0
b590da33a54fa45da18b924e7392c38a
42.070175
158
0.726569
5.288793
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/blame/calculator/persistence/BlameCalculationPersistence.kt
1
4156
package zielu.gittoolbox.blame.calculator.persistence import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vfs.VirtualFile import zielu.gittoolbox.GitToolBoxException import zielu.gittoolbox.revision.RevisionDataProvider import zielu.gittoolbox.util.AppUtil import java.time.Clock import java.time.Duration import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock @State(name = "GitToolBoxBlamePersistence", storages = [Storage(StoragePathMacros.CACHE_FILE)]) internal class BlameCalculationPersistence( private val project: Project ) : PersistentStateComponent<BlameState> { private val lock = ReentrantLock() private var state: BlameState = BlameState() override fun getState(): BlameState { lock.withLock { return state } } override fun loadState(state: BlameState) { lock.withLock { this.state = state } } override fun initializeComponent() { cleanGarbage() } fun storeBlame(revisionData: RevisionDataProvider) { if (revisionData.baseRevision != VcsRevisionNumber.NULL) { lock.withLock { storeBlameImpl(revisionData) } } } private fun storeBlameImpl(revisionData: RevisionDataProvider) { val fileBlameState = BlameCodec.toPersistent(revisionData) val path = filePath(revisionData.file) val key = path + ";" + revisionData.baseRevision.asString() lock.withLock { fileBlameState.accessTimestamp = nowTimestamp() val modified = state.fileBlames.toMutableMap() modified[key] = fileBlameState state.fileBlames = modified log.info("Stored blame: $key") cleanGarbage() } } private fun filePath(file: VirtualFile): String { return FileUtil.getRelativePath(project.basePath!!, file.path, '/') ?: file.path } fun getBlame(file: VirtualFile, revision: VcsRevisionNumber): RevisionDataProvider? { val path = filePath(file) val key = path + ";" + revision.asString() lock.withLock { val fileBlameState = state.fileBlames[key] return fileBlameState?.let { it.accessTimestamp = nowTimestamp() BlameCodec.fromPersistent(file, it) }?.let { log.info("Restored blame: $key") it } } } private fun nowTimestamp(): Long = Clock.systemUTC().millis() private fun cleanGarbage() { lock.withLock { try { cleanGarbageImpl() } catch (e: NullPointerException) { // remove corrupted data val corrupted = state.fileBlames state.fileBlames = mapOf() throw GitToolBoxException("Garbage cleanup failed, corrupted blames: $corrupted", e) } } } private fun cleanGarbageImpl() { val cleaned = state.fileBlames.toMutableMap() val ttlBound = nowTimestamp() - ttlMillis val toRemoveByTtl = cleaned.entries .filter { it.value.accessTimestamp < ttlBound } .map { it.key } log.info("Remove outdated entries: $toRemoveByTtl") val overflow = cleaned.size - maxSize var toRemove = mutableSetOf<String>() if (overflow > 0) { toRemove = cleaned.entries .sortedBy { it.value.accessTimestamp } .take(overflow) .map { it.key } .toMutableSet() log.info("Remove overflowing entries: $toRemove") } toRemove.addAll(toRemoveByTtl) toRemove.forEach { cleaned.remove(it) } state.fileBlames = cleaned } companion object { private val log = Logger.getInstance(BlameCalculationPersistence::class.java) private val ttlMillis = Duration.ofDays(7).toMillis() private const val maxSize = 15 @JvmStatic fun getInstance(project: Project): BlameCalculationPersistence { return AppUtil.getServiceInstance(project, BlameCalculationPersistence::class.java) } } }
apache-2.0
c52959ced628f0fd091aeedf5e48c306
30.24812
95
0.709095
4.370137
false
false
false
false
rbatista/algorithms
challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/warmup/MiniMaxSum.kt
1
560
/** * https://www.hackerrank.com/challenges/mini-max-sum/problem */ package com.raphaelnegrisoli.hackerrank.warmup import java.util.* fun miniMaxSum(arr: Array<Int>) { var min = arr[0] var max = arr[0] var total = 0L for (i in arr) { total += i if (min > i) min = i if (max < i) max = i } println("${total - max} ${total - min}") } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val arr = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray() miniMaxSum(arr) }
mit
aa1c2bfd382bf3fe48f106ad0a933f8e
18.344828
80
0.575
3.093923
false
false
false
false
nischalbasnet/kotlin-android-tictactoe
app/src/main/java/com/nbasnet/tictactoe/ai/EasyAI.kt
1
3479
package com.nbasnet.tictactoe.ai import android.util.Log import com.nbasnet.tictactoe.controllers.TicTacToeGameController import com.nbasnet.tictactoe.models.PlayAreaInfo import java.util.* class EasyAI : IPlayGameAI { private val selections = listOf<List<PlayAreaInfo>>( listOf( PlayAreaInfo(1, 1), PlayAreaInfo(2, 2), PlayAreaInfo(3, 3), PlayAreaInfo(1, 3), PlayAreaInfo(3, 1), PlayAreaInfo(2, 3), PlayAreaInfo(3, 2), PlayAreaInfo(1, 2), PlayAreaInfo(2, 1) ), listOf( PlayAreaInfo(2, 2), PlayAreaInfo(3, 3), PlayAreaInfo(2, 1), PlayAreaInfo(1, 1), PlayAreaInfo(3, 1), PlayAreaInfo(1, 2), PlayAreaInfo(3, 2), PlayAreaInfo(1, 3), PlayAreaInfo(2, 3) ) ) private var currentSelection: List<PlayAreaInfo> = selectCurrentSelection() private var currentSelectionIndex: Int = 0 override fun playRound(gameController: TicTacToeGameController): Unit { if (!gameController.isGameFinished) { val playArea: PlayAreaInfo //check if next player has winner region val nextUsersWinningRegion = gameController.getNextPlayersWiningAreas() .firstOrNull() Log.d("AI", "next player winning region is $nextUsersWinningRegion") if (nextUsersWinningRegion != null) { playArea = nextUsersWinningRegion } else { //check my winning region or get the next play area to play playArea = gameController.getCurrentPlayersWinningAreas() .firstOrNull() ?: getNextPlayAreaInfo(gameController) } gameController.playNextRound(playArea) } } override fun getNextPlayAreaInfo(gameController: TicTacToeGameController): PlayAreaInfo { val playArea: PlayAreaInfo //check if player has winner region take val currentPlayerWinningRegion = gameController.getCurrentPlayersWinningAreas() .firstOrNull() Log.d("AI", "next player winning region is $currentPlayerWinningRegion") if (currentPlayerWinningRegion != null) { playArea = currentPlayerWinningRegion } else { //check next players winning region or get the next play area to play playArea = gameController.getNextPlayersWiningAreas() .firstOrNull() ?: getPlayAreaFromSelection(gameController) } return playArea } private fun getPlayAreaFromSelection(gameController: TicTacToeGameController): PlayAreaInfo { val selection = currentSelection[currentSelectionIndex] if (currentSelectionIndex >= gameController.totalRounds || gameController.isAreaPlayable(selection)) { return selection } else { if (currentSelectionIndex <= gameController.totalRounds) currentSelectionIndex++ return getPlayAreaFromSelection(gameController) } } private fun selectCurrentSelection(): List<PlayAreaInfo> { val randomKey = Random().nextInt(selections.count() - 0) + 0 return selections[randomKey] } }
mit
342da89c0409a8516ca1e9003a657b82
37.241758
110
0.596723
4.778846
false
false
false
false
hazuki0x0/YuzuBrowser
module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/progress/BaseDrawable.kt
1
4691
/* * Copyright (C) 2017-2021 Hazuki * * 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. */ /* * Copyright (c) 2016 Zhang Hai <[email protected]> * All Rights Reserved. */ package jp.hazuki.yuzubrowser.ui.widget.progress import android.content.res.ColorStateList import android.graphics.* import android.graphics.drawable.Drawable import androidx.annotation.ColorInt import androidx.annotation.IntRange import androidx.core.graphics.drawable.TintAwareDrawable internal abstract class BaseDrawable : Drawable(), TintAwareDrawable { @IntRange(from = 0, to = 255) protected var mAlpha = 255 protected var mColorFilter: ColorFilter? = null protected var mTintList: ColorStateList? = null protected var mTintMode: PorterDuff.Mode = PorterDuff.Mode.SRC_IN protected var mTintFilter: PorterDuffColorFilter? = null private val mConstantState = DummyConstantState() protected val colorFilterForDrawing: ColorFilter? get() = if (mColorFilter != null) mColorFilter else mTintFilter override fun getAlpha(): Int { return mAlpha } /** * {@inheritDoc} */ override fun setAlpha(@IntRange(from = 0, to = 255) alpha: Int) { if (mAlpha != alpha) { mAlpha = alpha invalidateSelf() } } /** * {@inheritDoc} */ override fun getColorFilter(): ColorFilter? { return mColorFilter } /** * {@inheritDoc} */ override fun setColorFilter(colorFilter: ColorFilter?) { mColorFilter = colorFilter invalidateSelf() } /** * {@inheritDoc} */ override fun setTint(@ColorInt tintColor: Int) { setTintList(ColorStateList.valueOf(tintColor)) } /** * {@inheritDoc} */ override fun setTintList(tint: ColorStateList?) { mTintList = tint if (updateTintFilter()) { invalidateSelf() } } /** * {@inheritDoc} */ override fun setTintMode(tintMode: PorterDuff.Mode?) { if (tintMode == null) return mTintMode = tintMode if (updateTintFilter()) { invalidateSelf() } } override fun isStateful(): Boolean { return mTintList != null && mTintList!!.isStateful } override fun onStateChange(state: IntArray): Boolean { return updateTintFilter() } private fun updateTintFilter(): Boolean { val tintList = mTintList if (tintList == null) { val hadTintFilter = mTintFilter != null mTintFilter = null return hadTintFilter } val tintColor = tintList.getColorForState(state, Color.TRANSPARENT) // They made PorterDuffColorFilter.setColor() and setMode() @hide. mTintFilter = PorterDuffColorFilter(tintColor, mTintMode) return true } /** * {@inheritDoc} */ override fun getOpacity(): Int { // Be safe. return PixelFormat.TRANSLUCENT } /** * {@inheritDoc} */ override fun draw(canvas: Canvas) { val bounds = bounds if (bounds.width() == 0 || bounds.height() == 0) { return } val saveCount = canvas.save() canvas.translate(bounds.left.toFloat(), bounds.top.toFloat()) onDraw(canvas, bounds.width(), bounds.height()) canvas.restoreToCount(saveCount) } protected abstract fun onDraw(canvas: Canvas, width: Int, height: Int) // Workaround LayerDrawable.ChildDrawable which calls getConstantState().newDrawable() // without checking for null. // We are never inflated from XML so the protocol of ConstantState does not apply to us. In // order to make LayerDrawable happy, we return ourselves from DummyConstantState.newDrawable(). override fun getConstantState(): Drawable.ConstantState { return mConstantState } private inner class DummyConstantState : Drawable.ConstantState() { override fun getChangingConfigurations(): Int { return 0 } override fun newDrawable(): Drawable { return this@BaseDrawable } } }
apache-2.0
2ef9ac74c8086c873d6bd5936271e41a
26.594118
100
0.639309
4.621675
false
false
false
false
hazuki0x0/YuzuBrowser
module/download/src/main/java/jp/hazuki/yuzubrowser/download/Download.kt
1
3520
/* * Copyright (C) 2017-2021 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.download import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import jp.hazuki.yuzubrowser.core.utility.storage.toDocumentFile import jp.hazuki.yuzubrowser.core.utility.utils.ui import jp.hazuki.yuzubrowser.download.core.data.DownloadFile import jp.hazuki.yuzubrowser.download.core.data.MetaData import jp.hazuki.yuzubrowser.download.core.utils.guessDownloadFileName import jp.hazuki.yuzubrowser.download.service.DownloadService import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import java.io.File import java.io.IOException fun Context.download(root: Uri, file: DownloadFile, meta: MetaData?) { if (file.url.length > INTENT_LIMIT) { ui { val tmp = File(cacheDir, DOWNLOAD_TMP_FILENAME) try { val save = async(Dispatchers.IO) { tmp.outputStream().use { it.write(file.url.toByteArray()) } } var name: Deferred<String>? = null if (file.name == null) { name = async(Dispatchers.IO) { guessDownloadFileName(root.toDocumentFile(this@download), file.url, null, null, null) } } save.await() val intent = Intent(this@download, DownloadService::class.java).apply { action = INTENT_ACTION_START_DOWNLOAD putExtra(INTENT_EXTRA_DOWNLOAD_ROOT_URI, root) putExtra(INTENT_EXTRA_DOWNLOAD_REQUEST, DownloadFile(file.url.convertToTmpDownloadUrl(), name?.await() ?: file.name, file.request)) putExtra(INTENT_EXTRA_DOWNLOAD_METADATA, meta) } startService(intent) } catch (e: IOException) { } } return } val intent = Intent(this, DownloadService::class.java).apply { action = INTENT_ACTION_START_DOWNLOAD putExtra(INTENT_EXTRA_DOWNLOAD_ROOT_URI, root) putExtra(INTENT_EXTRA_DOWNLOAD_REQUEST, file) putExtra(INTENT_EXTRA_DOWNLOAD_METADATA, meta) } startService(intent) } fun Context.reDownload(id: Long) { val intent = Intent(this, DownloadService::class.java).apply { action = INTENT_ACTION_RESTART_DOWNLOAD putExtra(INTENT_EXTRA_DOWNLOAD_ID, id) } startService(intent) } internal fun checkValidRootDir(root: Uri): Boolean { return Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || root.scheme != "file" } fun String.convertToTmpDownloadUrl(): String { var last = indexOf(';') if (last < 0) last = indexOf(',') return substring(0, last) + DOWNLOAD_TMP_TYPE } private const val HALF_MB = 512 * 1024 private const val INTENT_LIMIT = HALF_MB - 1024 - 1 internal const val DOWNLOAD_TMP_TYPE = ";yuzu_tmp_download" internal const val DOWNLOAD_TMP_FILENAME = "tmp_download"
apache-2.0
d0cf1ff80c272b020d584cf1da407d7e
37.26087
138
0.677273
4.12178
false
false
false
false
ilya-g/kotlinx.collections.immutable
core/jvmTest/src/contract/set/GuavaImmutableSetTest.kt
1
3554
/* * Copyright 2016-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.txt file. */ package tests.contract.set import com.google.common.collect.testing.SetTestSuiteBuilder import com.google.common.collect.testing.TestSetGenerator import com.google.common.collect.testing.features.CollectionFeature import com.google.common.collect.testing.features.CollectionSize import com.google.common.collect.testing.features.Feature import tests.contract.GuavaImmutableCollectionBaseTest import tests.contract.set.PersistentSetGenerator.HashSet import tests.contract.set.PersistentSetGenerator.OrderedSet import kotlin.test.Test class GuavaImmutableSetTest: GuavaImmutableCollectionBaseTest() { private fun <E> runImmutableSetTestsUsing(generator: TestSetGenerator<E>, knownOrder: Boolean) { val features = mutableListOf<Feature<*>>( CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.SUBSET_VIEW, CollectionFeature.DESCENDING_VIEW/*, CollectionFeature.REJECTS_DUPLICATES_AT_CREATION*/ ) if (knownOrder) features.add(CollectionFeature.KNOWN_ORDER) SetTestSuiteBuilder .using(generator) .named(generator.javaClass.simpleName) .withFeatures(features) .createTestSuite() .run { runTestSuite(this) } } private fun <E> runMutableSetTestsUsing(generator: TestSetGenerator<E>, knownOrder: Boolean) { val features = mutableListOf<Feature<*>>( CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.GENERAL_PURPOSE, CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SUBSET_VIEW, CollectionFeature.DESCENDING_VIEW/*, CollectionFeature.REJECTS_DUPLICATES_AT_CREATION*/ ) if (knownOrder) features.add(CollectionFeature.KNOWN_ORDER) SetTestSuiteBuilder .using(generator) .named(generator.javaClass.simpleName) .withFeatures(features) .createTestSuite() .run { runTestSuite(this) } } @Test fun hashSet() { listOf( HashSet.Of, HashSet.AddAll, HashSet.AddEach, HashSet.MutateAddAll, HashSet.MutateAddEach ).forEach { runImmutableSetTestsUsing(it, knownOrder = false) } } @Test fun hashSetBuilder() { listOf( HashSet.Builder.Of, HashSet.Builder.AddAll, HashSet.Builder.AddEach ).forEach { runMutableSetTestsUsing(it, knownOrder = false) } } @Test fun orderedSet() { listOf( OrderedSet.Of, OrderedSet.AddAll, OrderedSet.AddEach, OrderedSet.MutateAddAll, OrderedSet.MutateAddEach ).forEach { runImmutableSetTestsUsing(it, knownOrder = true) } } @Test fun orderedSetBuilder() { listOf( OrderedSet.Builder.Of, OrderedSet.Builder.AddAll, OrderedSet.Builder.AddEach ).forEach { runMutableSetTestsUsing(it, knownOrder = true) } } }
apache-2.0
64f38b8221f03f1505cea64b75607458
31.614679
107
0.608047
4.789757
false
true
false
false
erubit-open/platform
erubit.platform/src/main/java/a/erubit/platform/InteractionService.kt
1
5763
package a.erubit.platform import a.erubit.platform.R import a.erubit.platform.course.CourseManager import a.erubit.platform.course.ProgressManager import a.erubit.platform.course.lesson.Lesson import a.erubit.platform.interaction.InteractionManager import a.erubit.platform.interaction.InteractionManager.InteractionEvent import a.erubit.platform.interaction.InteractionManager.InteractionListener import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.Context import android.content.Intent import android.graphics.PixelFormat import android.os.Build import android.os.IBinder import android.provider.Settings import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat.PRIORITY_MIN import t.TinyDB import u.C class InteractionService : Service(), InteractionListener { private val interactionServiceFgId = 9990 private lateinit var mWindowManager: WindowManager private lateinit var mInteractionContainerView: View private val defaultLayoutParams: WindowManager.LayoutParams = WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY else WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_FULLSCREEN or WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, PixelFormat.TRANSLUCENT ) private var mNextTimeSlot: Long = 0 override fun onBind(intent: Intent): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val enabled = (TinyDB(applicationContext).getBoolean(C.SP_ENABLED_ON_UNLOCK, true) && System.currentTimeMillis() > mNextTimeSlot && (Build.VERSION.SDK_INT < 23 || Settings.canDrawOverlays(applicationContext))) if (enabled && mInteractionContainerView.windowToken == null) { val lesson = CourseManager.i().getNextLesson() ?: return super.onStartCommand(intent, flags, startId) val interactionView = InteractionManager.i().getInteractionView(applicationContext, lesson, this) if (interactionView != null) { setupQuickButtons(applicationContext, lesson, this) val root = mInteractionContainerView.findViewById<ViewGroup>(R.id.content) root.removeAllViews() root.addView(interactionView) mWindowManager.addView(mInteractionContainerView, defaultLayoutParams) startForeground() } } return super.onStartCommand(intent, flags, startId) } private fun startForeground() { val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createNotificationChannel() else "" val notificationBuilder = NotificationCompat.Builder(this, channel) val builder = notificationBuilder.setOngoing(true) .setSmallIcon(R.drawable.ic_learning) .setPriority(PRIORITY_MIN) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) builder.setCategory(Notification.CATEGORY_SERVICE) val notification = builder.build() startForeground(interactionServiceFgId, notification) } @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel(): String { val id = "erubit-foreground-service" val chan = NotificationChannel( id, "Screen-unlock learning service", NotificationManager.IMPORTANCE_NONE) chan.lightColor = R.color.color_purple chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager service.createNotificationChannel(chan) return id } override fun onCreate() { super.onCreate() mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager mInteractionContainerView = View.inflate(applicationContext, R.layout.view_interaction, null) } override fun onDestroy() { super.onDestroy() removeView() } private fun removeView() { if (mInteractionContainerView.windowToken != null) mWindowManager.removeView(mInteractionContainerView) stopForeground(true) } fun setupQuickButtons(context: Context, lesson: Lesson, listener: InteractionListener) { mInteractionContainerView.findViewById<View>(android.R.id.closeButton).setOnClickListener { listener.onInteraction(InteractionEvent.CLOSE) } val disableForListener = View.OnClickListener { v: View -> var event = InteractionEvent.CLOSE when (v.id) { R.id.disableFor1h -> event = InteractionEvent.BUSY1 R.id.disableFor2h -> event = InteractionEvent.BUSY2 R.id.disableFor4h -> event = InteractionEvent.BUSY4 } listener.onInteraction(event) val progress = lesson.mProgress!! if (progress.interactionDate == 0L) { progress.interactionDate = System.currentTimeMillis() ProgressManager.i().save(context, lesson) } } mInteractionContainerView.findViewById<View>(R.id.disableFor1h).setOnClickListener(disableForListener) mInteractionContainerView.findViewById<View>(R.id.disableFor2h).setOnClickListener(disableForListener) mInteractionContainerView.findViewById<View>(R.id.disableFor4h).setOnClickListener(disableForListener) } override fun onInteraction(event: InteractionEvent) { when (event) { InteractionEvent.BUSY1 -> mNextTimeSlot = System.currentTimeMillis() + C.TIME_1H InteractionEvent.BUSY2 -> mNextTimeSlot = System.currentTimeMillis() + C.TIME_2H InteractionEvent.BUSY4 -> mNextTimeSlot = System.currentTimeMillis() + C.TIME_4H else -> { } } if (event !== InteractionEvent.NEGATIVE) removeView() } }
gpl-3.0
09ab8fe9d73d357eecb8c07a5d81ec13
32.9
142
0.787611
4.072792
false
false
false
false
proxer/ProxerLibAndroid
library/src/test/kotlin/me/proxer/library/api/messenger/CheckLinkEndpointTest.kt
2
1312
package me.proxer.library.api.messenger import me.proxer.library.ProxerTest import me.proxer.library.entity.messenger.LinkCheckResponse import me.proxer.library.runRequest import okhttp3.HttpUrl.Companion.toHttpUrl import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test class CheckLinkEndpointTest : ProxerTest() { private val expectedResponse = LinkCheckResponse(false, "https://proxer.biz") @Test fun testDefault() { val (result, _) = server.runRequest("link_check.json") { api.messenger.checkLink("https://proxer.biz") .build() .execute() } result shouldBeEqualTo expectedResponse } @Test fun testPath() { val (_, request) = server.runRequest("link_check.json") { api.messenger.checkLink("https://proxer.biz".toHttpUrl()) .build() .execute() } request.path shouldBeEqualTo "/api/v1/messenger/checkLink" } @Test fun testParameter() { val (_, request) = server.runRequest("link_check.json") { api.messenger.checkLink("https://proxer.biz") .build() .execute() } request.body.readUtf8() shouldBeEqualTo "link=https%3A%2F%2Fproxer.biz" } }
gpl-3.0
e36415c909b35acc58badb02c24218d6
27.521739
81
0.619665
4.232258
false
true
false
false
soeminnminn/EngMyanDictionary
app/src/main/java/com/s16/engmyan/Constants.kt
1
1365
package com.s16.engmyan import android.content.Context import android.graphics.Typeface object Constants { const val ARG_PARAM_ID = "id" const val ARG_PARAM_TWO_PANE = "twoPane" const val TEXT_SIZE = 16f const val PREFS_THEMES = "prefs_theme" const val PREFS_THEMES_LIGHT = "light" const val PREFS_THEMES_DARK = "dark" const val PREFS_THEMES_BATTERY = "battery" const val PREFS_THEMES_SYSTEM = "system" const val PREFS_FONT_SIZE = "prefs_font_size" const val PREFS_FORCE_ZAWGYI = "prefs_force_zawgyi" const val PREFS_WORD_CLICKABLE = "prefs_used_word_clickable" const val PREFS_SHOW_SYNONYM = "prefs_show_synonym" const val PREFS_CREDIT = "prefs_credit" const val PREFS_ABOUT = "prefs_about" const val PREFS_LAST_KEYWORD = "prefs_last_keyword" const val PREFS_LAST_ID = "prefs_last_id" const val URL_CREDIT = "file:///android_asset/credit.html" const val WELCOME_ID : Long = 21470 @Volatile private var zawgyiTypeFace: Typeface? = null fun getZawgyiTypeface(context: Context): Typeface = zawgyiTypeFace ?: Typeface.createFromAsset(context.assets, "fonts/zawgyi.ttf") @Volatile private var mmTypeFace: Typeface? = null fun getMMTypeFace(context: Context): Typeface = mmTypeFace ?: Typeface.createFromAsset(context.assets, "fonts/mmrtext.ttf") }
gpl-2.0
4ff0484c510db953d4bad452e8decc02
32.317073
86
0.701099
3.508997
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/accessors/PluginAccessorsClassPath.kt
2
20084
/* * 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.accessors import kotlinx.metadata.Flag import kotlinx.metadata.KmTypeVisitor import kotlinx.metadata.flagsOf import kotlinx.metadata.jvm.JvmMethodSignature import org.gradle.api.Project import org.gradle.api.internal.file.FileCollectionFactory import org.gradle.api.internal.initialization.ClassLoaderScope import org.gradle.api.internal.project.ProjectInternal import org.gradle.internal.classpath.ClassPath import org.gradle.internal.classpath.DefaultClassPath import org.gradle.internal.execution.ExecutionEngine import org.gradle.internal.execution.InputFingerprinter import org.gradle.internal.execution.UnitOfWork import org.gradle.internal.execution.UnitOfWork.InputVisitor import org.gradle.internal.execution.UnitOfWork.OutputFileValueSupplier import org.gradle.internal.file.TreeType.DIRECTORY import org.gradle.internal.fingerprint.CurrentFileCollectionFingerprint import org.gradle.internal.hash.ClassLoaderHierarchyHasher import org.gradle.internal.hash.HashCode import org.gradle.internal.snapshot.ValueSnapshot import org.gradle.kotlin.dsl.cache.KotlinDslWorkspaceProvider import org.gradle.kotlin.dsl.codegen.fileHeader import org.gradle.kotlin.dsl.codegen.fileHeaderFor import org.gradle.kotlin.dsl.codegen.kotlinDslPackagePath import org.gradle.kotlin.dsl.codegen.pluginEntriesFrom import org.gradle.kotlin.dsl.codegen.sourceNameOfBinaryName import org.gradle.kotlin.dsl.concurrent.IO import org.gradle.kotlin.dsl.concurrent.withAsynchronousIO import org.gradle.kotlin.dsl.concurrent.withSynchronousIO import org.gradle.kotlin.dsl.concurrent.writeFile import org.gradle.kotlin.dsl.provider.kotlinScriptClassPathProviderOf import org.gradle.kotlin.dsl.support.appendReproducibleNewLine import org.gradle.kotlin.dsl.support.bytecode.ALOAD import org.gradle.kotlin.dsl.support.bytecode.ARETURN import org.gradle.kotlin.dsl.support.bytecode.DUP import org.gradle.kotlin.dsl.support.bytecode.GETFIELD import org.gradle.kotlin.dsl.support.bytecode.INVOKEINTERFACE import org.gradle.kotlin.dsl.support.bytecode.INVOKESPECIAL import org.gradle.kotlin.dsl.support.bytecode.InternalName import org.gradle.kotlin.dsl.support.bytecode.InternalNameOf import org.gradle.kotlin.dsl.support.bytecode.KmTypeBuilder import org.gradle.kotlin.dsl.support.bytecode.LDC import org.gradle.kotlin.dsl.support.bytecode.NEW import org.gradle.kotlin.dsl.support.bytecode.PUTFIELD import org.gradle.kotlin.dsl.support.bytecode.RETURN import org.gradle.kotlin.dsl.support.bytecode.internalName import org.gradle.kotlin.dsl.support.bytecode.jvmGetterSignatureFor import org.gradle.kotlin.dsl.support.bytecode.moduleFileFor import org.gradle.kotlin.dsl.support.bytecode.moduleMetadataBytesFor import org.gradle.kotlin.dsl.support.bytecode.publicClass import org.gradle.kotlin.dsl.support.bytecode.publicKotlinClass import org.gradle.kotlin.dsl.support.bytecode.publicMethod import org.gradle.kotlin.dsl.support.bytecode.publicStaticMethod import org.gradle.kotlin.dsl.support.bytecode.writeFileFacadeClassHeader import org.gradle.kotlin.dsl.support.bytecode.writePropertyOf import org.gradle.kotlin.dsl.support.useToRun import org.gradle.plugin.use.PluginDependenciesSpec import org.gradle.plugin.use.PluginDependencySpec import org.jetbrains.org.objectweb.asm.ClassWriter import org.jetbrains.org.objectweb.asm.MethodVisitor import java.io.BufferedWriter import java.io.File import javax.inject.Inject /** * Produces an [AccessorsClassPath] with type-safe accessors for all plugin ids found in the * `buildSrc` classpath of the given [project]. * * The accessors provide content-assist for plugin ids and quick navigation to the plugin source code. */ class PluginAccessorClassPathGenerator @Inject constructor( private val classLoaderHierarchyHasher: ClassLoaderHierarchyHasher, private val fileCollectionFactory: FileCollectionFactory, private val executionEngine: ExecutionEngine, private val inputFingerprinter: InputFingerprinter, private val workspaceProvider: KotlinDslWorkspaceProvider ) { fun pluginSpecBuildersClassPath(project: ProjectInternal): AccessorsClassPath = project.owner.owner.projects.rootProject.mutableModel.let { rootProject -> rootProject.getOrCreateProperty("gradleKotlinDsl.pluginAccessorsClassPath") { val buildSrcClassLoaderScope = baseClassLoaderScopeOf(rootProject) val classLoaderHash = requireNotNull(classLoaderHierarchyHasher.getClassLoaderHash(buildSrcClassLoaderScope.exportClassLoader)) val work = GeneratePluginAccessors( rootProject, buildSrcClassLoaderScope, classLoaderHash, fileCollectionFactory, inputFingerprinter, workspaceProvider ) val result = executionEngine.createRequest(work).execute() result.execution.get().output as AccessorsClassPath } } } class GeneratePluginAccessors( private val rootProject: Project, private val buildSrcClassLoaderScope: ClassLoaderScope, private val classLoaderHash: HashCode, private val fileCollectionFactory: FileCollectionFactory, private val inputFingerprinter: InputFingerprinter, private val workspaceProvider: KotlinDslWorkspaceProvider ) : UnitOfWork { companion object { const val BUILD_SRC_CLASSLOADER_INPUT_PROPERTY = "buildSrcClassLoader" const val SOURCES_OUTPUT_PROPERTY = "sources" const val CLASSES_OUTPUT_PROPERTY = "classes" } override fun execute(executionRequest: UnitOfWork.ExecutionRequest): UnitOfWork.WorkOutput { val workspace = executionRequest.workspace kotlinScriptClassPathProviderOf(rootProject).run { withAsynchronousIO(rootProject) { buildPluginAccessorsFor( pluginDescriptorsClassPath = exportClassPathFromHierarchyOf(buildSrcClassLoaderScope), srcDir = getSourcesOutputDir(workspace), binDir = getClassesOutputDir(workspace) ) } } return object : UnitOfWork.WorkOutput { override fun getDidWork() = UnitOfWork.WorkResult.DID_WORK override fun getOutput() = loadAlreadyProducedOutput(workspace) } } override fun loadAlreadyProducedOutput(workspace: File) = AccessorsClassPath( DefaultClassPath.of(getClassesOutputDir(workspace)), DefaultClassPath.of(getSourcesOutputDir(workspace)) ) override fun identify(identityInputs: MutableMap<String, ValueSnapshot>, identityFileInputs: MutableMap<String, CurrentFileCollectionFingerprint>) = UnitOfWork.Identity { classLoaderHash.toString() } override fun getWorkspaceProvider() = workspaceProvider.accessors override fun getInputFingerprinter() = inputFingerprinter override fun getDisplayName(): String = "Kotlin DSL plugin accessors for classpath '$classLoaderHash'" override fun visitIdentityInputs(visitor: InputVisitor) { visitor.visitInputProperty(BUILD_SRC_CLASSLOADER_INPUT_PROPERTY) { classLoaderHash } } override fun visitOutputs(workspace: File, visitor: UnitOfWork.OutputVisitor) { val sourcesOutputDir = getSourcesOutputDir(workspace) val classesOutputDir = getClassesOutputDir(workspace) visitor.visitOutputProperty(SOURCES_OUTPUT_PROPERTY, DIRECTORY, OutputFileValueSupplier.fromStatic(sourcesOutputDir, fileCollectionFactory.fixed(sourcesOutputDir))) visitor.visitOutputProperty(CLASSES_OUTPUT_PROPERTY, DIRECTORY, OutputFileValueSupplier.fromStatic(classesOutputDir, fileCollectionFactory.fixed(classesOutputDir))) } } private fun getClassesOutputDir(workspace: File) = File(workspace, "classes") private fun getSourcesOutputDir(workspace: File): File = File(workspace, "sources") fun writeSourceCodeForPluginSpecBuildersFor( pluginDescriptorsClassPath: ClassPath, sourceFile: File, packageName: String ) { withSynchronousIO { writePluginAccessorsSourceCodeTo( sourceFile, pluginAccessorsFor(pluginDescriptorsClassPath), format = AccessorFormats.internal, header = fileHeaderFor(packageName) ) } } private fun pluginAccessorsFor(pluginDescriptorsClassPath: ClassPath): List<PluginAccessor> = pluginAccessorsFor(pluginTreesFrom(pluginDescriptorsClassPath)).toList() internal fun IO.buildPluginAccessorsFor( pluginDescriptorsClassPath: ClassPath, srcDir: File, binDir: File ) { makeAccessorOutputDirs(srcDir, binDir, kotlinDslPackagePath) val pluginTrees = pluginTreesFrom(pluginDescriptorsClassPath) val baseFileName = "$kotlinDslPackagePath/PluginAccessors" val sourceFile = srcDir.resolve("$baseFileName.kt") val accessorList = pluginAccessorsFor(pluginTrees).toList() writePluginAccessorsSourceCodeTo(sourceFile, accessorList) val fileFacadeClassName = InternalName(baseFileName + "Kt") val moduleName = "kotlin-dsl-plugin-spec-builders" val moduleMetadata = moduleMetadataBytesFor(listOf(fileFacadeClassName)) writeFile( moduleFileFor(binDir, moduleName), moduleMetadata ) val properties = ArrayList<Pair<PluginAccessor, JvmMethodSignature>>(accessorList.size) val header = writeFileFacadeClassHeader(moduleName) { accessorList.forEach { accessor -> if (accessor is PluginAccessor.ForGroup) { val (internalClassName, classBytes) = emitClassForGroup(accessor) writeClassFileTo(binDir, internalClassName, classBytes) } val extensionSpec = accessor.extension val propertyName = extensionSpec.name val receiverType = extensionSpec.receiverType val returnType = extensionSpec.returnType val getterSignature = jvmGetterSignatureFor(propertyName, "(L${receiverType.internalName};)L${returnType.internalName};") writePropertyOf( receiverType = receiverType.builder, returnType = returnType.builder, propertyName = propertyName, getterSignature = getterSignature, getterFlags = nonInlineGetterFlags ) properties.add(accessor to getterSignature) } } val classBytes = publicKotlinClass(fileFacadeClassName, header) { properties.forEach { (accessor, signature) -> emitAccessorMethodFor(accessor, signature) } } writeClassFileTo(binDir, fileFacadeClassName, classBytes) } internal fun pluginTreesFrom(pluginDescriptorsClassPath: ClassPath): Map<String, PluginTree> = PluginTree.of(pluginSpecsFrom(pluginDescriptorsClassPath)) private fun ClassWriter.emitAccessorMethodFor(accessor: PluginAccessor, signature: JvmMethodSignature) { val extension = accessor.extension val receiverType = extension.receiverType publicStaticMethod(signature) { when (accessor) { is PluginAccessor.ForGroup -> { val returnType = extension.returnType NEW(returnType.internalName) DUP() GETPLUGINS(receiverType) INVOKESPECIAL(returnType.internalName, "<init>", groupTypeConstructorSignature) ARETURN() } is PluginAccessor.ForPlugin -> { GETPLUGINS(receiverType) LDC(accessor.id) INVOKEINTERFACE(pluginDependenciesSpecInternalName, "id", pluginDependenciesSpecIdMethodDesc) ARETURN() } } } } private fun IO.writePluginAccessorsSourceCodeTo( sourceFile: File, accessors: List<PluginAccessor>, format: AccessorFormat = AccessorFormats.default, header: String = fileHeader ) = io { sourceFile.bufferedWriter().useToRun { appendReproducibleNewLine(header) appendSourceCodeForPluginAccessors(accessors, format) } } private fun BufferedWriter.appendSourceCodeForPluginAccessors( accessors: List<PluginAccessor>, format: AccessorFormat ) { appendReproducibleNewLine( """ import ${PluginDependenciesSpec::class.qualifiedName} import ${PluginDependencySpec::class.qualifiedName} """.trimIndent() ) defaultPackageTypesIn(accessors).forEach { appendReproducibleNewLine("import $it") } accessors.runEach { // Keep accessors separated by an empty line write("\n\n") val extendedType = extension.receiverType.sourceName val pluginsRef = pluginDependenciesSpecOf(extendedType) when (this) { is PluginAccessor.ForPlugin -> { appendReproducibleNewLine( format( """ /** * The `$id` plugin implemented by [${sourceNameOfBinaryName(implementationClass)}]. */ val `$extendedType`.`${extension.name}`: PluginDependencySpec get() = $pluginsRef.id("$id") """ ) ) } is PluginAccessor.ForGroup -> { val groupType = extension.returnType.sourceName appendReproducibleNewLine( format( """ /** * The `$id` plugin group. */ @org.gradle.api.Generated class `$groupType`(internal val plugins: PluginDependenciesSpec) /** * Plugin ids starting with `$id`. */ val `$extendedType`.`${extension.name}`: `$groupType` get() = `$groupType`($pluginsRef) """ ) ) } } } } private fun defaultPackageTypesIn(pluginAccessors: List<PluginAccessor>) = defaultPackageTypesIn( pluginImplementationClassesExposedBy(pluginAccessors) ) private fun pluginImplementationClassesExposedBy(pluginAccessors: List<PluginAccessor>) = pluginAccessors .filterIsInstance<PluginAccessor.ForPlugin>() .map { it.implementationClass } private const val pluginsFieldName = "plugins" private fun pluginDependenciesSpecOf(extendedType: String): String = when (extendedType) { "PluginDependenciesSpec" -> "this" else -> pluginsFieldName } private inline fun <T> Iterable<T>.runEach(f: T.() -> Unit) { forEach { it.run(f) } } internal data class TypeSpec(val sourceName: String, val internalName: InternalName) { val builder: KmTypeBuilder get() = { visitClass(internalName) } } internal fun KmTypeVisitor.visitClass(internalName: InternalName) { visitClass(internalName.value) } private val pluginDependencySpecInternalName = PluginDependencySpec::class.internalName private val pluginDependenciesSpecInternalName = PluginDependenciesSpec::class.internalName internal val pluginDependenciesSpecTypeSpec = TypeSpec("PluginDependenciesSpec", pluginDependenciesSpecInternalName) internal val pluginDependencySpecTypeSpec = TypeSpec("PluginDependencySpec", pluginDependencySpecInternalName) private val pluginDependenciesSpecTypeDesc = "L$pluginDependenciesSpecInternalName;" private val groupTypeConstructorSignature = "($pluginDependenciesSpecTypeDesc)V" private val pluginDependenciesSpecIdMethodDesc = "(Ljava/lang/String;)L$pluginDependencySpecInternalName;" internal fun pluginAccessorsFor(pluginTrees: Map<String, PluginTree>, extendedType: TypeSpec = pluginDependenciesSpecTypeSpec): Sequence<PluginAccessor> = sequence { for ((extensionName, pluginTree) in pluginTrees) { when (pluginTree) { is PluginTree.PluginGroup -> { val groupId = pluginTree.path.joinToString(".") val groupType = pluginGroupTypeName(pluginTree.path) val groupTypeSpec = typeSpecForPluginGroupType(groupType) yield( PluginAccessor.ForGroup( groupId, ExtensionSpec(extensionName, extendedType, groupTypeSpec) ) ) yieldAll(pluginAccessorsFor(pluginTree.plugins, groupTypeSpec)) } is PluginTree.PluginSpec -> { yield( PluginAccessor.ForPlugin( pluginTree.id, pluginTree.implementationClass, ExtensionSpec(extensionName, extendedType, pluginDependencySpecTypeSpec) ) ) } } } } internal fun typeSpecForPluginGroupType(groupType: String) = TypeSpec(groupType, InternalName("$kotlinDslPackagePath/$groupType")) internal sealed class PluginAccessor { abstract val extension: ExtensionSpec data class ForPlugin( val id: String, val implementationClass: String, override val extension: ExtensionSpec ) : PluginAccessor() data class ForGroup( val id: String, override val extension: ExtensionSpec ) : PluginAccessor() } internal data class ExtensionSpec( val name: String, val receiverType: TypeSpec, val returnType: TypeSpec ) private fun pluginSpecsFrom(pluginDescriptorsClassPath: ClassPath): Sequence<PluginTree.PluginSpec> = pluginDescriptorsClassPath .asFiles .asSequence() .filter { it.isFile && it.extension.equals("jar", true) } .flatMap { pluginEntriesFrom(it).asSequence() } .map { PluginTree.PluginSpec(it.pluginId, it.implementationClass) } private fun pluginGroupTypeName(path: List<String>) = path.joinToString(separator = "") { it.capitalize() } + "PluginGroup" private fun IO.writeClassFileTo(binDir: File, internalClassName: InternalName, classBytes: ByteArray) { val classFile = binDir.resolve("$internalClassName.class") writeFile(classFile, classBytes) } private val nonInlineGetterFlags = flagsOf(Flag.IS_PUBLIC, Flag.PropertyAccessor.IS_NOT_DEFAULT) private fun MethodVisitor.GETPLUGINS(receiverType: TypeSpec) { ALOAD(0) if (receiverType !== pluginDependenciesSpecTypeSpec) { GETFIELD(receiverType.internalName, pluginsFieldName, pluginDependenciesSpecTypeDesc) } } private fun emitClassForGroup(group: PluginAccessor.ForGroup): Pair<InternalName, ByteArray> = group.run { val className = extension.returnType.internalName val classBytes = publicClass(className) { packagePrivateField(pluginsFieldName, pluginDependenciesSpecTypeDesc) publicMethod("<init>", groupTypeConstructorSignature) { ALOAD(0) INVOKESPECIAL(InternalNameOf.javaLangObject, "<init>", "()V") ALOAD(0) ALOAD(1) PUTFIELD(className, pluginsFieldName, pluginDependenciesSpecTypeDesc) RETURN() } } className to classBytes } private fun ClassWriter.packagePrivateField(name: String, desc: String) { visitField(0, name, desc, null, null).run { visitEnd() } } private fun baseClassLoaderScopeOf(rootProject: Project) = (rootProject as ProjectInternal).baseClassLoaderScope
apache-2.0
096695eacc31219a5a985dbd059695c4
34.111888
203
0.70947
4.982387
false
false
false
false
terracotta-ko/Android_Treasure_House
MVP/app/src/main/java/com/ko/mvp/app/MvpServiceLocator.kt
1
1720
package com.ko.mvp.app import android.content.Context import com.ko.common.coroutines.CoroutinesDispatcher import com.ko.common.coroutines.CoroutinesDispatcherDefault import com.ko.common.navigation.AddActivityNavigator import com.ko.mvp.base.MvpContract import com.ko.mvp.base.MvpModelMapper import com.ko.mvp.base.MvpModelMapperDefault import com.ko.mvp.base.MvpPresenter import com.ko.mvp.core.MvpInteractor import com.ko.mvp.data.MvpDomainMapper import com.ko.mvp.data.MvpDomainMapperDefault import com.ko.mvp.data.MvpRepository import com.ko.mvp.navigation.NavigationProviderDefault import com.ko.user_database.UserLocalDataSource import com.ko.user_database.UserLocalDataSourceProvider internal class MvpServiceLocator(private val context: Context) { fun getPresenter(): MvpContract.Presenter = MvpPresenter(getInteractor(), getModelMapper(), getDispatcher()) fun getAdapter(): MvpRecyclerViewAdapter = MvpRecyclerViewAdapter() fun getAddActivityNavigator(): AddActivityNavigator = NavigationProviderDefault().getAddActivityNavigator(context) private fun getInteractor(): MvpContract.Interactor = MvpInteractor(getRepository()) private fun getRepository(): MvpContract.Repository = MvpRepository(getUserLocalDataSource(), getDomainMapper()) private fun getUserLocalDataSource(): UserLocalDataSource = UserLocalDataSourceProvider.getInstance(context).localDataSource private fun getDomainMapper(): MvpDomainMapper = MvpDomainMapperDefault() private fun getModelMapper(): MvpModelMapper = MvpModelMapperDefault() private fun getDispatcher(): CoroutinesDispatcher = CoroutinesDispatcherDefault() }
mit
66f5063f3fedefe65182ae33cb58ee09
35.595745
72
0.793023
4.764543
false
false
false
false
satahippy/mailru-cloud-client
src/main/kotlin/com/github/satahippy/mailru/Cloud.kt
1
6139
package com.github.satahippy.mailru import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.http.* import java.util.regex.Pattern import javax.xml.bind.DatatypeConverter class Cloud(inner: CloudApi, val cookieJar: MailruCookieJar) : CloudApi by inner { private lateinit var requestInterceptor: MailruRequestInterceptor private lateinit var uploadUrl: String private lateinit var downloadUrl: String companion object Factory { fun instance(): Cloud { val requestInterceptor = MailruRequestInterceptor() val cookieJar = MailruCookieJar() val client = OkHttpClient.Builder() .cookieJar(cookieJar) .addInterceptor(requestInterceptor) .build() val retrofit = Retrofit.Builder() .client(client) .baseUrl("https://cloud.mail.ru/api/v2/") .addConverterFactory(FormUrlEncodedConverterFactory()) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() val instance = Cloud(retrofit.create(CloudApi::class.java), cookieJar) instance.requestInterceptor = requestInterceptor return instance } } fun login(username: String, password: String) { // изначальный запрос нужен чтобы получить act_token init().execute() val actToken = cookieJar.getActToken() ?: throw MailruException("Act token is not found in cookies") val html = internalLogin(InternalLoginRequest( Login = username, Password = password, act_token = actToken, page = "https://cloud.mail.ru/?from=login&from-page=promo&from-promo=blue-2018", Domain = "mail.ru", FromAccount = "opener=account&twoSteps=1", new_auth_form = 1, saveauth = 1, lang = "ru_RU" )).execute().body() ?: throw MailruException("Can't receive login page") requestInterceptor.csrf = searchOnLoginPage("csrf", html) ?: throw MailruException("Can't extract csrf from login page") requestInterceptor.xPageId = searchOnLoginPage("x-page-id", html) ?: throw MailruException("Can't extract x-page-id from login page") requestInterceptor.build = searchOnLoginPage("BUILD", html) ?: throw MailruException("Can't extract BUILD from login page") uploadUrl = searchUploadUrlOnLoginPage(html) ?: throw MailruException("Can't extract upload url from login page") downloadUrl = searchDownloadUrlOnLoginPage(html) ?: throw MailruException("Can't extract download url from login page") requestInterceptor.email = username + "@mail.ru" requestInterceptor.logined = true } private fun searchOnLoginPage(parameter: String, html: String): String? { val matcher = Pattern.compile(""""$parameter":\s*"(.*?)"""").matcher(html) if (!matcher.find()) { return null } return matcher.group(1) } private fun searchUploadUrlOnLoginPage(html: String): String? { val matcher = Pattern.compile(""""([^"]+mail.ru/upload/)"""").matcher(html) if (!matcher.find()) { return null } return matcher.group(1) } private fun searchDownloadUrlOnLoginPage(html: String): String? { val matcher = Pattern.compile(""""([^"]+mail.ru/attach/)"""").matcher(html) if (!matcher.find()) { return null } return matcher.group(1) } fun uploadFile(home: String, data: ByteArray): Call<MailruResponse<String>> { val size = data.size val hash = uploadFileHash(data) return addFile(home, hash, size) } private fun uploadFileHash(data: ByteArray): String { if (data.size < 21) { return String.format("%-40s", DatatypeConverter.printHexBinary(data)) .replace(" ", "0") } return internalUploadFile( uploadUrl, RequestBody.create(MediaType.parse("application/octet-stream"), data) ).execute().body() ?: throw MailruException("Can't upload file") } fun downloadFile(home: String): Call<ResponseBody> { val downloadFileUrl = downloadUrl + home return internalDownloadFile(downloadFileUrl) } } interface CloudApi { @GET("https://account.mail.ru/login/") fun init(): Call<String> @POST("https://auth.mail.ru/cgi-bin/auth") fun internalLogin(@Body request: InternalLoginRequest): Call<String> @PUT fun internalUploadFile(@Url url: String, @Body bytes: RequestBody): Call<String> @GET fun internalDownloadFile(@Url url: String): Call<ResponseBody> @GET("folder") fun getFolder( @Query("home") home: String, @Query("sort") sort: Sort = Sort(type = "name", order = "asc"), @Query("offset") offset: Int = 0, @Query("limit") limit: Int = 500 ): Call<MailruResponse<FolderOrFile>> @POST("folder/add") fun addFolder( @Query("home") home: String, @Query("conflict") conflict: String = "rename" ): Call<MailruResponse<String>> @POST("file") fun getFile( @Query("home") home: String ): Call<MailruResponse<FolderOrFile>> @POST("file/add") fun addFile( @Query("home") home: String, @Query("hash") hash: String, @Query("size") size: Int ): Call<MailruResponse<String>> @POST("file/remove") fun removeFile( @Query("home") home: String ): Call<MailruResponse<String>> }
bsd-2-clause
4fe1a3fb8b7925b593187329236d9d2d
34.905882
96
0.610911
4.484938
false
false
false
false
shymmq/librus-client-kotlin
app/src/test/kotlin/com/wabadaba/dziennik/api/LiveLoginClientTest.kt
1
2146
package com.wabadaba.dziennik.api import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.wabadaba.dziennik.vo.Me import org.amshove.kluent.shouldEqualTo import org.amshove.kluent.shouldNotBe import org.amshove.kluent.shouldNotEqualTo import org.junit.Ignore import org.junit.Test @Ignore class LiveLoginClientTest { private val networkInfoMock = mock<NetworkInfo> { on { isConnectedOrConnecting } doReturn true } private val connectivityManagerMock = mock<ConnectivityManager> { on { activeNetworkInfo } doReturn networkInfoMock } private val contextMock = mock<Context> { on { getSystemService(Context.CONNECTIVITY_SERVICE) } doReturn connectivityManagerMock } private val httpClientMock = RxHttpClient(contextMock, 60) private val client: LoginClient = LoginClient(httpClientMock) private val username = "13335" private val password = "librus11" @Test fun shouldLogIn() { val result = client.login(username, password).blockingGet() result.accessToken shouldNotBe null result.refreshToken shouldNotBe null } @Test(expected = HttpException.Authorization::class) fun shouldNotLogIn() { client.login(username, "invalid password").blockingGet() } @Test fun shouldFetchData() { val result = client.login(username, password).blockingGet() val apiClient = APIClient(result, httpClientMock) val fetchedEntities = apiClient.fetchEntities(Me::class).toList().blockingGet() fetchedEntities shouldNotBe null fetchedEntities.size shouldEqualTo 1 } @Test fun shouldRefreshToken() { val oldTokens = client.login(username, password).blockingGet() val apiClient = APIClient(oldTokens, httpClientMock) val newTokens = apiClient.refreshAccess().blockingGet() oldTokens.accessToken shouldNotEqualTo newTokens.accessToken oldTokens.refreshToken shouldNotEqualTo newTokens.refreshToken } }
gpl-3.0
fc2d1043aa881aad7e0ded8ea1d8907f
31.515152
94
0.733924
4.800895
false
true
false
false
industrial-data-space/trusted-connector
ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/cm/impl/trustx/TrustXCM.kt
1
10507
/*- * ========================LICENSE_START================================= * ids-container-manager * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.cm.impl.trustx import com.google.protobuf.InvalidProtocolBufferException import de.fhg.aisec.ids.api.cm.ApplicationContainer import de.fhg.aisec.ids.api.cm.ContainerManager import de.fhg.aisec.ids.api.cm.ContainerStatus import de.fhg.aisec.ids.api.cm.Decision import de.fhg.aisec.ids.api.cm.Direction import de.fhg.aisec.ids.api.cm.Protocol import de.fhg.aisec.ids.comm.unixsocket.TrustmeUnixSocketResponseHandler import de.fhg.aisec.ids.comm.unixsocket.TrustmeUnixSocketThread import de.fraunhofer.aisec.trustme.Container.ContainerState import de.fraunhofer.aisec.trustme.Control.ContainerStartParams import de.fraunhofer.aisec.trustme.Control.ControllerToDaemon import de.fraunhofer.aisec.trustme.Control.DaemonToController import org.slf4j.LoggerFactory import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.time.Duration import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.util.Locale import kotlin.math.abs /** * ContainerManager implementation for trust-x containers. * * * /dev/socket/cml-control Protobuf: control.proto container.proto für container configs * * @author Julian Schütte ([email protected]) */ class TrustXCM @JvmOverloads constructor(socket: String = SOCKET) : ContainerManager { private var socketThread: TrustmeUnixSocketThread = TrustmeUnixSocketThread(socket) private var responseHandler: TrustmeUnixSocketResponseHandler = TrustmeUnixSocketResponseHandler() private val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) .withLocale(Locale.GERMANY) .withZone(ZoneId.systemDefault()) private fun stateToStatusString(state: ContainerState): ContainerStatus { return when (state) { ContainerState.RUNNING, ContainerState.SETUP -> ContainerStatus.RUNNING else -> ContainerStatus.EXITED } } override fun list(onlyRunning: Boolean): List<ApplicationContainer> { LOG.debug("Starting list containers") val result: MutableList<ApplicationContainer> = ArrayList() val response = sendCommandAndWaitForResponse(ControllerToDaemon.Command.GET_CONTAINER_STATUS) try { val dtc = DaemonToController.parseFrom(response) val containerStats = dtc.containerStatusList for (cs in containerStats) { var container: ApplicationContainer if (!onlyRunning || ContainerState.RUNNING == cs.state) { container = ApplicationContainer() container.id = cs.uuid container.image = "" container.created = formatter.format(Instant.ofEpochSecond(cs.created)) // container.setStatus(cs.getState().name()); container.status = stateToStatusString(cs.state) container.ports = emptyList() container.names = cs.name container.name = cs.name container.size = "" container.uptime = formatDuration(Duration.ofSeconds(cs.uptime)) container.signature = "" container.owner = "" container.description = "trustx container" container.labels = emptyMap() LOG.debug("List add Container: $container") result.add(container) } } } catch (e: InvalidProtocolBufferException) { LOG.error("Response Length: " + response.size, e) LOG.error( """ Response was: ${bytesToHex(response)} """.trimIndent() ) } return result } override fun wipe(containerID: String) { sendCommand(ControllerToDaemon.Command.CONTAINER_WIPE) } override fun startContainer(containerID: String, key: String?) { LOG.debug("Starting start container with ID {}", containerID) val ctdmsg = ControllerToDaemon.newBuilder() ctdmsg.command = ControllerToDaemon.Command.CONTAINER_START ctdmsg.addContainerUuids(containerID) val cspbld = ContainerStartParams.newBuilder() if (key != null) { cspbld.key = key } cspbld.noSwitch = true ctdmsg.containerStartParams = cspbld.build() try { val dtc = parseResponse(sendProtobufAndWaitForResponse(ctdmsg.build())) if (DaemonToController.Response.CONTAINER_START_OK != dtc.response) { LOG.error("Container start failed, response was {}", dtc.response) } LOG.error("Container start ok, response was {}", dtc.response) } catch (e: InvalidProtocolBufferException) { LOG.error("Protobuf error", e) } } override fun stopContainer(containerID: String) { LOG.debug("Starting stop container with ID {}", containerID) val ctdmsg = ControllerToDaemon.newBuilder() ctdmsg.command = ControllerToDaemon.Command.CONTAINER_STOP ctdmsg.addContainerUuids(containerID) sendProtobuf(ctdmsg.build()) } override fun restartContainer(containerID: String) { sendCommand(ControllerToDaemon.Command.CONTAINER_STOP) sendCommand(ControllerToDaemon.Command.CONTAINER_START) } override fun pullImage(app: ApplicationContainer): String? { return null } override fun inspectContainer(containerID: String): String? { // TODO Auto-generated method stub return null } override fun getMetadata(containerID: String): String? { // TODO Auto-generated method stub return null } override fun setIpRule( containerID: String, direction: Direction, srcPort: Int, dstPort: Int, srcDstRange: String, protocol: Protocol, decision: Decision ) { // TODO Auto-generated method stub } // TODO Auto-generated method stub override val version: String get() = "1.0" /** * Used for sending control commands to a device. * * @param command The command to be sent. */ private fun sendCommand(command: ControllerToDaemon.Command) { val ctdmsg = ControllerToDaemon.newBuilder() ctdmsg.command = command sendProtobuf(ctdmsg.build()) } /** * More flexible than the sendCommand method. Required when other parameters need to be set than * the Command * * @param ctd the control command */ private fun sendProtobuf(ctd: ControllerToDaemon) { LOG.debug("sending message {}", ctd.command) LOG.debug(ctd.toString()) val encodedMessage = ctd.toByteArray() try { socketThread.sendWithHeader(encodedMessage, responseHandler) } catch (e: IOException) { LOG.error(e.message, e) } catch (e: InterruptedException) { LOG.error(e.message, e) } } /** * Used for sending control commands to a device. * * @param command The command to be sent. * @return Success state. */ private fun sendCommandAndWaitForResponse(command: ControllerToDaemon.Command): ByteArray { sendCommand(command) return responseHandler.waitForResponse() } /** * Used for sending control commands to a device. * * @param ctd The command to be sent. * @return Success state. */ private fun sendProtobufAndWaitForResponse(ctd: ControllerToDaemon): ByteArray { sendProtobuf(ctd) return responseHandler.waitForResponse() } @Throws(InvalidProtocolBufferException::class) private fun parseResponse(response: ByteArray?): DaemonToController { return DaemonToController.parseFrom(response) } companion object { private val LOG = LoggerFactory.getLogger(TrustXCM::class.java) private const val SOCKET = "/run/socket/cml-control" val isSupported: Boolean get() { val path = Paths.get(SOCKET) var exists = false if (Files.exists(path)) { exists = true } return exists } private val hexArray = "0123456789ABCDEF".toCharArray() fun bytesToHex(bytes: ByteArray): String { val hexChars = CharArray(bytes.size * 2) for (j in bytes.indices) { val v = bytes[j].toInt() and 0xFF hexChars[j * 2] = hexArray[v ushr 4] hexChars[j * 2 + 1] = hexArray[v and 0x0F] } return String(hexChars) } private fun formatDuration(duration: Duration): String { val seconds = duration.seconds val absSeconds = abs(seconds) val days = dayString(absSeconds) val hoursAndMinutes = String.format("%d:%02d", absSeconds / 3600 / 24, absSeconds % 3600 / 60) return days + hoursAndMinutes } private fun dayString(seconds: Long): String { if (seconds != 0L) { val hours = seconds / 3600 return when { hours < 24 -> "" hours < 48 -> "1 day " else -> { String.format("%d days ", hours / 24) } } } return "" } } init { Thread(socketThread).apply { isDaemon = true start() } } }
apache-2.0
aa45a6e2019e5b14c031651f60fcd3e3
35.475694
106
0.620466
4.605436
false
false
false
false
kittinunf/ReactiveAndroid
reactiveandroid-ui/src/androidTest/kotlin/com/github/kittinunf/reactiveandroid/widget/AdapterEventTest.kt
1
1863
package com.github.kittinunf.reactiveandroid.widget import android.support.test.InstrumentationRegistry import android.support.test.annotation.UiThreadTest import android.support.test.rule.UiThreadTestRule import android.support.test.runner.AndroidJUnit4 import android.widget.ArrayAdapter import io.reactivex.observers.TestObserver import org.junit.BeforeClass import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class AdapterEventTest { @Rule @JvmField val uiThreadTestRule = UiThreadTestRule() private val context = InstrumentationRegistry.getContext() companion object { @BeforeClass @JvmStatic fun setUp() { } } @Test @UiThreadTest fun testAdapterChanged() { val adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, mutableListOf("a", "b", "c", "d", "e")) val t = TestObserver<Unit>() val s = adapter.rx_changed().subscribeWith(t) t.assertNoValues() t.assertNoErrors() adapter.add("1") t.assertValueCount(1) adapter.add("2") t.assertValueCount(2) s.dispose() adapter.add("3") t.assertValueCount(2) } @Test @UiThreadTest fun testAdapterInvalidated() { val adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, mutableListOf("1", "2", "3", "4")) val t = TestObserver<Unit>() val s = adapter.rx_invalidated().subscribeWith(t) t.assertNoValues() t.assertNoErrors() adapter.filter.filter("1") t.assertNoValues() adapter.filter.filter("2") t.assertNoValues() adapter.filter.filter("a") t.awaitCount(1) s.dispose() adapter.filter.filter("b") t.awaitCount(1) } }
mit
006e8daf065c75f72e6c83236f2c0c01
22.582278
120
0.64788
4.186517
false
true
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/MainActivity.kt
1
9336
package fr.geobert.efficio import android.app.Fragment import android.app.PendingIntent import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.preference.PreferenceManager import android.support.v7.app.ActionBarDrawerToggle import android.util.Log import android.view.View import android.widget.AdapterView import com.crashlytics.android.Crashlytics import fr.geobert.efficio.data.Store import fr.geobert.efficio.data.StoreLoaderListener import fr.geobert.efficio.data.StoreManager import fr.geobert.efficio.db.DbContentProvider import fr.geobert.efficio.db.StoreTable import fr.geobert.efficio.dialog.DeleteConfirmationDialog import fr.geobert.efficio.dialog.StoreNameDialog import fr.geobert.efficio.misc.* import fr.geobert.efficio.service.EfficioService import fr.geobert.efficio.service.InstallServiceReceiver import fr.geobert.efficio.service.OnAlarmReceiver import io.fabric.sdk.android.Fabric import kotlinx.android.synthetic.main.main_activity.* import kotlinx.android.synthetic.main.toolbar.* import kotlin.properties.Delegates class MainActivity : BaseActivity(), DeleteDialogInterface, StoreLoaderListener, SharedPreferences.OnSharedPreferenceChangeListener { private var lastStoreId: Long by Delegates.notNull() private var taskListFrag: TaskListFragment? = null private var currentStore: Store by Delegates.notNull() private var storeManager: StoreManager = StoreManager(this, this) private val TAG = "MainActivity" val prefs: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(this) } private val mDrawerToggle: ActionBarDrawerToggle by lazy { object : ActionBarDrawerToggle(this, /* host Activity */ drawer_layout, /* DrawerLayout object */ mToolbar, R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */) { override fun onDrawerClosed(drawerView: View?) { invalidateOptionsMenu() // calls onPrepareOptionsMenu() } override fun onDrawerOpened(drawerView: View?) { invalidateOptionsMenu() // calls onPrepareOptionsMenu() } } } private fun cleanDatabaseIfTestingMode() { // if run by espresso, delete database, can't do it from test, doesn't work // see https://stackoverflow.com/questions/33059307/google-espresso-delete-user-data-on-each-test if (TEST_MODE) { //DBPrefsManager.getInstance(this).resetAll() Log.d(TAG, "ERASING DB") val client = contentResolver.acquireContentProviderClient("fr.geobert.efficio") val provider = client.localContentProvider as DbContentProvider provider.deleteDatabase(this) @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT < 24) client.release() else client.close() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) cleanDatabaseIfTestingMode() if (!BuildConfig.DEBUG) Fabric.with(this, Crashlytics()) setContentView(R.layout.main_activity) PreferenceManager.setDefaultValues(this, R.xml.settings, false) title = "" if (savedInstanceState == null) { taskListFrag = TaskListFragment() fragmentManager.beginTransaction().replace(R.id.flContent, taskListFrag, "tasksList").commit() } setSupportActionBar(mToolbar) setUpDrawerToggle() setupDrawerContent() lastStoreId = prefs.getLong("lastStoreId", 1) prefs.registerOnSharedPreferenceChangeListener(this) installServiceTimer() } private fun installServiceTimer() { val pi = PendingIntent.getBroadcast(this, 0, Intent(this, OnAlarmReceiver::class.java), PendingIntent.FLAG_NO_CREATE) if (pi == null) { // no alarm set val intent = Intent(this, InstallServiceReceiver::class.java) intent.action = "fr.geobert.efficio.INSTALL_TIMER" sendBroadcast(intent) } EfficioService.callMe(this, lastStoreId) } override fun onResume() { super.onResume() if (taskListFrag == null) { taskListFrag = fragmentManager.findFragmentByTag("tasksList") as TaskListFragment } store_spinner.onItemSelectedListener = null lastStoreId = prefs.getLong("lastStoreId", 1) storeManager.fetchAllStores() store_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { // nothing } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { lastStoreId = id prefs.edit().putLong("lastStoreId", id).apply() currentStore = storeManager.storesList[position] refreshTaskList(this@MainActivity, id) } } } override fun onDestroy() { super.onDestroy() prefs.unregisterOnSharedPreferenceChangeListener(this) } override fun onDeletedConfirmed() { StoreTable.deleteStore(this, currentStore) // now that currentStore is deleted, select another one, in none, create a default one storeManager.storesList.remove(currentStore) storeManager.storeAdapter.deleteStore(lastStoreId) if (storeManager.storesList.count() > 0) { currentStore = storeManager.storesList[0] lastStoreId = currentStore.id prefs.edit().putLong("lastStoreId", lastStoreId).apply() refreshTaskList(this, lastStoreId) } else { StoreTable.create(this, getString(R.string.store)) storeManager.fetchAllStores() } } fun refreshTask(taskId: Long) { val intent = Intent(OnRefreshReceiver.REFRESH_ACTION) intent.putExtra("storeId", lastStoreId) intent.putExtra("taskId", taskId) sendBroadcast(intent) } private fun setUpDrawerToggle() { // Defer code dependent on restoration of previous instance state. // NB: required for the drawer indicator to show up! drawer_layout.addDrawerListener(mDrawerToggle) drawer_layout.post({ mDrawerToggle.syncState() }) } private fun setupDrawerContent() { nvView.setNavigationItemSelectedListener({ item -> when (item.itemId) { R.id.edit_departments -> callEditDepartment() R.id.create_new_store -> callCreateNewStore() R.id.rename_store -> callRenameStore() R.id.delete_current_store -> callDeleteStore() R.id.settings -> callSettings() } drawer_layout.closeDrawer(nvView) true }) } private fun callSettings() { SettingsActivity.callMe(this) } private fun callDeleteStore() { val d = DeleteConfirmationDialog.newInstance(getString(R.string.confirm_delete_store). format(currentStore.name), getString(R.string.delete_current_store), DELETE_STORE) d.show(fragmentManager, "deleteStore") } private fun callRenameStore() { val d = StoreNameDialog.newInstance(getString(R.string.choose_new_store_name), getString(R.string.rename_current_store), currentStore.name, lastStoreId, RENAME_STORE) d.show(fragmentManager, "renameStore") } fun storeRenamed(name: String) { currentStore.name = name storeManager.renameStore(name, lastStoreId) updateWidgets() } private fun callCreateNewStore() { val d = StoreNameDialog.newInstance(getString(R.string.choose_new_store_name), getString(R.string.create_new_store), getString(R.string.store), 0, CREATE_STORE) d.show(fragmentManager, "createStore") } fun storeCreated() { storeManager.fetchAllStores() } private fun callEditDepartment() { EditDepartmentsActivity.callMe(taskListFrag as Fragment, lastStoreId) } override fun onStoreLoaded() { store_spinner.adapter = storeManager.storeAdapter if (storeManager.storesList.count() == 1) { currentStore = storeManager.storesList[0] lastStoreId = currentStore.id title = currentStore.name setSpinnerVisibility(View.GONE) } else { currentStore = storeManager.storesList.find { it.id == lastStoreId } as Store store_spinner.setSelection(storeManager.indexOf(lastStoreId)) setSpinnerVisibility(View.VISIBLE) title = "" } } fun updateWidgets() { Log.d(TAG, "updateWidgets") updateWidgets(this) } override fun onSharedPreferenceChanged(preferences: SharedPreferences, key: String) { when (key) { "invert_checkbox_pref", "invert_list_pref" -> refreshTaskList(this, lastStoreId) } } companion object { var TEST_MODE: Boolean = false } }
gpl-2.0
88c02f079bfd8f3ed06e99bf2fa1fca2
37.419753
106
0.662989
4.743394
false
false
false
false
CPRTeam/CCIP-Android
app/src/main/java/app/opass/ccip/extension/LiveData.kt
1
516
package app.opass.ccip.extension import android.os.Handler import android.os.Looper import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData fun <T> LiveData<T>.debounce(duration: Long) = MediatorLiveData<T>().also { mld -> val source = this val handler = Handler(Looper.getMainLooper()) val runnable = Runnable { mld.value = source.value } mld.addSource(source) { handler.removeCallbacks(runnable) handler.postDelayed(runnable, duration) } }
gpl-3.0
8393303e765ae5b7f18af1b5c86d447a
24.8
82
0.71124
4.128
false
false
false
false
MaibornWolff/codecharta
analysis/filter/StructureModifier/src/main/kotlin/de/maibornwolff/codecharta/filter/structuremodifier/NodeRemover.kt
1
2770
package de.maibornwolff.codecharta.filter.structuremodifier import de.maibornwolff.codecharta.model.AttributeDescriptor import de.maibornwolff.codecharta.model.AttributeType import de.maibornwolff.codecharta.model.BlacklistItem import de.maibornwolff.codecharta.model.Edge import de.maibornwolff.codecharta.model.MutableNode import de.maibornwolff.codecharta.model.Project import de.maibornwolff.codecharta.model.ProjectBuilder import mu.KotlinLogging class NodeRemover(private val project: Project) { private val logger = KotlinLogging.logger {} fun remove(paths: Array<String>): Project { var pathSegments = paths.map { it.removePrefix("/").removeSuffix("/").split("/") } if (pathSegments.contains(listOf("root"))) { logger.warn("Root node cannot be removed") pathSegments = pathSegments.filter { it != listOf("root") } } return ProjectBuilder( removeNodes(pathSegments), removeEdges(paths), copyAttributeTypes(), copyAttributeDescriptors(), removeBlacklistItems(paths) ).build(true) } private fun filterNodes(path: List<String>, node: MutableNode): MutableNode { val filteredChildren = node.children.filter { it.name != path.firstOrNull() || path.size > 1 } node.children = filteredChildren.map { filterNodes(path.drop(1), it) }.toMutableSet() return node } private fun removeNodes(paths: List<List<String>>): MutableList<MutableNode> { var root = project.rootNode.toMutableNode() paths.forEach { root = filterNodes(it.drop(1), root) } return mutableListOf(root) } private fun removeEdges(removePatterns: Array<String>): MutableList<Edge> { var edges = project.edges removePatterns.forEach { path -> edges = edges.filter { !it.fromNodeName.contains(path) && !it.toNodeName.contains(path) } } return edges.toMutableList() } private fun copyAttributeTypes(): MutableMap<String, MutableMap<String, AttributeType>> { val mergedAttributeTypes: MutableMap<String, MutableMap<String, AttributeType>> = mutableMapOf() project.attributeTypes.forEach { mergedAttributeTypes[it.key] = it.value } return mergedAttributeTypes.toMutableMap() } private fun copyAttributeDescriptors(): MutableMap<String, AttributeDescriptor> { return project.attributeDescriptors.toMutableMap() } private fun removeBlacklistItems(paths: Array<String>): MutableList<BlacklistItem> { var blacklist = project.blacklist paths.forEach { path -> blacklist = blacklist.filter { !it.path.contains(path) } } return blacklist.toMutableList() } }
bsd-3-clause
04063c6a774e737c1ebd3ba8b09121da
39.144928
132
0.689531
4.735043
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/loritta/GetFanArtsController.kt
1
2639
package net.perfectdreams.loritta.morenitta.website.routes.api.v1.loritta import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ObjectNode import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.extensions.getOrNull import io.ktor.server.application.ApplicationCall import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.utils.config.FanArtArtist import net.perfectdreams.loritta.morenitta.utils.extensions.objectNode import net.perfectdreams.loritta.morenitta.utils.extensions.set import net.perfectdreams.sequins.ktor.BaseRoute import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson class GetFanArtsController(val loritta: LorittaBot) : BaseRoute("/api/v1/loritta/fan-arts") { override suspend fun onRequest(call: ApplicationCall) { loritta as LorittaBot val query = call.parameters["query"] val filter = call.parameters["filter"]?.split(",") val fanArtArtists = loritta.fanArtArtists .let { if (filter != null) it.filter { it.id in filter } else it } val fanArtists = Constants.JSON_MAPPER.valueToTree<JsonNode>(fanArtArtists) if (query == "all") { val discordIds = fanArtArtists .mapNotNull { it.socialNetworks?.asSequence()?.filterIsInstance<FanArtArtist.SocialNetwork.DiscordSocialNetwork>() ?.firstOrNull()?.let { discordInfo -> discordInfo.id.toLong() } } val userProfiles = discordIds.map { it to loritta.getLorittaProfileDeferred(it) } val users = discordIds.asSequence().mapNotNull { loritta.cachedRetrievedArtists.getIfPresent(it)?.getOrNull() } fanArtists.forEach { val discordInfo = it["networks"]?.firstOrNull { it["type"].textValue() == "discord" } if (discordInfo != null) { val id = discordInfo["id"].textValue() val user = users.firstOrNull { it.id.toString() == id } val profileJob = userProfiles.firstOrNull { entry -> entry.first == id.toLong() } if (profileJob != null) { val profile = profileJob.second.await() if (profile != null) { val aboutMe = loritta.newSuspendedTransaction { profile.settings.aboutMe } if (aboutMe != null) { it as ObjectNode it.set("aboutMe", aboutMe) } } } if (user != null) { it as ObjectNode it.set<JsonNode>("user", objectNode( "id" to user.id, "name" to user.name, "effectiveAvatarUrl" to user.effectiveAvatarUrl )) } } } } call.respondJson(fanArtists) } }
agpl-3.0
fc75049de2071dab768264e133c58be0
32.417722
114
0.700265
3.824638
false
false
false
false
darakeon/dfm
android/Lib/src/main/kotlin/com/darakeon/dfm/lib/api/entities/moves/Move.kt
1
1677
package com.darakeon.dfm.lib.api.entities.moves import com.darakeon.dfm.lib.api.entities.Date import com.darakeon.dfm.lib.extensions.toDoubleByCulture import java.io.Serializable import java.util.ArrayList import java.util.UUID data class Move ( var guid: UUID? = null, var description: String? = null, var year: Int = 0, var month: Int = 0, var day: Int = 0, var nature: Int? = null, var categoryName: String? = null, var outUrl: String? = null, var inUrl: String? = null, var value: Double? = null, var detailList: MutableList<Detail> = ArrayList(), var checked: Boolean = false ) : Serializable { var isDetailed: Boolean = false var natureEnum get() = Nature.get(nature) set(value) { nature = value?.value } var warnCategory: Boolean = false private set var date: Date get() = Date(year, month, day) set(value) { year = value.year month = value.month day = value.day } fun add(description: String, amount: Int, value: Double) { val detail = Detail(description, amount, value) detailList.add(detail) } fun remove(description: String, amount: Int, value: Double) { for (detail in detailList) { if (detail == Detail(description, amount, value)) { detailList.remove(detail) return } } } fun setValue(value: String) { this.value = value.toDoubleByCulture() ?: 0.0 } fun setDefaultData(accountUrl: String, useCategories: Boolean) { if (guid == null) { if (accountUrl != "") { outUrl = accountUrl } } else { warnCategory = !useCategories && categoryName != null } } fun clearNotUsedValues() { if (isDetailed) { value = null } else { detailList = ArrayList() } } }
gpl-3.0
3e0769ca534fb7c85c879e2cd3ca7596
19.9625
65
0.672033
3.077064
false
false
false
false
shyiko/ktlint
ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundColonRuleTest.kt
1
11612
package com.pinterest.ktlint.ruleset.standard import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.test.format import com.pinterest.ktlint.test.lint import org.assertj.core.api.Assertions.assertThat import org.junit.Test class SpacingAroundColonRuleTest { @Test fun testLint() { assertThat( SpacingAroundColonRule().lint( """ class A:B class A2 : B2 fun main() { var x:Boolean var y: Boolean call(object: DefaultConsumer(channel) { }) } interface D interface C: D interface C2 : D """.trimIndent() ) ).isEqualTo( listOf( LintError(1, 8, "colon-spacing", "Missing spacing around \":\""), LintError(4, 11, "colon-spacing", "Missing spacing after \":\""), LintError(6, 16, "colon-spacing", "Missing spacing before \":\""), LintError(9, 12, "colon-spacing", "Missing spacing before \":\"") ) ) assertThat( SpacingAroundColonRule().lint( """ @file:JvmName("Foo") class Example(@field:Ann val foo: String, @get:Ann val bar: String) class Example { @set:[Inject VisibleForTesting] public var collaborator: Collaborator } fun @receiver:Fancy String.myExtension() { } """.trimIndent() ) ).isEmpty() assertThat( SpacingAroundColonRule().lint( """ fun main() { val x = Foo::class } """.trimIndent() ) ).isEmpty() assertThat( SpacingAroundColonRule().lint( """ class A { constructor() : this("") constructor(s: String) { } } class A { @Deprecated("") @Throws(IOException::class, SecurityException::class) protected abstract fun <T> f( @Nullable thing: String, things: List<T>): Runnable where T : Runnable, T: Closeable } class A : B { constructor(): super() constructor(param: String) : super(param) } """.trimIndent() ) ).isEqualTo( listOf( LintError(9, 82, "colon-spacing", "Missing spacing before \":\""), LintError(12, 18, "colon-spacing", "Missing spacing before \":\"") ) ) } @Test fun testFormat() { assertThat( SpacingAroundColonRule().format( """ class A:B fun main() { var x:Boolean var y: Boolean } interface D interface C: D class F(param: String):D(param) class F2 constructor(param: String): D3(param) class F3 : D3 { constructor():super() constructor(param: String): super(param) val x = object:D3 { } } fun <T> max(a: T, b: T) where T: Comparable<T> """.trimIndent() ) ).isEqualTo( """ class A : B fun main() { var x: Boolean var y: Boolean } interface D interface C : D class F(param: String) : D(param) class F2 constructor(param: String) : D3(param) class F3 : D3 { constructor() : super() constructor(param: String) : super(param) val x = object : D3 { } } fun <T> max(a: T, b: T) where T : Comparable<T> """.trimIndent() ) } @Test fun testLintMethod() { assertThat( SpacingAroundColonRule().lint( """ fun main() : String = "duck" fun duck(): String = "main" """.trimIndent() ) ).isEqualTo( listOf( LintError(1, 12, "colon-spacing", "Unexpected spacing before \":\"") ) ) } @Test fun testFormatMethod() { assertThat( SpacingAroundColonRule().format( """ fun main() : String = "duck" """.trimIndent() ) ).isEqualTo( """ fun main(): String = "duck" """.trimIndent() ) } @Test fun testLintMethodParams() { assertThat( SpacingAroundColonRule().lint( """ fun identity(value: String): String = value fun unformattedIdentity(value : String): String = value """.trimIndent() ) ).isEqualTo( listOf( LintError(2, 31, "colon-spacing", "Unexpected spacing before \":\"") ) ) } @Test fun testFormatMethodParams() { assertThat( SpacingAroundColonRule().format( """ fun validIdentity(value: String): String = value fun identity(value : String): String = value fun oneSpaceIdentity(value : String): String = value """.trimIndent() ) ).isEqualTo( """ fun validIdentity(value: String): String = value fun identity(value: String): String = value fun oneSpaceIdentity(value: String): String = value """.trimIndent() ) } @Test fun testLintGenericMethodParam() { assertThat( SpacingAroundColonRule().lint( """ fun <T: Any> trueIdentity(value: T): T = value """.trimIndent() ) ).isEqualTo( listOf( LintError(1, 7, "colon-spacing", "Missing spacing before \":\"") ) ) } @Test fun testFormatGenericMethodParam() { assertThat( SpacingAroundColonRule().format( """ fun <T: Any> trueIdentity(value: T): T = value fun <T : Any> trueIdentity(value: T): T = value """.trimIndent() ) ).isEqualTo( """ fun <T : Any> trueIdentity(value: T): T = value fun <T : Any> trueIdentity(value: T): T = value """.trimIndent() ) } @Test fun testFormatEOF() { assertThat( SpacingAroundColonRule().format( """ class X : Y, Z class A // comment : B class A /* */ : B val xmlFormatter : String = "" """.trimIndent() ) ).isEqualTo( """ class X : Y, Z class A : // comment B class A : /* */ B val xmlFormatter: String = "" """.trimIndent() ) } // https://github.com/pinterest/ktlint/issues/1057 @Test fun testLintNewLineBeforeColon() { assertThat( SpacingAroundColonRule().lint( """ fun test() { val v1 : Int = 1 val v2 // comment : Int = 1 val v3 // comment : Int = 1 fun f1() : Int = 1 fun f2() // comment : Int = 1 fun f3() // comment : Int = 1 fun g1() : Int { return 1 } fun g2() // comment : Int { return 1 } fun g3() // comment : Int { return 1 } } """.trimIndent() ) ).isEqualTo( listOf( LintError(2, 11, "colon-spacing", "Unexpected newline before \":\""), LintError(5, 22, "colon-spacing", "Unexpected newline before \":\""), LintError(9, 19, "colon-spacing", "Unexpected newline before \":\""), LintError(12, 13, "colon-spacing", "Unexpected newline before \":\""), LintError(15, 24, "colon-spacing", "Unexpected newline before \":\""), LintError(19, 19, "colon-spacing", "Unexpected newline before \":\""), LintError(22, 13, "colon-spacing", "Unexpected newline before \":\""), LintError(27, 24, "colon-spacing", "Unexpected newline before \":\""), LintError(33, 19, "colon-spacing", "Unexpected newline before \":\""), ) ) } @Test fun testFormatNewLineBeforeColon() { assertThat( SpacingAroundColonRule().format( """ fun test() { val v1 : Int = 1 val v2 // comment : Int = 1 val v3 // comment : Int = 1 fun f1() : Int = 1 fun f2() // comment : Int = 1 fun f3() // comment : Int = 1 fun g1() : Int { return 1 } fun g2() // comment : Int { return 1 } fun g3() // comment : Int { return 1 } } """.trimIndent() ) ).isEqualTo( """ fun test() { val v1: Int = 1 val v2: Int = // comment 1 val v3: Int = // comment 1 fun f1(): Int = 1 fun f2(): Int = // comment 1 fun f3(): Int = // comment 1 fun g1(): Int { return 1 } fun g2(): Int { // comment return 1 } fun g3(): Int { // comment return 1 } } """.trimIndent() ) } }
mit
ea195b031d63f8a9bfe7a2fdd06b1067
27.600985
108
0.36979
5.604247
false
true
false
false
lanhuaguizha/Christian
app/src/main/java/com/christian/nav/NavActivity.kt
1
38301
package com.christian.nav import android.Manifest.permission.* import android.annotation.SuppressLint import android.content.* import android.os.* import android.util.AttributeSet import android.util.Log import android.view.* import androidx.annotation.Nullable import androidx.annotation.StringRes import androidx.appcompat.widget.TooltipCompat import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.bumptech.glide.Glide import com.christian.R import com.christian.SettingsActivity import com.christian.common.* import com.christian.nav.disciple.DiscipleFragment import com.christian.nav.gospel.GospelFragment import com.christian.nav.home.HomeFragment import com.christian.nav.me.MeFragment import com.christian.swipe.SwipeBackActivity import com.christian.view.showPopupMenu import com.firebase.ui.auth.ErrorCodes import com.firebase.ui.auth.IdpResponse import com.github.anzewei.parallaxbacklayout.ParallaxHelper import com.google.android.material.appbar.AppBarLayout import com.google.android.material.snackbar.Snackbar import com.google.android.material.tabs.TabLayout import eightbitlab.com.blurview.makeViewBlurExtendsFrameLayout import kotlinx.android.synthetic.main.fragment_disciple_child.* import kotlinx.android.synthetic.main.fragment_disciple_child.view.* import kotlinx.android.synthetic.main.fragment_home_child.* import kotlinx.android.synthetic.main.fragment_home_child.view.* import kotlinx.android.synthetic.main.fragment_home_child.view.home_child_rv import kotlinx.android.synthetic.main.fragment_nav_rv.* import kotlinx.android.synthetic.main.nav_activity.* import kotlinx.android.synthetic.main.nav_activity.view.* import kotlinx.android.synthetic.main.nav_item_me_portrait.* import me.everything.android.ui.overscroll.HorizontalOverScrollBounceEffectDecorator import me.everything.android.ui.overscroll.adapters.IOverScrollDecoratorAdapter import org.jetbrains.anko.dip import ren.qinc.markdowneditors.view.EditorActivity import java.lang.ref.WeakReference import java.util.* import kotlin.math.abs import kotlin.math.min private const val ERROR_DIALOG_REQUEST_CODE = 1 fun TabLayout.canScrollDown(): Boolean { return scrollX != (getChildAt(0).width - width) } fun TabLayout.canScrollUp(): Boolean { return scrollX != 0 } /** * Home, Gospel, Communication, Me 4 TAB main entrance activity. * implementation of NavContract.View. */ open class NavActivity : SwipeBackActivity(), NavContract.INavActivity { private var retryProviderInstall: Boolean = false override fun handleSignInResponse(resultCode: Int, @Nullable response: IdpResponse?) { // Successfully signed in if (resultCode == RESULT_OK) { invalidateSignInUI() } else { // Sign in failed if (response == null) { // User pressed back button snackbar(R.string.sign_in_cancelled) return } if (response.error?.errorCode == ErrorCodes.NO_NETWORK) { snackbar(R.string.no_internet_connection) return } if (response.error?.errorCode == ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT) { // val intent = Intent( // this, // AnonymousUpgradeActivity::class.java // ).putExtra(ExtraConstants.IDP_RESPONSE, response) // startActivity(intent) } if (response.error?.errorCode == ErrorCodes.ERROR_USER_DISABLED) { snackbar(R.string.account_disabled) return } snackbar(R.string.unknown_error) } } private fun showSnackbar(@StringRes errorMessageRes: Int) { Snackbar.make(cl_nav, errorMessageRes, Snackbar.LENGTH_LONG).show() // Snackbar.make(mBinding.getRoot(), errorMessageRes, Snackbar.LENGTH_LONG).show() } // override fun onConfigurationChanged(newConfig: Configuration) { // super.onConfigurationChanged(newConfig) // if (sharedPreferences.getBoolean("isOn", false)) { // // 恢复应用默认皮肤 // shouldEnableDarkMode(SettingsActivity.DarkModeConfig.NO) // isOn = false // sharedPreferences.edit { putBoolean("isOn", isOn) } // } else { // // 夜间模式 // shouldEnableDarkMode(SettingsActivity.DarkModeConfig.YES) // isOn = true // sharedPreferences.edit { putBoolean("isOn", isOn) } // } // recreate() // } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_nav, menu) menuSearch = menu.findItem(R.id.menu_search) menuSetting = menu.findItem(R.id.menu_setting) menuSort = menu.findItem(R.id.menu_sort) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_sort -> { showPopupMenu(findViewById(R.id.menu_sort), this@NavActivity, arrayOf( getString(R.string.action_sort_by_name_reverse), getString(R.string.action_sort_by_time_reverse), getString(R.string.action_sort_by_name), getString(R.string.action_sort_by_time) ), dp2px(-48) ) { _, text -> when(navFragmentPagerAdapter.currentFragment) { is HomeFragment -> { val homeFragment = navFragmentPagerAdapter.currentFragment as HomeFragment val homeChildFragment = homeFragment.navChildFragmentPagerAdapter.currentFragment when(text) { getString(R.string.action_sort_by_name_reverse) -> { homeChildFragment.sortByNameReverse() } getString(R.string.action_sort_by_time_reverse) -> { homeChildFragment.sortByTimeReverse() } getString(R.string.action_sort_by_name) -> { homeChildFragment.sortByName() } getString(R.string.action_sort_by_time) -> { homeChildFragment.sortByTime() } } } is GospelFragment -> { val gospelFragment = navFragmentPagerAdapter.currentFragment as GospelFragment val gospelChildFragment = gospelFragment.navChildFragmentPagerAdapter.currentFragment when(text) { getString(R.string.action_sort_by_name_reverse) -> { gospelChildFragment.sortByNameReverse() } getString(R.string.action_sort_by_time_reverse) -> { gospelChildFragment.sortByTimeReverse() } getString(R.string.action_sort_by_name) -> { gospelChildFragment.sortByName() } getString(R.string.action_sort_by_time) -> { gospelChildFragment.sortByTime() } } } is DiscipleFragment -> { val discipleFragment = navFragmentPagerAdapter.currentFragment as DiscipleFragment val discipleChildFragment = discipleFragment.navChildFragmentPagerAdapter.currentFragment when(text) { getString(R.string.action_sort_by_name_reverse) -> { discipleChildFragment.sortByNameReverse() } getString(R.string.action_sort_by_time_reverse) -> { discipleChildFragment.sortByTimeReverse() } getString(R.string.action_sort_by_name) -> { discipleChildFragment.sortByName() } getString(R.string.action_sort_by_time) -> { discipleChildFragment.sortByTime() } } } } } true } R.id.menu_setting -> { val i = Intent(this, SettingsActivity::class.java) i.putExtra(showExitButton, auth.currentUser != null) startActivityForResult(i, RC_SIGN_IN) true } else -> super.onOptionsItemSelected(item) } } lateinit var menuSetting: MenuItem private lateinit var menuSearch: MenuItem private lateinit var menuSort: MenuItem private var customTime = 0L val SHOTRER_DURATION = 225L val LONGER_DURATION = 375L companion object { class StaticHandler(navActivity: NavActivity) : Handler() { private val navActivityWeakReference = WeakReference<NavActivity>(navActivity) override fun handleMessage(msg: Message) { when (msg.what) { MESSAGE_SET_TOOLBAR_EXPANDED -> { navActivityWeakReference.get()?.let { initAppBarLayout(it, msg.arg1) } } } } } } @SuppressLint("MissingSuperCall") override fun onSaveInstanceState(outState: Bundle) { } private lateinit var mStaticHandler: StaticHandler var pageSelectedPosition = 0 /** * presenter will be initialized when the NavPresenter is initialized */ override lateinit var presenter: NavContract.IPresenter var verticalOffset = -1 lateinit var navFragmentPagerAdapter: NavFragmentPagerAdapter open val viewPagerOnPageChangeListener = object : androidx.viewpager.widget.ViewPager.OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { bnv_nav.menu.getItem(position).isChecked = true mStaticHandler.removeMessages(MESSAGE_SET_TOOLBAR_EXPANDED) val msg = Message() msg.what = MESSAGE_SET_TOOLBAR_EXPANDED msg.arg1 = position mStaticHandler.sendMessageDelayed(msg, 0) // setTabLayoutExpanded(this@NavActivity, position) pageSelectedPosition = position pageSelected(position) } override fun onPageScrollStateChanged(state: Int) { /* if (state == 2) { // fab_nav.hide() } else if (state == 0) { // fab_nav.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_edit_black_24dp, theme)) // if (showOrHideLogicExecute) { // showFAB() // } }*/ } } private fun initTl(position: Int) { // UITools.elasticPadding(tl_nav, 500); // OverScrollDecoratorHelper.setUpStaticOverScroll(tl_nav, OverScrollDecoratorHelper.ORIENTATION_HORIZONTAL) when (position) { VIEW_HOME -> { HorizontalOverScrollBounceEffectDecorator(object : IOverScrollDecoratorAdapter { override fun isInAbsoluteEnd(): Boolean { return !tl_home.canScrollDown() } override fun isInAbsoluteStart(): Boolean { return !tl_home.canScrollUp() } override fun getView(): View { return tl_home } }) tl_home.visibility = View.VISIBLE tl_gospel.visibility = View.GONE tl_disciple.visibility = View.GONE tl_me.visibility = View.GONE } VIEW_GOSPEL -> { HorizontalOverScrollBounceEffectDecorator(object : IOverScrollDecoratorAdapter { override fun isInAbsoluteEnd(): Boolean { return !tl_gospel.canScrollDown() } override fun isInAbsoluteStart(): Boolean { return !tl_gospel.canScrollUp() } override fun getView(): View { return tl_gospel } }) tl_gospel.visibility = View.VISIBLE tl_home.visibility = View.GONE tl_disciple.visibility = View.GONE tl_me.visibility = View.GONE } VIEW_DISCIPLE -> { HorizontalOverScrollBounceEffectDecorator(object : IOverScrollDecoratorAdapter { override fun isInAbsoluteEnd(): Boolean { return !tl_disciple.canScrollDown() } override fun isInAbsoluteStart(): Boolean { return !tl_disciple.canScrollUp() } override fun getView(): View { return tl_disciple } }) tl_disciple.visibility = View.VISIBLE tl_home.visibility = View.GONE tl_gospel.visibility = View.GONE tl_me.visibility = View.GONE } VIEW_ME -> { HorizontalOverScrollBounceEffectDecorator(object : IOverScrollDecoratorAdapter { override fun isInAbsoluteEnd(): Boolean { return !tl_me.canScrollDown() } override fun isInAbsoluteStart(): Boolean { return !tl_me.canScrollUp() } override fun getView(): View { return tl_me } }) tl_me.visibility = View.VISIBLE tl_home.visibility = View.GONE tl_gospel.visibility = View.GONE tl_disciple.visibility = View.GONE initPortrait() } } } private fun pageSelected(position: Int) { // pageSelected这是一个重要方法,initTl这里进行TabLayout的UI初始化工作 initTl(position) when (position) { 0 -> { tb_nav.title = getString(R.string.title_home) if (::menuSearch.isInitialized) menuSearch.isVisible = true if (::menuSetting.isInitialized) menuSetting.isVisible = false if (::menuSort.isInitialized) menuSort.isVisible = true // 为了在Home到Disciple的时候FAB有一个显示到消失再到显示的过程 if (::navFragmentPagerAdapter.isInitialized && navFragmentPagerAdapter.isCurrentFragmentIn() && navFragmentPagerAdapter.currentFragment is HomeFragment) { val homeFragment = navFragmentPagerAdapter.currentFragment as HomeFragment homeFragment.navChildFragmentPagerAdapter.currentFragment.v.home_child_rv.setHide(false) } // showFab() // fragment_home_fab.show() // fragment_disciple_fab.hide() fragment_home_fab.setImageDrawable( ResourcesCompat.getDrawable( resources, R.drawable.ic_edit_black_24dp, theme ) ) // fab_nav.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources, R.color.colorAccent,theme)) // if (verticalOffset != -tb_nav.height && !fab_nav.isVisible) // fab_nav.show() TooltipCompat.setTooltipText(fragment_home_fab, getString(R.string.action_edit)) } 1 -> { tb_nav.title = getString(R.string.title_gospel) if (::menuSearch.isInitialized) menuSearch.isVisible = true if (::menuSetting.isInitialized) menuSetting.isVisible = false if (::menuSort.isInitialized) menuSort.isVisible = true // fragment_home_fab.hide() // fragment_disciple_fab.hide() // hideFab() // activity_nav_fab.setImageDrawable( // ResourcesCompat.getDrawable( // resources, // R.drawable.ic_baseline_wifi_protected_setup_24, // theme // ) // null // ) // fab_nav.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources, R.color.colorAccent,theme)) /*if (verticalOffset > -tb_nav.height) fab_nav.hide()*/ // TooltipCompat.setTooltipText(activity_nav_fab, "Filter") /*activity_nav_fab.setOnClickListener { startActivity( Intent( this@NavActivity, ren.qinc.markdowneditors.view.MainActivity::class.java ) ) }*/ } 2 -> { tb_nav.title = getString(R.string.title_disciple) if (::menuSearch.isInitialized) menuSearch.isVisible = true if (::menuSetting.isInitialized) menuSetting.isVisible = false if (::menuSort.isInitialized) menuSort.isVisible = true if (::navFragmentPagerAdapter.isInitialized && navFragmentPagerAdapter.isCurrentFragmentIn() && navFragmentPagerAdapter.currentFragment is DiscipleFragment) { val discipleFragment = navFragmentPagerAdapter.currentFragment as DiscipleFragment discipleFragment.navChildFragmentPagerAdapter.currentFragment.v.disciple_child_rv.setHide(false) } // 为了在Home到Disciple的时候FAB有一个显示到消失再到显示的过程 // showFab() // fragment_disciple_fab.show() // fragment_home_fab.hide() // hideFab() fragment_disciple_fab.setImageDrawable( ResourcesCompat.getDrawable( resources, R.drawable.ic_baseline_person_add_24, theme ) ) // fab_nav.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources, R.color.colorAccent,theme)) TooltipCompat.setTooltipText(fragment_disciple_fab, getString(R.string.send)) /*activity_nav_fab.setOnClickListener { if (::navFragmentPagerAdapter.isInitialized) { val discipleFragment = navFragmentPagerAdapter.currentFragment as DiscipleFragment if (discipleFragment.binding.messageEditText.text.isEmpty()) { abl_nav.setExpanded(false, true) // snackbar(getString(R.string.content_empty)).show() discipleFragment.binding.messageEditText.requestFocusWithKeyboard() } else { discipleFragment.sendMessage() } } }*/ } 3 -> { tb_nav.title = getString(R.string.title_me) if (::menuSearch.isInitialized) menuSearch.isVisible = false if (::menuSetting.isInitialized) menuSetting.isVisible = true if (::menuSort.isInitialized) menuSort.isVisible = false invalidateSignInUI() // fragment_home_fab.hide() // fragment_disciple_fab.hide() // hideFab() // activity_nav_fab.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_baseline_help_24, theme)) // fab_nav.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources, R.color.colorAccentRed,theme)) // TooltipCompat.setTooltipText(activity_nav_fab, getString(R.string.help)) /*activity_nav_fab.setOnClickListener {}*/ } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mStaticHandler = StaticHandler(this@NavActivity) setContentView(R.layout.nav_activity) NavPresenter(view = this) presenter.init(whichActivity = NAV_ACTIVITY) // 配合ImmersionBar给Toolbar设置一个类似topView的高度的视图加在Toolbar上 immersiveToolbar(this, tb_nav) } override fun initView() { initAbl() initTb() initPortrait() initVp() initFab() initBv() initBnv() // 自动夜间模式 // sunriseSunset() ParallaxHelper.disableParallaxBack(this) HorizontalOverScrollBounceEffectDecorator(object : IOverScrollDecoratorAdapter { override fun isInAbsoluteEnd(): Boolean { return !tl_home.canScrollDown() } override fun isInAbsoluteStart(): Boolean { return !tl_home.canScrollUp() } override fun getView(): View { return tl_home } }) } /*private fun sunriseSunset() { getLatitudeLongitudePermissions() }*/ /*private fun getLatitudeLongitudePermissions() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { KotlinPermissions.with(this) // where this is an FragmentActivity instance .permissions(INTERNET, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION) .onAccepted { permissions -> //List of accepted permissions if (permissions.contains(ACCESS_FINE_LOCATION)) bindNavService() } .onDenied { permissions -> //List of denied permissions } .onForeverDenied { permissions -> //List of forever denied permissions } .ask() } else { bindNavService() } }*/ private fun initAbl() { // makeViewBlurExtendsAppBarLayout(abl_nav, cl_nav, window) makeViewBlurExtendsFrameLayout(fl_wrapper, cl_nav, window) tb_nav.setOnClickListener { scrollRvToTop(this@NavActivity) } /*tb_nav.setOnClickListener(object : DoubleClickListener() { override fun onDoubleClick(v: View) { scrollRvToTop(this@NavActivity) } })*/ } open fun initTb() { setSupportActionBar(tb_nav) } private fun initPortrait() { // applyMarqueeEffect(intro) sign_in.setOnClickListener { signIn() } sign_out.setOnClickListener { } portrait_container.setPadding(0, getStatusBarHeight(this@NavActivity), 0, 0) } open fun initVp() { navFragmentPagerAdapter = NavFragmentPagerAdapter(supportFragmentManager) vp_nav.offscreenPageLimit = 3 vp_nav.adapter = navFragmentPagerAdapter vp_nav.addOnPageChangeListener(viewPagerOnPageChangeListener) } open fun initFab() { // fab_nav.visibility = View.GONE // fab_nav.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_edit_black_24dp, theme)) // fab_nav.setOnClickListener { // ViewModelProviders.of(this).get(NavViewModel::class.java).loadImage() // } fragment_home_fab.setOnClickListener { startActivity(Intent(this@NavActivity, EditorActivity::class.java)) } } open fun initBv() { makeViewBlur(bv_nav, cl_nav, window) val params = CoordinatorLayout.LayoutParams(bv_nav.layoutParams) params.gravity = Gravity.BOTTOM params.behavior = BottomNavigationViewBehavior(this, null) bv_nav.layoutParams = params } /*open fun showFAB() { fab_nav.show() }*/ /*解决暗黑模式重启无首页标题*/ override fun onResume() { super.onResume() if (pageSelectedPosition == 0) tb_nav.title = getString(R.string.title_home) abl_nav.post { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { abl_nav.elevation = dip(4).toFloat() } } } open fun initBnv() { // disableShiftMode(bnv_nav) /** 切换夜间模式重启的时候,需要通过设置currentItem来设置标题等一系列参数(但是无效,只能采用下一行的方式) */ // vp_nav.currentItem = 0 bnv_nav.setOnItemSelectedListener { val itemPosition = (presenter as NavPresenter).generateNavId(it.itemId) vp_nav.currentItem = itemPosition true } bnv_nav.setOnItemReselectedListener { scrollRvToTop(this@NavActivity) } } /** * Immersive reading, swipe hidden. */ class BottomNavigationViewBehavior(context: Context?, attrs: AttributeSet?) : androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior<View>(context, attrs) { override fun onLayoutChild( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, layoutDirection: Int ): Boolean { (child.layoutParams as CoordinatorLayout.LayoutParams).topMargin = parent.measuredHeight.minus(child.measuredHeight) return super.onLayoutChild(parent, child, layoutDirection) } override fun layoutDependsOn( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View ): Boolean { return dependency is AppBarLayout } override fun onDependentViewChanged( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View ): Boolean { val top = ((dependency.layoutParams as CoordinatorLayout.LayoutParams).behavior as AppBarLayout.Behavior).topAndBottomOffset Log.i("dd", top.toString()) //因为BottomNavigation的滑动与ToolBar是反向的,所以取-top值 child.translationY = (-top).toFloat() return false } } /** * Locate nav detail FAB */ class BottomNavigationViewBehaviorDetail(context: Context?, attrs: AttributeSet?) : androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior<View>(context, attrs) { override fun onLayoutChild( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, layoutDirection: Int ): Boolean { (child.layoutParams as CoordinatorLayout.LayoutParams).topMargin = parent.measuredHeight.minus(child.measuredHeight) return super.onLayoutChild(parent, child, layoutDirection) } override fun layoutDependsOn( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View ): Boolean { return dependency is AppBarLayout } override fun onDependentViewChanged( parent: androidx.coordinatorlayout.widget.CoordinatorLayout, child: View, dependency: View ): Boolean { child.translationY = 2000f return false } } fun invalidateSignInUI() { val user = auth.currentUser if (user != null) { sign_in.visibility = View.GONE sign_out.visibility = View.GONE // fab_nav.show() portrait.visibility = View.VISIBLE name.visibility = View.VISIBLE intro.visibility = View.VISIBLE name.text = user.displayName intro.text = user.email Glide.with(this).load(user.photoUrl).into(iv_nav_item_small) portrait_nav.isClickable = true portrait_nav.isFocusable = true portrait_nav.isFocusableInTouchMode = true } else { sign_in.visibility = View.VISIBLE sign_out.visibility = View.GONE // fab_nav.hide() portrait.visibility = View.GONE name.visibility = View.GONE intro.visibility = View.GONE portrait_nav.isClickable = false portrait_nav.isFocusable = false portrait_nav.isFocusableInTouchMode = false } // ... } open class NavFragmentPagerAdapter( fm: FragmentManager, ) : androidx.fragment.app.FragmentPagerAdapter(fm) { lateinit var currentFragment: Fragment fun isCurrentFragmentIn() = ::currentFragment.isInitialized override fun getItem(position: Int): Fragment { when (position) { 0 -> { val homeFragment = HomeFragment() homeFragment.navId = position return homeFragment } 1 -> { val gospelFragment = GospelFragment() gospelFragment.navId = position return gospelFragment } 2 -> { return DiscipleFragment() } 3 -> { return MeFragment() } } val navFragment = GospelFragment() navFragment.navId = position return navFragment } override fun getCount(): Int { return 4 } override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) { when (position) { 0 -> { currentFragment = `object` as HomeFragment } 1 -> { currentFragment = `object` as GospelFragment } 2 -> { currentFragment = `object` as DiscipleFragment } 3 -> { currentFragment = `object` as MeFragment } } super.setPrimaryItem(container, position, `object`) } } /*val appBarLayoutOnOffsetChangedListener = AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset -> appBarLayoutOnOffsetChangedListener(this@NavActivity, appBarLayout, verticalOffset) [email protected] = verticalOffset }*/ fun snackbar(@StringRes id: Int) { val snackbar = Snackbar.make(cl_nav_2, resources.getString(id), Snackbar.LENGTH_SHORT) val snackbarView = snackbar.view if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { snackbarView.elevation = dp2px(3).toFloat() } // Snackbar // val params = snackbarView.layoutParams as CoordinatorLayout.LayoutParams // params.anchorId = R.id.bnv_nav // params.width = CoordinatorLayout.LayoutParams.MATCH_PARENT // params.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL// 相对锚点的位置 // params.anchorGravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL // 锚点的位置 // snackbarView.layoutParams = params return snackbar.show() } open fun scrollRvToTop(navActivity: NavActivity) { try { if (::navFragmentPagerAdapter.isInitialized) when (vp_nav.currentItem) { 0 -> { navActivity.navFragmentPagerAdapter.currentFragment.home_child_rv.smoothScrollToPosition( 0 ) // 为了滚到顶 (navActivity.navFragmentPagerAdapter.currentFragment as HomeFragment).scrollChildRVToTop() } 1 -> { navActivity.navFragmentPagerAdapter.currentFragment.fragment_nav_rv.smoothScrollToPosition( 0 ) // 为了滚到顶 (navActivity.navFragmentPagerAdapter.currentFragment as GospelFragment).scrollChildRVToTop() } 2 -> { navActivity.navFragmentPagerAdapter.currentFragment.disciple_child_rv.smoothScrollToPosition( 0 ) // 为了滚到顶 (navActivity.navFragmentPagerAdapter.currentFragment as DiscipleFragment).scrollChildRVToTop() } 3 -> { navActivity.navFragmentPagerAdapter.currentFragment.fragment_nav_rv.smoothScrollToPosition( 0 ) // 为了滚到顶 (navActivity.navFragmentPagerAdapter.currentFragment as MeFragment).scrollChildRVToTop() } } { } navActivity.abl_nav.setExpanded(true, true) } catch (e: Exception) { } } abstract class DoubleClickListener : View.OnClickListener { companion object { const val DOUBLE_TIME = 1000 var lastClickTime = 0L } override fun onClick(v: View) { val currentTimeMillis = System.currentTimeMillis() if (currentTimeMillis - lastClickTime < DOUBLE_TIME) { onDoubleClick(v) } lastClickTime = currentTimeMillis } abstract fun onDoubleClick(v: View) } override fun onDestroy() { super.onDestroy() // unbindNavService() } // private lateinit var navService: NavService // private var isBind: Boolean = false /** * 用于获取NavService */ /*val navServiceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { val navBinder = service as NavService.NavBinder navService = navBinder.navService isBind = true } override fun onServiceDisconnected(name: ComponentName) { isBind = false } }*/ /* fun bindNavService() { val intent = Intent(this, NavService::class.java) bindService(intent, navServiceConnection, Context.BIND_AUTO_CREATE) } fun unbindNavService() { if (isBind) { unbindService(navServiceConnection); isBind = false; } }*/ override fun onBackPressed() { //没有东西可以返回了,剩下软件退出逻辑 //没有东西可以返回了,剩下软件退出逻辑 if (abs(customTime - System.currentTimeMillis()) < 2000) { finish() } else { // 提示用户退出 customTime = System.currentTimeMillis() snackbar(R.string.double_click_exit) } } // presenter solve login in and login out logic override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { val response = IdpResponse.fromResultIntent(data) invalidateSignInUI() /*if (resultCode == Activity.RESULT_OK) { // Successfully signed in invalidateSignInUI() } else { // Sign in failed. If response is null the user canceled the // sign-in flow using the back button. Otherwise check // response.getError().getErrorCode() and handle the error. // ... val snackbar = snackbar(getString(R.string.sign_in_failed)) snackbar.show() }*/ } } } class MoveUpwardBehavior @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : CoordinatorLayout.Behavior<View>() { override fun layoutDependsOn( parent: CoordinatorLayout, child: View, dependency: View ): Boolean { return dependency is Snackbar.SnackbarLayout } override fun onDependentViewChanged( parent: CoordinatorLayout, child: View, dependency: View ): Boolean { val translationY = min(0f, dependency.translationY - dependency.height.toFloat()) if (dependency.translationY != 0f) child.translationY = translationY return true } override fun onDependentViewRemoved( parent: CoordinatorLayout, child: View, dependency: View ) { child.translationY = 0f } }
gpl-3.0
577f067d197659a45f494e735c7cd2c6
37.142281
174
0.556417
5.202175
false
false
false
false
alibaba/multi-thread-context
src/test/java/com/alibaba/ttl/TtlWrappersTest.kt
1
9282
package com.alibaba.ttl import com.alibaba.expandThreadPool import com.alibaba.support.junit.conditional.BelowJava8 import com.alibaba.support.junit.conditional.ConditionalIgnoreRule import com.alibaba.ttl.TtlUnwrap.unwrap import com.alibaba.ttl.TtlWrappers.* import org.junit.AfterClass import org.junit.Assert.* import org.junit.Rule import org.junit.Test import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.function.* import java.util.function.Function class TtlWrappersTest { @Rule @JvmField val rule = ConditionalIgnoreRule() @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BelowJava8::class) fun test_null() { val supplier: Supplier<String>? = null assertNull(wrap(supplier)) assertNull(wrapSupplier(supplier)) assertNull(unwrap(supplier)) val consumer: Consumer<String>? = null assertNull(wrap(consumer)) assertNull(wrapConsumer(consumer)) assertNull(unwrap(consumer)) val biConsumer: BiConsumer<String, String>? = null assertNull(wrap(biConsumer)) assertNull(wrapBiConsumer(biConsumer)) assertNull(unwrap(biConsumer)) val function: Function<String, String>? = null assertNull(wrap(function)) assertNull(wrapFunction(function)) assertNull(unwrap(function)) val biFunction: BiFunction<String, String, String>? = null assertNull(wrap(biFunction)) assertNull(wrapBiFunction(biFunction)) assertNull(unwrap(biFunction)) } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BelowJava8::class) fun wrap_ReWrap_Unwrap_same() { // Supplier val supplier = Supplier { 42 } val ttlSupplier = wrap(supplier) assertSame(ttlSupplier, wrap(ttlSupplier)) assertSame(ttlSupplier, wrapSupplier(ttlSupplier)) assertSame(supplier, unwrap(ttlSupplier)) val ttlSupplier2 = wrapSupplier(supplier) assertSame(ttlSupplier2, wrapSupplier(ttlSupplier2)) assertSame(ttlSupplier2, wrap(ttlSupplier2)) assertSame(supplier, unwrap(ttlSupplier2)) // Consumer val consumer = Consumer<String> {} val ttlConsumer = wrap(consumer) assertSame(ttlConsumer, wrap(ttlConsumer)) assertSame(ttlConsumer, wrapConsumer(ttlConsumer)) assertSame(consumer, unwrap(ttlConsumer)) val ttlConsumer2 = wrapConsumer(consumer) assertSame(ttlConsumer2, wrapConsumer(ttlConsumer2)) assertSame(ttlConsumer2, wrap(ttlConsumer2)) assertSame(consumer, unwrap(ttlConsumer2)) // BiConsumer val biConsumer = BiConsumer<String, String> { _, _ -> } val ttlBiConsumer = wrap(biConsumer) assertSame(ttlBiConsumer, wrap(ttlBiConsumer)) assertSame(ttlBiConsumer, wrapBiConsumer(ttlBiConsumer)) assertSame(biConsumer, unwrap(ttlBiConsumer)) val ttlBiConsumer2 = wrapBiConsumer(biConsumer) assertSame(ttlBiConsumer2, wrapBiConsumer(ttlBiConsumer2)) assertSame(ttlBiConsumer2, wrap(ttlBiConsumer2)) assertSame(biConsumer, unwrap(ttlBiConsumer2)) // Function val function = Function<String, String> { "" } val ttlFunction = wrap(function) assertSame(ttlFunction, wrap(ttlFunction)) assertSame(ttlFunction, wrapFunction(ttlFunction)) assertSame(function, unwrap(ttlFunction)) val ttlFunction2 = wrapFunction(function) assertSame(ttlFunction2, wrapFunction(ttlFunction2)) assertSame(ttlFunction2, wrap(ttlFunction2)) assertSame(function, unwrap(ttlFunction2)) // BiFunction val biFunction = BiFunction<String, String, String> { _, _ -> "" } val ttlBiFunction = wrap(biFunction) assertSame(ttlBiFunction, wrap(ttlBiFunction)) assertSame(ttlBiFunction, wrapBiFunction(ttlBiFunction)) assertSame(biFunction, unwrap(ttlBiFunction)) val ttlBiFunction2 = wrapBiFunction(biFunction) assertSame(ttlBiFunction2, wrapBiFunction(ttlBiFunction2)) assertSame(ttlBiFunction2, wrap(ttlBiFunction2)) assertSame(biFunction, unwrap(ttlBiFunction2)) } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BelowJava8::class) fun test_Supplier() { val ttl = TransmittableThreadLocal<String>() fun Supplier<String>.ttlWrapThenAsRunnable(): Runnable { val wrap = wrap(this)!! return Runnable { wrap.get() } } ttl.set("1") Supplier<String> { assertEquals("1", ttl.get()) "world" }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } ttl.set("2") Supplier<String> { assertEquals("2", ttl.get()) "world" }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BelowJava8::class) fun test_Consumer() { fun Consumer<String>.ttlWrapThenAsRunnable(): Runnable { val wrap = wrap(this)!! return Runnable { wrap.accept("hello ${System.nanoTime()}") } } val ttl = TransmittableThreadLocal<String>() ttl.set("1") Consumer<String> { assertEquals("1", ttl.get()) }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } ttl.set("2") Consumer<String> { assertEquals("2", ttl.get()) }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BelowJava8::class) fun test_BiConsumer() { fun BiConsumer<String, String>.ttlWrapThenAsRunnable(): Runnable { val wrap = wrap(this)!! return Runnable { wrap.accept("hello ${System.nanoTime()}", "world ${System.nanoTime()}") } } val ttl = TransmittableThreadLocal<String>() ttl.set("1") BiConsumer<String, String> { _, _ -> assertEquals("1", ttl.get()) }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } ttl.set("2") BiConsumer<String, String> { _, _ -> assertEquals("2", ttl.get()) }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BelowJava8::class) fun test_Function() { fun Function<String, String>.ttlWrapThenAsRunnable(): Runnable { val wrap = wrap(this)!! return Runnable { wrap.apply("hello ${System.nanoTime()}") } } val ttl = TransmittableThreadLocal<String>() ttl.set("1") Function<String, String> { assertEquals("1", ttl.get()) "world" }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } ttl.set("2") Function<String, String> { assertEquals("2", ttl.get()) "world" }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } } @Test @ConditionalIgnoreRule.ConditionalIgnore(condition = BelowJava8::class) fun test_BiFunction() { fun BiFunction<String, String, String>.ttlWrapThenAsRunnable(): Runnable { val wrap = wrap(this)!! return Runnable { wrap.apply("hello ${System.nanoTime()}", "world") } } val ttl = TransmittableThreadLocal<String>() ttl.set("1") BiFunction<String, String, String> { _, _ -> assertEquals("1", ttl.get()) "world" }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } ttl.set("2") BiFunction<String, String, String> { _, _ -> assertEquals("2", ttl.get()) "world" }.ttlWrapThenAsRunnable().let { ttl.set("main") executorService.submit(it).get() assertEquals("main", ttl.get()) } } companion object { private val executorService = Executors.newFixedThreadPool(3).also { expandThreadPool(it) } @AfterClass @JvmStatic @Suppress("unused") fun afterClass() { executorService.shutdown() assertTrue("Fail to shutdown thread pool", executorService.awaitTermination(100, TimeUnit.MILLISECONDS)) } } }
apache-2.0
a8958ca9f976e711ac73299bcd8a45cd
30.787671
116
0.610213
4.536657
false
true
false
false
ReactiveCircus/FlowBinding
flowbinding-android/src/main/java/reactivecircus/flowbinding/android/view/ViewTouchFlow.kt
1
1894
package reactivecircus.flowbinding.android.view import android.view.MotionEvent import android.view.View import androidx.annotation.CheckResult import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import reactivecircus.flowbinding.common.checkMainThread /** * Create a [Flow] of touch events on the [View] instance. * * @param handled function to be invoked with each value to determine the return value of * the underlying [View.OnTouchListener]. Note that the [Flow] will only emit when this function * evaluates to true. * * Note: Values emitted by this flow are **mutable** and part of a shared * object pool and thus are **not safe** to cache or delay reading (such as by observing * on a different thread). If you want to cache or delay reading the items emitted then you must * map values through a function which calls [MotionEvent.obtain] or * [MotionEvent.obtainNoHistory] to create a copy. * * Note: Created flow keeps a strong reference to the [View] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * view.touch { event.action == MotionEvent.ACTION_DOWN } * .onEach { event -> * // handle touch event * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun View.touches(handled: (MotionEvent) -> Boolean = { true }): Flow<MotionEvent> = callbackFlow { checkMainThread() val listener = View.OnTouchListener { _, event -> performClick() if (handled(event)) { trySend(event) true } else { false } } setOnTouchListener(listener) awaitClose { setOnTouchListener(null) } }.conflate()
apache-2.0
162b058c7b0981218ad343de433e2f25
34.074074
105
0.715417
4.425234
false
false
false
false
JavaEden/OrchidCore
OrchidCore/src/main/kotlin/com/eden/orchid/impl/commands/HelpCommand.kt
1
2256
package com.eden.orchid.impl.commands import com.caseyjbrooks.clog.Clog import com.copperleaf.krow.formatters.html.HtmlTableFormatter import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.OptionsExtractor import com.eden.orchid.api.options.OptionsHolder import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.server.OrchidServer import com.eden.orchid.api.tasks.OrchidCommand import com.eden.orchid.utilities.OrchidUtils import com.google.inject.Provider import javax.inject.Inject @Description("This will show a table will all the available options for a type, along with other relevant data.") class HelpCommand @Inject constructor( private val contextProvider: Provider<OrchidContext>, private val server: OrchidServer? ) : OrchidCommand(100, "help") { enum class HelpType { CLASS, CONFIG, PAGE } @Option @Description("CLASS: The fully-qualified name of a class to describe." + "CONFIG: An object query for a given property in the site config." + "PAGE: A page type." ) lateinit var type: HelpType @Option lateinit var query: String override fun parameters(): Array<String> { return arrayOf("type", "query") } override fun run(commandName: String) { val parsedClass = getDescribedClass() if (OptionsHolder::class.java.isAssignableFrom(parsedClass)) { val extractor = contextProvider.get().injector.getInstance(OptionsExtractor::class.java) val description = extractor.describeAllOptions(parsedClass) val table = extractor.getDescriptionTable(description) val asciiTable = table.print(OrchidUtils.compactTableFormatter) Clog.i("\n{}", asciiTable) if (server != null && server.websocket != null) { var htmlTable = table.print(HtmlTableFormatter()) htmlTable = htmlTable.replace("<table>".toRegex(), "<table class=\"table\">") server.websocket.sendMessage("describe", htmlTable) } } } private fun getDescribedClass(): Class<*> { return Class.forName(query) } }
mit
effaf1a80215682c81da944dc7b7e243
33.707692
113
0.692376
4.414873
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/enums/Theme.kt
1
2781
/* * Copyright 2018 Allan Wang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pitchedapps.frost.enums import android.graphics.Color import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting import com.pitchedapps.frost.R import com.pitchedapps.frost.prefs.sections.ThemePrefs import java.util.Locale /** Created by Allan Wang on 2017-06-14. */ const val FACEBOOK_BLUE = 0xff3b5998.toInt() const val BLUE_LIGHT = 0xff5d86dd.toInt() enum class Theme( @StringRes val textRes: Int, file: String?, val textColorGetter: (ThemePrefs) -> Int, val accentColorGetter: (ThemePrefs) -> Int, val backgroundColorGetter: (ThemePrefs) -> Int, val headerColorGetter: (ThemePrefs) -> Int, val iconColorGetter: (ThemePrefs) -> Int ) { DEFAULT( R.string.kau_default, "default", { 0xde000000.toInt() }, { FACEBOOK_BLUE }, { 0xfffafafa.toInt() }, { FACEBOOK_BLUE }, { Color.WHITE } ), LIGHT( R.string.kau_light, "material_light", { 0xde000000.toInt() }, { FACEBOOK_BLUE }, { 0xfffafafa.toInt() }, { FACEBOOK_BLUE }, { Color.WHITE } ), DARK( R.string.kau_dark, "material_dark", { Color.WHITE }, { BLUE_LIGHT }, { 0xff303030.toInt() }, { 0xff2e4b86.toInt() }, { Color.WHITE } ), AMOLED( R.string.kau_amoled, "material_amoled", { Color.WHITE }, { BLUE_LIGHT }, { Color.BLACK }, { Color.BLACK }, { Color.WHITE } ), GLASS( R.string.kau_glass, "material_glass", { Color.WHITE }, { BLUE_LIGHT }, { 0x80000000.toInt() }, { 0xb3000000.toInt() }, { Color.WHITE } ), CUSTOM( R.string.kau_custom, "custom", { it.customTextColor }, { it.customAccentColor }, { it.customBackgroundColor }, { it.customHeaderColor }, { it.customIconColor } ); @VisibleForTesting internal val file = file?.let { "$it.css" } companion object { val values = values() // save one instance operator fun invoke(index: Int) = values[index] } } enum class ThemeCategory { FACEBOOK, MESSENGER; @VisibleForTesting internal val folder = name.toLowerCase(Locale.CANADA) }
gpl-3.0
6c3484bb4adcc0465b67ba335c95aac2
24.990654
74
0.66343
3.569961
false
false
false
false
google/ksp
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/AnnotationArrayValueProcessor.kt
1
2063
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.processor import com.google.devtools.ksp.getClassDeclarationByName import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration class AnnotationArrayValueProcessor : AbstractTestProcessor() { val result = mutableListOf<String>() override fun toResult(): List<String> { return result } override fun process(resolver: Resolver): List<KSAnnotated> { val ktClass = resolver.getClassDeclarationByName("KotlinAnnotated")!! logAnnotations(ktClass) val javaClass = resolver.getClassDeclarationByName("JavaAnnotated")!! logAnnotations(javaClass) return emptyList() } private fun logAnnotations(classDeclaration: KSClassDeclaration) { result.add(classDeclaration.qualifiedName!!.asString()) classDeclaration.annotations.forEach { annotation -> result.add("${annotation.shortName.asString()} ->") annotation.arguments.forEach { val value = it.value val key = it.name?.asString() if (value is Array<*>) { result.add("$key = [${value.joinToString(", ")}]") } else { result.add("$key = ${it.value}") } } } } }
apache-2.0
7f9440da78d342cec6d080a7f646f75b
36.509091
85
0.673776
4.797674
false
false
false
false
Doctoror/FuckOffMusicPlayer
presentation/src/test/java/com/doctoror/fuckoffmusicplayer/presentation/library/LibraryPermissionsPresenterTest.kt
2
4979
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.fuckoffmusicplayer.presentation.library import com.doctoror.commons.reactivex.SchedulersProvider import com.doctoror.commons.reactivex.TestSchedulersProvider import com.doctoror.fuckoffmusicplayer.RuntimePermissions import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import io.reactivex.Observable import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test class LibraryPermissionsPresenterTest { private val libraryPermissionProvider: LibraryPermissionsProvider = mock() private val runtimePermissions: RuntimePermissions = mock() private val underTest = Impl( libraryPermissionProvider, runtimePermissions, TestSchedulersProvider()) private fun givenPermissionDenied() { whenever(libraryPermissionProvider.permissionsGranted()) .thenReturn(false) whenever(libraryPermissionProvider.requestPermission()) .thenReturn(Observable.just(false)) } private fun givenPermissionGranted() { whenever(libraryPermissionProvider.permissionsGranted()) .thenReturn(true) } private fun givenPermissionDeniedButGrantedOnRequest() { whenever(libraryPermissionProvider.permissionsGranted()) .thenReturn(false) whenever(libraryPermissionProvider.requestPermission()) .thenReturn(Observable.just(true)) } @Test fun permissionsRequestedAssignedFromRuntimePermissions() { whenever(runtimePermissions.permissionsRequested).thenReturn(true) val underTest = Impl( libraryPermissionProvider, runtimePermissions, TestSchedulersProvider()) assertTrue(underTest.permissionRequested) } @Test fun requestsPermissionOnStart() { // Given givenPermissionDenied() // When underTest.onStart() // Then verify(libraryPermissionProvider).requestPermission() } @Test fun deliversPermissionDenied() { // Given givenPermissionDenied() // When underTest.onStart() // Then assertEquals(1, underTest.permissionDeniedInvocationCount) assertEquals(0, underTest.permissionGrantedInvocationCount) } @Test fun deliversPermissionDeniedEveryTime() { // Given givenPermissionDenied() // When underTest.onStart() underTest.onStart() // Then assertEquals(2, underTest.permissionDeniedInvocationCount) } @Test fun deliversPermissionGranted() { // Given givenPermissionGranted() // When underTest.onStart() // Then assertEquals(0, underTest.permissionDeniedInvocationCount) assertEquals(1, underTest.permissionGrantedInvocationCount) } @Test fun deliversPermissionGrantedOnRequest() { // Given givenPermissionDeniedButGrantedOnRequest() // When underTest.onStart() // Then assertEquals(0, underTest.permissionDeniedInvocationCount) assertEquals(1, underTest.permissionGrantedInvocationCount) } @Test fun requestsPermissionOnlyOnce() { // Given givenPermissionDenied() // When underTest.onStart() underTest.onStart() // Then verify(libraryPermissionProvider, times(1)).requestPermission() assertEquals(2, underTest.permissionDeniedInvocationCount) assertEquals(0, underTest.permissionGrantedInvocationCount) } internal class Impl( libraryPermissionProvider: LibraryPermissionsProvider, runtimePermissions: RuntimePermissions, schedulersProvider: SchedulersProvider) : LibraryPermissionsPresenter( libraryPermissionProvider, runtimePermissions, schedulersProvider) { var permissionDeniedInvocationCount = 0 var permissionGrantedInvocationCount = 0 override fun onPermissionDenied() { permissionDeniedInvocationCount++ } override fun onPermissionGranted() { permissionGrantedInvocationCount++ } } }
apache-2.0
5c97095146c3ce12756e2251c52ef3d3
28.288235
80
0.687086
5.736175
false
true
false
false
toastkidjp/Yobidashi_kt
rss/src/main/java/jp/toastkid/rss/model/Parser.kt
2
6692
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.rss.model import java.util.regex.Pattern /** * @author toastkidjp */ class Parser { /** current extracting item. */ private var rss: Rss = Rss() /** current extracting item. */ private var currentItem: Item? = null /** is processing content. */ private var isInContent: Boolean = false /** * Parse RSS. * @param rss String. * @return Rss items. */ fun parse(rssLines: Iterable<String>): Rss { rssLines.forEach(::extractFromLine) return this.rss } private fun extractFromLine(line: String) { when { line.contains("<item") or line.contains("<entry") -> { initializeItem() } line.contains("<title") -> { extractTitle(line) } line.contains("<link") -> { if (line.contains("href=")) { extract(line, LINK_HREF_PATTERN)?.let { currentItem?.link = it } } else { extractLink(line) } } line.contains("<description") -> { extractDescription(line) } line.contains("</summary") -> { isInContent = false } line.contains("<summary") -> { isInContent = true } isInContent -> { currentItem?.content?.append(line) } line.contains("<pubDate") -> { extractPubDate(line) } line.contains("<published") -> { extractPublished(line) } line.contains("<issued") -> { extractIssued(line) } line.contains("<dc:creator>") -> { extractCreator(line) } line.contains("<dc:date>") -> { extractDate(line) } line.contains("<dc:subject>") -> { extractSubject(line) } line.contains("</item>") or line.contains("</entry>") -> { currentItem?.let { rss.items.add(it) } } } } /** * Extract pubData. * @param line */ private fun extractPubDate(line: String) { val extract = extract(line, PUBLISH_DATE_PATTERN) if (extract?.isNotBlank() == true) { currentItem?.date = extract } } private fun extractPublished(line: String) { val extract = extract(line, PUBLISHED_PATTERN) if (extract?.isNotBlank() == true) { currentItem?.date = extract } } private fun extractIssued(line: String) { val extract = extract(line, ISSUED_PATTERN) if (extract?.isNotBlank() == true) { currentItem?.date = extract } } /** * Extract date. * @param line */ private fun extractDate(line: String) { val extract = extract(line, DATE_PATTERN) if (extract?.isNotBlank() == true) { currentItem?.date = extract } } /** * Extract creator. * @param line */ private fun extractCreator(line: String) { rss.creator = extract(line, CREATOR_PATTERN) } /** * Extract subject. * @param line */ private fun extractSubject(line: String) { extract(line, SUBJECT_PATTERN)?.let { rss.subjects.add(it) } } /** * extract title from html. * @param line */ private fun extractTitle(line: String) { val title = extract(line, TITLE_PATTERN) if (rss.title == null) { rss.title = title return } title?.let { currentItem?.title = it } } /** * Extract description. * @param line */ private fun extractDescription(line: String) { val description = extract(line, DESCRIPTION_PATTERN) if (currentItem == null) { rss.description = description return } description?.let { currentItem?.description = it } } /** * Extract link. * @param line */ private fun extractLink(line: String) { val link = extract(line, LINK_PATTERN) if (currentItem == null) { rss.link = link return } link?.let { currentItem?.link = it } } /** * extract string with passed pattern. * * @param line string line. * @param pattern pattern. * @return string */ private fun extract(line: String?, pattern: Pattern?): String? { if (line.isNullOrBlank() || pattern == null) { return line } val matcher = pattern.matcher(line) return if (matcher.find()) matcher.group(1) else line } /** * init Item. */ private fun initializeItem() { currentItem = Item() currentItem?.source = rss.title ?: "" } companion object { private val TITLE_PATTERN = Pattern.compile("<title.*>(.+?)</title>", Pattern.DOTALL) /** pattern of description. */ private val DESCRIPTION_PATTERN = Pattern.compile("<description>(.+?)</description>", Pattern.DOTALL) /** pattern of link. */ private val LINK_PATTERN = Pattern.compile("<link>(.+?)</link>", Pattern.DOTALL) /** pattern of link. */ private val LINK_HREF_PATTERN = Pattern.compile("href=\"(.+?)\"", Pattern.DOTALL) /** pattern of creator. */ private val CREATOR_PATTERN = Pattern.compile("<dc:creator>(.+?)</dc:creator>", Pattern.DOTALL) /** pattern of date. */ private val DATE_PATTERN = Pattern.compile("<dc:date>(.+?)</dc:date>", Pattern.DOTALL) /** pattern of subject. */ private val SUBJECT_PATTERN = Pattern.compile("<dc:subject>(.+?)</dc:subject>", Pattern.DOTALL) /** pattern of pubDate. */ private val PUBLISH_DATE_PATTERN = Pattern.compile("<pubDate>(.+?)</pubDate>", Pattern.DOTALL) /** pattern of published (for atom). */ private val PUBLISHED_PATTERN = Pattern.compile("<published>(.+?)</published>", Pattern.DOTALL) /** pattern of published (for atom). */ private val ISSUED_PATTERN = Pattern.compile("<issued>(.+?)</issued>", Pattern.DOTALL) } }
epl-1.0
4906e9d589ba6740f58a63316e8c879f
27.004184
109
0.527047
4.530806
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/settings/TestNotificationsView.kt
1
1613
package com.garpr.android.features.settings import android.content.Context import android.content.DialogInterface import android.util.AttributeSet import android.view.View import androidx.appcompat.app.AlertDialog import com.garpr.android.BuildConfig import com.garpr.android.R import com.garpr.android.features.common.views.SimplePreferenceView import com.garpr.android.managers.NotificationsManager import org.koin.core.KoinComponent import org.koin.core.inject class TestNotificationsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : SimplePreferenceView(context, attrs), DialogInterface.OnClickListener, KoinComponent, View.OnClickListener { protected val notificationsManager: NotificationsManager by inject() init { titleText = context.getText(R.string.show_test_notification) descriptionText = context.getText(R.string.debug_only) visibility = if (BuildConfig.DEBUG) VISIBLE else GONE setOnClickListener(this) } override fun onClick(dialog: DialogInterface, which: Int) { dialog.dismiss() when (which) { 0 -> notificationsManager.cancelRankingsUpdated() 1 -> notificationsManager.showRankingsUpdated() else -> throw RuntimeException("illegal which: $which") } } override fun onClick(v: View) { val items = arrayOf(resources.getText(R.string.cancel_rankings), resources.getText(R.string.show)) AlertDialog.Builder(context) .setItems(items, this) .show() } }
unlicense
9fd506cde3fa4f8912852300950623a5
31.918367
89
0.710477
4.702624
false
false
false
false
http4k/http4k
http4k-server/apache4/src/main/kotlin/org/http4k/server/Apache4Server.kt
1
4148
package org.http4k.server import org.apache.http.Header import org.apache.http.HttpEntityEnclosingRequest import org.apache.http.HttpInetConnection import org.apache.http.config.SocketConfig import org.apache.http.entity.InputStreamEntity import org.apache.http.impl.bootstrap.HttpServer import org.apache.http.impl.bootstrap.ServerBootstrap import org.apache.http.impl.io.EmptyInputStream import org.apache.http.protocol.HttpContext import org.apache.http.protocol.HttpCoreContext import org.apache.http.protocol.HttpRequestHandler import org.http4k.core.Headers import org.http4k.core.HttpHandler import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.RequestSource import org.http4k.core.Response import org.http4k.core.safeLong import org.http4k.core.then import org.http4k.filter.ServerFilters import org.http4k.server.ServerConfig.StopMode import java.net.InetAddress import java.util.concurrent.TimeUnit.MILLISECONDS import org.apache.http.HttpRequest as ApacheRequest import org.apache.http.HttpResponse as ApacheResponse /** * Exposed to allow for insertion into a customised Apache WebServer instance */ class Http4kApache4RequestHandler(handler: HttpHandler) : HttpRequestHandler { private val safeHandler = ServerFilters.CatchAll().then(handler) override fun handle(request: ApacheRequest, response: ApacheResponse, context: HttpContext) { safeHandler(request.asHttp4kRequest(context)).into(response) } private fun ApacheRequest.asHttp4kRequest(context: HttpContext): Request { val connection = context.getAttribute(HttpCoreContext.HTTP_CONNECTION) as HttpInetConnection return Request(Method.valueOf(requestLine.method), requestLine.uri) .headers(allHeaders.toHttp4kHeaders()).let { when (this) { is HttpEntityEnclosingRequest -> it.body(entity.content, getFirstHeader("Content-Length")?.value.safeLong()) else -> it.body(EmptyInputStream.INSTANCE, 0) } } .source(RequestSource(connection.remoteAddress.hostAddress, connection.remotePort)) } private val headersThatApacheInterceptorSets = setOf("Transfer-Encoding", "Content-Length") private fun Response.into(response: ApacheResponse) { with(response) { setStatusCode(status.code) setReasonPhrase(status.description) headers.filter { !headersThatApacheInterceptorSets.contains(it.first) }.forEach { (key, value) -> addHeader(key, value) } entity = InputStreamEntity(body.stream, body.length ?: -1L) } } private fun Array<Header>.toHttp4kHeaders(): Headers = map { it.name to it.value } } class Apache4Server(val port: Int = 8000, override val stopMode: StopMode, val address: InetAddress?) : ServerConfig { constructor(port: Int = 8000, address: InetAddress?) : this(port, StopMode.Immediate, address) constructor(port: Int = 8000, stopMode: StopMode) : this(port, stopMode, null) constructor(port: Int = 8000) : this(port, null) init { if(stopMode != StopMode.Immediate){ throw ServerConfig.UnsupportedStopMode(stopMode) } } override fun toServer(http: HttpHandler): Http4kServer = object : Http4kServer { private val server: HttpServer init { val bootstrap = ServerBootstrap.bootstrap() .setListenerPort(port) .setSocketConfig(SocketConfig.custom() .setTcpNoDelay(true) .setSoKeepAlive(true) .setSoReuseAddress(true) .setBacklogSize(1000) .build()) .registerHandler("*", Http4kApache4RequestHandler(http)) if (address != null) bootstrap.setLocalAddress(address) server = bootstrap.create() } override fun start() = apply { server.start() } override fun stop() = apply { server.shutdown(0, MILLISECONDS) } override fun port(): Int = if (port != 0) port else server.localPort } }
apache-2.0
7aa100ecef396175abdf8326cc3bcb96
38.504762
133
0.694793
4.289555
false
true
false
false
GlimpseFramework/glimpse-framework
api/src/main/kotlin/glimpse/gles/delegates/DisposableLazyDelegate.kt
1
673
package glimpse.gles.delegates import glimpse.gles.Disposable import glimpse.gles.Disposables import kotlin.reflect.KProperty /** * Disposable lazy property delegate. * * @param T Property type. * @property init Lazy initialization function. */ class DisposableLazyDelegate<T>(private val init: () -> T?) : Disposable { private var value: T? = null /** * Gets delegated property value. */ operator fun getValue(thisRef: Any?, property: KProperty<*>): T? { if (value == null && !Disposables.isDisposing) { value = init() registerDisposable() } return value } /** * Disposes property value. */ override fun dispose() { value = null } }
apache-2.0
ed25cb7b190b8882bebbf75ee756dd13
18.794118
74
0.684993
3.718232
false
false
false
false
Vavassor/Tusky
app/src/main/java/com/keylesspalace/tusky/components/conversation/ConversationsFragment.kt
1
6507
/* Copyright 2019 Conny Duck * * This file is a part of Tusky. * * 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. * * Tusky 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 Tusky; if not, * see <http://www.gnu.org/licenses>. */ package com.keylesspalace.tusky.components.conversation import android.content.Intent import android.os.Bundle import android.preference.PreferenceManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.paging.PagedList import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.SimpleItemAnimator import com.keylesspalace.tusky.AccountActivity import com.keylesspalace.tusky.R import com.keylesspalace.tusky.ViewTagActivity import com.keylesspalace.tusky.db.AppDatabase import com.keylesspalace.tusky.di.Injectable import com.keylesspalace.tusky.di.ViewModelFactory import com.keylesspalace.tusky.fragment.SFragment import com.keylesspalace.tusky.interfaces.StatusActionListener import com.keylesspalace.tusky.network.TimelineCases import com.keylesspalace.tusky.util.NetworkState import com.keylesspalace.tusky.util.ThemeUtils import com.keylesspalace.tusky.util.hide import kotlinx.android.synthetic.main.fragment_timeline.* import javax.inject.Inject class ConversationsFragment : SFragment(), StatusActionListener, Injectable { @Inject lateinit var timelineCases: TimelineCases @Inject lateinit var viewModelFactory: ViewModelFactory @Inject lateinit var db: AppDatabase private lateinit var viewModel: ConversationsViewModel private lateinit var adapter: ConversationAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { viewModel = ViewModelProviders.of(this, viewModelFactory)[ConversationsViewModel::class.java] return inflater.inflate(R.layout.fragment_timeline, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val preferences = PreferenceManager.getDefaultSharedPreferences(view.context) val useAbsoluteTime = preferences.getBoolean("absoluteTimeView", false) val account = accountManager.activeAccount val mediaPreviewEnabled = account?.mediaPreviewEnabled ?: true adapter = ConversationAdapter(useAbsoluteTime, mediaPreviewEnabled,this, ::onTopLoaded, viewModel::retry) recyclerView.addItemDecoration(DividerItemDecoration(view.context, DividerItemDecoration.VERTICAL)) recyclerView.layoutManager = LinearLayoutManager(view.context) recyclerView.adapter = adapter (recyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false progressBar.hide() statusView.hide() initSwipeToRefresh() viewModel.conversations.observe(this, Observer<PagedList<ConversationEntity>> { adapter.submitList(it) }) viewModel.networkState.observe(this, Observer { adapter.setNetworkState(it) }) viewModel.load() } private fun initSwipeToRefresh() { viewModel.refreshState.observe(this, Observer { swipeRefreshLayout.isRefreshing = it == NetworkState.LOADING }) swipeRefreshLayout.setOnRefreshListener { viewModel.refresh() } swipeRefreshLayout.setColorSchemeResources(R.color.tusky_blue) swipeRefreshLayout.setProgressBackgroundColorSchemeColor(ThemeUtils.getColor(swipeRefreshLayout.context, android.R.attr.colorBackground)) } private fun onTopLoaded() { recyclerView.scrollToPosition(0) } override fun onReblog(reblog: Boolean, position: Int) { // its impossible to reblog private messages } override fun onFavourite(favourite: Boolean, position: Int) { viewModel.favourite(favourite, position) } override fun onMore(view: View, position: Int) { viewModel.conversations.value?.getOrNull(position)?.lastStatus?.let { more(it.toStatus(), view, position) } } override fun onViewMedia(position: Int, attachmentIndex: Int, view: View) { viewModel.conversations.value?.getOrNull(position)?.lastStatus?.let { viewMedia(attachmentIndex, it.toStatus(), view) } } override fun onViewThread(position: Int) { viewModel.conversations.value?.getOrNull(position)?.lastStatus?.let { viewThread(it.toStatus()) } } override fun onOpenReblog(position: Int) { // there are no reblogs in search results } override fun onExpandedChange(expanded: Boolean, position: Int) { viewModel.expandHiddenStatus(expanded, position) } override fun onContentHiddenChange(isShowing: Boolean, position: Int) { viewModel.showContent(isShowing, position) } override fun onLoadMore(position: Int) { // not using the old way of pagination } override fun onContentCollapsedChange(isCollapsed: Boolean, position: Int) { viewModel.collapseLongStatus(isCollapsed, position) } override fun onViewAccount(id: String) { val intent = AccountActivity.getIntent(requireContext(), id) startActivity(intent) } override fun onViewTag(tag: String) { val intent = Intent(context, ViewTagActivity::class.java) intent.putExtra("hashtag", tag) startActivity(intent) } override fun timelineCases(): TimelineCases { return timelineCases } override fun removeItem(position: Int) { viewModel.remove(position) } override fun onReply(position: Int) { viewModel.conversations.value?.getOrNull(position)?.lastStatus?.let { reply(it.toStatus()) } } companion object { fun newInstance() = ConversationsFragment() } }
gpl-3.0
af7d58326409f961d7ee79de4d08b93f
34.172973
145
0.729983
4.990031
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/scopedstorage/MoveDirectoryContent.kt
1
4385
/* * Copyright (c) 2022 Arthur Milchior <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.servicelayer.scopedstorage import androidx.annotation.VisibleForTesting import com.ichi2.anki.model.Directory import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.MigrateUserData.MigrationContext import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.MigrateUserData.Operation import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.operationCompleted import com.ichi2.compat.CompatHelper import com.ichi2.compat.FileStream import java.io.File import java.io.IOException /** * This operation moves content of source to destination. This Operation is called one time for each file in the directory, and one last time. Unless an exception occurs. Use the [createInstance] to instantiate the object. It will convert the given Directory source to a FileStream. This conversion is a potentially long-running operation. * @param [source]: an iterator over File content, [source] will be closed in [execute] once the source is empty or if accessing its content raise an exception. * @param [destination]: a directory to copy the source content. * This is different than [MoveFile], [MoveDirectory] and [MoveFileOrDirectory] where destination is the new path of the copied element. * Because in this case, there is not a single destination path. */ class MoveDirectoryContent private constructor(val source: FileStream, val destination: File) : Operation() { companion object { /** * Return a [MoveDirectoryContent], moving the content of [source] to [destination]. * Its running time is potentially proportional to the number of files in [source]. * @param [source] a directory that should be moved * @param [destination] a directory, assumed to exists, to which [source] content will be transferred. * @throws [NoSuchFileException] if the file do not exists (starting at API 26) * @throws [java.nio.file.NotDirectoryException] if the file exists and is not a directory (starting at API 26) * @throws [FileNotFoundException] if the file do not exists (up to API 25) * @throws [IOException] if files can not be listed. On non existing or non-directory file up to API 25. This also occurred on an existing directory because of permission issue * that we could not reproduce. See https://github.com/ankidroid/Anki-Android/issues/10358 * @throws [SecurityException] – If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory */ fun createInstance(source: Directory, destination: File): MoveDirectoryContent = MoveDirectoryContent(CompatHelper.compat.contentOfDirectory(source.directory), destination) } override fun execute(context: MigrationContext): List<Operation> { try { val hasNext = source.hasNext() // can throw an IOException if (!hasNext) { source.close() return operationCompleted() } } catch (e: IOException) { source.close() throw e } val nextFile = source.next() // Guaranteed not to throw since hasNext returned true. val moveNextFile = toMoveOperation(nextFile) val moveRemainingDirectoryContent = this return listOf(moveNextFile, moveRemainingDirectoryContent) } /** * @returns An operation to move file or directory [sourceFile] to [destination] */ @VisibleForTesting internal fun toMoveOperation(sourceFile: File): Operation { return MoveFileOrDirectory(sourceFile, File(destination, sourceFile.name)) } }
gpl-3.0
61f4b54357f3ef3dca39d6127c1d6e47
55.192308
340
0.727584
4.603992
false
false
false
false
huhanpan/smart
app/src/main/java/com/etong/smart/Other/RxServie.kt
1
12855
package com.etong.smart.Other import com.alibaba.fastjson.JSONObject import com.facebook.stetho.okhttp3.StethoInterceptor import com.google.gson.internal.LinkedTreeMap import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.net.URLDecoder import java.util.concurrent.TimeUnit interface RxServie { data class Result<T>(var status: Int?, var data: T?, var error: String?) data class ListResult<T>(var status: Int?, var data: List<T>?, var error: String?) data class ImageBean(var id: String?, var type: String?, val value: String?) data class FloorBean(var id: String?, var name: String?) data class GateBean(var id: String, var roomName: String, var cardNumber: String) data class GateData(var gates: List<GateBean>?) data class ActivityDetailBean(var title: String?, var conver_url: String?, var img_url: String?, var create_date: String?, var discuss_count: String? = "0", var content: String?, var name: String?, var header_img: String?, var start_date: String?, var end_date: String?) data class WorkOrderBean(var id: String, var member_id: String, var admin_id: String, var title: String="", var status: String, var create_date: String?, var content: String?) data class TalkInfoBean(var id: String, var content: String?, var info_type: Int, val create_date: String) companion object { val url = "121.43.186.73" private val rxRetrofit = Retrofit.Builder().baseUrl("http://$url") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(OkHttpClient.Builder() .writeTimeout(10, TimeUnit.SECONDS) .addNetworkInterceptor(StethoInterceptor()) .build()) .build() private val mRxService = rxRetrofit.create(RxServie::class.java) fun GetWelcomeImage(back: (Url: String) -> Unit) = mRxService.mGetWelcomeImage() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null && it.status == 1) { val value = it.data?.value back.invoke(value ?: "http://f2.dn.anqu.com/down/MGYwNQ==/allimg/1308/54-130R1093120.jpg") } else { back.invoke("http://f2.dn.anqu.com/down/MGYwNQ==/allimg/1308/54-130R1093120.jpg") it.error?.showToast() } }, { back.invoke("http://f2.dn.anqu.com/down/MGYwNQ==/allimg/1308/54-130R1093120.jpg") it.printStackTrace() }) fun getFloor(back: (List<FloorBean>?) -> Unit) = mRxService.mGetFloor(Storage.readToken()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke(it.data) } else { it.error?.showToast() } } }, { back.invoke(null) it.printStackTrace() }) fun getGates(floorId: String?, back: (List<GateBean>?) -> Unit) = mRxService.mGetGates(Storage.readToken(), floorId ?: "0") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke((it.data as? GateData)?.gates) } else { back.invoke(null) it.error?.showToast() } } }, { back.invoke(null) it.printStackTrace() }) fun getActivityDetail(activityId: String, back: (ActivityDetailBean?) -> Unit) = mRxService.mGetActivityDetail(Storage.readToken(), activityId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke(it.data) } else { it.error?.showToast() } } }, { it.message?.showToast() }) fun removeDiscuss(discussId: String, back: (Boolean) -> Unit) = mRxService.mDeleteDiscuss(Storage.readToken(), discussId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { back.invoke(it.status == 1) it.error?.showToast() } }, { it.message?.showToast() }) fun openDoor(gates_id: String, cardNumber: String, back: (Boolean) -> Unit) = mRxService.mOpenGates(Storage.readToken(), gates_id, cardNumber) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke(true) } else { back.invoke(false) it.error?.showToast() } } else { back.invoke(false) } }, { back.invoke(false) it.printStackTrace() }) fun getUserIcon(name: String, back: (String?) -> Unit): Subscription { val str = URLDecoder.decode(name) return mRxService.mGetUserIcon(str) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it.status == 1) { back.invoke(it.data) } else { back.invoke(null) } }, { back.invoke(null) }) } fun sendMessage(message: String, work_id: String = "0", back: (Boolean) -> Unit): Subscription { val data = JSONObject() data.put("token", Storage.readToken()) data.put("content", message) data.put("work_order_id",work_id) return mRxService.mSendMessage(data) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke(true) } else { back.invoke(false) it.error?.showToast() } } }, { back.invoke(false) it.message?.showToast() }) } fun getWorkOrder(back: (List<List<WorkOrderBean>>?) -> Unit): Subscription { return mRxService.mGetWorkorder(Storage.readToken()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke(it.data?.map { it.map { WorkOrderBean(it["id"]!!, it["member_id"]!!, it["admin_id"]!!, it["roomName"]!!, it["status"]!!, it["create_date"], it["content"]) } }) } else { back.invoke(null) it.error?.showToast() } } }, { it.message?.showToast() back.invoke(null) }) } fun setStatus(item: WorkOrderBean, back: (Boolean) -> Unit): Subscription { val data = JSONObject() data.put("token", Storage.readToken()) data.put("work_order_id", item.id) data.put("status", if (item.status == "0") "1" else if (item.status == "1") "2" else "1") return mRxService.mSetStatus(data) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke(true) } else { back.invoke(false) it.error?.showToast() } } }, { println(it.message) back.invoke(false) }) } fun getTalkList(id: String = "0", back: (List<TalkInfoBean>?) -> Unit): Subscription { return mRxService.mGetTalkList(Storage.readToken(), id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it != null) { if (it.status == 1) { back.invoke(it.data) } else { back.invoke(null) it.error?.showToast() } } }, { println(it.message) back.invoke(null) }) } } @GET("/config/get_img") fun mGetWelcomeImage(): Observable<Result<ImageBean>> @GET("/room/get_floor/token/{token}") fun mGetFloor(@Path("token") token: String): Observable<ListResult<FloorBean>> @GET("/gates/get_list/token/{token}/floor_id/{floor_id}") fun mGetGates(@Path("token") token: String, @Path("floor_id") floor: String): Observable<Result<GateData>> @GET("/activity/get_content/token/{token}/activity_id/{activity_id}") fun mGetActivityDetail(@Path("token") token: String, @Path("activity_id") activityId: String): Observable<Result<ActivityDetailBean>> @GET("/discuss/del/token/{token}/id/{id}") fun mDeleteDiscuss(@Path("token") token: String, @Path("id") discussId: String): Observable<Result<String>> @GET("/gates/open/token/{token}/gates_id/{gates_id}/card_num/{card_num}") fun mOpenGates(@Path("token") token: String, @Path("gates_id") gates_id: String, @Path("card_num") cardNumber: String): Observable<Result<Map<String, Boolean>>> @GET("/user/get_headimg/username/{username}") fun mGetUserIcon(@Path("username") username: String): Observable<Result<String>> @POST("/work_order/sendmsg") fun mSendMessage(@Body body: JSONObject): Observable<Result<String>> @GET("/work_order/get_order_list/token/{token}") fun mGetWorkorder(@Path("token") token: String): Observable<ListResult<List<LinkedTreeMap<String, String>>>> @POST("/work_order/change_status") fun mSetStatus(@Body body: JSONObject): Observable<Result<String>> @GET("/work_order/get_talk_list/token/{token}/work_order_id/{work_order_id}") fun mGetTalkList(@Path("token") token: String, @Path("work_order_id") orderId: String): Observable<ListResult<TalkInfoBean>> }
gpl-2.0
06f9ea46d24657cf03baf79fb4a00254
44.914286
274
0.471801
4.884119
false
false
false
false
JetBrains/anko
anko/library/generated/coroutines/src/main/java/bg.kt
2
1122
/** * Created by yan on 15/03/2017. */ /* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko.coroutines.experimental import kotlinx.coroutines.* @PublishedApi @Deprecated(message = "Use the default pool") internal var POOL = newFixedThreadPoolContext(2 * Runtime.getRuntime().availableProcessors(), "bg") @Deprecated(message = "Use the default pool", replaceWith = ReplaceWith("async(block)", "kotlinx.coroutines.async")) inline fun <T> bg(crossinline block: () -> T): Deferred<T> = GlobalScope.async(POOL, CoroutineStart.DEFAULT) { block() }
apache-2.0
144df9b94c3398aa7b97b26ac412cdfc
35.193548
116
0.737968
3.964664
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/viewmodel/PlaysSummaryViewModel.kt
1
4441
package com.boardgamegeek.ui.viewmodel import android.app.Application import androidx.lifecycle.* import com.boardgamegeek.db.PlayDao import com.boardgamegeek.entities.* import com.boardgamegeek.extensions.* import com.boardgamegeek.livedata.LiveSharedPreference import com.boardgamegeek.pref.SyncPrefs import com.boardgamegeek.repository.PlayRepository import com.boardgamegeek.service.SyncService import com.boardgamegeek.util.RateLimiter import kotlinx.coroutines.launch import java.util.concurrent.TimeUnit class PlaysSummaryViewModel(application: Application) : AndroidViewModel(application) { private val playRepository = PlayRepository(getApplication()) private val playsRateLimiter = RateLimiter<Int>(10, TimeUnit.MINUTES) private val syncTimestamp = MutableLiveData<Long>() private val h = LiveSharedPreference<Int>(getApplication(), PlayStats.KEY_GAME_H_INDEX) private val n = LiveSharedPreference<Int>(getApplication(), PlayStats.KEY_GAME_H_INDEX + PlayStats.KEY_H_INDEX_N_SUFFIX) private val username = LiveSharedPreference<String>(getApplication(), AccountPreferences.KEY_USERNAME) init { refresh() } val syncPlays = LiveSharedPreference<Boolean>(getApplication(), PREFERENCES_KEY_SYNC_PLAYS) val syncPlaysTimestamp = LiveSharedPreference<Long>(getApplication(), PREFERENCES_KEY_SYNC_PLAYS_TIMESTAMP) val oldestSyncDate = LiveSharedPreference<Long>(getApplication(), SyncPrefs.TIMESTAMP_PLAYS_OLDEST_DATE, SyncPrefs.NAME) val newestSyncDate = LiveSharedPreference<Long>(getApplication(), SyncPrefs.TIMESTAMP_PLAYS_NEWEST_DATE, SyncPrefs.NAME) val plays = syncTimestamp.switchMap { liveData { try { val list = playRepository.getPlays() SyncService.sync(getApplication(), SyncService.FLAG_SYNC_PLAYS_UPLOAD) val refreshedList = if (syncPlays.value == true && playsRateLimiter.shouldProcess(0)) { emit(RefreshableResource.refreshing(list)) // TODO - while refreshing, the plays aren't updated in the UI. Figure out how to do that. Maybe listen to the play sync dates playRepository.refreshPlays() playRepository.getPlays() } else list emit(RefreshableResource.success(refreshedList)) } catch (e: Exception) { playsRateLimiter.reset(0) emit(RefreshableResource.error(e, getApplication())) } } } val playCount: LiveData<Int> = plays.map { list -> list.data?.sumOf { it.quantity } ?: 0 } val playsInProgress: LiveData<List<PlayEntity>> = plays.map { list -> list.data?.filter { it.dirtyTimestamp > 0L }.orEmpty() } val playsNotInProgress: LiveData<List<PlayEntity>> = plays.map { list -> list.data?.filter { it.dirtyTimestamp == 0L }?.take(ITEMS_TO_DISPLAY).orEmpty() } val players: LiveData<List<PlayerEntity>> = plays.switchMap { liveData { emit(playRepository.loadPlayers(PlayDao.PlayerSortBy.PLAY_COUNT)) } }.map { p -> p.filter { it.username != username.value }.take(ITEMS_TO_DISPLAY) } val locations: LiveData<List<LocationEntity>> = plays.switchMap { liveData { emit(playRepository.loadLocations(PlayDao.LocationSortBy.PLAY_COUNT)) } }.map { p -> p.filter { it.name.isNotBlank() }.take(ITEMS_TO_DISPLAY) } val colors: LiveData<List<PlayerColorEntity>> = liveData { emit( if (username.value.isNullOrBlank()) emptyList() else playRepository.loadUserColors(username.value.orEmpty()) ) } val hIndex = MediatorLiveData<HIndexEntity>().apply { addSource(h) { value = HIndexEntity(it ?: HIndexEntity.INVALID_H_INDEX, n.value ?: 0) } addSource(n) { value = HIndexEntity(h.value ?: HIndexEntity.INVALID_H_INDEX, it ?: 0) } } fun refresh(): Boolean { val value = syncTimestamp.value return if (value == null || value.isOlderThan(1, TimeUnit.SECONDS)) { syncTimestamp.postValue(System.currentTimeMillis()) true } else false } fun reset() { viewModelScope.launch { playRepository.resetPlays() } } companion object { const val ITEMS_TO_DISPLAY = 5 } }
gpl-3.0
613585f3ac9ef71e8ae0def4efacd202
37.95614
146
0.663364
4.481332
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/shows/SyncUpdatedShows.kt
1
3104
/* * Copyright (C) 2015 Simon Vig Therkildsen * * 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 net.simonvt.cathode.actions.shows import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import android.text.format.DateUtils import net.simonvt.cathode.actions.PagedAction import net.simonvt.cathode.actions.PagedResponse import net.simonvt.cathode.api.entity.UpdatedItem import net.simonvt.cathode.api.service.ShowsService import net.simonvt.cathode.api.util.TimeUtils import net.simonvt.cathode.provider.DatabaseContract.ShowColumns import net.simonvt.cathode.provider.ProviderSchematic.Shows import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.ShowDatabaseHelper import net.simonvt.cathode.settings.Timestamps import retrofit2.Call import javax.inject.Inject class SyncUpdatedShows @Inject constructor( private val context: Context, private val showsService: ShowsService, private val showHelper: ShowDatabaseHelper ) : PagedAction<Unit, UpdatedItem>() { override fun key(params: Unit): String = "SyncUpdatedShows" private val currentTime = System.currentTimeMillis() override fun getCall(params: Unit, page: Int): Call<List<UpdatedItem>> { val lastUpdated = Timestamps.get(context).getLong(Timestamps.SHOWS_LAST_UPDATED, currentTime) val millis = lastUpdated - 12 * DateUtils.HOUR_IN_MILLIS val updatedSince = TimeUtils.getIsoTime(millis) return showsService.getUpdatedShows(updatedSince, page, LIMIT) } override suspend fun handleResponse( params: Unit, pagedResponse: PagedResponse<Unit, UpdatedItem> ) { val ops = arrayListOf<ContentProviderOperation>() var page: PagedResponse<Unit, UpdatedItem>? = pagedResponse do { for (item in page!!.response) { val updatedAt = item.updated_at.timeInMillis val show = item.show!! val traktId = show.ids.trakt!! val id = showHelper.getId(traktId) if (id != -1L) { if (showHelper.isUpdated(traktId, updatedAt)) { val values = ContentValues() values.put(ShowColumns.NEEDS_SYNC, true) ops.add(ContentProviderOperation.newUpdate(Shows.withId(id)).withValues(values).build()) } } } page = page.nextPage() } while (page != null) context.contentResolver.batch(ops) } override fun onDone() { Timestamps.get(context).edit().putLong(Timestamps.SHOWS_LAST_UPDATED, currentTime).apply() } companion object { private const val LIMIT = 100 } }
apache-2.0
c45f209aae5154e6249c00fd7e6cc6af
34.272727
100
0.737758
4.257888
false
false
false
false
JetBrains-Research/npy
src/main/kotlin/org/jetbrains/bio/npy/Npz.kt
1
7949
package org.jetbrains.bio.npy import java.io.Closeable import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.Channels import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.zip.CRC32 import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipOutputStream import kotlin.math.min /** * A ZIP file where each individual file is in NPY format. * * By convention each file has `.npy` extension, however, the API * doesn't expose it. So for instance the array named "X" will be * accessibly via "X" and **not** "X.npy". * * See https://docs.scipy.org/doc/numpy-dev/neps/npy-format.html */ object NpzFile { /** * A reader for NPZ format. * * @since 0.2.0 */ data class Reader internal constructor(private val path: Path) : Closeable, AutoCloseable { private val zf = ZipFile(path.toFile(), ZipFile.OPEN_READ, Charsets.US_ASCII) /** * Returns a mapping from array names to the corresponding * scalar types in Java. * * @since 0.2.0 */ fun introspect() = zf.entries().asSequence().map { val header = NpyFile.Header.read(zf.getBuffers(it, Integer.MAX_VALUE).first()) val type = when (header.type) { 'b' -> when (header.bytes) { 1 -> Boolean::class.java else -> unexpectedByteNumber(header.type, header.bytes) } 'i', 'u' -> when (header.bytes) { 1 -> Byte::class.java 2 -> Short::class.java 4 -> Int::class.java 8 -> Long::class.java else -> unexpectedByteNumber(header.type, header.bytes) } 'f' -> when (header.bytes) { 4 -> Float::class.java 8 -> Double::class.java else -> unexpectedByteNumber(header.type, header.bytes) } 'S' -> String::class.java else -> unexpectedHeaderType(header.type) } NpzEntry(it.name.substringBeforeLast('.'), type, header.shape) }.toList() /** * Returns an array for a given name. * * The caller is responsible for casting the resulting array to an * appropriate type. * * @param name array name. * @param step amount of bytes to use for the temporary buffer, when * reading the entry. Defaults to 1 << 18 to mimic NumPy * behaviour. */ operator fun get(name: String, step: Int = 1 shl 18): NpyArray { return NpyFile.read(zf.getBuffers(zf.getEntry("$name.npy"), step)) } private fun ZipFile.getBuffers(entry: ZipEntry, step: Int): Sequence<ByteBuffer> { val `is` = getInputStream(entry) var chunk = ByteBuffer.allocate(0) return generateSequence { val remaining = `is`.available() + chunk.remaining() if (remaining > 0) { chunk = ByteBuffer.allocate(min(remaining, step)).apply { // Make sure we don't miss any unaligned bytes. put(chunk) Channels.newChannel(`is`).read(this) rewind() }.asReadOnlyBuffer() chunk } else { `is`.close() null } } } override fun close() = zf.close() } /** Opens an NPZ file at [path] for reading. */ @JvmStatic fun read(path: Path) = Reader(path) /** * A writer for NPZ format. * * The implementation uses a temporary [ByteBuffer] to store the * serialized array prior to archiving. Thus each [write] call * requires N extra bytes of memory for an array of N bytes. */ data class Writer internal constructor(private val path: Path, private val compressed: Boolean) : Closeable, AutoCloseable { private val zos = ZipOutputStream(Files.newOutputStream(path).buffered(), Charsets.US_ASCII) @JvmOverloads fun write(name: String, data: BooleanArray, shape: IntArray = intArrayOf(data.size)) { writeEntry(name, NpyFile.allocate(data, shape)) } @JvmOverloads fun write(name: String, data: ByteArray, shape: IntArray = intArrayOf(data.size)) { writeEntry(name, NpyFile.allocate(data, shape)) } @JvmOverloads fun write( name: String, data: ShortArray, shape: IntArray = intArrayOf(data.size), order: ByteOrder = ByteOrder.nativeOrder() ) { writeEntry(name, NpyFile.allocate(data, shape, order)) } @JvmOverloads fun write( name: String, data: IntArray, shape: IntArray = intArrayOf(data.size), order: ByteOrder = ByteOrder.nativeOrder() ) { writeEntry(name, NpyFile.allocate(data, shape, order)) } @JvmOverloads fun write( name: String, data: LongArray, shape: IntArray = intArrayOf(data.size), order: ByteOrder = ByteOrder.nativeOrder() ) { writeEntry(name, NpyFile.allocate(data, shape, order)) } @JvmOverloads fun write( name: String, data: FloatArray, shape: IntArray = intArrayOf(data.size), order: ByteOrder = ByteOrder.nativeOrder() ) { writeEntry(name, NpyFile.allocate(data, shape, order)) } @JvmOverloads fun write( name: String, data: DoubleArray, shape: IntArray = intArrayOf(data.size), order: ByteOrder = ByteOrder.nativeOrder() ) { writeEntry(name, NpyFile.allocate(data, shape, order)) } @JvmOverloads fun write( name: String, data: Array<String>, shape: IntArray = intArrayOf(data.size) ) { writeEntry(name, NpyFile.allocate(data, shape)) } private fun writeEntry(name: String, chunks: Sequence<ByteBuffer>) { val entry = ZipEntry("$name.npy").apply { if (compressed) { method = ZipEntry.DEFLATED } else { method = ZipEntry.STORED val crcAcc = CRC32() var sizeAcc = 0L for (chunk in chunks) { sizeAcc += chunk.capacity().toLong() crcAcc.update(chunk) chunk.rewind() } size = sizeAcc crc = crcAcc.value } } zos.putNextEntry(entry) try { val fc = Channels.newChannel(zos) for (chunk in chunks) { while (chunk.hasRemaining()) { fc.write(chunk) } } } finally { zos.closeEntry() } } override fun close() = zos.close() } /** Opens an NPZ file at [path] for writing. */ @JvmStatic fun write(path: Path, compressed: Boolean = false): Writer { return Writer(path, compressed) } } /** A stripped down NPY header for an array in NPZ. */ class NpzEntry(val name: String, val type: Class<*>, private val shape: IntArray) { override fun toString() = StringJoiner(", ", "NpzEntry{", "}") .add("name=$name") .add("type=$type") .add("shape=${shape.contentToString()}") .toString() }
mit
8f4e991279a843f6595237a6eac8dab0
32.125
101
0.521952
4.616144
false
false
false
false
GeoffreyMetais/vlc-android
application/tools/src/main/java/org/videolan/tools/AppUtils.kt
1
1241
package org.videolan.tools import android.content.Context import android.os.Build import android.os.Environment import android.os.StatFs object AppUtils { fun getVersionName(context: Context): String { return context.packageManager.getPackageInfo(context.packageName, 0).versionName } fun getVersionCode(context: Context): Long { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) context.packageManager.getPackageInfo(context.packageName, 0).longVersionCode else context.packageManager.getPackageInfo(context.packageName, 0).versionCode.toLong() } fun totalMemory(): Long { val statFs = StatFs(Environment.getRootDirectory().absolutePath) return (statFs.blockCount * statFs.blockSize).toLong() } fun freeMemory(): Long { val statFs = StatFs(Environment.getRootDirectory().absolutePath) return (statFs.availableBlocks * statFs.blockSize).toLong() } fun busyMemory(): Long { val statFs = StatFs(Environment.getRootDirectory().absolutePath) val total = (statFs.blockCount * statFs.blockSize).toLong() val free = (statFs.availableBlocks * statFs.blockSize).toLong() return total - free } }
gpl-2.0
246e2c6634a537ad7e34d2f253f566a2
33.5
95
0.705882
4.512727
false
false
false
false
RoyalDev/Fictitious
src/main/kotlin/org/royaldev/fictitious/commands/impl/PromptCommand.kt
1
2769
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.royaldev.fictitious.commands.impl import org.kitteh.irc.client.library.IRCFormat import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent import org.royaldev.fictitious.FictitiousBot import org.royaldev.fictitious.commands.InGameCommand import org.royaldev.fictitious.games.FictitiousGame import org.royaldev.fictitious.games.rounds.FictitiousRound import org.royaldev.fictitious.games.rounds.RoundType import org.royaldev.fictitious.players.SlashPlayer import xyz.cardstock.cardstock.commands.BaseCommand import xyz.cardstock.cardstock.commands.CallInfo import xyz.cardstock.cardstock.commands.Command @Command( name = "prompt", aliases = arrayOf( "setprompt", "getprompt" ), description = "Lets the matchmaker set the prompt and players get the prompt.", usage = "<command> (prompt)", commandType = BaseCommand.CommandType.CHANNEL ) class PromptCommand(fictitious: FictitiousBot) : InGameCommand(fictitious) { override fun run(event: ChannelMessageEvent, callInfo: CallInfo, game: FictitiousGame, player: SlashPlayer, arguments: List<String>) { val round = game.currentRound as FictitiousRound? if (round == null) { player.user.sendNotice("There is no current round.") return } if (round.characterAndType?.roundType != RoundType.HARDCORE) { player.user.sendNotice("This is not a hardcore round.") return } if (round.state.uniqueName == FictitiousRound.RoundState.HARDCORE_MATCHMAKER_SETTING_PROMPT.name) { this.matchmakerSetPrompt(arguments, player, round) } else { this.getPrompt(game, player, round) } } private fun getPrompt(game: FictitiousGame, player: SlashPlayer, round: FictitiousRound) { val prompt = round.hardcore?.prompt if (prompt == null) { player.user.sendNotice("There is no prompt.") return } game.sendMessage("The prompt is ${IRCFormat.BOLD}$prompt${IRCFormat.RESET}.") } private fun matchmakerSetPrompt(arguments: List<String>, player: SlashPlayer, round: FictitiousRound) { if (player != round.matchmaker) { player.user.sendNotice("The matchmaker must set a prompt first.") return } if (arguments.size < 1) { player.user.sendNotice("You must include a prompt to use.") return } round.hardcore?.prompt = arguments.joinToString(" ") round.advanceState() } }
mpl-2.0
42dac1fe43555d65b7673d520680b3e3
39.130435
138
0.685085
3.856546
false
false
false
false
cloose/luftbild4p3d
src/main/kotlin/org/luftbild4p3d/p3d/InfFile.kt
1
2803
package org.luftbild4p3d.p3d import org.luftbild4p3d.bing.LevelOfDetail import org.luftbild4p3d.bing.Tile import java.io.Closeable import java.io.File class InfFile(val filePath: String, val numberOfSources: Int) : Closeable { private val writer = File(filePath).printWriter() init { writeMultiSourceHeader() } fun writeSource(index: Int, waterMask: Int, sourceDirectory: String, sourceFile: String, tiledImage: TiledImage) { writer.appendln("[Source$index]") writer.appendln("Type = BMP") writer.appendln("Layer = Imagery") writer.appendln("SourceDir = \"$sourceDirectory\"") writer.appendln("SourceFile = \"$sourceFile\"") writer.appendln("PixelIsPoint = 0") writer.appendln("ulxMap = ${tiledImage.longitude}") writer.appendln("ulyMap = ${tiledImage.latitude}") writer.appendln("xDim = ${tiledImage.pixelSizeX()}") writer.appendln("yDim = ${tiledImage.pixelSizeY()}") //writer.appendln("Variation = March,April,May,June,July,August,September,October,November") //writer.appendln("NullValue = ,,,,0") writer.appendln("Channel_LandWaterMask = ${waterMask}.0") writer.appendln("") } fun writeWaterMask(index: Int, sourceDirectory: String, sourceFile: String, tiledImage: TiledImage) { writer.appendln("[Source$index]") writer.appendln("Type = TIFF") writer.appendln("Layer = None") writer.appendln("SourceDir = \"$sourceDirectory\"") writer.appendln("SourceFile = \"$sourceFile\"") writer.appendln("PixelIsPoint = 0") writer.appendln("ulxMap = ${tiledImage.longitude}") writer.appendln("ulyMap = ${tiledImage.latitude}") writer.appendln("xDim = ${tiledImage.pixelSizeX()}") writer.appendln("yDim = ${tiledImage.pixelSizeY()}") writer.appendln("SamplingMethod = Gaussian") //writer.appendln("NullValue = ,,,0,0") writer.appendln("") } fun writeDestination(destinationDirectory: String, destinationFile: String, levelOfDetail: LevelOfDetail) { writer.appendln("[Destination]") writer.appendln("DestFileType = BGL") writer.appendln("DestDir = \"$destinationDirectory\"") writer.appendln("DestBaseFileName = \"$destinationFile\"") writer.appendln("LOD = Auto,${levelOfDetail.prepar3dLOD}") writer.appendln("CompressionQuality = 95") writer.appendln("UseSourceDimensions = 1") writer.appendln("") } override fun close() { writer.close() } private fun writeMultiSourceHeader() { writer.appendln("[Source]") writer.appendln("Type = MultiSource") writer.appendln("NumberOfSources = $numberOfSources") writer.appendln() } }
gpl-3.0
9e4607f3e215107e68443cd83144909b
38.492958
118
0.652158
4.215038
false
false
false
false
CharlieZheng/NestedGridViewByListView
app/src/main/java/com/cdc/androidsamples/widget/HenCoder14a.kt
1
3219
package com.cdc.androidsamples.widget import android.animation.ObjectAnimator import android.content.Context import android.graphics.* import android.support.v4.content.ContextCompat import android.util.AttributeSet import android.view.View import com.cdc.R /** * @author zhenghanrong on 2017/10/28. */ class HenCoder14a : View { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private val camera = Camera() var rotateDegree = 0f private var bitmap: Bitmap? = null private val paint = Paint(Paint.ANTI_ALIAS_FLAG) init { bitmap = BitmapFactory.decodeResource(context.resources, R.mipmap.doraemon) } private fun getCenter() : Array<Float> { return arrayOf(measuredWidth / 2f, measuredHeight / 2f) } private fun getHypotenuse():Float { val center = getCenter() return Math.sqrt((center[0] * center[0] + center[1] * center[1]).toDouble()).toFloat() } private fun ltrbPositive() : RectF { val centerX = getCenter()[0] val centerY = getCenter()[1] val hypotenuse = getHypotenuse() val top = centerY - hypotenuse val left = centerX - hypotenuse return RectF(left, top, centerX + hypotenuse, centerY) } private fun ltrbNegative() : RectF { val center = getCenter() val hypotenuse = getHypotenuse() val bottom = center[1] + hypotenuse return RectF(center[0] - hypotenuse, center[1], center[0] + hypotenuse, bottom) } private fun myDraw(canvas: Canvas?) { val center = getCenter() canvas?.save() canvas?.rotate(rotateDegree, center[0], center[1]) canvas?.clipRect(ltrbPositive()) // canvas?.drawColor(ContextCompat.getColor(context, android.R.color.holo_blue_light)) camera.save() camera.rotateX(-10f) canvas?.translate(measuredWidth / 2f, measuredHeight / 2f) camera.applyToCanvas(canvas) canvas?.translate(-measuredWidth / 2f, -measuredHeight / 2f) camera.restore() canvas?.rotate(-rotateDegree, center[0], center[1]) canvas?.drawBitmap(bitmap, (measuredWidth - (bitmap?.width ?: 0)) / 2f, (measuredHeight - (bitmap?.height ?: 0)) / 2f, paint) canvas?.restore() canvas?.save() canvas?.rotate(rotateDegree, center[0], center[1]) canvas?.clipRect(ltrbNegative()) // canvas?.drawColor(ContextCompat.getColor(context, android.R.color.holo_orange_light)) canvas?.rotate(-rotateDegree, center[0], center[1]) canvas?.drawBitmap(bitmap, (measuredWidth - (bitmap?.width ?: 0)) / 2f, (measuredHeight - (bitmap?.height ?: 0)) / 2f, paint) canvas?.restore() } override fun onDraw(canvas: Canvas?) { myDraw(canvas) } fun anim() { val objectAnimator = ObjectAnimator.ofFloat(this, "rotateDegree", 0f, 3600f) objectAnimator.addUpdateListener { invalidate() } objectAnimator.duration = 10000 objectAnimator.start() } }
apache-2.0
9bbe2b2b2f2ef46027c84e1730dc6b50
30.881188
133
0.64927
4.028786
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/settings/SettingsFragment.kt
1
8626
package org.tvheadend.tvhclient.ui.features.settings import android.Manifest import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.os.* import android.view.View import androidx.core.app.ActivityCompat import androidx.core.app.TaskStackBuilder import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.files.folderChooser import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.ui.common.interfaces.ToolbarInterface import org.tvheadend.tvhclient.ui.features.MainActivity import org.tvheadend.tvhclient.util.extensions.sendSnackbarMessage import timber.log.Timber class SettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener, ActivityCompat.OnRequestPermissionsResultCallback { lateinit var sharedPreferences: SharedPreferences lateinit var settingsViewModel: SettingsViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) PreferenceManager.setDefaultValues(activity, R.xml.preferences, false) settingsViewModel = ViewModelProvider(activity as SettingsActivity)[SettingsViewModel::class.java] (activity as ToolbarInterface).let { it.setTitle(getString(R.string.settings)) it.setSubtitle("") } sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity) findPreference<Preference>("list_connections")?.onPreferenceClickListener = this findPreference<Preference>("user_interface")?.onPreferenceClickListener = this findPreference<Preference>("profiles")?.onPreferenceClickListener = this findPreference<Preference>("playback")?.onPreferenceClickListener = this findPreference<Preference>("unlocker")?.onPreferenceClickListener = this findPreference<Preference>("advanced")?.onPreferenceClickListener = this findPreference<Preference>("changelog")?.onPreferenceClickListener = this findPreference<Preference>("language")?.onPreferenceClickListener = this findPreference<Preference>("selected_theme")?.onPreferenceClickListener = this findPreference<Preference>("information")?.onPreferenceClickListener = this findPreference<Preference>("privacy_policy")?.onPreferenceClickListener = this findPreference<Preference>("download_directory")?.onPreferenceClickListener = this } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) } override fun onResume() { super.onResume() sharedPreferences.registerOnSharedPreferenceChangeListener(this) updateDownloadDirSummary() } override fun onPause() { super.onPause() sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } private fun updateDownloadDirSummary() { Timber.d("Updating download directory summary") val path = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { Timber.d("Android API version is ${Build.VERSION.SDK_INT}, loading download folder from preference") sharedPreferences.getString("download_directory", Environment.DIRECTORY_DOWNLOADS) } else { Timber.d("Android API version is ${Build.VERSION.SDK_INT}, using default folder") Environment.DIRECTORY_DOWNLOADS } Timber.d("Setting download directory summary to $path") findPreference<Preference>("download_directory")?.summary = getString(R.string.pref_download_directory_sum, path) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && permissions.isNotEmpty() && permissions[0] == "android.permission.READ_EXTERNAL_STORAGE") { // The delay is needed, otherwise an illegalStateException would be thrown. This is // a known bug in android. Until it is fixed this workaround is required. Handler(Looper.getMainLooper()).postDelayed({ activity?.let { showFolderSelectionDialog(it) } }, 200) } } override fun onSharedPreferenceChanged(prefs: SharedPreferences, key: String) { Timber.d("Shared preference $key has changed") when (key) { "selected_theme" -> handlePreferenceThemeChanged() "language" -> { activity?.let { val intent = Intent(it, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK it.startActivity(intent) } } } } override fun onPreferenceClick(preference: Preference): Boolean { when (preference.key) { "profiles" -> handlePreferenceProfilesSelected() "playback" -> handlePreferencePlaybackSelected() "download_directory" -> handlePreferenceDownloadDirectorySelected() else -> settingsViewModel.setNavigationMenuId(preference.key) } return true } private fun handlePreferenceThemeChanged() { activity?.let { TaskStackBuilder.create(it) .addNextIntent(Intent(it, MainActivity::class.java)) .addNextIntent(it.intent) .startActivities() } } private fun handlePreferenceProfilesSelected() { if (view != null) { if (settingsViewModel.currentServerStatus.htspVersion < 16) { context?.sendSnackbarMessage(R.string.feature_not_supported_by_server) } else { settingsViewModel.setNavigationMenuId("profiles") } } } private fun handlePreferencePlaybackSelected() { if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) } else { settingsViewModel.setNavigationMenuId("playback") } } private fun handlePreferenceDownloadDirectorySelected() { if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) } else { activity?.let { if (isReadPermissionGranted(it)) { showFolderSelectionDialog(it) } } } } @Suppress("DEPRECATION") private fun showFolderSelectionDialog(context: Context) { Timber.d("Showing folder selection dialog") if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { Timber.d("Android API version is ${Build.VERSION.SDK_INT}, showing folder selection dialog") // Show the folder chooser dialog which defaults to the external storage dir MaterialDialog(context).show { folderChooser(context) { _, file -> Timber.d("Folder ${file.absolutePath}, ${file.name} was selected") val strippedPath = file.absolutePath.replace(Environment.getExternalStorageDirectory().absolutePath, "") sharedPreferences.edit().putString("download_directory", strippedPath).apply() updateDownloadDirSummary() } } } else { Timber.d("Android API version is ${Build.VERSION.SDK_INT}, showing information about default folder") context.sendSnackbarMessage("On Android 10 and higher devices the download folder is always ${Environment.DIRECTORY_DOWNLOADS}") } } private fun isReadPermissionGranted(activity: FragmentActivity): Boolean { return if (Build.VERSION.SDK_INT >= 23) { if (activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { true } else { requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) false } } else { true } } }
gpl-3.0
e70977dde09d1de3ee194e608a8e5f07
43.932292
194
0.677139
5.608583
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/ingestion/extensions/links/GitHubIngestionBuildLinksMutationsIT.kt
1
9823
package net.nemerosa.ontrack.extension.github.ingestion.extensions.links import net.nemerosa.ontrack.extension.general.ReleaseProperty import net.nemerosa.ontrack.extension.general.ReleasePropertyType import net.nemerosa.ontrack.extension.github.ingestion.AbstractIngestionTestSupport import net.nemerosa.ontrack.extension.github.workflow.BuildGitHubWorkflowRun import net.nemerosa.ontrack.extension.github.workflow.BuildGitHubWorkflowRunProperty import net.nemerosa.ontrack.extension.github.workflow.BuildGitHubWorkflowRunPropertyType import net.nemerosa.ontrack.json.getRequiredTextField import net.nemerosa.ontrack.model.security.Roles import net.nemerosa.ontrack.model.structure.BuildLinkForm import net.nemerosa.ontrack.model.structure.BuildLinkFormItem import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertTrue internal class GitHubIngestionBuildLinksMutationsIT : AbstractIngestionTestSupport() { @Test fun `Automation users can set the build links`() { basicTest { code -> asAccountWithGlobalRole(Roles.GLOBAL_AUTOMATION) { code() } } } @Test fun `Build by ID`() { basicTest() } @Test fun `Build by ID not found`() { basicTest( runIdProperty = 10, runIdQuery = 11, expectedLinks = emptyMap(), ) } @Test fun `Build by name`() { basicTest(buildIdentification = BuildIdentification.BUILD_NAME) } @Test fun `Build by label`() { basicTest(buildIdentification = BuildIdentification.BUILD_LABEL) } @Test fun `Links replaced by default`() { basicTest( existingLinks = setOf("three"), expectedLinks = mapOf( "one" to "build-one", "two" to "build-two", ), ) } @Test fun `Links replaced explicitly`() { basicTest( existingLinks = setOf("three"), expectedLinks = mapOf( "one" to "build-one", "two" to "build-two", ), addOnly = false, ) } @Test fun `Links added only`() { basicTest( existingLinks = setOf("three"), expectedLinks = mapOf( "one" to "build-one", "two" to "build-two", "three" to "build-three", ), addOnly = true, ) } private fun basicTest( buildIdentification: BuildIdentification = BuildIdentification.RUN_ID, runIdProperty: Long = 10, runIdQuery: Long = 10, buildName: String = "my-build-name", buildLabel: String = "0.0.1", addOnly: Boolean? = null, existingLinks: Set<String> = emptySet(), expectedLinks: Map<String, String> = mapOf( "one" to "build-one", "two" to "build-two", ), asAuth: (code: () -> Unit) -> Unit = { code -> asAdmin { code() } }, ) { val mutationName = when (buildIdentification) { BuildIdentification.RUN_ID -> "gitHubIngestionBuildLinksByRunId" BuildIdentification.BUILD_NAME -> "gitHubIngestionBuildLinksByBuildName" BuildIdentification.BUILD_LABEL -> "gitHubIngestionBuildLinksByBuildLabel" } val mutationParams = when (buildIdentification) { BuildIdentification.RUN_ID -> "runId: $runIdQuery," BuildIdentification.BUILD_NAME -> """buildName: "$buildName",""" BuildIdentification.BUILD_LABEL -> """buildLabel: "$buildLabel",""" } asAdmin { withGitHubIngestionSettings { val targets = mapOf( "one" to project { branch { build(name = "build-one") } }, "two" to project { branch { build(name = "build-two") { setProperty( this, ReleasePropertyType::class.java, ReleaseProperty("2.0.0") ) } } }, "three" to project { branch { build(name = "build-three") { setProperty( this, ReleasePropertyType::class.java, ReleaseProperty("3.0.0") ) } } }, ) project { branch { build(buildName) { setProperty( this, BuildGitHubWorkflowRunPropertyType::class.java, BuildGitHubWorkflowRunProperty( workflows = listOf( BuildGitHubWorkflowRun( runId = runIdProperty, url = "", name = "some-workflow", runNumber = 1, running = true, event = "push", ) ) ) ) if (buildIdentification == BuildIdentification.BUILD_LABEL) { setProperty( this, ReleasePropertyType::class.java, ReleaseProperty(buildLabel) ) } if (existingLinks.isNotEmpty()) { structureService.editBuildLinks(this, BuildLinkForm( addOnly = false, links = existingLinks.map { BuildLinkFormItem( project = targets[it]?.name ?: error("Cannot find project $it"), build = "build-$it", ) } )) } asAuth { run( """ mutation IngestLinks(${'$'}addOnly: Boolean) { $mutationName(input: { owner: "nemerosa", repository: "${project.name}", $mutationParams buildLinks: [ { project: "${targets["one"]?.name}", buildRef: "build-one" }, { project: "${targets["two"]?.name}", buildRef: "#2.0.0" } ], addOnly: ${'$'}addOnly, }) { payload { uuid } errors { message exception location } } } """, mapOf("addOnly" to addOnly) ) { data -> checkGraphQLUserErrors(data, mutationName) { node -> val uuid = node.path("payload").getRequiredTextField("uuid") assertTrue(uuid.isNotBlank(), "UUID has been returned") } asAdmin { val links = structureService.getBuildsUsedBy(this).pageItems.associate { it.project.name to it.name } assertEquals( expectedLinks.mapKeys { (key, _) -> targets[key]?.name ?: "" }, links ) } } } } } } } } } enum class BuildIdentification { RUN_ID, BUILD_NAME, BUILD_LABEL, } }
mit
0ce8d1129e4eb0fe4f0190d7eb6b25e2
39.262295
112
0.369337
6.769814
false
true
false
false
BjoernPetersen/JMusicBot
src/test/kotlin/net/bjoernpetersen/musicbot/internal/loader/DefaultResourceCacheTest.kt
1
8102
package net.bjoernpetersen.musicbot.internal.loader import com.google.inject.AbstractModule import com.google.inject.Guice import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.time.delay import kotlinx.coroutines.time.withTimeout import kotlinx.coroutines.withContext import net.bjoernpetersen.musicbot.api.config.Config import net.bjoernpetersen.musicbot.api.module.DefaultSongLoaderModule import net.bjoernpetersen.musicbot.api.player.Song import net.bjoernpetersen.musicbot.api.player.song import net.bjoernpetersen.musicbot.api.plugin.IdBase import net.bjoernpetersen.musicbot.api.plugin.management.LogInitStateWriter import net.bjoernpetersen.musicbot.spi.loader.Resource import net.bjoernpetersen.musicbot.spi.loader.ResourceCache import net.bjoernpetersen.musicbot.spi.plugin.Playback import net.bjoernpetersen.musicbot.spi.plugin.Plugin import net.bjoernpetersen.musicbot.spi.plugin.PluginLookup import net.bjoernpetersen.musicbot.spi.plugin.Provider import net.bjoernpetersen.musicbot.spi.plugin.management.ProgressFeedback import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotSame import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.time.Duration import kotlin.coroutines.CoroutineContext import kotlin.reflect.KClass private fun createCache(): ResourceCache = Guice .createInjector(DefaultSongLoaderModule(), DummyPluginLookupModule) .getInstance(DefaultResourceCache::class.java) class DefaultResourceCacheTest { @AfterEach fun resetProvider() { DummyProvider.loadDuration = Duration.ofMillis(50) DummyProvider.freeDuration = Duration.ofMillis(50) } @Test fun `all cleaned up`() { val cache: ResourceCache = createCache() val size = 1000 val resources: List<Resource> = runBlocking { (1..size) .asSequence() .map { it.toString() } .map { runBlocking { DummyProvider.lookup(it) } } .map { async { cache.get(it) } } .toList() .mapTo(ArrayList(size)) { try { it.await() } catch (e: Exception) { e.printStackTrace() throw e } } } assertEquals(size, resources.size) runBlocking { cache.close() resources.forEach { assertFalse(it.isValid) } } } @Test fun `clean up aborts with timeout`() { val cache = createCache() val resource = runBlocking { DummyProvider.freeDuration = Duration.ofMinutes(2) val song = DummyProvider.lookup("longFreeResource") cache.get(song) } assertThrows<TimeoutCancellationException> { runBlocking { withTimeout(Duration.ofSeconds(90)) { cache.close() } } } assertTrue(resource.isValid) } @Test fun `get works`() { val cache = createCache() runBlocking { val song = DummyProvider.lookup("test") val resource = cache.get(song) assertTrue(resource.isValid) } } @Test fun `get refreshes`() { val cache = createCache() runBlocking { val song = DummyProvider.lookup("test") val resource = cache.get(song) resource.free() assertFalse(resource.isValid) val refreshed = cache.get(song) assertNotSame(resource, refreshed) assertTrue(refreshed.isValid) } } @Test fun `get on closed cache`() { val cache = createCache() runBlocking { val song = DummyProvider.lookup("test") cache.close() assertThrows<IllegalStateException> { runBlocking { cache.get(song) } } } } @Test fun `get while closing`() { val cache = createCache() runBlocking { DummyProvider.freeDuration = Duration.ofSeconds(1) val song = DummyProvider.lookup("test") withContext(Dispatchers.Default) { cache.get(song) val closing = CompletableDeferred<Unit>() launch { closing.complete(Unit) cache.close() } closing.await() delay(50) assertThrows<IllegalStateException> { runBlocking { cache.get(song) } } } } } companion object { @BeforeAll @JvmStatic fun initProvider() { runBlocking { DummyProvider.initialize(LogInitStateWriter()) } } @AfterAll @JvmStatic fun closeProvider() { runBlocking { DummyProvider.close() } } } } private class DummyResource(private val freeDuration: Duration) : Resource { private val mutex = Mutex() override var isValid: Boolean = true override suspend fun free() { mutex.withLock { if (!isValid) return delay(freeDuration) isValid = false } } } private object DummyPluginLookupModule : AbstractModule() { override fun configure() { bind(PluginLookup::class.java).toInstance(DummyProviderLookup) } } @Suppress("UNCHECKED_CAST") private object DummyProviderLookup : PluginLookup { override fun <T : Plugin> lookup(id: String): T { return DummyProvider as T } override fun <T : Plugin> lookup(base: KClass<T>): T { return DummyProvider as T } } @IdBase("Dummy") private object DummyProvider : Provider, CoroutineScope { override val name = "DummyProvider" override val description = "" override val subject get() = name private lateinit var job: Job override val coroutineContext: CoroutineContext get() = Dispatchers.IO + job var loadDuration: Duration = Duration.ofMillis(50) var freeDuration: Duration = Duration.ofMillis(50) override suspend fun search(query: String, offset: Int): List<Song> { TODO("not implemented") } override suspend fun lookup(id: String) = song(id) { title = id description = "" } override suspend fun supplyPlayback(song: Song, resource: Resource): Playback { TODO("not implemented") } override suspend fun loadSong(song: Song): Resource { return coroutineScope { withContext(coroutineContext) { delay(loadDuration) DummyResource(freeDuration) } } } override fun createConfigEntries(config: Config): List<Config.Entry<*>> { TODO("not implemented") } override fun createSecretEntries(secrets: Config): List<Config.Entry<*>> { TODO("not implemented") } override fun createStateEntries(state: Config) { TODO("not implemented") } override suspend fun initialize(progressFeedback: ProgressFeedback) { job = Job() } override suspend fun close() { job.cancel() } }
mit
1a0f0f2be36886c37d5587630a0ba10e
28.355072
83
0.620588
4.928224
false
false
false
false
bihe/mydms-java
Api/src/main/kotlin/net/binggl/mydms/infrastructure/actuator/InfoEndPointExtension.kt
1
1125
package net.binggl.mydms.infrastructure.actuator import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.actuate.info.Info import org.springframework.boot.actuate.info.InfoContributor import org.springframework.context.ApplicationContext import org.springframework.stereotype.Component import java.net.InetAddress import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.util.* @Component class InfoEndPointExtension(@Autowired private val ctx:ApplicationContext): InfoContributor { override fun contribute(builder: Info.Builder?) { val details = HashMap<String, Any>() val instant = Instant.ofEpochMilli(ctx.startupDate) val startupDate = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()) details["application-name"] = ctx.applicationName details["startup-date"] = startupDate.toString() val inetAddr = InetAddress.getLocalHost() details["local-ip"] = inetAddr.hostAddress details["hostname"] = inetAddr.hostName builder?.withDetail("context", details) } }
apache-2.0
4616b3d2144573a5fb39fd2516f9a10f
34.15625
93
0.763556
4.610656
false
false
false
false
Le-Chiffre/Yttrium
Core/src/com/rimmer/yttrium/Error.kt
2
1244
package com.rimmer.yttrium /* * Contains generic error types used within the server. * These errors are caught by the router and transformed into http responses. */ open class RouteException(text: String, val response: Any?): Exception(text) { override fun toString(): String { return "${javaClass.simpleName}: $message" } } /** This is mapped to 404 and should be thrown whenever something that was requested doesn't exist. */ open class NotFoundException(response: Any? = null) : RouteException("not_found", response) /** This is mapped to 403 and should be thrown whenever a session has insufficient permissions for an operation. */ open class UnauthorizedException(text: String = "invalid_token", response: Any? = null) : RouteException(text, response) /** This is mapped to 400 and should be thrown whenever a request tries to do something that's impossible in that context. */ open class InvalidStateException(cause: String, response: Any? = null): RouteException(cause, response) /** This is mapped to the provided http code and should be thrown for errors that don't fit any other exception. */ open class HttpException(val errorCode: Int, cause: String, response: Any? = null): RouteException(cause, response)
mit
c4b9f3285e6adf2ecf3cbf63175aacdb
50.833333
125
0.750804
4.523636
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/repository/git/path/matcher/name/EqualsMatcher.kt
1
1487
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository.git.path.matcher.name import svnserver.repository.git.path.NameMatcher /** * Simple matcher for equals compare. * * @author Artem V. Navrotskiy <[email protected]> */ class EqualsMatcher constructor(override val svnMask: String, private val dirOnly: Boolean) : NameMatcher { override fun isMatch(name: String, isDir: Boolean): Boolean { return (!dirOnly || isDir) && (svnMask == name) } override val isRecursive: Boolean get() { return false } override fun hashCode(): Int { var result: Int = svnMask.hashCode() result = 31 * result + (if (dirOnly) 1 else 0) return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that: EqualsMatcher = other as EqualsMatcher return ((dirOnly == that.dirOnly) && (svnMask == that.svnMask)) } override fun toString(): String { return svnMask + (if (dirOnly) "/" else "") } }
gpl-2.0
a07afd1735e71889f300e304c2286979
32.795455
107
0.64963
4.130556
false
false
false
false
icapps/niddler-ui
client-lib/src/main/kotlin/com/icapps/niddler/lib/debugger/model/DebuggerService.kt
1
4471
package com.icapps.niddler.lib.debugger.model import com.google.gson.GsonBuilder import com.icapps.niddler.lib.debugger.NiddlerDebuggerConnection import java.util.* /** * @author nicolaverbeeck */ class DebuggerService(private val connection: NiddlerDebuggerConnection) { private val gson = GsonBuilder() .disableHtmlEscaping() .create() fun addBlacklistItem(regex: String) { sendMessage(AddBlacklistMessage(regex)) } fun removeBlacklistItem(regex: String) { sendMessage(RemoveBlacklistMessage(regex)) } fun addDefaultRequestOverride(regex: String?, method: String?, request: DebugRequest, active: Boolean): String { val id = UUID.randomUUID().toString() sendMessage(NiddlerDebugControlMessage(MESSAGE_ADD_DEFAULT_REQUEST_OVERRIDE, mergeToJson(gson, RegexPayload(regex), MethodPayload(method), ActionPayload(id), ActivePayload(active), request))) return id } fun addDefaultResponse(regex: String?, method: String?, response: DebugResponse, active: Boolean): String { val id = UUID.randomUUID().toString() sendMessage(NiddlerDebugControlMessage(MESSAGE_ADD_DEFAULT_RESPONSE, mergeToJson(gson, RegexPayload(regex), MethodPayload(method), ActionPayload(id), ActivePayload(active), response))) return id } fun addRequestIntercept(regex: String?, method: String?, active: Boolean): String { val id = UUID.randomUUID().toString() sendMessage(NiddlerDebugControlMessage(MESSAGE_ADD_REQUEST, mergeToJson(gson, RegexPayload(regex), MethodPayload(method), ActionPayload(id), ActivePayload(active)))) return id } fun addResponseIntercept(regex: String?, method: String?, responseCode: Int?, active: Boolean): String { val id = UUID.randomUUID().toString() sendMessage(NiddlerDebugControlMessage(MESSAGE_ADD_RESPONSE, mergeToJson(gson, RegexPayload(regex), MethodPayload(method), ResponseCodePayload(responseCode), ActionPayload(id), ActivePayload(active)))) return id } fun addRequestOverride(regex: String?, method: String?, active: Boolean): String { val id = UUID.randomUUID().toString() sendMessage(NiddlerDebugControlMessage(MESSAGE_ADD_REQUEST_OVERRIDE, mergeToJson(gson, RegexPayload(regex), MethodPayload(method), ActionPayload(id), ActivePayload(active)))) return id } fun respondTo(niddlerMessageId: String, response: DebugResponse) { sendMessage(NiddlerDebugControlMessage(MESSAGE_DEBUG_REPLY, mergeToJson(gson, DebugReplyPayload(niddlerMessageId), response))) } fun muteAction(id: String) { sendMessage(DeactivateActionMessage(id)) } fun unmuteAction(id: String) { sendMessage(ActivateActionMessage(id)) } fun removeRequestAction(id: String) { sendMessage(RemoveRequestActionMessage(id)) } fun removeResponseAction(id: String) { sendMessage(RemoveResponseActionMessage(id)) } fun removeRequestOverrideMethod(id: String) { sendMessage(RemoveRequestOverrideActionMessage(id)) } fun updateDelays(delays: DebuggerDelays) { sendMessage(UpdateDelaysMessage(delays)) } fun setAllActionsMuted(muted: Boolean) { if (muted) sendMessage(MuteActionsMessage()) else sendMessage(UnmuteActionsMessage()) } fun connect() { sendMessage(NiddlerRootMessage(MESSAGE_START_DEBUG)) } fun disconnect() { sendMessage(NiddlerRootMessage(MESSAGE_END_DEBUG)) } private fun sendMessage(msg: Any) { connection.sendMessage(gson.toJson(msg)) } fun setActive(active: Boolean) { if (active) sendMessage(NiddlerDebugControlMessage(MESSAGE_ACTIVATE, payload = null)) else sendMessage(NiddlerDebugControlMessage(MESSAGE_DEACTIVATE, payload = null)) } }
apache-2.0
4b657f457be8e0a023bfc51ab70b590b
32.616541
116
0.616864
5.051977
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/Context.kt
1
9321
package org.pixelndice.table.pixelclient.connection.lobby.client import com.google.common.eventbus.Subscribe import com.google.protobuf.ByteString import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.App import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.connection.lobby.client.runnable.* import org.pixelndice.table.pixelclient.ds.Account import org.pixelndice.table.pixelclient.ds.resource.Board import org.pixelndice.table.pixelclient.ds.drawable.DrawableFreeHand import org.pixelndice.table.pixelclient.ds.drawable.DrawableImage import org.pixelndice.table.pixelclient.isGm import org.pixelndice.table.pixelclient.myAccount import org.pixelndice.table.pixelprotocol.Channel import org.pixelndice.table.pixelprotocol.ChannelCanceledException import org.pixelndice.table.pixelprotocol.Protobuf import java.net.InetAddress import java.nio.file.Files private val logger = LogManager.getLogger(Context::class.java) /** * Context class for lobby client connection * @author Marcelo Costa Toyama */ class Context(address: InetAddress, val account: Account) { /** * State of the connection on a given moment */ var state: State = State00Start() /** * Channel for reading/writing packets */ val channel: Channel = Channel(address) /** * ApplicationBus event handler */ val handler = Handler() init { ApplicationBus.register(handler) } /** * method for processing information that is read from channel */ fun process() { try { val packet: Protobuf.Packet? = channel.peekPacket() if( packet != null ) { if (packet.payloadCase == Protobuf.Packet.PayloadCase.ENDWITHERROR) { logger.error("Channel ended with Error ${packet.endWithError.reason}. It will be recycled in the next cycle.") } } // state processing state.process(this) } catch (e: ChannelCanceledException) { logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } } /** * ApplicationBus event handler class for Context */ inner class Handler{ /** * Server lobby is reachable, sending lobby auth */ @Suppress("unused") @Subscribe fun handleLobbyServerReachable(@Suppress("UNUSED_PARAMETER") event: ApplicationBus.LobbyServerReachable){ [email protected] = State01SendingLobbyAuth() } /** * GM authorized the player, sending auth ok */ @Suppress("unused") @Subscribe fun handleGmAuthPlayerOk(ev: ApplicationBus.GmAuthPlayerOk){ [email protected] = StateRunning02GMLobbyAuthPlayerOk(ev.player) } /** * GM does not authorized the player, sending auth not ok */ @Suppress("unused") @Subscribe fun handleGmAuthPlayerNOk(ev: ApplicationBus.GmAuthPlayerNOk){ [email protected] = StateRunning03GMLobbyAuthPlayerNOk(ev.player) } /** * GM is kicking the player */ @Suppress("unused") @Subscribe fun handleKickPlayer(event: ApplicationBus.KickPlayer){ if( isGm() ) { val packet = Protobuf.Packet.newBuilder() val kick = Protobuf.KickPlayer.newBuilder() packet.from = myAccount.toProtobuf().build() packet.sender = Protobuf.SenderEnum.FROM_GM packet.to = event.player.toProtobuf().build() packet.receiver = Protobuf.ReceiverEnum.TO_ACCOUNT packet.kickPlayer = kick.build() try { channel.packet = packet.build() } catch (e: ChannelCanceledException) { logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } } } /** * Lobby client connection is sharing a file */ @Suppress("unused") @Subscribe fun handleShareFileToLobby(event: ApplicationBus.ShareFileToLobby){ ApplicationBus.post(ApplicationBus.ExecuteRunnable(SyncFile(this@Context, event.file))) } /** * Updates the actor and share with the lobby */ @Suppress("unused") @Subscribe fun handleUpdateActor(event: ApplicationBus.UpdateActorToLobby){ ApplicationBus.post(ApplicationBus.ExecuteRunnable(SyncActor(this@Context, event.actor))) } /** * Updates the note and share with the lobby */ @Suppress("unused") @Subscribe fun handleUpdateNoteToLobby(event: ApplicationBus.UpdateNoteToLobby){ ApplicationBus.post(ApplicationBus.ExecuteRunnable(SyncNote(this@Context, event.note))) } /** * Updates the board and share with the lobby */ @Suppress("unused") @Subscribe fun handleUpdateBoardToLobby(event: ApplicationBus.UpdateBoardToLobby){ ApplicationBus.post(ApplicationBus.ExecuteRunnable(SyncBoard(this@Context, event.board))) } /** * Update GameResource Parent */ @Suppress("unused") @Subscribe fun handleUpdateGameResourceParent(event: ApplicationBus.UpdateGameResourceParent){ ApplicationBus.post(ApplicationBus.ExecuteRunnable(UpdateGameResourceParent(this@Context, event.id, event.oldParent, event.newParent))) } /** * sends a text message for the entire lobby */ @Suppress("unused") @Subscribe fun handleSendTextMessage(event: ApplicationBus.SendTextMessage){ val packet = Protobuf.Packet.newBuilder() val textMessage = Protobuf.TextMessage.newBuilder() textMessage.from = event.from.toProtobuf().build() textMessage.toAll = event.toAll textMessage.to = event.to.toProtobuf().build() textMessage.text = event.text packet.textMessage = textMessage.build() channel.packet = packet.build() } /** * Sends a drawable to the entire lobby */ @Suppress("unused") @Subscribe fun handleSendDrawableProtocol(event: ApplicationBus.SendDrawableProtocol){ when(event.drawable){ is DrawableImage -> { val di = event.drawable val packet = Protobuf.Packet.newBuilder() val addDrawable = Protobuf.AddDrawableImage.newBuilder() addDrawable.id = di.id addDrawable.gameResourceId = di.gameResource!!.id addDrawable.boardId = di.board!!.id addDrawable.layer = when(di.layer){ Board.Layer.BACKGROUND -> {Protobuf.BoardLayer.BACKGROUND} Board.Layer.TOKEN -> {Protobuf.BoardLayer.TOKEN} Board.Layer.GM -> {Protobuf.BoardLayer.GM} } addDrawable.x = di.x addDrawable.y = di.y addDrawable.imageFileHash = di.file!!.hash addDrawable.width = di.width addDrawable.height = di.height packet.addDrawableImage = addDrawable.build() try { channel.packet = packet.build() }catch (e: ChannelCanceledException) { logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } } is DrawableFreeHand -> {} } } /** * Show turn order widget to all lobby */ @Suppress("unused") @Subscribe fun handleShowTurnOrder(@Suppress("UNUSED_PARAMETER") event: ApplicationBus.SendShowTurnOrderProtocol){ val packet = Protobuf.Packet.newBuilder() val showTurnOrder = Protobuf.ShowTurnOrder.newBuilder() packet.showTurnOrder = showTurnOrder.build() try{ channel.packet = packet.build() } catch (e: ChannelCanceledException) { logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } logger.debug("Sent:\n$packet") } /** * Hide turn order widget to all lobby */ @Suppress("unused") @Subscribe fun handleHideTurnOrder(@Suppress("UNUSED_PARAMETER") event: ApplicationBus.SendHideTurnOrderProtocol){ val packet = Protobuf.Packet.newBuilder() val hideTurnOrder = Protobuf.HideTurnOrder.newBuilder() packet.hideTurnOrder = hideTurnOrder.build() try{ channel.packet = packet.build() } catch (e: ChannelCanceledException) { logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } logger.debug("Sent:\n$packet") } } }
bsd-2-clause
6f0166324a63d9fae14f0623cef10c9d
33.14652
130
0.595752
4.942206
false
false
false
false
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/plugin/commands/DelWarpCommand.kt
1
1887
package com.projectcitybuild.plugin.commands import com.projectcitybuild.core.exceptions.InvalidCommandArgumentsException import com.projectcitybuild.core.utilities.Failure import com.projectcitybuild.core.utilities.Success import com.projectcitybuild.features.warps.usecases.DeleteWarpUseCase import com.projectcitybuild.modules.textcomponentbuilder.send import com.projectcitybuild.plugin.environment.SpigotCommand import com.projectcitybuild.plugin.environment.SpigotCommandInput import com.projectcitybuild.repositories.WarpRepository import org.bukkit.command.CommandSender import javax.inject.Inject class DelWarpCommand @Inject constructor( private val deleteWarpUseCase: DeleteWarpUseCase, private val warpRepository: WarpRepository, ) : SpigotCommand { override val label = "delwarp" override val permission = "pcbridge.warp.delete" override val usageHelp = "/delwarp <name>" override suspend fun execute(input: SpigotCommandInput) { if (input.args.size != 1) { throw InvalidCommandArgumentsException() } val warpName = input.args.first() val result = deleteWarpUseCase.deleteWarp(warpName) when (result) { is Failure -> { input.sender.send().error( when (result.reason) { DeleteWarpUseCase.FailureReason.WARP_NOT_FOUND -> "Warp $warpName does not exist" } ) } is Success -> input.sender.send().success("Warp $warpName deleted") } } override fun onTabComplete(sender: CommandSender?, args: List<String>): Iterable<String>? { return when { args.isEmpty() -> warpRepository.names() args.size == 1 -> warpRepository.names().filter { it.lowercase().startsWith(args.first()) } else -> null } } }
mit
d071dc60bd5d6c7a37bccce57e2a8a27
36.74
105
0.684685
4.580097
false
false
false
false
Dmedina88/SSB
example/app/src/main/kotlin/com/grayherring/devtalks/ui/home/TalkViewAdapter.kt
1
1645
package com.grayherring.devtalks.ui.home import android.support.v7.widget.RecyclerView import android.support.v7.widget.RecyclerView.Adapter import android.view.View import android.widget.TextView import com.grayherring.devtalks.R.id import com.grayherring.devtalks.R.layout import com.grayherring.devtalks.data.model.Talk import com.grayherring.devtalks.ui.home.events.ItemClickEvent class TalkViewAdapter(private val homeViewModel: HomeViewModel) : Adapter<TalkViewAdapter.ViewHolder>() { val data get() = homeViewModel.lastState.talks override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.mItem = data[position] holder.mIdView.text = data[position].title holder.mContentView.text = data[position].presenter holder.mView.setOnClickListener { homeViewModel.addEvent(ItemClickEvent(data[position])) } } override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): ViewHolder { val view = android.view.LayoutInflater.from(parent.context) .inflate(layout.fragment_talkitem, parent, false) return ViewHolder(view) } inner class ViewHolder(val mView: android.view.View) : RecyclerView.ViewHolder(mView) { val mIdView: TextView val mContentView: TextView var mItem: Talk? = null init { mIdView = mView.findViewById<View>(id.title) as TextView mContentView = mView.findViewById<View>(id.name) as TextView } override fun toString(): String { return super.toString() + " '" + mContentView.text + "'" } } }
apache-2.0
3b4e2f105aa4d0d70f33af9d509eaa33
31.254902
105
0.727052
4.283854
false
false
false
false
Xenoage/Zong
utils-kotlin/src/com/xenoage/utils/math/Point2i.kt
1
562
package com.xenoage.utils.math import kotlin.math.round import kotlin.math.roundToInt /** * 2D point in integer precision. */ data class Point2i( val x: Int, val y: Int) { constructor(p: Point2f) : this(p.x.roundToInt(), p.y.roundToInt()) fun add(x: Int, y: Int) = Point2i(this.x + x, this.y + y) fun add(p: Point2i) = Point2i(this.x + p.x, this.y + p.y) fun sub(p: Point2i) = Point2i(this.x - p.x, this.y - p.y) override fun toString() = "($x, $y)" companion object { /** Point at the origin (0, 0). */ val origin = Point2i(0, 0) } }
agpl-3.0
ccfade7f814f6771ef548f39f45e9fcc
19.071429
67
0.622776
2.443478
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/reactnativestripesdk/StripeContainerView.kt
2
1357
package versioned.host.exp.exponent.modules.api.components.reactnativestripesdk import android.content.Context import android.graphics.Rect import android.view.MotionEvent import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.FrameLayout import com.facebook.react.uimanager.ThemedReactContext class StripeContainerView(private val context: ThemedReactContext) : FrameLayout(context) { private var keyboardShouldPersistTapsValue: Boolean = true init { rootView.isFocusable = true rootView.isFocusableInTouchMode = true rootView.isClickable = true } fun setKeyboardShouldPersistTaps(value: Boolean) { keyboardShouldPersistTapsValue = value } override fun dispatchTouchEvent(event: MotionEvent?): Boolean { if (event!!.action == MotionEvent.ACTION_DOWN && !keyboardShouldPersistTapsValue) { val v = context.currentActivity!!.currentFocus if (v is EditText) { val outRect = Rect() v.getGlobalVisibleRect(outRect) if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(v.windowToken, 0) rootView.requestFocus() } } } return super.dispatchTouchEvent(event) } }
bsd-3-clause
4911ee17978e781b7f5c8d20fa5539f5
33.794872
96
0.747237
4.881295
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/kotlin/types/TypeConverterProvider.kt
2
3961
@file:OptIn(ExperimentalStdlibApi::class) package abi44_0_0.expo.modules.kotlin.types import abi44_0_0.com.facebook.react.bridge.Dynamic import abi44_0_0.com.facebook.react.bridge.ReadableArray import abi44_0_0.com.facebook.react.bridge.ReadableMap import abi44_0_0.expo.modules.kotlin.exception.MissingTypeConverter import abi44_0_0.expo.modules.kotlin.records.Record import abi44_0_0.expo.modules.kotlin.records.RecordTypeConverter import kotlin.reflect.KClass import kotlin.reflect.KType import kotlin.reflect.full.createType import kotlin.reflect.full.isSubclassOf import kotlin.reflect.typeOf interface TypeConverterProvider { fun obtainTypeConverter(type: KType): TypeConverter<*> } inline fun <reified T : Any> obtainTypeConverter(): TypeConverter<T> { @Suppress("UNCHECKED_CAST") return TypeConverterProviderImpl.obtainTypeConverter(typeOf<T>()) as TypeConverter<T> } inline fun <reified T> convert(value: Dynamic): T { val converter = TypeConverterProviderImpl.obtainTypeConverter(typeOf<T>()) return converter.convert(value) as T } fun convert(value: Dynamic, type: KType): Any? { val converter = TypeConverterProviderImpl.obtainTypeConverter(type) return converter.convert(value) } object TypeConverterProviderImpl : TypeConverterProvider { private val cachedConverters = createCashedConverters(false) + createCashedConverters(true) override fun obtainTypeConverter(type: KType): TypeConverter<*> { cachedConverters[type]?.let { return it } val kClass = type.classifier as? KClass<*> ?: throw MissingTypeConverter(type) if (kClass.java.isArray) { return ArrayTypeConverter(this, type) } if (kClass.isSubclassOf(List::class)) { return ListTypeConverter(this, type) } if (kClass.isSubclassOf(Map::class)) { return MapTypeConverter(this, type) } if (kClass.isSubclassOf(Pair::class)) { return PairTypeConverter(this, type) } if (kClass.isSubclassOf(Array::class)) { return ArrayTypeConverter(this, type) } if (kClass.java.isEnum) { @Suppress("UNCHECKED_CAST") return EnumTypeConverter(kClass as KClass<Enum<*>>, type.isMarkedNullable) } if (kClass.isSubclassOf(Record::class)) { return RecordTypeConverter<Record>(this, type) } throw MissingTypeConverter(type) } private fun createCashedConverters(isOptional: Boolean): Map<KType, TypeConverter<*>> { val intTypeConverter = IntTypeConverter(isOptional) val doubleTypeConverter = DoubleTypeConverter(isOptional) val floatTypeConverter = FloatTypeConverter(isOptional) val boolTypeConverter = BoolTypeConverter(isOptional) return mapOf( Int::class.createType(nullable = isOptional) to intTypeConverter, java.lang.Integer::class.createType(nullable = isOptional) to intTypeConverter, Double::class.createType(nullable = isOptional) to doubleTypeConverter, java.lang.Double::class.createType(nullable = isOptional) to doubleTypeConverter, Float::class.createType(nullable = isOptional) to floatTypeConverter, java.lang.Float::class.createType(nullable = isOptional) to floatTypeConverter, Boolean::class.createType(nullable = isOptional) to boolTypeConverter, java.lang.Boolean::class.createType(nullable = isOptional) to boolTypeConverter, String::class.createType(nullable = isOptional) to StringTypeConverter(isOptional), ReadableArray::class.createType(nullable = isOptional) to ReadableArrayTypeConverter(isOptional), ReadableMap::class.createType(nullable = isOptional) to ReadableMapTypeConverter(isOptional), IntArray::class.createType(nullable = isOptional) to PrimitiveIntArrayTypeConverter(isOptional), DoubleArray::class.createType(nullable = isOptional) to PrimitiveDoubleArrayTypeConverter(isOptional), FloatArray::class.createType(nullable = isOptional) to PrimitiveFloatArrayTypeConverter(isOptional), ) } }
bsd-3-clause
42a9ef670c29e1387e58baacef53cda7
36.018692
108
0.759152
4.450562
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/annotator/RsEdition2018KeywordsAnnotatorTest.kt
2
4229
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import org.rust.MockEdition import org.rust.cargo.project.workspace.CargoWorkspace.Edition import org.rust.ide.colors.RsColor class RsEdition2018KeywordsAnnotatorTest : RsAnnotatorTestBase(RsEdition2018KeywordsAnnotator::class) { override fun setUp() { super.setUp() annotationFixture.registerSeverities(listOf(RsColor.KEYWORD.testSeverity)) } @MockEdition(Edition.EDITION_2015) fun `test edition 2018 keywords in edition 2015`() = checkErrors(""" fn main() { let async = (); let await = (); let try = (); let x = async; let y = await; let z = try; } """) fun `test edition 2018 keywords in edition 2018`() = checkErrors(""" fn main() { let <error descr="`async` is reserved keyword in Edition 2018">async</error> = (); let <error descr="`await` is reserved keyword in Edition 2018">await</error> = (); let <error descr="`try` is reserved keyword in Edition 2018">try</error> = (); let x = <error descr="`async` is reserved keyword in Edition 2018">async</error>; let y = <error descr="`await` is reserved keyword in Edition 2018">await</error>; let z = <error descr="`try` is reserved keyword in Edition 2018">try</error>; } """) // We should report an error here fun `test reserved keywords in macro names in edition 2018`() = checkErrors(""" fn main() { let x = async!(); let y = await!(x); let z = try!(()); } """) @MockEdition(Edition.EDITION_2015) fun `test async in edition 2015`() = checkErrors(""" <error descr="This feature is only available in Edition 2018">async</error> fn foo() {} fn main() { <error descr="This feature is only available in Edition 2018">async</error> { () }; <error descr="This feature is only available in Edition 2018">async</error> || { () }; <error descr="This feature is only available in Edition 2018">async</error> move || { () }; } """) fun `test async in edition 2018`() = checkErrors(""" <KEYWORD>async</KEYWORD> fn foo() {} fn main() { <KEYWORD>async</KEYWORD> { () }; <KEYWORD>async</KEYWORD> || { () }; <KEYWORD>async</KEYWORD> move || { () }; } """) @MockEdition(Edition.EDITION_2015) fun `test try in edition 2015`() = checkErrors(""" fn main() { <error descr="This feature is only available in Edition 2018">try</error> { () }; } """) fun `test try in edition 2018`() = checkErrors(""" fn main() { <KEYWORD>try</KEYWORD> { () }; } """) fun `test don't analyze macro def-call bodies, attributes and use items`() = checkErrors(""" use dummy::async; use dummy::await; use dummy::{async, await}; macro_rules! foo { () => { async }; } #[<error descr="`async` is reserved keyword in Edition 2018">async</error>] fn foo1() { #![<error descr="`async` is reserved keyword in Edition 2018">async</error>] } #[foo::<error descr="`async` is reserved keyword in Edition 2018">async</error>] fn foo2() { #![foo::<error descr="`async` is reserved keyword in Edition 2018">async</error>] } #[bar(async)] fn foo3() { #![bar(async)] } fn main() { foo!(async); } """) fun `test await postfix syntax`() = checkErrors(""" fn main() { let x = f().await; let y = f().<error descr="`await` is reserved keyword in Edition 2018">await</error>(); } """) @BatchMode fun `test no keyword highlighting in batch mode`() = checkHighlighting(""" async fn foo() {} fn main() { try { () }; let x = foo().await; } """, ignoreExtraHighlighting = false) }
mit
ddb76cdaf820e86d494db7e0f1611a1d
31.782946
103
0.545519
4.386929
false
true
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/utils/Graph.kt
2
5647
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.utils import org.rust.stdext.nextOrNull import java.util.* open class Graph<N, E>( private val nodes: MutableList<Node<N, E>> = mutableListOf(), private val edges: MutableList<Edge<N, E>> = mutableListOf() ) { private val nextNodeIndex: Int get() = nodes.size private val nextEdgeIndex: Int get() = edges.size val nodesCount: Int get() = nodes.size fun getNode(index: Int): Node<N, E> = nodes[index] fun addNode(data: N): Node<N, E> { val newNode = Node<N, E>(data, nextNodeIndex) nodes.add(newNode) return newNode } fun addEdge(source: Node<N, E>, target: Node<N, E>, data: E): Edge<N, E> { val sourceFirst = source.firstOutEdge val targetFirst = target.firstInEdge val newEdge = Edge(source, target, data, nextEdgeIndex, sourceFirst, targetFirst) edges.add(newEdge) source.firstOutEdge = newEdge target.firstInEdge = newEdge return newEdge } fun addEdge(sourceIndex: Int, targetIndex: Int, data: E): Edge<N, E> { val source = nodes[sourceIndex] val target = nodes[targetIndex] return addEdge(source, target, data) } fun outgoingEdges(source: Node<N, E>): Sequence<Edge<N, E>> = generateSequence(source.firstOutEdge) { it.nextSourceEdge } fun incomingEdges(target: Node<N, E>): Sequence<Edge<N, E>> = generateSequence(target.firstInEdge) { it.nextTargetEdge } private fun incidentEdges(node: Node<N, E>, direction: Direction): Sequence<Edge<N, E>> = when (direction) { Direction.OUTGOING -> outgoingEdges(node) Direction.INCOMING -> incomingEdges(node) } fun forEachNode(f: (Node<N, E>) -> Unit) = nodes.forEach { f(it) } fun forEachEdge(f: (Edge<N, E>) -> Unit) = edges.forEach { f(it) } fun depthFirstTraversal( startNode: Node<N, E>, direction: Direction = Direction.OUTGOING, edgeFilter: (Edge<N, E>) -> Boolean = { true } ): Sequence<Node<N, E>> { val visited = mutableSetOf(startNode) val stack = ArrayDeque<Node<N, E>>() stack.push(startNode) val visit = { node: Node<N, E> -> if (visited.add(node)) stack.push(node) } return generateSequence { val next = stack.poll() if (next != null) { incidentEdges(next, direction) .filter(edgeFilter) .forEach { edge -> val incident = edge.incidentNode(direction) visit(incident) } } next } } fun nodesInPostOrder(entryNode: Node<N, E>, direction: Direction = Direction.OUTGOING): List<Node<N, E>> { val visited = mutableSetOf<Node<N, E>>() val stack = ArrayDeque<Pair<Node<N, E>, Iterator<Edge<N, E>>>>() val result = mutableListOf<Node<N, E>>() val pushNode = { node: Node<N, E> -> if (visited.add(node)) stack.push(Pair(node, incidentEdges(node, direction).iterator())) } val nodesWithEntry = listOf(entryNode) + nodes for (nextNode in nodesWithEntry) { pushNode(nextNode) while (stack.isNotEmpty()) { val (node, iter) = stack.pop() val child = iter.nextOrNull() if (child != null) { val incident = child.incidentNode(direction) stack.push(Pair(node, iter)) pushNode(incident) } else { result.add(node) } } } return result } } interface PresentableNodeData { val text: String } class PresentableGraph<N : PresentableNodeData, E> : Graph<N, E>() { /** * Creates graph description in the DOT language format. * The graph can be rendered right inside the IDE using the [DOT Language plugin](https://plugins.jetbrains.com/plugin/10312-dot-language) * Also, the graph can be rendered from the file using the CLI: `dot -Tpng cfg.dot -o cfg.png` */ fun createDotDescription(): String = buildString { append("digraph {\n") forEachEdge { edge -> val source = edge.source val target = edge.target val sourceNode = source.data val targetNode = target.data val escapedSourceText = sourceNode.text.replace("\"", "\\\"") val escapedTargetText = targetNode.text.replace("\"", "\\\"") append(" \"${source.index}: $escapedSourceText\" -> \"${target.index}: $escapedTargetText\";\n") } append("}\n") } fun depthFirstTraversalTrace(startNode: Node<N, E> = getNode(0)): String = depthFirstTraversal(startNode).joinToString("\n") { it.data.text } } class Node<N, E>( val data: N, val index: Int, var firstOutEdge: Edge<N, E>? = null, var firstInEdge: Edge<N, E>? = null ) class Edge<N, E>( val source: Node<N, E>, val target: Node<N, E>, val data: E, val index: Int, val nextSourceEdge: Edge<N, E>?, val nextTargetEdge: Edge<N, E>? ) { fun incidentNode(direction: Direction): Node<N, E> = when (direction) { Direction.OUTGOING -> target Direction.INCOMING -> source } } enum class Direction { OUTGOING, INCOMING }
mit
06b5a80aa311f6452150deca5874e3aa
30.724719
142
0.566673
3.987994
false
false
false
false
yakov116/FastHub
app/src/main/java/com/fastaccess/ui/modules/editor/emoji/EmojiBottomSheet.kt
2
2618
package com.fastaccess.ui.modules.editor.emoji import android.content.Context import android.os.Bundle import android.text.Editable import android.view.View import butterknife.BindView import butterknife.OnTextChanged import com.fastaccess.R import com.fastaccess.provider.emoji.Emoji import com.fastaccess.ui.adapter.EmojiAdapter import com.fastaccess.ui.base.BaseMvpBottomSheetDialogFragment import com.fastaccess.ui.widgets.recyclerview.DynamicRecyclerView import com.fastaccess.ui.widgets.recyclerview.layout_manager.GridManager import com.fastaccess.ui.widgets.recyclerview.scroll.RecyclerViewFastScroller /** * Created by kosh on 17/08/2017. */ class EmojiBottomSheet : BaseMvpBottomSheetDialogFragment<EmojiMvp.View, EmojiPresenter>(), EmojiMvp.View { @BindView(R.id.recycler) lateinit var recycler: DynamicRecyclerView @BindView(R.id.fastScroller) lateinit var fastScroller: RecyclerViewFastScroller val adapter: EmojiAdapter by lazy { EmojiAdapter(this) } var emojiCallback: EmojiMvp.EmojiCallback? = null @OnTextChanged(value = R.id.editText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED) fun onTextChange(text: Editable) { adapter.filter.filter(text) } override fun onAttach(context: Context) { super.onAttach(context) emojiCallback = when { parentFragment is EmojiMvp.EmojiCallback -> parentFragment as EmojiMvp.EmojiCallback context is EmojiMvp.EmojiCallback -> context else -> throw IllegalArgumentException("${context.javaClass.simpleName} must implement EmojiMvp.EmojiCallback") } } override fun onDetach() { emojiCallback = null super.onDetach() } override fun fragmentLayout(): Int = R.layout.emoji_popup_layout override fun providePresenter(): EmojiPresenter = EmojiPresenter() override fun clearAdapter() { adapter.clear() } override fun onAddEmoji(emoji: Emoji) { adapter.addItem(emoji) } override fun onItemClick(position: Int, v: View?, item: Emoji) { emojiCallback?.onEmojiAdded(item) dismiss() } override fun onItemLongClick(position: Int, v: View?, item: Emoji?) {} override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler.adapter = adapter fastScroller.attachRecyclerView(recycler) presenter.onLoadEmoji() val gridManager = recycler.layoutManager as GridManager gridManager.iconSize = resources.getDimensionPixelSize(R.dimen.header_icon_zie) } }
gpl-3.0
ea90ab9d306cfff31de2e76de9a024ec
33.460526
123
0.735676
4.617284
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/solver/query/result/LiveDataQueryResultBinder.kt
3
2596
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver.query.result import androidx.room.compiler.codegen.XPropertySpec import androidx.room.compiler.codegen.toJavaPoet import androidx.room.compiler.processing.XType import androidx.room.ext.CallableTypeSpecBuilder import androidx.room.ext.L import androidx.room.ext.N import androidx.room.ext.T import androidx.room.ext.arrayTypeName import androidx.room.solver.CodeGenScope /** * Converts the query into a LiveData and returns it. No query is run until necessary. */ class LiveDataQueryResultBinder( val typeArg: XType, val tableNames: Set<String>, adapter: QueryResultAdapter? ) : BaseObservableQueryResultBinder(adapter) { @Suppress("JoinDeclarationAndAssignment") override fun convertAndReturn( roomSQLiteQueryVar: String, canReleaseQuery: Boolean, dbProperty: XPropertySpec, inTransaction: Boolean, scope: CodeGenScope ) { val dbField = dbProperty.toJavaPoet() val callableImpl = CallableTypeSpecBuilder(typeArg.typeName) { createRunQueryAndReturnStatements( builder = this, roomSQLiteQueryVar = roomSQLiteQueryVar, inTransaction = inTransaction, dbField = dbField, scope = scope, cancellationSignalVar = "null" // LiveData can't be cancelled ) }.apply { if (canReleaseQuery) { addMethod(createFinalizeMethod(roomSQLiteQueryVar)) } }.build() scope.builder().apply { val tableNamesList = tableNames.joinToString(",") { "\"$it\"" } addStatement( "return $N.getInvalidationTracker().createLiveData(new $T{$L}, $L, $L)", dbField, String::class.arrayTypeName, tableNamesList, if (inTransaction) "true" else "false", callableImpl ) } } }
apache-2.0
bd4fae8f34a139ef6a7a9128ce56916d
34.561644
88
0.65832
4.825279
false
false
false
false
oleksiyp/mockk
agent/android/src/main/kotlin/io/mockk/proxy/android/JvmtiAgent.kt
1
3285
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mockk.proxy.android import android.os.Build import android.os.Debug import dalvik.system.BaseDexClassLoader import io.mockk.proxy.MockKAgentException import io.mockk.proxy.android.transformation.InliningClassTransformer import java.io.File import java.io.FileOutputStream import java.io.InputStream import java.security.ProtectionDomain internal class JvmtiAgent { var transformer: InliningClassTransformer? = null init { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { throw MockKAgentException("Requires API level " + Build.VERSION_CODES.P + ". API level is " + Build.VERSION.SDK_INT) } if (Build.VERSION.CODENAME != "P") { } val cl = JvmtiAgent::class.java.classLoader as? BaseDexClassLoader ?: throw MockKAgentException("Could not load jvmti plugin as AndroidMockKJvmtiAgent class was not loaded " + "by a BaseDexClassLoader") Debug.attachJvmtiAgent(libName, null, cl) nativeRegisterTransformerHook() } fun appendToBootstrapClassLoaderSearch(inStream: InputStream) { val jarFile = File.createTempFile("mockk-boot", ".jar") .apply { deleteOnExit() } .also { FileOutputStream(it).use { inStream.copyTo(it) } } nativeAppendToBootstrapClassLoaderSearch(jarFile.absolutePath) } fun requestTransformClasses(classes: Array<Class<*>>) { synchronized(lock) { nativeRetransformClasses(classes) } } @Suppress("unused") // called by JNI fun shouldTransform(classBeingRedefined: Class<*>?): Boolean { if (classBeingRedefined == null) { return false } return transformer?.shouldTransform(classBeingRedefined) ?: false } @Suppress("unused") // called by JNI fun runTransformers( loader: ClassLoader?, className: String, classBeingRedefined: Class<*>, protectionDomain: ProtectionDomain?, classfileBuffer: ByteArray ) = transformer?.transform(classBeingRedefined, classfileBuffer) ?: classfileBuffer fun disconnect() { nativeUnregisterTransformerHook() } private external fun nativeRegisterTransformerHook() private external fun nativeUnregisterTransformerHook() private external fun nativeRetransformClasses(classes: Array<Class<*>>) companion object { private const val libName = "libmockkjvmtiagent.so" private val lock = Any() @JvmStatic private external fun nativeAppendToBootstrapClassLoaderSearch(absolutePath: String) } }
apache-2.0
ac2281a1fc21b9210cd2bfa4c9168cae
31.85
155
0.686149
4.699571
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_framebuffer_no_attachments.kt
1
4582
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val ARB_framebuffer_no_attachments = "ARBFramebufferNoAttachments".nativeClassGL("ARB_framebuffer_no_attachments") { documentation = """ Native bindings to the $registryLink extension. Framebuffer objects as introduced by ${ARB_framebuffer_object.link} and OpenGL 3.0 provide a generalized mechanism for rendering to off-screen surfaces. Each framebuffer object may have depth, stencil and zero or more color attachments that can be written to by the GL. The size of the framebuffer (width, height, layer count, sample count) is derived from the attachments of that framebuffer. In unextended OpenGL 4.2, it is not legal to render into a framebuffer object that has no attachments. Such a framebuffer would be considered incomplete with the GL30#FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT status. With OpenGL 4.2 and ${ARB_shader_image_load_store.link}, fragment shaders are capable of doing random access writes to buffer and texture memory via image loads, stores, and atomics. This ability enables algorithms using the conventional rasterizer to generate a collection of fragments, where each fragment shader invocation will write its outputs to buffer or texture memory using image stores or atomics. Such algorithms may have no need to write color or depth values to a conventional framebuffer. However, a framebuffer with no attachments will be considered incomplete and no rasterization or fragment shader exectuion will occur. To avoid such errors, an application may be required to create an otherwise unnecessary "dummy" texture and attach it to the framebuffer (possibly with color writes masked off). If the algorithm requires the rasterizer to operate over a large number of pixels, this dummy texture will needlessly consume a significant amount of memory. This extension enables the algorithms described above to work even with a framebuffer with no attachments. Applications can specify default width, height, layer count, and sample count parameters for a framebuffer object. When a framebuffer with no attachments is bound, it will be considered complete as long as the application has specified non-zero default width and height parameters. For the purposes of rasterization, the framebuffer will be considered to have a width, height, layer count, and sample count derived from its default parameters. Framebuffers with one or more attachments are not affected by these default parameters; the size of the framebuffer will still be derived from the sizes of the attachments in that case. Additionally, this extension provides queryable implementation-dependent maximums for framebuffer width, height, layer count, and sample count, which may differ from similar limits on textures and renderbuffers. These maximums will be used to error-check the default framebuffer parameters and also permit implementations to expose the ability to rasterize to an attachment-less framebuffer larger than the maximum supported texture size. Requires ${GL30.core} or ${ARB_framebuffer_object.link}. ${GL43.promoted} """ IntConstant( """ Accepted by the {@code pname} parameter of FramebufferParameteri, GetFramebufferParameteriv, NamedFramebufferParameteriEXT, and GetNamedFramebufferParameterivEXT. """, "FRAMEBUFFER_DEFAULT_WIDTH"..0x9310, "FRAMEBUFFER_DEFAULT_HEIGHT"..0x9311, "FRAMEBUFFER_DEFAULT_LAYERS"..0x9312, "FRAMEBUFFER_DEFAULT_SAMPLES"..0x9313, "FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS"..0x9314 ) IntConstant( "Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetInteger64v, GetFloatv, and GetDoublev.", "MAX_FRAMEBUFFER_WIDTH"..0x9315, "MAX_FRAMEBUFFER_HEIGHT"..0x9316, "MAX_FRAMEBUFFER_LAYERS"..0x9317, "MAX_FRAMEBUFFER_SAMPLES"..0x9318 ) GL43 reuse "FramebufferParameteri" GL43 reuse "GetFramebufferParameteriv" var src = GL43["FramebufferParameteri"] DependsOn("GL_EXT_direct_state_access")..void( "NamedFramebufferParameteriEXT", "DSA version of #FramebufferParameteri().", GLuint.IN("framebuffer", "the framebuffer object"), src["pname"], src["param"] ) src = GL43["GetFramebufferParameteriv"] DependsOn("GL_EXT_direct_state_access", postfix = "EXT")..void( "GetNamedFramebufferParameterivEXT", "DSA version of #GetFramebufferParameteriv().", GLuint.IN("framebuffer", "the framebuffer object"), src["pname"], src["params"] ) }
bsd-3-clause
b46779b25831882305a9de1babaeeb6a
52.290698
154
0.785028
4.372137
false
false
false
false
rustamgaifullin/kotlin-lunch-learn
src/main/kotlin/com/rustam/basic/4.Functions.kt
1
660
package com.rustam.basic fun simpleFunction(): String { return "I'm simple function" } fun printName(name: String) { println("My name is $name") } fun justPrintMyName(name: String) = println(name) fun printFancyName(name: String, prefix:String = "", notes: String = "" ) = println("$prefix$name$notes") fun main(args: Array<String>) { println(simpleFunction()) printName("Rustam") justPrintMyName("Rustam") printFancyName("Rustam") printFancyName("Rustam", "Dear ") printFancyName("Rustam", "Dear ", " Please remember about...") printFancyName(prefix = "Dear ", name = "Rustam", notes = "P lease remember about...") }
unlicense
e23a8af1df90961de33e3bd6239ccdb8
25.44
105
0.669697
3.419689
false
false
false
false
REDNBLACK/advent-of-code2016
src/main/kotlin/day20/Advent20.kt
1
2121
package day20 import parseInput import splitToLines import java.util.stream.LongStream /** --- Day 20: Firewall Rules --- You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the corporate firewall only allows communication with certain external IP addresses. You've retrieved the list of blocked IPs from the firewall, but the list seems to be messy and poorly maintained, and it's not clear which IPs are allowed. Also, rather than being written in dot-decimal notation, they are written as plain 32-bit integers, which can have any value from 0 through 4294967295, inclusive. For example, suppose only the values 0 through 9 were valid, and that you retrieved the following blacklist: 5-8 0-2 4-7 The blacklist specifies ranges of IPs (inclusive of both the start and end value) that are not allowed. Then, the only IPs that this firewall allows are 3 and 9, since those are the only numbers not in any range. Given the list of blocked IPs you retrieved from the firewall (your puzzle input), what is the lowest-valued IP that is not blocked? --- Part Two --- How many IPs are allowed by the blacklist? */ fun main(args: Array<String>) { val test = """5-8 |0-2 |4-7""".trimMargin() val input = parseInput("day20-input.txt") println(findLowestIP(test) == 3L) println(countWhitelisted(test)) println(findLowestIP(input)) println(countWhitelisted(input)) } fun findLowestIP(input: String): Long? { val ranges = parseRanges(input) return (0..4294967295).first { number -> ranges.none { range -> range.contains(number) } } } fun countWhitelisted(input: String): Long { val ranges = parseRanges(input) // For speedup return LongStream.rangeClosed(0, 4294967295L) .parallel() .filter { number -> ranges.none { range -> range.contains(number) } } .count() } private fun parseRanges(input: String) = input.splitToLines() .map { it -> val (min, max) = it.split("-") min.toLong()..max.toLong() }
mit
a2ef283cff684eb89a8990768b5a5b61
33.209677
318
0.691655
3.870438
false
false
false
false
NayeemUrRehman/friendly-timer-app
src/main/java/com/example/friendly_timer_app/MainActivity.kt
1
1466
package com.example.friendly_timer_app import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.util.Log class MainActivity : AppCompatActivity() { var timerHandler = Handler() var starttime = 0.0 var netTime = 0.0 val that = this var timerRunnable = object : Runnable { override fun run() { val diffInMillis = (starttime + netTime) - System.currentTimeMillis() val diffInSeconds = (diffInMillis / 1000).toInt() if (diffInSeconds >= 0) { Log.e("time", (diffInSeconds).toString()) var secs = (diffInSeconds) val mints = (diffInSeconds) / 60 secs = secs % 60 that.timer.post { that.timer.text = String.format("%d:%02d", mints, secs) } timerHandler.postDelayed(this, 1000) } else { timerHandler.removeCallbacksAndMessages(this) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun startTimer(time:Double){ starttime = System.currentTimeMillis().toDouble() netTime = time*1000 timerHandler.postDelayed(timerRunnable, 0) } fun stopTimer(){ timerHandler.removeCallbacksAndMessages(timerRunnable) } }
mit
69acb4e96f8883e99f86208f22f46531
28.918367
81
0.598226
4.624606
false
false
false
false
inorichi/tachiyomi-extensions
src/en/mangamutiny/src/eu/kanade/tachiyomi/extension/en/mangamutiny/MangaMutinyUrlActivity.kt
1
1409
package eu.kanade.tachiyomi.extension.en.mangamutiny import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.util.Log import kotlin.system.exitProcess /** * Springboard that accepts https://mangamutiny.org/title/xxx intents and redirects them to * the main tachiyomi process. The idea is to not install the intent filter unless * you have this extension installed, but still let the main tachiyomi app control * things. */ class MangaMutinyUrlActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val pathSegments = intent?.data?.pathSegments if (pathSegments != null && pathSegments.size > 1) { val slug = pathSegments[1] val mainIntent = Intent().apply { action = "eu.kanade.tachiyomi.SEARCH" putExtra("query", "${MangaMutiny.PREFIX_ID_SEARCH}$slug") putExtra("filter", packageName) } try { startActivity(mainIntent) } catch (e: ActivityNotFoundException) { Log.e("MangaMutinyUrlActivity", e.toString()) } } else { Log.e("MangaMutinyUrlActivity", "could not parse uri from intent $intent") } finish() exitProcess(0) } }
apache-2.0
0a08a62b8ffb6132e2019a63f087a1f7
33.365854
91
0.649397
4.665563
false
false
false
false